blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 132
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 28
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
352
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
efd7a9736469a39c29a5d475a2787459ded9d36b
|
f8f32a589736a1e8cbec7e3601de8f6fc572c43c
|
/src/com/book/servlet/BookCategoryServlet.java
|
fb41daa9faf08bc9d54337991601ff0fa8fd0921
|
[] |
no_license
|
myischenxiaohua/book
|
1cad197eb4004191520f65c9a8bbbb298ef57868
|
ae89edc645adf5d9b82a0e46a5d9173d5cdfe316
|
refs/heads/master
| 2020-04-13T20:11:50.186545
| 2019-03-19T13:54:38
| 2019-03-19T13:54:38
| 163,423,734
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,032
|
java
|
package com.book.servlet;
import com.book.domian.BookCategory;
import com.book.service.impl.BookCategoryServiceImpl;
import com.book.util.WebUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/*
ClassName:${PACKAGE_NAME}
Description:
User: myischenxiaohua@163.com
Date: 2019-01-23
Time: 17:14
*/
public class BookCategoryServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String status=request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
System.out.println(status);
switch (status){
case "add":add(request,response);break;
case "list":list(request,response);break;
}
}
public void add(HttpServletRequest request, HttpServletResponse response){}
public void list(HttpServletRequest request, HttpServletResponse response){
try {
if(WebUtils.validateEmpty(request.getParameter("ajax"))){
JSONArray jsonArray=new JSONArray();
//response.getWriter().print(jsonArray.toString());
// String jsonStr="";
//
for (BookCategory bc : new BookCategoryServiceImpl().list()){
jsonArray.put(new JSONObject(bc));
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("status",1);
jsonObject.put("data",jsonArray);
response.getWriter().print(jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
[
"myischenxiaohua@163.com"
] |
myischenxiaohua@163.com
|
6de4d7badd5b9f0fb942233a08801ae300512d70
|
f142738b9a5de8b7fcd6b4c0ed57ee70b66d9dac
|
/src/main/java/de/edgelord/saltyengine/core/stereotypes/ComponentParent.java
|
976c67109f374dcdc402f8756cc2e00749263512
|
[
"MIT"
] |
permissive
|
igorimagine/salty-engine
|
94921f119f824384ae252d8e63b624a179bca4b5
|
532c99fb3f1afc98db17c5a3ea54547d457b63d9
|
refs/heads/master
| 2020-04-02T06:37:16.123268
| 2018-10-17T17:04:57
| 2018-10-17T17:04:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,755
|
java
|
/*
* This software was published under the MIT License.
* The full LICENSE file can be found here: https://github.com/edgelord314/salty-enigne/tree/master/LICENSE
*
* Copyright (c) 2018 Malte Dostal
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package de.edgelord.saltyengine.core.stereotypes;
import de.edgelord.saltyengine.core.Component;
import de.edgelord.saltyengine.core.Game;
import de.edgelord.saltyengine.core.interfaces.TransformedObject;
import de.edgelord.saltyengine.graphics.SaltyGraphics;
import de.edgelord.saltyengine.transform.Transform;
import java.util.List;
public abstract class ComponentParent implements TransformedObject {
private String tag;
public ComponentParent(String tag) {
this.tag = tag;
}
/**
* Adds the given {@link Component}
*
* @param component the component to add
*/
public abstract void addComponent(Component component);
/**
* Removes a {@link Component} by searching for the one with the given name
* and remove that one
*
* @param identifier the identifier of the component to be removed
*/
public abstract void removeComponent(String identifier);
/**
* Removes the given {@link Component}
* The implementation should be different from {@link #getComponent(String)}
* due to better performance possible when directly removing a Component
*
* @param component the {@link Component} to be removed
*/
public abstract void removeComponent(Component component);
/**
* Returns the {@link List} of {@link Component}s
*
* @return the {@link List} of {@link Component}s
*/
public abstract List<Component> getComponents();
/**
* Returns the {@link Component} with the given identifier
*
* @param identifier the identifier of the {@link Component} to be returned
* @return the requested {@link Component}
*/
public abstract Component getComponent(String identifier);
/**
* Calls the method {@link Component#onFixedTick()} for every {@link Component}.
*/
public void doComponentOnFixedTick() {
getComponents().forEach(component -> {
if (component.isEnabled()) {
component.onFixedTick();
}
});
}
/**
* Calls the method {@link Component#draw(SaltyGraphics)} for every component with the given {@link SaltyGraphics}
*
* @param graphics the graphics context to draw the components
*/
public void doComponentDrawing(SaltyGraphics graphics) {
getComponents().forEach(component -> {
if (component.isEnabled()) {
component.draw(graphics);
}
});
}
/**
* Places this object in the middle of the {@link de.edgelord.saltyengine.core.Host} {@link Game#host}
*/
public void centrePosition() {
setPosition(Game.getHost().getCentrePosition(getDimensions()));
}
/**
* Centres this object horizontally in the {@link de.edgelord.saltyengine.core.Host} {@link Game#host}
*/
public void centreHorizontalPosition() {
setX(Game.getHost().getHorizontalCentrePosition(getWidth()));
}
/**
* Centres this object vertically in the {@link de.edgelord.saltyengine.core.Host} {@link Game#host}
*/
public void centreVerticalPosition() {
setX(Game.getHost().getVerticalCentrePosition(getHeight()));
}
@Override
public abstract Transform getTransform();
@Override
public abstract void setTransform(Transform transform);
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
|
[
"malte.dostal@gmail.com"
] |
malte.dostal@gmail.com
|
e0327d2cdbf062b4ac103f1bb7b37f9635347c8c
|
cd4802766531a9ccf0fb54ca4b8ea4ddc15e31b5
|
/dist/game/data/scripts/quests/Q10758_TheOathOfTheWind/Q10758_TheOathOfTheWind.java
|
006bed445bc4910c263f2232a8189bf4015c4736
|
[] |
no_license
|
singto53/underground
|
8933179b0d72418f4b9dc483a8f8998ef5268e3e
|
94264f5168165f0b17cc040955d4afd0ba436557
|
refs/heads/master
| 2021-01-13T10:30:20.094599
| 2016-12-11T20:32:47
| 2016-12-11T20:32:47
| 76,455,182
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,673
|
java
|
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package quests.Q10758_TheOathOfTheWind;
import com.l2jmobius.gameserver.enums.ChatType;
import com.l2jmobius.gameserver.enums.Race;
import com.l2jmobius.gameserver.model.actor.L2Npc;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.quest.Quest;
import com.l2jmobius.gameserver.model.quest.QuestState;
import com.l2jmobius.gameserver.model.quest.State;
import com.l2jmobius.gameserver.network.NpcStringId;
import quests.Q10757_QuietingTheStorm.Q10757_QuietingTheStorm;
/**
* The Oath of the Wind (10758)
* @author malyelfik
*/
public final class Q10758_TheOathOfTheWind extends Quest
{
// NPC
private static final int PIO = 33963;
// Monster
private static final int WINDIMA = 27522;
// Misc
private static final int MIN_LEVEL = 28;
public Q10758_TheOathOfTheWind()
{
super(10758);
addStartNpc(PIO);
addTalkId(PIO);
addSpawnId(WINDIMA);
addKillId(WINDIMA);
addCondRace(Race.ERTHEIA, "33963-00.htm");
addCondMinLevel(MIN_LEVEL, "33963-00.htm");
addCondCompletedQuest(Q10757_QuietingTheStorm.class.getSimpleName(), "33963-00.htm");
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
final QuestState qs = getQuestState(player, false);
if (qs == null)
{
return null;
}
String htmltext = event;
switch (event)
{
case "33963-01.htm":
case "33963-02.htm":
break;
case "33963-03.htm":
{
qs.startQuest();
break;
}
case "SPAWN":
{
if (qs.isCond(1))
{
final L2Npc mob = addSpawn(WINDIMA, -93427, 89595, -3216, 0, true, 180000);
addAttackPlayerDesire(mob, player);
}
htmltext = null;
break;
}
case "33963-06.html":
{
if (qs.isCond(2))
{
giveStoryQuestReward(player, 3);
addExpAndSp(player, 561645, 134);
qs.exitQuest(false, true);
}
break;
}
default:
htmltext = null;
}
return htmltext;
}
@Override
public String onTalk(L2Npc npc, L2PcInstance player)
{
final QuestState qs = getQuestState(player, true);
String htmltext = getNoQuestMsg(player);
switch (qs.getState())
{
case State.CREATED:
htmltext = "33963-01.htm";
break;
case State.STARTED:
htmltext = (qs.isCond(1)) ? "33963-04.html" : "33963-05.html";
break;
case State.COMPLETED:
htmltext = getAlreadyCompletedMsg(player);
break;
}
return htmltext;
}
@Override
public String onSpawn(L2Npc npc)
{
npc.broadcastSay(ChatType.NPC_GENERAL, NpcStringId.ARGHH);
return super.onSpawn(npc);
}
@Override
public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
{
final QuestState qs = getQuestState(killer, false);
if ((qs != null) && qs.isCond(1))
{
qs.setCond(2, true);
}
npc.broadcastSay(ChatType.NPC_GENERAL, NpcStringId.I_AM_LOYAL_TO_YOU_MASTER_OF_THE_WINDS_AND_LOYAL_I_SHALL_REMAIN_IF_MY_VERY_SOUL_BETRAYS_ME);
return super.onKill(npc, killer, isSummon);
}
}
|
[
"MobiusDev@7325c9f8-25fd-504a-9f63-8876acdc129b"
] |
MobiusDev@7325c9f8-25fd-504a-9f63-8876acdc129b
|
1b8a2f20f14f9ee3153805cdbe7693c5bea2a753
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/6/6_7532b921b64d0f9159adb4080422cb222237a131/RuleFileGenerator/6_7532b921b64d0f9159adb4080422cb222237a131_RuleFileGenerator_s.java
|
2bae8170b95e64a6aa8a41744f5f1f79f95e0e12
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 14,619
|
java
|
/*
* @(#)$Id$
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package com.sun.tahiti.compiler.ll;
import com.sun.msv.datatype.xsd.XSDatatype;
import com.sun.msv.grammar.*;
import com.sun.msv.grammar.util.ExpressionWalker;
import com.sun.tahiti.compiler.XMLWriter;
import com.sun.tahiti.compiler.Symbolizer;
import com.sun.tahiti.grammar.*;
import com.sun.tahiti.reader.TypeUtil;
import org.relaxng.datatype.Datatype;
import org.xml.sax.DocumentHandler;
import org.xml.sax.SAXException;
import java.io.PrintStream;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.text.MessageFormat;
public class RuleFileGenerator implements Symbolizer {
private RuleFileGenerator() {}
/**
*
* @param grammar
* Grammar object to be generated as a Java source code.
* @param rules
* production rules of the grammar. Actual type must be
* non-terminal -> Rule[].
* @param grammarClassName
* the fully-qualified name of the class that is going to be generated.
* @param outHandler
* Generated source code will be sent to this handler.
*
* @return
* return a symbolizer that is necessary to serialize class definitions.
*/
public static Symbolizer generate( Grammar grammar, Map rules, String grammarClassName, DocumentHandler outHandler ) throws SAXException {
RuleFileGenerator gen = new RuleFileGenerator();
gen._generate( grammar, rules, grammarClassName, outHandler );
return gen;
}
/**
* this map serves as a dictionary to lookup the name of the given symbol.
*/
final Map allNames = new java.util.HashMap();
public String getId( Object symbol ) {
if(symbol==null) return "null";
String s = (String)allNames.get(symbol);
if(s==null) {
System.out.println(symbol);
assert(false);
}
return s;
}
private void _generate( Grammar grammar, Map rules, String grammarClassName, DocumentHandler outHandler ) throws SAXException {
// add pre-defined special symbols.
allNames.put( Expression.epsilon, "epsilon" );
try {
final XMLWriter out = new XMLWriter(outHandler);
outHandler.setDocumentLocator(new org.xml.sax.helpers.LocatorImpl());
outHandler.startDocument();
outHandler.processingInstruction("xml-stylesheet","type='text/xsl' href='../grammarDebug.xslt'");
out.start("grammar");
{
int idx = grammarClassName.lastIndexOf('.');
if(idx<0) {
out.element("name", grammarClassName);
} else {
out.element("package", grammarClassName.substring(0,idx));
out.start("name", grammarClassName.substring(idx+1));
}
}
// collect various primitives (a map to its name)
//====================================================================
final Map elements = new java.util.HashMap(); // ElementExps
final Map attributes = new java.util.HashMap(); // AttributeExps
final Map datatypes = new java.util.HashMap(); // Datatypes
final Map classes = new java.util.HashMap(); // ClassItems
final Map fields = new java.util.HashMap(); // FieldItems
final Map primitives = new java.util.HashMap(); // PrimitiveItems
final Map ignores = new java.util.HashMap(); // IgnoreItems
grammar.getTopLevel().visit( new ExpressionWalker(){
public void onElement( ElementExp exp ) {
if(!elements.containsKey(exp)) {
elements.put(exp,computeName(exp.getNameClass(),elements));
super.onElement(exp);
}
}
public void onAttribute( AttributeExp exp ) {
if(!attributes.containsKey(exp)) {
attributes.put(exp,computeName(exp.nameClass,attributes));
super.onAttribute(exp);
}
}
public void onTypedString( TypedStringExp exp ) {
if(!datatypes.containsKey(exp)) {
datatypes.put(exp,computeName(exp.dt,datatypes));
super.onTypedString(exp);
}
}
public void onOther( OtherExp exp ) {
if(exp instanceof ClassItem) {
if(!classes.containsKey(exp)) {
classes.put(exp,computeName((ClassItem)exp,classes));
super.onOther(exp);
}
return;
}
if(exp instanceof PrimitiveItem) {
if(!primitives.containsKey(exp)) {
primitives.put(exp,computeName((PrimitiveItem)exp,primitives));
super.onOther(exp);
}
return;
}
if(exp instanceof FieldItem) {
if(!fields.containsKey(exp)) {
fields.put(exp,computeName((FieldItem)exp,fields));
super.onOther(exp);
}
return;
}
if(exp instanceof IgnoreItem) {
if(!ignores.containsKey(exp)) {
ignores.put(exp,computeName((IgnoreItem)exp,ignores));
super.onOther(exp);
}
return;
}
super.onOther(exp);
}
});
// assign names to intermediate non-terminals.
//====================================================================
copyAll( elements, "E", allNames );
copyAll( attributes, "A", allNames );
copyAll( datatypes, "D", allNames );
copyAll( classes, "C", allNames );
copyAll( fields, "N", allNames );
copyAll( primitives, "P", allNames );
copyAll( ignores, "Ignore", allNames );
final ElementExp[] elms = (ElementExp[])elements.keySet().toArray(new ElementExp[0]);
final AttributeExp[] atts = (AttributeExp[])attributes.keySet().toArray(new AttributeExp[0]);
final TypedStringExp[] dts = (TypedStringExp[])datatypes.keySet().toArray(new TypedStringExp[0]);
final ClassItem[] cis = (ClassItem[])classes.keySet().toArray(new ClassItem[0]);
final FieldItem[] fis = (FieldItem[])fields.keySet().toArray(new FieldItem[0]);
final PrimitiveItem[] pis = (PrimitiveItem[])primitives.keySet().toArray(new PrimitiveItem[0]);
final IgnoreItem[] iis = (IgnoreItem[])ignores.keySet().toArray(new IgnoreItem[0]);
for( int i=0; i<dts.length; i++ ) {
// TODO: serious implementation
out.start( "dataSymbol", new String[]{
"id",(String)allNames.get(dts[i])});
out.element("library", dts[i].name.namespaceURI );
out.element("name", dts[i].name.localName );
out.end("dataSymbol");
// "type", ((XSDatatype)dts[i].dt).getConcreteType().getName()
// } );
}
for( int i=0; i<cis.length; i++ ) {
out.element( "classSymbol", new String[]{
"id",(String)allNames.get(cis[i]),
"type",(String)cis[i].getTypeName()
} );
}
for( int i=0; i<pis.length; i++ )
out.element( "primitiveSymbol", new String[]{"id",(String)allNames.get(pis[i])} );
for( int i=0; i<fis.length; i++ )
out.element( "namedSymbol", new String[]{"id",(String)allNames.get(fis[i])} );
for( int i=0; i<iis.length; i++ )
out.element( "ignoreSymbol", new String[]{"id",(String)allNames.get(iis[i])} );
{// generate intermediate symbols.
int cnt=1;
for( Iterator itr = rules.keySet().iterator(); itr.hasNext(); ) {
Expression symbol = (Expression)itr.next();
if(!allNames.containsKey(symbol)) {
out.element( "intermediateSymbol", new String[]{"id","T"+cnt});
allNames.put( symbol, "T"+cnt );
cnt++;
}
}
}
{// write all rules
int rcounter = 0;
Iterator itr = rules.keySet().iterator();
while(itr.hasNext()) {
Expression nonTerminal = (Expression)itr.next();
out.start("rules",
new String[]{"nonTerminal",getId(nonTerminal)});
Rule[] rs = (Rule[])rules.get(nonTerminal);
for( int j=0; j<rs.length; j++ ) {
// name this rule.
allNames.put( rs[j], "r"+(rcounter++) );
// write this rule
rs[j].write(out,this);
}
out.end("rules");
}
}
// generate a source code that constructs the grammar.
//==============================================================
ExpressionSerializer eser = new ExpressionSerializer(this,out);
/*
visit all elements and attributes to compute the dependency between expressions.
*/
for( int i=0; i<atts.length; i++ ) {
atts[i].exp.visit(eser.sequencer);
eser.assignId( atts[i] );
// attributes are serialized just like other particles.
}
for( int i=0; i<elms.length; i++ )
elms[i].contentModel.visit(eser.sequencer);
// ... and don't forget to visit top level expression.
grammar.getTopLevel().visit(eser.sequencer);
// then obtain the serialization order by creating a map from id to expr.
java.util.TreeMap id2expr = new java.util.TreeMap();
for( Iterator itr=eser.sharedExps.iterator(); itr.hasNext(); ) {
Expression exp = (Expression)itr.next();
id2expr.put( eser.expr2id.get(exp), exp );
}
// then serialize shared expressions
for( Iterator itr=id2expr.keySet().iterator(); itr.hasNext(); ) {
Integer n = (Integer)itr.next();
Expression exp = (Expression)id2expr.get(n);
if( exp instanceof AttributeExp ) {
AttributeExp aexp = (AttributeExp)exp;
out.start( "attributeSymbol", new String[]{"id",(String)allNames.get(aexp)} );
ExpressionSerializer.serializeNameClass(aexp.getNameClass(),out);
out.start("content");
aexp.visit(eser.serializer);
out.end("content");
LLTableCalculator.calc( aexp, rules, grammar.getPool(),this ).write(out,this);
out.end("attributeSymbol");
} else {
// other normal particles.
out.start("particle",new String[]{"id","o"+n});
exp.visit(eser.serializer);
out.end("particle");
}
}
// elements are serialized at last.
for( int i=0; i<elms.length; i++ ) {
out.start("elementSymbol", new String[]{"id",(String)allNames.get(elms[i])} );
ExpressionSerializer.serializeNameClass(elms[i].getNameClass(),out);
out.start("content");
elms[i].visit(eser.serializer);
out.end("content");
LLTableCalculator.calc( elms[i], rules, grammar.getPool(),this ).write(out,this);
out.end("elementSymbol");
}
if( elements.containsKey(grammar.getTopLevel()) ) {
// if the top-level expression is element symbol,
// then we don't need the root grammar.
out.start("topLevel");
out.start("content");
eser.serialize(grammar.getTopLevel());
out.end("content");
out.end("topLevel");
} else {
// serialize top-level expression
out.start("topLevel",new String[]{"id",getId(grammar.getTopLevel())});
out.start("content");
grammar.getTopLevel().visit(eser.serializer);
out.end("content");
LLTableCalculator.calc( grammar.getTopLevel(), rules, grammar.getPool(),this ).write(out,this);
out.end("topLevel");
}
{// compute the base type of possible top-level classes
final Set rootClasses = new java.util.HashSet();
grammar.getTopLevel().visit( new ExpressionWalker(){
private Set visitedExps = new java.util.HashSet();
public void onOther( OtherExp exp ) {
if( exp instanceof TypeItem )
rootClasses.add(exp);
// we don't need to parse inside a JavaItem.
}
public void onElement( ElementExp exp ) {
if( visitedExps.add(exp) )
exp.contentModel.visit(this);
}
});
Type rootType = TypeUtil.getCommonBaseType(rootClasses);
out.element("rootType",
new String[]{"name", rootType.getTypeName()});
}
out.end("grammar");
outHandler.endDocument();
} catch( XMLWriter.SAXWrapper w ) {
throw w.e;
};
}
/**
* copy the source map to the destination map, while adding
* the specified prefix to values.
*/
private static void copyAll( Map src, String prefix, Map dst ) {
for( Iterator itr=src.keySet().iterator(); itr.hasNext(); ) {
Object symbol = itr.next();
dst.put( symbol, prefix+src.get(symbol) );
}
}
/**
* computes a unique name that is used as a field name for
* the ElementExp/AttributeExp.
*
* @param nc
* name class of that ElementExp/AttributeExp.
* @param m
* values of this map are the names of other ElementExp/AttributeExps.
* This method has to return the unique name.
*/
private static String computeName( NameClass nc, Map m ) {
if( nc instanceof SimpleNameClass ) {
SimpleNameClass snc = (SimpleNameClass)nc;
if(!m.containsValue(snc.localName))
return snc.localName;
return getNumberedName( snc.localName, 2, m );
} else {
return getNumberedName( "", 0, m );
}
}
/**
* generate an unique name by concatenating a number to its tail.
*/
private static String getNumberedName( String prefix, int count, Map m ) {
while(m.containsValue( prefix+Integer.toString(count) )) count++;
return prefix+Integer.toString(count);
}
/**
* computes a unique name that is used as a field name for
* the Datatype.
*
* @param dt
* Datatype object.
* @param m
* values of this map are the names of other ElementExp/AttributeExps.
* This method has to return the unique name.
*/
private static String computeName( Datatype dt, Map m ) {
if( dt instanceof XSDatatype ) {
XSDatatype xsdt = (XSDatatype)dt;
if( xsdt.getName()!=null && !m.containsValue(xsdt.getName()) )
return xsdt.getName();
return getNumberedName( xsdt.getConcreteType().getName(), 2, m );
}
return getNumberedName( "", 0, m );
}
private static String computeName( ClassItem cls, Map m ) {
String name = cls.getBareName();
if(!m.containsValue(name)) return name;
return getNumberedName( name, 2, m );
}
private static String computeName( PrimitiveItem pitm, Map m ) {
String name = pitm.type.getBareName();
if(!m.containsValue(name)) return name;
return getNumberedName( name, 2, m );
}
private static String computeName( FieldItem field, Map m ) {
if(!m.containsValue(field.name)) return field.name;
return getNumberedName( field.name, 2, m );
}
private static String computeName( IgnoreItem iim, Map m ) {
return getNumberedName( "", 1, m );
}
/**
* gets the source code representation of the specified string.
*/
private static String javaStringEscape( String s ) {
// throw new Error();
return "\""+s+"\"";
}
private static void assert( boolean b ) {
if(!b) throw new Error();
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
7efeff6b5c5052a3b9d1a82feee668ef8d014fe3
|
20b535a4f3d4f5ed3948368ca2b521f295346710
|
/src/main/java/com/springsource/roo/pizzashop/service/ToppingService.java
|
3c65615c8f1d81d118341daf0024eda5d81d51df
|
[] |
no_license
|
attilacsanyi/pizzashop-security
|
4dc82a7243e04f4f576f8a5b6e758522283fa0d9
|
6c400a050d76077b9551f4f4dcac18f567473b1f
|
refs/heads/master
| 2021-01-01T15:50:36.132067
| 2014-04-04T09:49:10
| 2014-04-04T09:49:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 233
|
java
|
package com.springsource.roo.pizzashop.service;
import org.springframework.roo.addon.layers.service.RooService;
@RooService(domainTypes = { com.springsource.roo.pizzashop.domain.Topping.class })
public interface ToppingService {
}
|
[
"v-acsanyi@expedia.com"
] |
v-acsanyi@expedia.com
|
2bfbfa3efab272217ac7ee42a18fdb6e0167d972
|
2e1e0c4c3fedb860de9a258e0d3c6e16c8df6139
|
/app/src/main/java/com/wy/djreader/utils/message/MessageManager.java
|
e73039937b35a7db2255c74608a2f585249c2858
|
[] |
no_license
|
Entropless/DJReader
|
d7d9f147cdef5aa92ccf3de6c2e82fc106293316
|
96549a94b0c458fc0268efd2d6399df542e5f767
|
refs/heads/master
| 2022-01-28T07:40:46.442361
| 2019-04-16T09:26:35
| 2019-04-16T09:26:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,439
|
java
|
package com.wy.djreader.utils.message;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
/**
* 使用建造者模式构建消息管理类
* @author wy
*/
public class MessageManager {
private Handler handler;
private int what;
private int arg1;
private int arg2;
private Object object;
private Bundle data;
public MessageManager() {
this(new MessageBuilder());
}
MessageManager(MessageBuilder builder){
this.handler = builder.handler;
this.what = builder.what;
this.arg1 = builder.arg1;
this.arg2 = builder.arg2;
this.object = builder.object;
this.data = builder.bundle;
}
public static class MessageBuilder{
Handler handler;
int what,arg1,arg2;
Object object;
Bundle bundle;
public MessageBuilder() {
}
MessageBuilder(MessageManager msg){
this.handler = msg.handler;
this.what = msg.what;
this.arg1 = msg.arg1;
this.arg2 = msg.arg2;
this.bundle = msg.data;
this.object = msg.object;
}
public MessageBuilder setHandler(Handler handler){
this.handler = handler;
return this;
}
public MessageBuilder setWhat(int what){
this.what = what;
return this;
}
public MessageBuilder setArg1(int Arg1){
this.arg1 = arg1;
return this;
}
public MessageBuilder setArg2(int Arg2){
this.arg2 = arg2;
return this;
}
public MessageBuilder setObject(Object object){
this.object = object;
return this;
}
public MessageBuilder setBundle(Bundle bundle){
this.bundle = bundle;
return this;
}
public MessageManager build(){
if (handler == null) throw new IllegalStateException("handler == null");
return new MessageManager(this);
}
}
public void sendMessage(){
if (null == handler) return;
Message msg = handler.obtainMessage();
msg.what = what;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (object != null){
msg.obj = object;
}
if (data != null) {
msg.setData(data);
}
handler.sendMessage(msg);
}
}
|
[
"18911971839@163.com"
] |
18911971839@163.com
|
b66ea2db08cca3aa59e3eb18fc70d97361013a30
|
aab4259e08981c075134196c4092bda0730e1e37
|
/app/src/main/java/com/vastinc/daggerquotesapp/di/ViewModelKey.java
|
80e595f842a9d97f957fba84e695d517b9efa0c9
|
[] |
no_license
|
olaitanade/dagger2-mvvm-quotesapp-java
|
03b56ce357ec23f9f4a2e331875ef6267487de0d
|
aa753582b79b1aaf9f643c5f963a54db54e7d7f5
|
refs/heads/master
| 2023-04-28T19:05:36.369553
| 2021-05-20T13:18:53
| 2021-05-20T13:18:53
| 364,160,243
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 465
|
java
|
package com.vastinc.daggerquotesapp.di;
import androidx.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
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
public @interface ViewModelKey {
Class<? extends ViewModel> value();
}
|
[
"olaitan.adetayo.com"
] |
olaitan.adetayo.com
|
edf408e5ebdda6cbd5b615da48a9b05e215e4dd3
|
ac953b474bb67722e8d890ea0f4d10c3dc9d1a6e
|
/backend/reserve-check-service/src/main/java/org/egovframe/cloud/reservechecksevice/domain/reserve/ReserveRepositoryCustom.java
|
787dff986ae56d589301d8c221ea1f749252cdb2
|
[] |
no_license
|
greenn-lab/egovframe-msa-edu
|
00fbeab4040040f6e1f955fa17fe5e199dec92a5
|
02e03dac79ebb3da42788430f25d196d8a7f83f7
|
refs/heads/main
| 2023-09-05T16:33:17.528244
| 2021-11-15T06:25:10
| 2021-11-15T06:25:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,737
|
java
|
package org.egovframe.cloud.reservechecksevice.domain.reserve;
import org.egovframe.cloud.common.dto.RequestDto;
import org.egovframe.cloud.reservechecksevice.api.reserve.dto.ReserveRequestDto;
import org.springframework.data.domain.Pageable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
/**
* org.egovframe.cloud.reservechecksevice.domain.reserve.ReserveRepositoryCustom
*
* 예약 도메인 custom Repository interface
*
* @author 표준프레임워크센터 shinmj
* @version 1.0
* @since 2021/09/15
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ---------- -------- ---------------------------
* 2021/09/15 shinmj 최초 생성
* </pre>
*/
public interface ReserveRepositoryCustom {
Flux<Reserve> search(ReserveRequestDto requestDto, Pageable pageable);
Mono<Long> searchCount(ReserveRequestDto requestDto, Pageable pageable);
Mono<Reserve> findReserveById(String reserveId);
Flux<Reserve> searchForUser(ReserveRequestDto requestDto, Pageable pageable, String userId);
Mono<Long> searchCountForUser(ReserveRequestDto requestDto, Pageable pageable, String userId);
Mono<Reserve> loadRelations(Reserve reserve);
Flux<Reserve> findAllByReserveDate(Long reserveItemId, LocalDateTime startDate, LocalDateTime endDate);
Flux<Reserve> findAllByReserveDateWithoutSelf(String reserveId, Long reserveItemId, LocalDateTime startDate, LocalDateTime endDate);
Mono<Long> findAllByReserveDateWithoutSelfCount(String reserveId, Long reserveItemId, LocalDateTime startDate, LocalDateTime endDate);
Mono<Reserve> insert(Reserve reserve);
}
|
[
"give928@gmail.com"
] |
give928@gmail.com
|
e8d06d82f80ce6f8909d6c95def16542406395c4
|
288384bf30fa240c2e1acce356e6a6fb4bba851e
|
/src/main/java/com/fairmusic/artist/controller/CompareKKServlet.java
|
02dc7ce3c2deb2281cd22d21e1b03138a6104267
|
[] |
no_license
|
wooheet/musicinblockchain
|
6cd9644dfb3e91178998a4a6d778edf08cb2da72
|
10b3d8b3f0152b8e2ee0fcae24f518252473dc48
|
refs/heads/master
| 2021-01-01T17:53:38.221144
| 2017-08-31T14:53:42
| 2017-08-31T14:53:42
| 98,190,870
| 0
| 0
| null | null | null | null |
UHC
|
Java
| false
| false
| 1,710
|
java
|
package com.fairmusic.artist.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fairmusic.artist.service.ArtistServiceimpl;
import com.fairmusic.dto.artistDTO;
@WebServlet(name = "compare_kk", urlPatterns = { "/compare_kk.do" })
public class CompareKKServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("카톡 compare 서블릿 실행~");
response.setContentType("text/html;charset=euc-kr");
response.setHeader("cache-control", "no-cache, no-store");
PrintWriter pw = response.getWriter();
String code = request.getParameter("code");
String name = request.getParameter("name");
String state = request.getParameter("state");
System.out.println("비교 서블릿 코드"+code);
System.out.println("name : " +name);
System.out.println("state : "+state);
ArtistServiceimpl service = new ArtistServiceimpl();
boolean compare = service.emailCheck(code);
artistDTO dto = new artistDTO(code, "", "", name, null, null, "1");
String rdpath = null;
if (compare == true) {
rdpath = "login-no-sidebar.jsp";
} else {
int result = service.regist(dto);
System.out.println(result+"명 삽입성공 ("+code+","+name+")");
rdpath = "login-no-sidebar.jsp";
}
RequestDispatcher rd = request
.getRequestDispatcher(rdpath);
rd.forward(request, response);
}
}
|
[
"godjs@DESKTOP-A52GUHO"
] |
godjs@DESKTOP-A52GUHO
|
cfe603f05c6c49c5e71238d2095fddaebeadd3cd
|
8f9f557728dbfc0a2d66d8d93f3c296bbaafcc1c
|
/app/src/main/java/com/why/newsbeat/ui/history/HistoryItemViewHolder.java
|
24133e62d7e97f202d18c3755f0fb987051c38c4
|
[] |
no_license
|
hongyunwu/NewsBeat
|
5f25701d07c7f4922e70e8d8d729420b1bf3b6f1
|
5932225e3350241190825dbc856f92c24fb7debf
|
refs/heads/master
| 2021-01-22T00:52:20.054342
| 2019-10-10T03:21:52
| 2019-10-10T03:21:52
| 102,196,075
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 961
|
java
|
package com.why.newsbeat.ui.history;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.why.base.ui.BaseHolder;
import com.why.newsbeat.R;
import butterknife.BindView;
/**
* Created by lenovo on 2017/9/3.
*/
public class HistoryItemViewHolder extends BaseHolder {
@BindView(R.id.item_top_news)
LinearLayout item_top_news;
@BindView(R.id.title)
TextView title;
@BindView(R.id.comments)
TextView comments;
@BindView(R.id.author)
TextView author;
@BindView(R.id.thumb_01)
ImageView thumb_01;
@BindView(R.id.delete)
ImageView delete;
ImageView thumb_02;
ImageView thumb_03;
/**
* 此处使用butterKnife进行了view绑定操作
*
* @param itemView
*/
public HistoryItemViewHolder(View itemView) {
super(itemView);
thumb_02 = (ImageView) itemView.findViewById(R.id.thumb_02);
thumb_03 = (ImageView) itemView.findViewById(R.id.thumb_03);
}
}
|
[
"android_wuhongyun@163.com"
] |
android_wuhongyun@163.com
|
6d0ddbf909c476d4e1be0c669287b6f865802179
|
65fed23fcd256e725480a0977d0c6aabac4a3809
|
/src/com/ds/azim/m_sort.java
|
21416d8efec84191a77d50215dae21b2c61fcc79
|
[] |
no_license
|
azimshaik/dspract
|
58df0d1e7fe6827da3d759d87cd57e8549f0aab7
|
6a89be96357f901cbd7c2d95071149c0b2803c81
|
refs/heads/master
| 2021-01-13T03:13:20.109566
| 2016-12-30T16:23:21
| 2016-12-30T16:23:21
| 77,626,269
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,074
|
java
|
package com.ds.azim;
public class m_sort {
public static void merg_helper(int[] a){
merge_sort(a,0,a.length-1);
}
public static void merge_sort(int[] a, int low, int high){
if(low>=high){
return;
}else{
int mid = low/2 + high/2;
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
public static void merge(int[] a, int low, int mid, int high){
int[] temp = new int[high-low+1];
int left = low;
int right = mid+1;
int k = 0; //index for the temp array
while(left<=mid && right<=high){
if(a[left]<a[right]){
temp[k] = a[left];
left++;
}else{
temp[k] = a[right];
right++;
}
k++;
}
if(left<=mid){
while(left<=mid){
temp[k] = a[left];
left++;
k++;
}
}else{
while(right<=high){
temp[k] = a[right];
right++;
k++;
}
}
for(int i=0 ;i<temp.length;i++){
a[low+i] = temp[i];
}
}
public static void main(String[] args){
int[] a = {23,4,76,-7,-4};
merg_helper(a);
for(int m=0 ; m<a.length; m++){
System.out.print(a[m]+",");
}
}
}
|
[
"cheer.buddu@gmail.com"
] |
cheer.buddu@gmail.com
|
26a4a0bf519c27860935013c5a33495b08b87289
|
8d1a35b094b45a3f97bdcea57d92e87b7b0bad2c
|
/java_test/src/DesignPattern/Command/SimpleRemote/RemoteControlTest.java
|
5fb2a19ab84618f8869c8a0e84e3e5520ab12a5e
|
[] |
no_license
|
gzltommy/design-paterns
|
141e36717f01f72a8d10944a753690e7dd0bf201
|
8c3f446c1680e1c3ffaa18c9b0d30cd2400cac17
|
refs/heads/master
| 2021-09-18T06:55:00.687690
| 2018-07-11T07:30:08
| 2018-07-11T07:30:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 847
|
java
|
package DesignPattern.Command.SimpleRemote;
/**
* Created by Administrator on 2018/4/13.
*/
public class RemoteControlTest {
public static void main(String[] args) {
//构建打开灯命令
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
//构建车库门打开命令
GarageDoor garageDoor = new GarageDoor();
GarageDoorOpenCommand garageDoorOpen = new GarageDoorOpenCommand(garageDoor);
/*-----------------------------------------------------------------------*/
//简单遥控
SimpleRemoteControl remote = new SimpleRemoteControl();
//开灯
remote.setCommand(lightOn);
remote.buttonWasPressed();
//开车库门
remote.setCommand(garageDoorOpen);
remote.buttonWasPressed();
}
}
|
[
"1046292959@qq.com"
] |
1046292959@qq.com
|
149797258626d2ab2475e5c7fd310fd1a4ab3a9f
|
8ab737c98dda9e4480366bd4d6f32ccade26ff20
|
/src/jp/co/nskint/uq/pd/signage/model/xml/DirectionType.java
|
0094567693d0c14f10187e182cdd027f29be24eb
|
[] |
no_license
|
munehiro-takahashi/uq-signage
|
5eda72bace1d3702432a2468b6df1895bcfbe199
|
84dcf281718a21fc8aab89396bd10b1f77c7f72e
|
refs/heads/master
| 2021-01-22T06:44:33.062679
| 2012-09-01T17:33:08
| 2012-09-01T17:33:08
| 35,258,883
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,721
|
java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// 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: 2012.02.09 at 07:06:54 �ߌ� JST
//
package jp.co.nskint.uq.pd.signage.model.xml;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for DirectionType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="DirectionType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="up"/>
* <enumeration value="down"/>
* <enumeration value="left"/>
* <enumeration value="right"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "DirectionType")
@XmlEnum
public enum DirectionType {
@XmlEnumValue("up")
UP("up"),
@XmlEnumValue("down")
DOWN("down"),
@XmlEnumValue("left")
LEFT("left"),
@XmlEnumValue("right")
RIGHT("right");
private final String value;
DirectionType(String v) {
value = v;
}
public String value() {
return value;
}
public static DirectionType fromValue(String v) {
for (DirectionType c: DirectionType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
[
"drmashu@gmail.com@54564b0a-3131-6a6e-b261-5d0d787781db"
] |
drmashu@gmail.com@54564b0a-3131-6a6e-b261-5d0d787781db
|
d0801ec933f3bf8028b39770d921a59cf8e24d6a
|
0d4edfbd462ed72da9d1e2ac4bfef63d40db2990
|
/app/src/main/java/com/dvc/mybilibili/mvp/presenter/activity/LoginPresenter.java
|
12ca248b98f837a87c1821bbf7b900527a431c13
|
[] |
no_license
|
dvc890/MyBilibili
|
1fc7e0a0d5917fb12a7efed8aebfd9030db7ff9f
|
0483e90e6fbf42905b8aff4cbccbaeb95c733712
|
refs/heads/master
| 2020-05-24T22:49:02.383357
| 2019-11-23T01:14:14
| 2019-11-23T01:14:14
| 187,502,297
| 31
| 3
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,238
|
java
|
package com.dvc.mybilibili.mvp.presenter.activity;
import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import com.dvc.base.di.ApplicationContext;
import com.dvc.base.utils.RxSchedulersHelper;
import com.dvc.mybilibili.app.retrofit2.callback.ObserverCallback;
import com.dvc.mybilibili.mvp.model.DataManager;
import com.dvc.mybilibili.mvp.model.api.exception.BiliApiException;
import com.dvc.mybilibili.mvp.model.api.service.account.entity.LoginInfo;
import com.dvc.mybilibili.mvp.presenter.MyMvpBasePresenter;
import com.dvc.mybilibili.mvp.ui.activity.LoginView;
import com.trello.rxlifecycle2.LifecycleProvider;
import javax.inject.Inject;
public class LoginPresenter extends MyMvpBasePresenter<LoginView> {
@Inject
public LoginPresenter(@ApplicationContext Context context, DataManager dataManager, LifecycleProvider<Lifecycle.Event> provider) {
super(context, dataManager, provider);
}
public LifecycleProvider<Lifecycle.Event> getProvider() {
return this.provider;
}
public void login(String name, String password) {
this.dataManager.getApiHelper().getKey(false)
.compose(RxSchedulersHelper.AllioThread())
.subscribe(authKey -> {
this.dataManager.getApiHelper().loginV3(name,authKey.encryptPassword(password))
.compose(RxSchedulersHelper.ioAndMainThread())
.compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY))
.subscribe(new ObserverCallback<LoginInfo>() {
@Override
public void onSuccess(LoginInfo loginInfo) {
dataManager.getUser().loadToLoginInfo(loginInfo);
ifViewAttached(view -> view.loginCompleted(loginInfo));
}
@Override
public void onError(BiliApiException apiException, int code) {
ifViewAttached(view -> view.loginFailed(apiException));
}
});
});
}
}
|
[
"dvc890@139.com"
] |
dvc890@139.com
|
48f11926fa29996d5aaa210d2cd54d635b5502cc
|
7eb04af401c447b8374aab386648af3ebabe87ef
|
/trustful-web-service/src/main/java/com/marksample/trustfulwebservice/SpringSecurityConfigBasic.java
|
017f3a05d2f7e4946404211fe3a1f183ebc196c1
|
[] |
no_license
|
markbdsouza/SpringBoot-Angular-ToDo-Application
|
d2a755e258e3cdde04e44fb87b6680d223f72296
|
11382d971682038cee0a6c8e86750e3ae71a6e63
|
refs/heads/master
| 2020-12-14T13:25:55.062093
| 2020-01-18T16:09:44
| 2020-01-18T16:09:44
| 234,758,254
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 904
|
java
|
package com.marksample.trustfulwebservice;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfigBasic extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated().and()//.formLogin().and())
.httpBasic();
http.headers().frameOptions().disable();
}
}
|
[
"mark.benjamin.dsouza@gmail.com"
] |
mark.benjamin.dsouza@gmail.com
|
31fc272d98c035caf428f0c59205a92468b3d315
|
9e748e5af99ad462949f5a125155d2cbf5c319a6
|
/src/main/java/denominator/discoverydns/DiscoveryDNSTarget.java
|
b6b274a27bd40c8b2cd2521f74a183572cdde6d4
|
[] |
no_license
|
discoverydns/denominator-discoverydns
|
de33d67ae59f18b30d6e5cf8d25a1408838272ef
|
128d8518970603d47fe0cd813fb4c1a893b05daf
|
refs/heads/master
| 2020-05-30T03:58:32.551378
| 2015-08-14T02:00:06
| 2015-08-14T02:00:06
| 32,360,777
| 3
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 854
|
java
|
package denominator.discoverydns;
import javax.inject.Inject;
import denominator.Denominator.Version;
import denominator.Provider;
import feign.Request;
import feign.RequestTemplate;
import feign.Target;
final class DiscoveryDNSTarget implements Target<DiscoveryDNS> {
private static final String CLIENT_ID = "Denominator " + Version.INSTANCE;
private final Provider provider;
@Inject
DiscoveryDNSTarget(Provider provider) {
this.provider = provider;
}
@Override
public Class<DiscoveryDNS> type() {
return DiscoveryDNS.class;
}
@Override
public String name() {
return provider.name();
}
@Override
public String url() {
return provider.url();
}
@Override
public Request apply(RequestTemplate in) {
in.insert(0, url());
in.header("X-Requested-By", CLIENT_ID);
return in.request();
}
}
|
[
"arnaud.dumont@ausregistry.com.au"
] |
arnaud.dumont@ausregistry.com.au
|
bdabfcf35ba10a8c8385021c4fe6bbbc5ce25c52
|
a5c2f06bd10237c9b43098453967012f3836acd9
|
/src/main/java/tries/ValidWordsFromDictionary.java
|
ce9336c7b7148f319b3eb151e6a92cb11962602d
|
[] |
no_license
|
swapnilbagadia/practice
|
bd33a158fe6267a96692ca267a83fc1981cf47a4
|
63b7999905081ae5202979eafde5d35224929612
|
refs/heads/master
| 2020-04-12T22:38:36.898976
| 2019-01-07T04:50:53
| 2019-01-07T04:50:53
| 162,793,912
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,257
|
java
|
package main.java.tries;
public class ValidWordsFromDictionary {
static final int SIZE = 26;
static class TrieNode{
boolean leaf;
TrieNode[] Child = new TrieNode[SIZE];
// Constructor
public TrieNode() {
leaf = false;
for (int i =0 ; i< SIZE ; i++)
Child[i] = null;
}
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
static void insert(TrieNode root, String Key)
{
int n = Key.length();
TrieNode pChild = root;
for (int i=0; i<n; i++)
{
int index = Key.charAt(i) - 'a';
if (pChild.Child[index] == null)
pChild.Child[index] = new TrieNode();
pChild = pChild.Child[index];
}
// make last node as leaf node
pChild.leaf = true;
}
// A recursive function to print all possible valid
// words present in array
static void searchWord(TrieNode root, boolean Hash[],
String str)
{
// if we found word in trie / dictionary
if (root.leaf == true)
System.out.println(str);
// traverse all child's of current root
for (int K =0; K < SIZE; K++)
{
if (Hash[K] == true && root.Child[K] != null )
{
// add current character
char c = (char) (K + 'a');
// Recursively search reaming character
// of word in trie
searchWord(root.Child[K], Hash, str + c);
}
}
}
// Prints all words present in dictionary.
static void printAllWords(char Arr[], TrieNode root,
int n)
{
// create a 'has' array that will store all
// present character in Arr[]
boolean[] Hash = new boolean[SIZE];
for (int i = 0 ; i < n; i++)
Hash[Arr[i] - 'a'] = true;
// tempary node
TrieNode pChild = root ;
// string to hold output words
String str = "";
// Traverse all matrix elements. There are only
// 26 character possible in char array
for (int i = 0 ; i < SIZE ; i++)
{
// we start searching for word in dictionary
// if we found a character which is child
// of Trie root
if (Hash[i] == true && pChild.Child[i] != null )
{
str = str+(char)(i + 'a');
searchWord(pChild.Child[i], Hash, str);
str = "";
}
}
}
//Driver program to test above function
public static void main(String args[])
{
// Let the given dictionary be following
String Dict[] = {"go", "bat", "me", "eat",
"goal", "boy", "run"} ;
// Root Node of Trie
TrieNode root = new TrieNode();
// insert all words of dictionary into trie
int n = Dict.length;
for (int i=0; i<n; i++)
insert(root, Dict[i]);
char arr[] = {'e', 'o', 'b', 'a', 'm', 'g', 'l', 't'} ;
int N = arr.length;
printAllWords(arr, root, N);
}
}
|
[
"swapnilbagadia@live.com"
] |
swapnilbagadia@live.com
|
a95ce53d91d1e7c24883e75b795df5b32eebf0d7
|
a0964e2c3e6a21c57db3d88d6b76eba9415a19b3
|
/common/src/main/java/com/keemono/common/utils/dozer/DozerI.java
|
0568aea8f33c7f6b068fc3b0efc53a80a55e2446
|
[] |
no_license
|
duardito/keemono
|
70f719b46903413d7349df0e32de8fb2f065af11
|
4a9324ae805f8186780210283760080f4b3ca3cd
|
refs/heads/master
| 2020-04-06T07:07:02.120617
| 2015-03-12T17:19:53
| 2015-03-12T17:19:53
| 28,585,066
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 339
|
java
|
package com.keemono.common.utils.dozer;
import org.dozer.Mapper;
import java.util.List;
/**
* Created by edu on 19/01/2015.
*/
public interface DozerI<T> {
public <M> M map (final Object sourceObject, final Class<M> destType);
public <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType);
}
|
[
"eduard.frades@gmail.com"
] |
eduard.frades@gmail.com
|
0636190cf7721c18ff390f9150ee0fe4132cbf9b
|
5a73698dad1d41e12c7b775fde6bfa2f7dad943a
|
/jhotdraw/src/main/java/org/jhotdraw/app/MenuBuilder.java
|
4f20cb9950aa687a8dd33daca3a7b44062095086
|
[] |
no_license
|
harkomal-chana/tools
|
f8ed1c738708eb6040a12695895cb7b3bfbbb761
|
f7c53d1864fca555f0178e3061678602e26c3a48
|
refs/heads/master
| 2020-04-19T15:49:27.416108
| 2016-09-22T03:28:45
| 2016-09-22T03:28:45
| 66,535,135
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 13,662
|
java
|
/*
* @(#)MenuBuilder.java
*
* Copyright (c) 2010 The authors and contributors of JHotDraw.
*
* You may not use, copy or modify this file, except in compliance with the
* accompanying license terms.
*/
package org.jhotdraw.app;
import javax.annotation.Nullable;
import java.util.List;
import javax.swing.JMenu;
/**
* {@code MenuBuilder} is used by {@link Application} to build to build its menu
* bar(s) and popup menu(s).
* <p>
* Each method adds a logical group of menu items to a menu provided by the
* {@code Application}.
* <p>
* Implementors of this interface typically use actions retrieved from the
* application to build the menu items. See {@link DefaultMenuBuilder} for a
* typical implementation.
* <p>
* Menus may be associated to a specific view or to all views (global) of the
* application. In the former case the corresponding view is provided, in the
* latter case null is passed. Note that some applications, specifically
* {@link OSXApplication}, need to create both kinds of menus.
* <p>
* During the lifetime of an application many menus may be created and destroyed.
* Implementors must ensure that menu items can be garbage collected.
*
* <hr>
* <b>Design Patterns</b>
*
* <p><em>Abstract Factory</em><br>
* {@code MenuBuilder} is used by {@code Application} for creating menu items.
* The {@code MenuBuilder} is provided by {@code ApplicationModel}.
* Abstract Factory: {@link MenuBuilder}<br>
* Client: {@link Application}.
* <hr>
*
* @author Werner Randelshofer
* @version $Id: MenuBuilder.java 791 2015-02-08 20:32:02Z rawcoder $
*/
public interface MenuBuilder {
/** Optionally adds one or more "Preferences" items to a menu.
* <p>
* Most applications use this method for adding items to the last section
* of the "Edit" menu.
* <p>
* Note that {@link OSXApplication} does <b>not</b> invoke this method and
* instead retrieves an action with ID {@code AbstractPreferencesAction.ID}
* from the action map of the {@code ApplicationModel} and adds it to the
* "Application" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addPreferencesItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Exit" items to a menu.
* <p>
* Most applications use this method for adding items to the last section
* of the "File" menu.
* <p>
* Note that {@link OSXApplication} does <b>not</b> invoke this method and
* instead retrieves an action with ID {@code ExitAction.ID}
* from the action map of the {@code ApplicationModel} and adds it to the
* "Application" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addExitItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Clear File" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addClearFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "New Window" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addNewWindowItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "New File" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addNewFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Load file" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addLoadFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Open File" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOpenFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Close File" items to a menu.
* <p>
* Most applications use this method for adding items to the second section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addCloseFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Save File" items to a menu.
* <p>
* Most applications use this method for adding items to the second section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addSaveFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Export File" items to a menu.
* <p>
* Most applications use this method for adding items to the second section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addExportFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Print File" items to a menu.
* <p>
* Most applications use this method for adding items to the third section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addPrintFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more file related items to a menu.
* <p>
* Most applications use this method for adding items to the third section
* of the "File" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOtherFileItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Undo" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "Edit" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addUndoItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Clipboard" items to a menu.
* <p>
* Most applications use this method for adding items to the second section
* of the "Edit" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addClipboardItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Selection" items to a menu.
* <p>
* Most applications use this method for adding items to the third section
* of the "Edit" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addSelectionItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Find" items to a menu.
* <p>
* Most applications use this method for adding items to the fourth section
* of the "Edit" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addFindItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more editing related items to a menu.
* <p>
* Most applications use this method for adding items to the fifth section
* of the "Edit" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOtherEditItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more view related items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "View" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOtherViewItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more additional menus to a menu bar or a pop up
* menu.
* <p>
* Most applications add additional menus between the "View" menu and the
* "Window" menu to the menu bar.
*
* @param m A (potentially non-empty) list of menus.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOtherMenus(List<JMenu> m, Application app, @Nullable View v);
/** Optionally adds one or more window related items to a menu.
* <p>
* Most applications use this method for adding items to the second section
* of the "Window" menu. (The first section usually contains application
* specific items). Some applications, such as {@link SDIApplication} add
* these items to the "View" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addOtherWindowItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "Help" items to a menu.
* <p>
* Most applications use this method for adding items to the first section
* of the "Help" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addHelpItems(JMenu m, Application app, @Nullable View v);
/** Optionally adds one or more "About" items to a menu.
* <p>
* Most applications use this method for adding items to the last section
* of the "Help" menu.
* <p>
* Note that {@link OSXApplication} does <b>not</b> invoke this method and
* instead retrieves an action with ID {@code AboutAction.ID}
* from the action map of the {@code ApplicationModel} and adds it to the
* "Application" menu.
*
* @param m A (potentially non-empty) menu.
* @param app The Application for which the menu is built.
* @param v A view the menu is used exclusively for a specific view, null
* if the menu is shared by all views.
*/
void addAboutItems(JMenu m, Application app, @Nullable View v);
}
|
[
"harkomal.chana@gmail.com"
] |
harkomal.chana@gmail.com
|
ddfcaa635b1571517e065a13cc9c0ca800d7fa07
|
5291a176fd6fbed1791308af8e0dcbd1d802b7e1
|
/Board.java
|
c4a19491faa3ae869f87d7ecb0f8c30ff12892af
|
[] |
no_license
|
OliveIsLazy/Amazons2018
|
992450aa1f2d1e215a7536bf72b74bd369a6cf5a
|
daf84282465c6e9327864c7d61a5c240d857ee80
|
refs/heads/master
| 2020-04-13T14:53:33.649133
| 2018-12-24T12:03:00
| 2018-12-24T12:03:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,632
|
java
|
import java.awt.Color;
import javafx.scene.layout.Border;
public class Board {
public GameTile[][] tiles;
public int size;
public boolean enabled = true;
private Game parentGame;
/*
* input: number of columns, number of rows Builds a args[2] x args[3] size
* chess board using GameTiles return: void
*/
Board(Integer width, Integer height, Game game) {
parentGame = game;
size = width.intValue();
this.tiles = new GameTile[width.intValue()][height.intValue()];
for (int ii = 0; ii < this.tiles.length; ii++) {
for (int jj = 0; jj < this.tiles[ii].length; jj++) {
if ((jj % 2 == 1 && ii % 2 == 1) || (jj % 2 == 0 && ii % 2 == 0))
this.tiles[jj][ii] = new GameTile(Color.WHITE, jj, ii, game);
else
this.tiles[jj][ii] = new GameTile(Color.BLACK, jj, ii, game);
}
}
}
public String encode() {
String board = "";
for (GameTile[] row : tiles) {
for (GameTile tile : row) {
if (tile.wasShot)
board += "a";
else if (tile.hasPiece)
board += (tile.piece.color == Color.black) ? "b" : "w";
else
board += "e";
}
}
return board;
}
public boolean decode(String board) {
try {
assert (board.length() == tiles.length * tiles[0].length);
int index, black_index, white_index;
index = black_index = white_index = 0;
GameTile[][] newTiles = tiles.clone();
for (GameTile[] row : newTiles) {
for (GameTile tile : row) {
switch (board.charAt(index)) {
case 'a':
tile.shoot();
break;
case 'b':
tile.setPiece(this.parentGame.getPlayer("Black").pawns.get(black_index));
black_index++;
break;
case 'w':
tile.setPiece(this.parentGame.getPlayer("White").pawns.get(white_index));
white_index++;
break;
case 'e':
tile.empty();
}
index++;
}
}
assert (black_index == 4 && white_index == 4);
tiles = newTiles;
this.parentGame.findAllPaths();
return true;
} catch (AssertionError e) {
return false;
}
}
/*
* input: void Resets board to not show any paths return: void
*/
public void clear() {
for (GameTile[] row : tiles)
for (GameTile tile : row)
tile.setToDefaultColor();
}
public void empty() {
for (GameTile[] row : tiles)
for (GameTile tile : row)
tile.empty();
}
public void assertEmptiness() {
for (GameTile[] row : tiles)
for (GameTile tile : row)
assert (tile.hasPiece == false);
}
public void disable() {
// disable the whole board
enabled = false;
for (GameTile[] row : tiles)
for (GameTile tile : row)
tile.setEnabled(false);
}
public void enable() {
enabled = true;
// disable the whole board
for (GameTile[] row : tiles)
for (GameTile tile : row)
tile.setEnabled(true);
}
}
|
[
"ramses.kamanda@gmail.com"
] |
ramses.kamanda@gmail.com
|
1d79139fd0c49ee453d8458094dffd7fde6154fc
|
e3f01452b33f785f136e55e56b0f03b1545979ee
|
/aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/VirtualGatewayTlsValidationContextMarshaller.java
|
80ac6be34728df467ef01067b5fa649db52a79c3
|
[
"Apache-2.0"
] |
permissive
|
kundan59/aws-sdk-java
|
4f7ba8f6b8fcad155e25e5b11f9c9a28ec99d6ac
|
00f289a50d8c910830f172599d6d0c6b034f6221
|
refs/heads/master
| 2023-02-26T13:01:37.888044
| 2021-01-29T21:48:34
| 2021-01-29T21:48:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,123
|
java
|
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.appmesh.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.appmesh.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* VirtualGatewayTlsValidationContextMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class VirtualGatewayTlsValidationContextMarshaller {
private static final MarshallingInfo<StructuredPojo> TRUST_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("trust").build();
private static final VirtualGatewayTlsValidationContextMarshaller instance = new VirtualGatewayTlsValidationContextMarshaller();
public static VirtualGatewayTlsValidationContextMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(VirtualGatewayTlsValidationContext virtualGatewayTlsValidationContext, ProtocolMarshaller protocolMarshaller) {
if (virtualGatewayTlsValidationContext == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(virtualGatewayTlsValidationContext.getTrust(), TRUST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
[
""
] | |
e04128c05ec3a772fc164135b43aeb556596e33f
|
f4bfa81d63a6cd596854be74dcce9d4f63f8390f
|
/src/main/java/com/watership/repository/CategoryRepository.java
|
786976bc6d65c983c32d6aa2b869f44fda67cbbe
|
[] |
no_license
|
magnusfiorepalm/watership
|
962faa972b1773f749d153c529e3bd71a56798d0
|
aed16fa9731c36304315bfc62dd06e2eb4670b64
|
refs/heads/master
| 2020-12-28T21:51:23.464132
| 2016-09-08T02:38:12
| 2016-09-08T02:38:12
| 46,250,715
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 237
|
java
|
package com.watership.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.watership.model.Category;
public interface CategoryRepository extends PagingAndSortingRepository<Category, Long> {
}
|
[
"magnus.palm@procore.com"
] |
magnus.palm@procore.com
|
23b331552021ebb50e074fb52746451c00bd1833
|
83ba1ffe094176c7c6036a9ea47751b031941fc4
|
/runners/google-cloud-dataflow-java/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java
|
764c0cba7f8a57b72e13c5ffb550c096cbca9dfa
|
[
"Apache-2.0"
] |
permissive
|
Sil1991/gcpdf-demo
|
b7b57f476bb5bce5e80e4c160512a52937036241
|
88ecd538a30f009b239a1b320ab6ad75f6901ae0
|
refs/heads/master
| 2022-11-24T23:36:03.156413
| 2018-04-10T15:29:49
| 2018-04-10T15:29:49
| 128,814,619
| 1
| 0
|
Apache-2.0
| 2022-11-16T08:29:25
| 2018-04-09T18:13:21
|
Java
|
UTF-8
|
Java
| false
| false
| 25,421
|
java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dataflow.sdk.runners;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.services.dataflow.Dataflow;
import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Get;
import com.google.api.services.dataflow.Dataflow.Projects.Jobs.GetMetrics;
import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Messages;
import com.google.api.services.dataflow.model.Job;
import com.google.api.services.dataflow.model.JobMetrics;
import com.google.api.services.dataflow.model.MetricStructuredName;
import com.google.api.services.dataflow.model.MetricUpdate;
import com.google.cloud.dataflow.sdk.PipelineResult.State;
import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms;
import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper;
import com.google.cloud.dataflow.sdk.transforms.Aggregator;
import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform;
import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.Sum;
import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff;
import com.google.cloud.dataflow.sdk.util.MonitoringUtil;
import com.google.cloud.dataflow.sdk.values.PInput;
import com.google.cloud.dataflow.sdk.values.POutput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
/**
* Tests for DataflowPipelineJob.
*/
@RunWith(JUnit4.class)
public class DataflowPipelineJobTest {
private static final String PROJECT_ID = "someProject";
private static final String JOB_ID = "1234";
@Mock
private Dataflow mockWorkflowClient;
@Mock
private Dataflow.Projects mockProjects;
@Mock
private Dataflow.Projects.Jobs mockJobs;
@Rule
public FastNanoClockAndSleeper fastClock = new FastNanoClockAndSleeper();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(mockWorkflowClient.projects()).thenReturn(mockProjects);
when(mockProjects.jobs()).thenReturn(mockJobs);
}
/**
* Validates that a given time is valid for the total time slept by a
* AttemptBoundedExponentialBackOff given the number of retries and
* an initial polling interval.
*
* @param pollingIntervalMillis The initial polling interval given.
* @param attempts The number of attempts made
* @param timeSleptMillis The amount of time slept by the clock. This is checked
* against the valid interval.
*/
void checkValidInterval(long pollingIntervalMillis, int attempts, long timeSleptMillis) {
long highSum = 0;
long lowSum = 0;
for (int i = 1; i < attempts; i++) {
double currentInterval =
pollingIntervalMillis
* Math.pow(AttemptBoundedExponentialBackOff.DEFAULT_MULTIPLIER, i - 1);
double offset =
AttemptBoundedExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR * currentInterval;
highSum += Math.round(currentInterval + offset);
lowSum += Math.round(currentInterval - offset);
}
assertThat(timeSleptMillis, allOf(greaterThanOrEqualTo(lowSum), lessThanOrEqualTo(highSum)));
}
@Test
public void testWaitToFinishMessagesFail() throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
Job statusResponse = new Job();
statusResponse.setCurrentState("JOB_STATE_" + State.DONE.name());
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenReturn(statusResponse);
MonitoringUtil.JobMessagesHandler jobHandler = mock(MonitoringUtil.JobMessagesHandler.class);
Dataflow.Projects.Jobs.Messages mockMessages =
mock(Dataflow.Projects.Jobs.Messages.class);
Messages.List listRequest = mock(Dataflow.Projects.Jobs.Messages.List.class);
when(mockJobs.messages()).thenReturn(mockMessages);
when(mockMessages.list(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(listRequest);
when(listRequest.execute()).thenThrow(SocketTimeoutException.class);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
State state = job.waitToFinish(5, TimeUnit.MINUTES, jobHandler, fastClock, fastClock);
assertEquals(null, state);
}
public State mockWaitToFinishInState(State state) throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
Job statusResponse = new Job();
statusResponse.setCurrentState("JOB_STATE_" + state.name());
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenReturn(statusResponse);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
return job.waitToFinish(1, TimeUnit.MINUTES, null, fastClock, fastClock);
}
/**
* Tests that the {@link DataflowPipelineJob} understands that the {@link State#DONE DONE}
* state is terminal.
*/
@Test
public void testWaitToFinishDone() throws Exception {
assertEquals(State.DONE, mockWaitToFinishInState(State.DONE));
}
/**
* Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED}
* state is terminal.
*/
@Test
public void testWaitToFinishFailed() throws Exception {
assertEquals(State.FAILED, mockWaitToFinishInState(State.FAILED));
}
/**
* Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED}
* state is terminal.
*/
@Test
public void testWaitToFinishCancelled() throws Exception {
assertEquals(State.CANCELLED, mockWaitToFinishInState(State.CANCELLED));
}
/**
* Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED}
* state is terminal.
*/
@Test
public void testWaitToFinishUpdated() throws Exception {
assertEquals(State.UPDATED, mockWaitToFinishInState(State.UPDATED));
}
@Test
public void testWaitToFinishFail() throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenThrow(IOException.class);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
long startTime = fastClock.nanoTime();
State state = job.waitToFinish(5, TimeUnit.MINUTES, null, fastClock, fastClock);
assertEquals(null, state);
long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime);
checkValidInterval(DataflowPipelineJob.MESSAGES_POLLING_INTERVAL,
DataflowPipelineJob.MESSAGES_POLLING_ATTEMPTS, timeDiff);
}
@Test
public void testWaitToFinishTimeFail() throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenThrow(IOException.class);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
long startTime = fastClock.nanoTime();
State state = job.waitToFinish(4, TimeUnit.MILLISECONDS, null, fastClock, fastClock);
assertEquals(null, state);
long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime);
// Should only sleep for the 4 ms remaining.
assertEquals(timeDiff, 4L);
}
@Test
public void testGetStateReturnsServiceState() throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
Job statusResponse = new Job();
statusResponse.setCurrentState("JOB_STATE_" + State.RUNNING.name());
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenReturn(statusResponse);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
assertEquals(
State.RUNNING,
job.getStateWithRetries(DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, fastClock));
}
@Test
public void testGetStateWithExceptionReturnsUnknown() throws Exception {
Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class);
when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest);
when(statusRequest.execute()).thenThrow(IOException.class);
DataflowAggregatorTransforms dataflowAggregatorTransforms =
mock(DataflowAggregatorTransforms.class);
DataflowPipelineJob job = new DataflowPipelineJob(
PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms);
long startTime = fastClock.nanoTime();
assertEquals(
State.UNKNOWN,
job.getStateWithRetries(DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, fastClock));
long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime);
checkValidInterval(DataflowPipelineJob.STATUS_POLLING_INTERVAL,
DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, timeDiff);
}
@Test
public void testGetAggregatorValuesWithNoMetricUpdatesReturnsEmptyValue()
throws IOException, AggregatorRetrievalException {
Aggregator<?, ?> aggregator = mock(Aggregator.class);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(aggregator, pTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(appliedTransform, stepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
JobMetrics jobMetrics = new JobMetrics();
when(getMetrics.execute()).thenReturn(jobMetrics);
jobMetrics.setMetrics(ImmutableList.<MetricUpdate>of());
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
AggregatorValues<?> values = job.getAggregatorValues(aggregator);
assertThat(values.getValues(), empty());
}
@Test
public void testGetAggregatorValuesWithNullMetricUpdatesReturnsEmptyValue()
throws IOException, AggregatorRetrievalException {
Aggregator<?, ?> aggregator = mock(Aggregator.class);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(aggregator, pTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(appliedTransform, stepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
JobMetrics jobMetrics = new JobMetrics();
when(getMetrics.execute()).thenReturn(jobMetrics);
jobMetrics.setMetrics(null);
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
AggregatorValues<?> values = job.getAggregatorValues(aggregator);
assertThat(values.getValues(), empty());
}
@Test
public void testGetAggregatorValuesWithSingleMetricUpdateReturnsSingletonCollection()
throws IOException, AggregatorRetrievalException {
CombineFn<Long, long[], Long> combineFn = new Sum.SumLongFn();
String aggregatorName = "agg";
Aggregator<Long, Long> aggregator = new TestAggregator<>(combineFn, aggregatorName);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(aggregator, pTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(appliedTransform, stepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
JobMetrics jobMetrics = new JobMetrics();
when(getMetrics.execute()).thenReturn(jobMetrics);
MetricUpdate update = new MetricUpdate();
long stepValue = 1234L;
update.setScalar(new BigDecimal(stepValue));
MetricStructuredName structuredName = new MetricStructuredName();
structuredName.setName(aggregatorName);
structuredName.setContext(ImmutableMap.of("step", stepName));
update.setName(structuredName);
jobMetrics.setMetrics(ImmutableList.of(update));
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
AggregatorValues<Long> values = job.getAggregatorValues(aggregator);
assertThat(values.getValuesAtSteps(), hasEntry(fullName, stepValue));
assertThat(values.getValuesAtSteps().size(), equalTo(1));
assertThat(values.getValues(), contains(stepValue));
assertThat(values.getTotalValue(combineFn), equalTo(Long.valueOf(stepValue)));
}
@Test
public void testGetAggregatorValuesWithMultipleMetricUpdatesReturnsCollection()
throws IOException, AggregatorRetrievalException {
CombineFn<Long, long[], Long> combineFn = new Sum.SumLongFn();
String aggregatorName = "agg";
Aggregator<Long, Long> aggregator = new TestAggregator<>(combineFn, aggregatorName);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> otherTransform = mock(PTransform.class);
String otherStepName = "s88";
String otherFullName = "Spam/Ham/Eggs";
AppliedPTransform<?, ?, ?> otherAppliedTransform =
appliedPTransform(otherFullName, otherTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(
aggregator, pTransform, aggregator, otherTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(
appliedTransform, stepName, otherAppliedTransform, otherStepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
JobMetrics jobMetrics = new JobMetrics();
when(getMetrics.execute()).thenReturn(jobMetrics);
MetricUpdate updateOne = new MetricUpdate();
long stepValue = 1234L;
updateOne.setScalar(new BigDecimal(stepValue));
MetricStructuredName structuredNameOne = new MetricStructuredName();
structuredNameOne.setName(aggregatorName);
structuredNameOne.setContext(ImmutableMap.of("step", stepName));
updateOne.setName(structuredNameOne);
MetricUpdate updateTwo = new MetricUpdate();
long stepValueTwo = 1024L;
updateTwo.setScalar(new BigDecimal(stepValueTwo));
MetricStructuredName structuredNameTwo = new MetricStructuredName();
structuredNameTwo.setName(aggregatorName);
structuredNameTwo.setContext(ImmutableMap.of("step", otherStepName));
updateTwo.setName(structuredNameTwo);
jobMetrics.setMetrics(ImmutableList.of(updateOne, updateTwo));
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
AggregatorValues<Long> values = job.getAggregatorValues(aggregator);
assertThat(values.getValuesAtSteps(), hasEntry(fullName, stepValue));
assertThat(values.getValuesAtSteps(), hasEntry(otherFullName, stepValueTwo));
assertThat(values.getValuesAtSteps().size(), equalTo(2));
assertThat(values.getValues(), containsInAnyOrder(stepValue, stepValueTwo));
assertThat(values.getTotalValue(combineFn), equalTo(Long.valueOf(stepValue + stepValueTwo)));
}
@Test
public void testGetAggregatorValuesWithUnrelatedMetricUpdateIgnoresUpdate()
throws IOException, AggregatorRetrievalException {
CombineFn<Long, long[], Long> combineFn = new Sum.SumLongFn();
String aggregatorName = "agg";
Aggregator<Long, Long> aggregator = new TestAggregator<>(combineFn, aggregatorName);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(aggregator, pTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(appliedTransform, stepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
JobMetrics jobMetrics = new JobMetrics();
when(getMetrics.execute()).thenReturn(jobMetrics);
MetricUpdate ignoredUpdate = new MetricUpdate();
ignoredUpdate.setScalar(null);
MetricStructuredName ignoredName = new MetricStructuredName();
ignoredName.setName("ignoredAggregator.elementCount.out0");
ignoredName.setContext(null);
ignoredUpdate.setName(ignoredName);
jobMetrics.setMetrics(ImmutableList.of(ignoredUpdate));
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
AggregatorValues<Long> values = job.getAggregatorValues(aggregator);
assertThat(values.getValuesAtSteps().entrySet(), empty());
assertThat(values.getValues(), empty());
}
@Test
public void testGetAggregatorValuesWithUnusedAggregatorThrowsException()
throws AggregatorRetrievalException {
Aggregator<?, ?> aggregator = mock(Aggregator.class);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of().asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("not used in this pipeline");
job.getAggregatorValues(aggregator);
}
@Test
public void testGetAggregatorValuesWhenClientThrowsExceptionThrowsAggregatorRetrievalException()
throws IOException, AggregatorRetrievalException {
CombineFn<Long, long[], Long> combineFn = new Sum.SumLongFn();
String aggregatorName = "agg";
Aggregator<Long, Long> aggregator = new TestAggregator<>(combineFn, aggregatorName);
@SuppressWarnings("unchecked")
PTransform<PInput, POutput> pTransform = mock(PTransform.class);
String stepName = "s1";
String fullName = "Foo/Bar/Baz";
AppliedPTransform<?, ?, ?> appliedTransform = appliedPTransform(fullName, pTransform);
DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms(
ImmutableSetMultimap.<Aggregator<?, ?>, PTransform<?, ?>>of(aggregator, pTransform).asMap(),
ImmutableMap.<AppliedPTransform<?, ?, ?>, String>of(appliedTransform, stepName));
GetMetrics getMetrics = mock(GetMetrics.class);
when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics);
IOException cause = new IOException();
when(getMetrics.execute()).thenThrow(cause);
Get getState = mock(Get.class);
when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState);
Job modelJob = new Job();
when(getState.execute()).thenReturn(modelJob);
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job =
new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms);
thrown.expect(AggregatorRetrievalException.class);
thrown.expectCause(is(cause));
thrown.expectMessage(aggregator.toString());
thrown.expectMessage("when retrieving Aggregator values for");
job.getAggregatorValues(aggregator);
}
private static class TestAggregator<InT, OutT> implements Aggregator<InT, OutT> {
private final CombineFn<InT, ?, OutT> combineFn;
private final String name;
public TestAggregator(CombineFn<InT, ?, OutT> combineFn, String name) {
this.combineFn = combineFn;
this.name = name;
}
@Override
public void addValue(InT value) {
throw new AssertionError();
}
@Override
public String getName() {
return name;
}
@Override
public CombineFn<InT, ?, OutT> getCombineFn() {
return combineFn;
}
}
private AppliedPTransform<?, ?, ?> appliedPTransform(
String fullName, PTransform<PInput, POutput> transform) {
return AppliedPTransform.of(fullName, mock(PInput.class), mock(POutput.class), transform);
}
}
|
[
"jason_l_l@qq.com"
] |
jason_l_l@qq.com
|
79b27f41a46a1e1b1b734d69f66d30109e20ad42
|
9c11efed24e6eac71320e18906cf03af5cbace1e
|
/backend/src/test/java/de/slackspace/rmanager/gameengine/service/CabinetServiceTest.java
|
5a18379fa6db92d3f0dfc972ca2533c7abb67247
|
[
"Apache-2.0"
] |
permissive
|
cternes/R-Manager
|
6772c8e69fcd4a9e9c496f3731efe272ea34f0a2
|
d484fdfca1beb115d8362f254814ca7b327965b5
|
refs/heads/master
| 2020-06-05T19:40:47.927589
| 2015-09-04T18:56:53
| 2015-09-04T18:56:53
| 33,321,431
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,311
|
java
|
package de.slackspace.rmanager.gameengine.service;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
import de.slackspace.rmanager.gameengine.domain.Cabinet;
import de.slackspace.rmanager.gameengine.domain.DepartmentType;
public class CabinetServiceTest {
CabinetService cut = new CabinetService();
@Test
public void whenCreateKitchenCabinetShouldReturnCabinet() {
List<Cabinet> cabinets = cut.createCabinet(DepartmentType.Kitchen);
assertThat(cabinets, hasSize(10));
}
@Test
public void whenCreateDiningHallCabinetShouldReturnCabinet() {
List<Cabinet> cabinets = cut.createCabinet(DepartmentType.Dininghall);
assertThat(cabinets, hasSize(9));
}
@Test
public void whenCreateLaundryCabinetShouldReturnCabinet() {
List<Cabinet> cabinets = cut.createCabinet(DepartmentType.Laundry);
assertThat(cabinets, hasSize(10));
}
@Test
public void whenCreateFacilitiesCabinetShouldReturnCabinet() {
List<Cabinet> cabinets = cut.createCabinet(DepartmentType.Facilities);
assertThat(cabinets, hasSize(7));
}
@Test
public void whenCreateReeferCabinetShouldReturnCabinet() {
List<Cabinet> cabinets = cut.createCabinet(DepartmentType.Reefer);
assertThat(cabinets, hasSize(10));
}
}
|
[
"github@slackspace.de"
] |
github@slackspace.de
|
f2290ca35cdf55ddcd27ff1e25d8d11e9762578f
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/1/1_701e99900d9312579f7e835163563db4dacc5f40/BsonJackson/1_701e99900d9312579f7e835163563db4dacc5f40_BsonJackson_s.java
|
9645b1f38cb5adecc1ae3a8347087bacae0c7ec5
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 384
|
java
|
package serializers;
import de.undercouch.bson4jackson.BsonFactory;
import de.undercouch.bson4jackson.BsonGenerator;
public class BsonJackson
{
public static void register(TestGroups groups)
{
BsonFactory factory = new BsonFactory();
groups.media.add(JavaBuiltIn.MediaTransformer,
new JsonJacksonManual.GenericSerializer("bson/jackson-manual", factory));
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
52a18f00cf7d671ebdfecc1c3bd75758b9dd46d6
|
cb47a69eb202feae227358af2493efe9c35d0cf6
|
/spring-cloud/springcloud-sso/sso/auth-center-master/auth-server/auth-server-core/src/main/java/com/lingchaomin/auth/server/core/role/entity/Authorization.java
|
3df48ff6007461ec1e386b7a0b8b3d2e4a22c41d
|
[
"Apache-2.0"
] |
permissive
|
WCry/demo
|
e4f6ee469e39e9a96e9deec2724eb89d642830b5
|
5801b12371a1beb610328a8b83a056276427817d
|
refs/heads/master
| 2023-05-28T14:42:29.175634
| 2021-06-14T14:06:43
| 2021-06-14T14:06:43
| 266,535,701
| 2
| 1
|
Apache-2.0
| 2020-10-21T01:03:55
| 2020-05-24T12:24:51
|
Java
|
UTF-8
|
Java
| false
| false
| 727
|
java
|
package com.lingchaomin.auth.server.core.role.entity;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author minlingchao
* @version 1.0
* @date 2017/2/20 下午9:35
* @description 授权信息
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Authorization implements Serializable {
private Long id;
private Date gmtCreate;
private Date gmtModified;
/**
* 用户id
*/
private Long userId;
/**
* 应用id
*/
private Long appId;
/**
* 权限ids
*/
private String roleIds;
}
|
[
"627292959@qq.com"
] |
627292959@qq.com
|
2b1f4f7b8ee67e0bc753be851e28d0167fd53a56
|
b0bf62b90ca33d9ab8b1f670a501ed6643590db8
|
/Exemplos/src/exemploComposite2/Elemento.java
|
8f01fa758d3d7437f3226a64ef7a3df0cfa3b068
|
[] |
no_license
|
SayuriJodai/AS-ADS
|
8e2d8320bdfd2920d7cbd21ebaa11de3ac906089
|
748adcb64ddf517e1dd0405e42c1de976eaed3b0
|
refs/heads/master
| 2020-03-27T00:29:10.960617
| 2018-08-22T00:55:43
| 2018-08-22T00:55:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 308
|
java
|
package exemploComposite2;
public abstract class Elemento implements IElemento {
private String nome;
public Elemento(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
|
[
"bruna_susuke@hotmail.com"
] |
bruna_susuke@hotmail.com
|
ee4e7e4b05ff19bb410de74db6ca3e0a572b42cf
|
96181829095d8fbd56b91116c553f1d77a105dc5
|
/Java/SelectionSort/src/SelectionSortApp.java
|
97fdfd11fb857c2910e074c712be29582d02d47b
|
[] |
no_license
|
curatorcorpus/FirstProgramming
|
ef94f345529ad8a3bec0e5f8f1d9dcdf47725c5f
|
a119709b748f272a0104e58258b4326f1c90460f
|
refs/heads/master
| 2021-06-19T15:25:52.398710
| 2017-07-11T09:36:44
| 2017-07-11T09:36:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 481
|
java
|
import javax.swing.*;
public class SelectionSortApp {
public static void main(String[] args){
// create main window
JFrame mainWindow = new JFrame("Selection Sort App");
// main window settings
mainWindow.getContentPane().add(new SelectionSortPanel());
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setExtendedState(mainWindow.getExtendedState()|JFrame.MAXIMIZED_BOTH );
mainWindow.pack();
mainWindow.setVisible(true);
}
}
|
[
"itachi383@hotmail.com"
] |
itachi383@hotmail.com
|
d53486c4e40354b6975e7e33eba6db823577877b
|
c188408c9ec0425666250b45734f8b4c9644a946
|
/open-sphere-base/core/src/main/java/net/opengis/gml/_311/TemporalDatumRefType.java
|
8a6f428ce3eb9b3e476e762bb83a8a3924e4086a
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
rkausch/opensphere-desktop
|
ef8067eb03197c758e3af40ebe49e182a450cc02
|
c871c4364b3456685411fddd22414fd40ce65699
|
refs/heads/snapshot_5.2.7
| 2023-04-13T21:00:00.575303
| 2020-07-29T17:56:10
| 2020-07-29T17:56:10
| 360,594,280
| 0
| 0
|
Apache-2.0
| 2021-04-22T17:40:38
| 2021-04-22T16:58:41
| null |
UTF-8
|
Java
| false
| false
| 6,882
|
java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147
// 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: 2010.01.26 at 02:04:22 PM MST
//
package net.opengis.gml._311;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* Association to a temporal datum, either referencing or containing the definition of that datum.
*
* <p>Java class for TemporalDatumRefType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TemporalDatumRefType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element ref="{http://www.opengis.net/gml}TemporalDatum"/>
* </sequence>
* <attGroup ref="{http://www.opengis.net/gml}AssociationAttributeGroup"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TemporalDatumRefType", propOrder = {
"temporalDatum"
})
public class TemporalDatumRefType {
@XmlElement(name = "TemporalDatum")
protected TemporalDatumType temporalDatum;
@XmlAttribute(name = "remoteSchema", namespace = "http://www.opengis.net/gml")
@XmlSchemaType(name = "anyURI")
protected String remoteSchema;
@XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
protected String type;
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String role;
@XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String arcrole;
@XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
protected String title;
@XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink")
protected String show;
@XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink")
protected String actuate;
/**
* Gets the value of the temporalDatum property.
*
* @return
* possible object is
* {@link TemporalDatumType }
*
*/
public TemporalDatumType getTemporalDatum() {
return temporalDatum;
}
/**
* Sets the value of the temporalDatum property.
*
* @param value
* allowed object is
* {@link TemporalDatumType }
*
*/
public void setTemporalDatum(TemporalDatumType value) {
this.temporalDatum = value;
}
/**
* Gets the value of the remoteSchema property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemoteSchema() {
return remoteSchema;
}
/**
* Sets the value of the remoteSchema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemoteSchema(String value) {
this.remoteSchema = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "simple";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the arcrole property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArcrole() {
return arcrole;
}
/**
* Sets the value of the arcrole property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArcrole(String value) {
this.arcrole = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the show property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShow() {
return show;
}
/**
* Sets the value of the show property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShow(String value) {
this.show = value;
}
/**
* Gets the value of the actuate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActuate() {
return actuate;
}
/**
* Sets the value of the actuate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActuate(String value) {
this.actuate = value;
}
}
|
[
"kauschr@opensphere.io"
] |
kauschr@opensphere.io
|
8cfe82e8575709ea376b88cf46054f0ce4709359
|
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
|
/src/number_of_direct_superinterfaces/i2469.java
|
1c1057dcd22b3fd0aeb78c9a1eadeca298061924
|
[] |
no_license
|
vincentclee/jvm-limits
|
b72a2f2dcc18caa458f1e77924221d585f23316b
|
2fd1c26d1f7984ea8163bc103ad14b6d72282281
|
refs/heads/master
| 2020-05-18T11:18:41.711400
| 2014-09-14T04:25:18
| 2014-09-14T04:25:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 68
|
java
|
package number_of_direct_superinterfaces;
public interface i2469 {}
|
[
"vincentlee.dolbydigital@yahoo.com"
] |
vincentlee.dolbydigital@yahoo.com
|
f538109cc1707389538f427bc23f15d262b5bc99
|
45b489697f33737a3512042246031d65e05cca1f
|
/Blog/src/main/java/com/threeFarmer/dao/common/IBaseDao.java
|
ba90e639e051de7929996241c3eef151a32c3410
|
[] |
no_license
|
WeBlogNew/Blog
|
77e44bf78d9a8c74312f26f2a4ceb4d62d5cd32e
|
7b42dc38c972260acca34f9cd3605c3663bebb27
|
refs/heads/master
| 2020-03-25T10:15:09.501066
| 2018-08-06T07:13:20
| 2018-08-06T07:13:20
| 143,688,623
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 326
|
java
|
package com.threeFarmer.dao.common;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 基础DAO接口
*/
public interface IBaseDao<T> {
T findById(@Param("id") Integer id);
int save(T entity);
int update(T entity);
int delete(@Param("id") Integer id);
List<T> allList();
}
|
[
"13016472460@163.com"
] |
13016472460@163.com
|
d746cbfe15dd6adb3be1086616df730f6a5016a1
|
6e2faaa40704d23ff112dbab6475a94bea03f36e
|
/src/main/java/org/duohuo/paper/manager/PageManager.java
|
7b33bfc8f620b3ac82b454868a8892ae37e0eb8f
|
[
"MIT"
] |
permissive
|
lwolvej/paper-project
|
05bc53b661d04260e95a915c337e86a16a0875c4
|
96c1729e0aacb40b80408fdbf2b706fe986103dd
|
refs/heads/master
| 2023-08-05T00:36:18.853889
| 2019-05-29T18:01:36
| 2019-05-29T18:01:36
| 172,909,632
| 16
| 3
|
MIT
| 2023-07-21T12:34:44
| 2019-02-27T12:16:30
|
Java
|
UTF-8
|
Java
| false
| false
| 981
|
java
|
package org.duohuo.paper.manager;
import org.duohuo.paper.constants.PageConstant;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
@Component("pageManager")
public class PageManager {
public PageRequest pageRequestCreate(final Integer pageNum, final Boolean ifDesc, final String... sortBy) {
Sort sort;
if (ifDesc) {
if (sortBy.length == 2) {
sort = Sort.by(Sort.Order.desc(sortBy[0]), Sort.Order.desc(sortBy[1]));
} else {
sort = Sort.by(Sort.Order.desc(sortBy[0]));
}
} else {
if (sortBy.length == 2) {
sort = Sort.by(Sort.Order.asc(sortBy[0]), Sort.Order.asc(sortBy[1]));
} else {
sort = Sort.by(Sort.Order.asc(sortBy[0]));
}
}
return PageRequest.of(pageNum, PageConstant.PAGE_SIZE, sort);
}
}
|
[
"lwolvej@gmail.com"
] |
lwolvej@gmail.com
|
a8c1fa7b8ce22f0691eace77b4c3c0c50abec237
|
30b14344d4abb01514cee567d736ee10fe86bb19
|
/springmvc-03-annotation/src/main/java/com/kuang/controller/HelloController.java
|
7465257be47005dca9c190c8f587d21d90d160a6
|
[] |
no_license
|
zhangqi887/SpringMVC_Study
|
be1db458a71d9886ca173c6708286d941f509d73
|
8c70ba73b788b556c6c49ff169d28aa34d642729
|
refs/heads/master
| 2023-02-19T16:13:14.168707
| 2020-08-03T02:56:58
| 2020-08-03T02:56:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 592
|
java
|
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
// localhost:8080/hello/h1
@RequestMapping("/h1")
public String hello(Model model) {
// 封装数据
// 在model中添加的值,可以在jsp页面直接获取
model.addAttribute("msg", "Hello SpringMVC");
// 会被视图解析器封装成 /web-inf/jsp/hello.jsp
return "hello";
}
}
|
[
"2681086480@qq.com"
] |
2681086480@qq.com
|
908f6c61e5fdb68d2f447cc7b7a48d8096c71569
|
dfe5caf190661c003619bfe7a7944c527c917ee4
|
/src/main/java/com/vmware/vim25/VirtualMachineSnapshotTree.java
|
63aa7cbc9a75f82345e9d3910faad6b58d73c2ef
|
[
"BSD-3-Clause"
] |
permissive
|
timtasse/vijava
|
c9787f9f9b3116a01f70a89d6ea29cc4f6dc3cd0
|
5d75bc0bd212534d44f78e5a287abf3f909a2e8e
|
refs/heads/master
| 2023-06-01T08:20:39.601418
| 2022-10-31T12:43:24
| 2022-10-31T12:43:24
| 150,118,529
| 4
| 1
|
BSD-3-Clause
| 2023-05-01T21:19:53
| 2018-09-24T14:46:15
|
Java
|
UTF-8
|
Java
| false
| false
| 3,979
|
java
|
/*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
import java.util.Calendar;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class VirtualMachineSnapshotTree extends DynamicData {
public ManagedObjectReference snapshot;
public ManagedObjectReference vm;
public String name;
public String description;
public Integer id;
public Calendar createTime;
public VirtualMachinePowerState state;
public boolean quiesced;
public String backupManifest;
public VirtualMachineSnapshotTree[] childSnapshotList;
public Boolean replaySupported;
public ManagedObjectReference getSnapshot() {
return this.snapshot;
}
public ManagedObjectReference getVm() {
return this.vm;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public Integer getId() {
return this.id;
}
public Calendar getCreateTime() {
return this.createTime;
}
public VirtualMachinePowerState getState() {
return this.state;
}
public boolean isQuiesced() {
return this.quiesced;
}
public String getBackupManifest() {
return this.backupManifest;
}
public VirtualMachineSnapshotTree[] getChildSnapshotList() {
return this.childSnapshotList;
}
public Boolean getReplaySupported() {
return this.replaySupported;
}
public void setSnapshot(ManagedObjectReference snapshot) {
this.snapshot=snapshot;
}
public void setVm(ManagedObjectReference vm) {
this.vm=vm;
}
public void setName(String name) {
this.name=name;
}
public void setDescription(String description) {
this.description=description;
}
public void setId(Integer id) {
this.id=id;
}
public void setCreateTime(Calendar createTime) {
this.createTime=createTime;
}
public void setState(VirtualMachinePowerState state) {
this.state=state;
}
public void setQuiesced(boolean quiesced) {
this.quiesced=quiesced;
}
public void setBackupManifest(String backupManifest) {
this.backupManifest=backupManifest;
}
public void setChildSnapshotList(VirtualMachineSnapshotTree[] childSnapshotList) {
this.childSnapshotList=childSnapshotList;
}
public void setReplaySupported(Boolean replaySupported) {
this.replaySupported=replaySupported;
}
}
|
[
"stefan.dilk@freenet.ag"
] |
stefan.dilk@freenet.ag
|
56436a8e08023eeb5fe6c0c5e856b2be435f06ae
|
c3825017e56ea81f7ec94420007077bfc521bec1
|
/src/main/java/com/sky/workflow/service/impl/CmFieldInfoTableServiceImpl.java
|
c2270afffe943cce9f664290131805eaa7490357
|
[] |
no_license
|
nswt2018/sky-wf-engine
|
cd8dde16c951af1f211dd035ba70ff1d1cc1beed
|
35f0846ae8ff30a6e2806a744019b8f4ab7a2989
|
refs/heads/master
| 2020-04-11T01:44:21.112307
| 2019-01-09T01:56:01
| 2019-01-09T01:56:01
| 161,424,885
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 411
|
java
|
package com.sky.workflow.service.impl;
import org.springframework.stereotype.Service;
import com.sky.core.base.service.impl.BaseServiceImpl;
import com.sky.workflow.model.CmFieldInfoTable;
import com.sky.workflow.service.ICmFieldInfoTableService;
@Service("CmFieldInfoTableService")
public class CmFieldInfoTableServiceImpl extends BaseServiceImpl<CmFieldInfoTable> implements ICmFieldInfoTableService {
}
|
[
"mahong@nswt.com.cn"
] |
mahong@nswt.com.cn
|
7181bba551a5321892c49860539e433e488abd0c
|
4cf11cf0b5eefc0140589b2b1708855fc0f5c861
|
/Goosegame/src/goosegame/Board.java
|
ac616f47147f417d17418f444974acd6feec039e
|
[] |
no_license
|
fouadMd/java
|
4549425afd2444468963e8a9ae589596156bb2aa
|
081ab40498cce4fe8fc71b4843054d46147c9ce6
|
refs/heads/master
| 2023-04-25T16:50:21.978480
| 2021-05-20T10:18:55
| 2021-05-20T10:18:55
| 358,635,639
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 869
|
java
|
package goosegame;
/**
* The representation of Board
*
* @author Medjahed Ainouch
* @version 1.0
*/
public abstract class Board{
/*the number of cells in the board*/
protected final int NB_OF_CELLS ;
/*the cells in the board*/
protected Cell [] theCells;
/**
*build a board
*@param nbofcells is the number of cells
*/
public Board (int nbofcells){
this.NB_OF_CELLS= nbofcells;
this.theCells= new Cell[nbofcells];
this.theCells[0]=new StartCell(0);
this.initBoard();
}
/**
*get cell which the index is n
*@param n is the number of cell
*@return nth Cell
*/
public Cell getCell(int n){
return this.theCells[n];
}
/**
*initialise the board
*/
protected abstract void initBoard();
/**
*Return the number of cells in the board
*@return the number of cells in the board
*/
public int nbOfCells(){
return this.NB_OF_CELLS;
}
}
|
[
"medjahed@DESKTOP-39GATQD.localdomain"
] |
medjahed@DESKTOP-39GATQD.localdomain
|
dc879336ad8099c286e0d241e19f8307317c161a
|
35e4aef9b8861ed439bd3695683933a0db52b630
|
/app/src/main/java/com/storm/cftest/base/Question.java
|
32576ba4b1875d2be374ced07757b481dc53de2c
|
[] |
no_license
|
acmlgogo/one_kotlin
|
4a06a2870813192d5b0a5c59f369b317aabc9aab
|
9d5f6cf71f3f24aaf6d5d8a5cd260751d2907b29
|
refs/heads/master
| 2021-01-13T07:12:09.987566
| 2019-06-24T09:51:01
| 2019-06-24T09:51:01
| 95,061,710
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 42,962
|
java
|
package com.storm.cftest.base;
import java.util.List;
/**
* 作者:程峰 on 2017/6/12
* 邮箱:cf550272553@live.com
* github :https://github.com/acmlgogo
*/
public class Question {
/**
* res : 0
* data : {"question_id":"1593","question_title":"美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","question_content":"美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗? ","answer_title":"","answer_content":"合同法关于赠与礼物有相关的规定,其中当受赠人严重侵害赠与人或赠与人近亲属,赠与可以被撤销。<br>\r\n <br>\r\n美国队长不但包庇杀害赠与人的凶手冬兵,还用这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情,很明显符合撤销赠与的条件。<br>\r\n <br>\r\n大家都觉得分手后找女生要回礼物的行为很low,但如果是女生出轨/家暴在先,那么男生要回礼物是有法律依据的。<br>\r\n <br>\r\n\u201c队长如果主张和霍华德斯塔克只是加工承揽关系,并能提供相关证据,那托尼就无权要求队长返还盾牌了。\u201d<br>\r\n <br>\r\n其实钢铁侠的爹在这里确实是加工承揽的关系的一方。霍华德斯塔克创建的斯塔克工业是美军的供应商,霍华德本人是\u201c超级士兵计划\u201d的核心科学家,这面盾作为武器也是霍华德提供的产品。但是,这个\u201c超级士兵计划\u201d是美国军方的项目,霍华德作为民间科学家积极参与,为国效力。这属于政府搭台,民企唱戏,其中霍华德是项目乙方,美国军方才是甲方爸爸,美队本人最多算是接受培训的员工。所以这盾牌自然属于美国军方财产,只是被作为武器下发到美队手中。后来,美队由于职务变动由美军宣传部门调动到了复仇者部门,他的盾和制服想来也是一并调动。<br>\r\n <br>\r\n在复仇者的内战中,美队由于反抗政府的监管,显然已经不再担任复仇者组织的领导职务。因此,钢铁侠作为与政府合作的一方,在法理上可以代表复仇者索要部门财产,这就跟警察被革职的时候要上交警枪和徽章一样。实际上,美队敲坏了钢铁侠的装甲,属于毁坏军事物资,也是违法并且要赔偿的。<br>\r\n <br>\r\n作为佐证,在美队后面的漫画中就有一集讲他被迫退役,离开时就向政府上交了盾和制服。<br>\r\n <br>\r\n如果再深入一些讨论,我们还可以继续探讨,金刚狼的骨头是他的骨头吗?<br>\r\n因为加拿大政府利用金刚狼做实验,在他骨骼中注入昂贵的振金。那么,这些振金属于谁所有呢?<br>\r\n <br>\r\n在现实中,以医疗为目的的植入设备的所有权都归患者。比如心脏搭桥手术里的桥,隆胸手术里的硅胶还有假牙等。即使后来这些植入设备被取出后,他们的所属权依然归于患者。(金牙还可以回炉,这硅胶可能只能当狗玩具了)所以,如果金刚狼骨折了,医院打的金属板是应该归他所有。<br>\r\n <br>\r\n但是,金刚狼在这里是以军人身份,受命完成Weapon X计划,在开始前应当了解并签署了相关文件。那么,军方是否就有权回收振金呢?<br>\r\n <br>\r\n根据电影里后面的内容,金刚狼在实验过程中显然处于被洗脑的状态,在法律上属于限制责任能力人,所签署的合同并没有法律效力。另外,即便军方能够证明他当时是完全清醒并自愿也不行。因为取出骨头会让他丧命,法院是不会支持立即执行的。或许在他死后,军方会有机会打官司争一争。<br>\r\n <br>\r\n不过,考虑到金刚狼在核弹中都能存活的恐怖生命力,军方恐怕需要很好的耐心,等上一阵子了。届时,如果他的第N代重孙对这堆骨头没兴趣,说不定连法院都不用去了。<br>\r\n ","question_makettime":"2017-01-07 08:00:00","recommend_flag":"0","charge_edt":"责任编辑:向可","charge_email":"xiangke@wufazhuce.com","last_update_date":"2017-03-30 15:31:07","web_url":"http://m.wufazhuce.com/question/1593","read_num":"45900","guide_word":"这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","audio":"","anchor":"","cover":"","content_bgcolor":"#80ACE1","cover_media_type":"0","cover_media_file":"","start_video":"","copyright":"","answerer":{"user_id":"7566818","user_name":"温义飞","desc":"有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。 ","wb_name":"@Blake老实人","is_settled":"0","settled_type":"0","summary":"温义飞,ONE热门回答者。","fans_total":"353","web_url":"http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1"},"asker":{"user_id":"0","user_name":"lilizhou","web_url":"http://image.wufazhuce.com/placeholder-author-avatar.png","summary":"","desc":"","is_settled":"","settled_type":"","fans_total":"","wb_name":""},"author_list":[{"user_id":"7566818","user_name":"温义飞","desc":"有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。 ","wb_name":"@Blake老实人","is_settled":"0","settled_type":"0","summary":"温义飞,ONE热门回答者。","fans_total":"353","web_url":"http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1"}],"asker_list":[{"user_id":"0","user_name":"lilizhou","web_url":"http://image.wufazhuce.com/placeholder-author-avatar.png","summary":"","desc":"","is_settled":"","settled_type":"","fans_total":"","wb_name":""}],"next_id":"1592","previous_id":"1590","tag_list":[],"share_list":{"wx":{"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=singlemessage","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""},"wx_timeline":{"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=timeline","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""},"weibo":{"title":"ONE一个《问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?》 文/温义飞: 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。 阅读全文:http://m.wufazhuce.com/question/1593?channel=weibo 下载ONE一个APP:http://weibo.com/p/100404157874","desc":"","link":"http://m.wufazhuce.com/question/1593?channel=weibo","imgUrl":"","audio":""},"qq":{"title":"美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=qq","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""}},"praisenum":407,"sharenum":209,"commentnum":144}
*/
private int res;
private DataBean data;
public int getRes() {
return res;
}
public void setRes(int res) {
this.res = res;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* question_id : 1593
* question_title : 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?
* question_content : 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?
* answer_title :
* answer_content : 合同法关于赠与礼物有相关的规定,其中当受赠人严重侵害赠与人或赠与人近亲属,赠与可以被撤销。<br>
<br>
美国队长不但包庇杀害赠与人的凶手冬兵,还用这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情,很明显符合撤销赠与的条件。<br>
<br>
大家都觉得分手后找女生要回礼物的行为很low,但如果是女生出轨/家暴在先,那么男生要回礼物是有法律依据的。<br>
<br>
“队长如果主张和霍华德斯塔克只是加工承揽关系,并能提供相关证据,那托尼就无权要求队长返还盾牌了。”<br>
<br>
其实钢铁侠的爹在这里确实是加工承揽的关系的一方。霍华德斯塔克创建的斯塔克工业是美军的供应商,霍华德本人是“超级士兵计划”的核心科学家,这面盾作为武器也是霍华德提供的产品。但是,这个“超级士兵计划”是美国军方的项目,霍华德作为民间科学家积极参与,为国效力。这属于政府搭台,民企唱戏,其中霍华德是项目乙方,美国军方才是甲方爸爸,美队本人最多算是接受培训的员工。所以这盾牌自然属于美国军方财产,只是被作为武器下发到美队手中。后来,美队由于职务变动由美军宣传部门调动到了复仇者部门,他的盾和制服想来也是一并调动。<br>
<br>
在复仇者的内战中,美队由于反抗政府的监管,显然已经不再担任复仇者组织的领导职务。因此,钢铁侠作为与政府合作的一方,在法理上可以代表复仇者索要部门财产,这就跟警察被革职的时候要上交警枪和徽章一样。实际上,美队敲坏了钢铁侠的装甲,属于毁坏军事物资,也是违法并且要赔偿的。<br>
<br>
作为佐证,在美队后面的漫画中就有一集讲他被迫退役,离开时就向政府上交了盾和制服。<br>
<br>
如果再深入一些讨论,我们还可以继续探讨,金刚狼的骨头是他的骨头吗?<br>
因为加拿大政府利用金刚狼做实验,在他骨骼中注入昂贵的振金。那么,这些振金属于谁所有呢?<br>
<br>
在现实中,以医疗为目的的植入设备的所有权都归患者。比如心脏搭桥手术里的桥,隆胸手术里的硅胶还有假牙等。即使后来这些植入设备被取出后,他们的所属权依然归于患者。(金牙还可以回炉,这硅胶可能只能当狗玩具了)所以,如果金刚狼骨折了,医院打的金属板是应该归他所有。<br>
<br>
但是,金刚狼在这里是以军人身份,受命完成Weapon X计划,在开始前应当了解并签署了相关文件。那么,军方是否就有权回收振金呢?<br>
<br>
根据电影里后面的内容,金刚狼在实验过程中显然处于被洗脑的状态,在法律上属于限制责任能力人,所签署的合同并没有法律效力。另外,即便军方能够证明他当时是完全清醒并自愿也不行。因为取出骨头会让他丧命,法院是不会支持立即执行的。或许在他死后,军方会有机会打官司争一争。<br>
<br>
不过,考虑到金刚狼在核弹中都能存活的恐怖生命力,军方恐怕需要很好的耐心,等上一阵子了。届时,如果他的第N代重孙对这堆骨头没兴趣,说不定连法院都不用去了。<br>
* question_makettime : 2017-01-07 08:00:00
* recommend_flag : 0
* charge_edt : 责任编辑:向可
* charge_email : xiangke@wufazhuce.com
* last_update_date : 2017-03-30 15:31:07
* web_url : http://m.wufazhuce.com/question/1593
* read_num : 45900
* guide_word : 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。
* audio :
* anchor :
* cover :
* content_bgcolor : #80ACE1
* cover_media_type : 0
* cover_media_file :
* start_video :
* copyright :
* answerer : {"user_id":"7566818","user_name":"温义飞","desc":"有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。 ","wb_name":"@Blake老实人","is_settled":"0","settled_type":"0","summary":"温义飞,ONE热门回答者。","fans_total":"353","web_url":"http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1"}
* asker : {"user_id":"0","user_name":"lilizhou","web_url":"http://image.wufazhuce.com/placeholder-author-avatar.png","summary":"","desc":"","is_settled":"","settled_type":"","fans_total":"","wb_name":""}
* author_list : [{"user_id":"7566818","user_name":"温义飞","desc":"有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。 ","wb_name":"@Blake老实人","is_settled":"0","settled_type":"0","summary":"温义飞,ONE热门回答者。","fans_total":"353","web_url":"http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1"}]
* asker_list : [{"user_id":"0","user_name":"lilizhou","web_url":"http://image.wufazhuce.com/placeholder-author-avatar.png","summary":"","desc":"","is_settled":"","settled_type":"","fans_total":"","wb_name":""}]
* next_id : 1592
* previous_id : 1590
* tag_list : []
* share_list : {"wx":{"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=singlemessage","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""},"wx_timeline":{"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=timeline","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""},"weibo":{"title":"ONE一个《问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?》 文/温义飞: 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。 阅读全文:http://m.wufazhuce.com/question/1593?channel=weibo 下载ONE一个APP:http://weibo.com/p/100404157874","desc":"","link":"http://m.wufazhuce.com/question/1593?channel=weibo","imgUrl":"","audio":""},"qq":{"title":"美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=qq","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""}}
* praisenum : 407
* sharenum : 209
* commentnum : 144
*/
private String question_id;
private String question_title;
private String question_content;
private String answer_title;
private String answer_content;
private String question_makettime;
private String recommend_flag;
private String charge_edt;
private String charge_email;
private String last_update_date;
private String web_url;
private String read_num;
private String guide_word;
private String audio;
private String anchor;
private String cover;
private String content_bgcolor;
private String cover_media_type;
private String cover_media_file;
private String start_video;
private String copyright;
private AnswererBean answerer;
private AskerBean asker;
private String next_id;
private String previous_id;
private ShareListBean share_list;
private int praisenum;
private int sharenum;
private int commentnum;
private List<AuthorListBean> author_list;
private List<AskerListBean> asker_list;
private List<?> tag_list;
public String getQuestion_id() {
return question_id;
}
public void setQuestion_id(String question_id) {
this.question_id = question_id;
}
public String getQuestion_title() {
return question_title;
}
public void setQuestion_title(String question_title) {
this.question_title = question_title;
}
public String getQuestion_content() {
return question_content;
}
public void setQuestion_content(String question_content) {
this.question_content = question_content;
}
public String getAnswer_title() {
return answer_title;
}
public void setAnswer_title(String answer_title) {
this.answer_title = answer_title;
}
public String getAnswer_content() {
return answer_content;
}
public void setAnswer_content(String answer_content) {
this.answer_content = answer_content;
}
public String getQuestion_makettime() {
return question_makettime;
}
public void setQuestion_makettime(String question_makettime) {
this.question_makettime = question_makettime;
}
public String getRecommend_flag() {
return recommend_flag;
}
public void setRecommend_flag(String recommend_flag) {
this.recommend_flag = recommend_flag;
}
public String getCharge_edt() {
return charge_edt;
}
public void setCharge_edt(String charge_edt) {
this.charge_edt = charge_edt;
}
public String getCharge_email() {
return charge_email;
}
public void setCharge_email(String charge_email) {
this.charge_email = charge_email;
}
public String getLast_update_date() {
return last_update_date;
}
public void setLast_update_date(String last_update_date) {
this.last_update_date = last_update_date;
}
public String getWeb_url() {
return web_url;
}
public void setWeb_url(String web_url) {
this.web_url = web_url;
}
public String getRead_num() {
return read_num;
}
public void setRead_num(String read_num) {
this.read_num = read_num;
}
public String getGuide_word() {
return guide_word;
}
public void setGuide_word(String guide_word) {
this.guide_word = guide_word;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getContent_bgcolor() {
return content_bgcolor;
}
public void setContent_bgcolor(String content_bgcolor) {
this.content_bgcolor = content_bgcolor;
}
public String getCover_media_type() {
return cover_media_type;
}
public void setCover_media_type(String cover_media_type) {
this.cover_media_type = cover_media_type;
}
public String getCover_media_file() {
return cover_media_file;
}
public void setCover_media_file(String cover_media_file) {
this.cover_media_file = cover_media_file;
}
public String getStart_video() {
return start_video;
}
public void setStart_video(String start_video) {
this.start_video = start_video;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public AnswererBean getAnswerer() {
return answerer;
}
public void setAnswerer(AnswererBean answerer) {
this.answerer = answerer;
}
public AskerBean getAsker() {
return asker;
}
public void setAsker(AskerBean asker) {
this.asker = asker;
}
public String getNext_id() {
return next_id;
}
public void setNext_id(String next_id) {
this.next_id = next_id;
}
public String getPrevious_id() {
return previous_id;
}
public void setPrevious_id(String previous_id) {
this.previous_id = previous_id;
}
public ShareListBean getShare_list() {
return share_list;
}
public void setShare_list(ShareListBean share_list) {
this.share_list = share_list;
}
public int getPraisenum() {
return praisenum;
}
public void setPraisenum(int praisenum) {
this.praisenum = praisenum;
}
public int getSharenum() {
return sharenum;
}
public void setSharenum(int sharenum) {
this.sharenum = sharenum;
}
public int getCommentnum() {
return commentnum;
}
public void setCommentnum(int commentnum) {
this.commentnum = commentnum;
}
public List<AuthorListBean> getAuthor_list() {
return author_list;
}
public void setAuthor_list(List<AuthorListBean> author_list) {
this.author_list = author_list;
}
public List<AskerListBean> getAsker_list() {
return asker_list;
}
public void setAsker_list(List<AskerListBean> asker_list) {
this.asker_list = asker_list;
}
public List<?> getTag_list() {
return tag_list;
}
public void setTag_list(List<?> tag_list) {
this.tag_list = tag_list;
}
public static class AnswererBean {
/**
* user_id : 7566818
* user_name : 温义飞
* desc : 有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。
* wb_name : @Blake老实人
* is_settled : 0
* settled_type : 0
* summary : 温义飞,ONE热门回答者。
* fans_total : 353
* web_url : http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1
*/
private String user_id;
private String user_name;
private String desc;
private String wb_name;
private String is_settled;
private String settled_type;
private String summary;
private String fans_total;
private String web_url;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getWb_name() {
return wb_name;
}
public void setWb_name(String wb_name) {
this.wb_name = wb_name;
}
public String getIs_settled() {
return is_settled;
}
public void setIs_settled(String is_settled) {
this.is_settled = is_settled;
}
public String getSettled_type() {
return settled_type;
}
public void setSettled_type(String settled_type) {
this.settled_type = settled_type;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getFans_total() {
return fans_total;
}
public void setFans_total(String fans_total) {
this.fans_total = fans_total;
}
public String getWeb_url() {
return web_url;
}
public void setWeb_url(String web_url) {
this.web_url = web_url;
}
}
public static class AskerBean {
/**
* user_id : 0
* user_name : lilizhou
* web_url : http://image.wufazhuce.com/placeholder-author-avatar.png
* summary :
* desc :
* is_settled :
* settled_type :
* fans_total :
* wb_name :
*/
private String user_id;
private String user_name;
private String web_url;
private String summary;
private String desc;
private String is_settled;
private String settled_type;
private String fans_total;
private String wb_name;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getWeb_url() {
return web_url;
}
public void setWeb_url(String web_url) {
this.web_url = web_url;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getIs_settled() {
return is_settled;
}
public void setIs_settled(String is_settled) {
this.is_settled = is_settled;
}
public String getSettled_type() {
return settled_type;
}
public void setSettled_type(String settled_type) {
this.settled_type = settled_type;
}
public String getFans_total() {
return fans_total;
}
public void setFans_total(String fans_total) {
this.fans_total = fans_total;
}
public String getWb_name() {
return wb_name;
}
public void setWb_name(String wb_name) {
this.wb_name = wb_name;
}
}
public static class ShareListBean {
/**
* wx : {"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=singlemessage","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""}
* wx_timeline : {"title":"问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=timeline","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""}
* weibo : {"title":"ONE一个《问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?》 文/温义飞: 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。 阅读全文:http://m.wufazhuce.com/question/1593?channel=weibo 下载ONE一个APP:http://weibo.com/p/100404157874","desc":"","link":"http://m.wufazhuce.com/question/1593?channel=weibo","imgUrl":"","audio":""}
* qq : {"title":"美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?","desc":"这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。","link":"http://m.wufazhuce.com/question/1593?channel=qq","imgUrl":"http://image.wufazhuce.com/ONE_logo_120_square.png","audio":""}
*/
private WxBean wx;
private WxTimelineBean wx_timeline;
private WeiboBean weibo;
private QqBean qq;
public WxBean getWx() {
return wx;
}
public void setWx(WxBean wx) {
this.wx = wx;
}
public WxTimelineBean getWx_timeline() {
return wx_timeline;
}
public void setWx_timeline(WxTimelineBean wx_timeline) {
this.wx_timeline = wx_timeline;
}
public WeiboBean getWeibo() {
return weibo;
}
public void setWeibo(WeiboBean weibo) {
this.weibo = weibo;
}
public QqBean getQq() {
return qq;
}
public void setQq(QqBean qq) {
this.qq = qq;
}
public static class WxBean {
/**
* title : 问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?
* desc : 文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。
* link : http://m.wufazhuce.com/question/1593?channel=singlemessage
* imgUrl : http://image.wufazhuce.com/ONE_logo_120_square.png
* audio :
*/
private String title;
private String desc;
private String link;
private String imgUrl;
private String audio;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
}
public static class WxTimelineBean {
/**
* title : 问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?
* desc : 文/温义飞 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。
* link : http://m.wufazhuce.com/question/1593?channel=timeline
* imgUrl : http://image.wufazhuce.com/ONE_logo_120_square.png
* audio :
*/
private String title;
private String desc;
private String link;
private String imgUrl;
private String audio;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
}
public static class WeiboBean {
/**
* title : ONE一个《问答 | 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?》 文/温义飞: 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。 阅读全文:http://m.wufazhuce.com/question/1593?channel=weibo 下载ONE一个APP:http://weibo.com/p/100404157874
* desc :
* link : http://m.wufazhuce.com/question/1593?channel=weibo
* imgUrl :
* audio :
*/
private String title;
private String desc;
private String link;
private String imgUrl;
private String audio;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
}
public static class QqBean {
/**
* title : 美国队长的盾是钢铁侠的爸爸送的,那么钢铁侠有权利要回来吗?
* desc : 这个盾反复殴打赠与人的亲儿子钢铁侠,深深地伤害了妮妮的肉体和感情。
* link : http://m.wufazhuce.com/question/1593?channel=qq
* imgUrl : http://image.wufazhuce.com/ONE_logo_120_square.png
* audio :
*/
private String title;
private String desc;
private String link;
private String imgUrl;
private String audio;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
}
}
public static class AuthorListBean {
/**
* user_id : 7566818
* user_name : 温义飞
* desc : 有时也会迷惑,人们爱的究竟是我的美貌还是我的才华。
* wb_name : @Blake老实人
* is_settled : 0
* settled_type : 0
* summary : 温义飞,ONE热门回答者。
* fans_total : 353
* web_url : http://image.wufazhuce.com/FjN55lHN2vK5VgA5c1c8opFeUrG1
*/
private String user_id;
private String user_name;
private String desc;
private String wb_name;
private String is_settled;
private String settled_type;
private String summary;
private String fans_total;
private String web_url;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getWb_name() {
return wb_name;
}
public void setWb_name(String wb_name) {
this.wb_name = wb_name;
}
public String getIs_settled() {
return is_settled;
}
public void setIs_settled(String is_settled) {
this.is_settled = is_settled;
}
public String getSettled_type() {
return settled_type;
}
public void setSettled_type(String settled_type) {
this.settled_type = settled_type;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getFans_total() {
return fans_total;
}
public void setFans_total(String fans_total) {
this.fans_total = fans_total;
}
public String getWeb_url() {
return web_url;
}
public void setWeb_url(String web_url) {
this.web_url = web_url;
}
}
public static class AskerListBean {
/**
* user_id : 0
* user_name : lilizhou
* web_url : http://image.wufazhuce.com/placeholder-author-avatar.png
* summary :
* desc :
* is_settled :
* settled_type :
* fans_total :
* wb_name :
*/
private String user_id;
private String user_name;
private String web_url;
private String summary;
private String desc;
private String is_settled;
private String settled_type;
private String fans_total;
private String wb_name;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getWeb_url() {
return web_url;
}
public void setWeb_url(String web_url) {
this.web_url = web_url;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getIs_settled() {
return is_settled;
}
public void setIs_settled(String is_settled) {
this.is_settled = is_settled;
}
public String getSettled_type() {
return settled_type;
}
public void setSettled_type(String settled_type) {
this.settled_type = settled_type;
}
public String getFans_total() {
return fans_total;
}
public void setFans_total(String fans_total) {
this.fans_total = fans_total;
}
public String getWb_name() {
return wb_name;
}
public void setWb_name(String wb_name) {
this.wb_name = wb_name;
}
}
}
}
|
[
"cf550272553@live.com"
] |
cf550272553@live.com
|
e881eeb3ebc6ceb36a0a70d663cacd528d90f64c
|
67c89388e84c4e28d1559ee6665304708e5bf0b2
|
/protocols/raft/src/main/java/io/atomix/protocols/raft/proxy/impl/RaftProxyManager.java
|
2229f7f169695101fd642b1e3b35eb1a59393112
|
[
"Apache-2.0"
] |
permissive
|
maniacs-ops/atomix
|
f66e4eca65466fdda7dee9aec08b3a1cb51724dc
|
c28f884754f26edfec3677849e864eb3311738e7
|
refs/heads/master
| 2021-01-02T08:55:42.350924
| 2017-07-28T23:48:05
| 2017-07-28T23:48:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 15,165
|
java
|
/*
* Copyright 2017-present Open Networking Laboratory
*
* 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 io.atomix.protocols.raft.proxy.impl;
import com.google.common.collect.Sets;
import com.google.common.primitives.Longs;
import io.atomix.protocols.raft.RaftClient;
import io.atomix.protocols.raft.RaftException;
import io.atomix.protocols.raft.ReadConsistency;
import io.atomix.protocols.raft.cluster.MemberId;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.RaftClientProtocol;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.protocols.raft.proxy.CommunicationStrategy;
import io.atomix.protocols.raft.proxy.RaftProxy;
import io.atomix.protocols.raft.proxy.RaftProxyClient;
import io.atomix.protocols.raft.service.ServiceType;
import io.atomix.protocols.raft.session.SessionId;
import io.atomix.utils.concurrent.Futures;
import io.atomix.utils.concurrent.ThreadContext;
import io.atomix.utils.concurrent.ThreadPoolContext;
import io.atomix.utils.logging.ContextualLoggerFactory;
import io.atomix.utils.logging.LoggerContext;
import org.slf4j.Logger;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Client session manager.
*/
public class RaftProxyManager {
private final Logger log;
private final String clientId;
private final MemberId memberId;
private final RaftClientProtocol protocol;
private final RaftProxyConnection connection;
private final ScheduledExecutorService threadPoolExecutor;
private final MemberSelectorManager selectorManager;
private final Map<Long, RaftProxyState> sessions = new ConcurrentHashMap<>();
private final Map<Long, ScheduledFuture<?>> keepAliveFutures = new ConcurrentHashMap<>();
private final AtomicBoolean open = new AtomicBoolean();
public RaftProxyManager(String clientId, MemberId memberId, RaftClientProtocol protocol, MemberSelectorManager selectorManager, ScheduledExecutorService threadPoolExecutor) {
this.clientId = checkNotNull(clientId, "clientId cannot be null");
this.memberId = checkNotNull(memberId, "memberId cannot be null");
this.protocol = checkNotNull(protocol, "protocol cannot be null");
this.selectorManager = checkNotNull(selectorManager, "selectorManager cannot be null");
this.log = ContextualLoggerFactory.getLogger(getClass(), LoggerContext.builder(RaftClient.class)
.addValue(clientId)
.build());
this.connection = new RaftProxyConnection(
protocol,
selectorManager.createSelector(CommunicationStrategy.ANY),
new ThreadPoolContext(threadPoolExecutor),
LoggerContext.builder(RaftClient.class)
.addValue(clientId)
.build());
this.threadPoolExecutor = checkNotNull(threadPoolExecutor, "threadPoolExecutor cannot be null");
}
/**
* Resets the session manager's cluster information.
*/
public void resetConnections() {
selectorManager.resetAll();
}
/**
* Resets the session manager's cluster information.
*
* @param leader The leader address.
* @param servers The collection of servers.
*/
public void resetConnections(MemberId leader, Collection<MemberId> servers) {
selectorManager.resetAll(leader, servers);
}
/**
* Opens the session manager.
*
* @return A completable future to be called once the session manager is opened.
*/
public CompletableFuture<Void> open() {
open.set(true);
return CompletableFuture.completedFuture(null);
}
/**
* Opens a new session.
*
* @param serviceName The session name.
* @param serviceType The session type.
* @param communicationStrategy The strategy with which to communicate with servers.
* @param timeout The session timeout.
* @return A completable future to be completed once the session has been opened.
*/
public CompletableFuture<RaftProxyClient> openSession(
String serviceName,
ServiceType serviceType,
ReadConsistency readConsistency,
CommunicationStrategy communicationStrategy,
Duration timeout) {
checkNotNull(serviceName, "serviceName cannot be null");
checkNotNull(serviceType, "serviceType cannot be null");
checkNotNull(communicationStrategy, "communicationStrategy cannot be null");
checkNotNull(timeout, "timeout cannot be null");
log.debug("Opening session; name: {}, type: {}", serviceName, serviceType);
OpenSessionRequest request = OpenSessionRequest.newBuilder()
.withMemberId(memberId)
.withServiceName(serviceName)
.withServiceType(serviceType)
.withReadConsistency(readConsistency)
.withTimeout(timeout.toMillis())
.build();
CompletableFuture<RaftProxyClient> future = new CompletableFuture<>();
ThreadContext proxyContext = new ThreadPoolContext(threadPoolExecutor);
connection.openSession(request).whenCompleteAsync((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
// Create and store the proxy state.
RaftProxyState state = new RaftProxyState(
clientId,
SessionId.from(response.session()),
serviceName,
serviceType,
response.timeout());
sessions.put(state.getSessionId().id(), state);
state.addStateChangeListener(s -> {
if (s == RaftProxy.State.CLOSED) {
sessions.remove(state.getSessionId().id());
}
});
// Ensure the proxy session info is reset and the session is kept alive.
keepAliveSessions(state.getSessionTimeout());
// Create the proxy client and complete the future.
RaftProxyClient client = new DiscreteRaftProxyClient(
state,
protocol,
selectorManager,
this,
communicationStrategy,
proxyContext);
future.complete(client);
} else {
future.completeExceptionally(new RaftException.Unavailable(response.error().message()));
}
} else {
future.completeExceptionally(new RaftException.Unavailable(error.getMessage()));
}
}, proxyContext);
return future;
}
/**
* Closes a session.
*
* @param sessionId The session identifier.
* @return A completable future to be completed once the session is closed.
*/
public CompletableFuture<Void> closeSession(SessionId sessionId) {
RaftProxyState state = sessions.get(sessionId.id());
if (state == null) {
return Futures.exceptionalFuture(new RaftException.UnknownSession("Unknown session: " + sessionId));
}
log.info("Closing session {}", sessionId);
CloseSessionRequest request = CloseSessionRequest.newBuilder()
.withSession(sessionId.id())
.build();
CompletableFuture<Void> future = new CompletableFuture<>();
connection.closeSession(request).whenComplete((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
sessions.remove(sessionId.id());
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
}
/**
* Resets indexes for the given session.
*
* @param sessionId The session for which to reset indexes.
* @return A completable future to be completed once the session's indexes have been reset.
*/
CompletableFuture<Void> resetIndexes(SessionId sessionId) {
RaftProxyState sessionState = sessions.get(sessionId.id());
if (sessionState == null) {
return Futures.exceptionalFuture(new IllegalArgumentException("Unknown session: " + sessionId));
}
CompletableFuture<Void> future = new CompletableFuture<>();
KeepAliveRequest request = KeepAliveRequest.newBuilder()
.withSessionIds(new long[]{sessionId.id()})
.withCommandSequences(new long[]{sessionState.getCommandResponse()})
.withEventIndexes(new long[]{sessionState.getEventIndex()})
.build();
connection.keepAlive(request).whenComplete((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
}
/**
* Sends a keep-alive request to the cluster.
*/
private void keepAliveSessions(long timeout) {
keepAliveSessions(timeout, true);
}
/**
* Sends a keep-alive request to the cluster.
*/
private synchronized void keepAliveSessions(long timeout, boolean retryOnFailure) {
// Filter the list of sessions by timeout.
List<RaftProxyState> needKeepAlive = sessions.values()
.stream()
.filter(session -> session.getSessionTimeout() == timeout)
.collect(Collectors.toList());
// If no sessions need keep-alives to be sent, skip and reschedule the keep-alive.
if (needKeepAlive.isEmpty()) {
return;
}
// Allocate session IDs, command response sequence numbers, and event index arrays.
long[] sessionIds = new long[needKeepAlive.size()];
long[] commandResponses = new long[needKeepAlive.size()];
long[] eventIndexes = new long[needKeepAlive.size()];
// For each session that needs to be kept alive, populate batch request arrays.
int i = 0;
for (RaftProxyState sessionState : needKeepAlive) {
sessionIds[i] = sessionState.getSessionId().id();
commandResponses[i] = sessionState.getCommandResponse();
eventIndexes[i] = sessionState.getEventIndex();
i++;
}
log.debug("Keeping {} sessions alive", sessionIds.length);
KeepAliveRequest request = KeepAliveRequest.newBuilder()
.withSessionIds(sessionIds)
.withCommandSequences(commandResponses)
.withEventIndexes(eventIndexes)
.build();
long startTime = System.currentTimeMillis();
connection.keepAlive(request).whenComplete((response, error) -> {
if (open.get()) {
long delta = System.currentTimeMillis() - startTime;
if (error == null) {
// If the request was successful, update the address selector and schedule the next keep-alive.
if (response.status() == RaftResponse.Status.OK) {
selectorManager.resetAll(response.leader(), response.members());
// Iterate through sessions and close sessions that weren't kept alive by the request (have already been closed).
Set<Long> keptAliveSessions = Sets.newHashSet(Longs.asList(response.sessionIds()));
for (RaftProxyState session : needKeepAlive) {
if (keptAliveSessions.contains(session.getSessionId().id())) {
session.setState(RaftProxy.State.CONNECTED);
} else {
session.setState(RaftProxy.State.CLOSED);
}
}
scheduleKeepAlive(timeout, delta);
}
// If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
// This will ensure that the address selector selects all servers without filtering on the leader.
else if (retryOnFailure && connection.leader() != null) {
selectorManager.resetAll(null, connection.servers());
keepAliveSessions(timeout, false);
}
// If no leader was set, set the session state to unstable and schedule another keep-alive.
else {
needKeepAlive.forEach(s -> s.setState(RaftProxy.State.SUSPENDED));
selectorManager.resetAll();
scheduleKeepAlive(timeout, delta);
}
}
// If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
// This will ensure that the address selector selects all servers without filtering on the leader.
else if (retryOnFailure && connection.leader() != null) {
selectorManager.resetAll(null, connection.servers());
keepAliveSessions(timeout, false);
}
// If no leader was set, set the session state to unstable and schedule another keep-alive.
else {
needKeepAlive.forEach(s -> s.setState(RaftProxy.State.SUSPENDED));
selectorManager.resetAll();
scheduleKeepAlive(timeout, delta);
}
}
});
}
/**
* Schedules a keep-alive request.
*/
private synchronized void scheduleKeepAlive(long timeout, long delta) {
ScheduledFuture<?> keepAliveFuture = keepAliveFutures.remove(timeout);
if (keepAliveFuture != null) {
keepAliveFuture.cancel(false);
}
// Schedule the keep alive for 3/4 the timeout minus the delta from the last keep-alive request.
keepAliveFutures.put(timeout, threadPoolExecutor.schedule(() -> {
if (open.get()) {
keepAliveSessions(timeout);
}
}, Math.max(Math.max((long)(timeout * .75) - delta, timeout - 2500 - delta), 0), TimeUnit.MILLISECONDS));
}
/**
* Closes the session manager.
*
* @return A completable future to be completed once the session manager is closed.
*/
public CompletableFuture<Void> close() {
if (open.compareAndSet(true, false)) {
CompletableFuture<Void> future = new CompletableFuture<>();
threadPoolExecutor.execute(() -> {
for (ScheduledFuture<?> keepAliveFuture : keepAliveFutures.values()) {
keepAliveFuture.cancel(false);
}
future.complete(null);
});
return future;
}
return CompletableFuture.completedFuture(null);
}
@Override
public String toString() {
return toStringHelper(this)
.add("client", clientId)
.toString();
}
}
|
[
"jordan.halterman@gmail.com"
] |
jordan.halterman@gmail.com
|
2159ee7fcb953bc7bbd6151887432ce26c14b55f
|
ebc4297fae19303a1fde2d649eb8387ecbca2f1b
|
/HomeWorks/Homework_5/Program.java
|
c40afcd2cc296a7054a01776f1fcef13c1c77302
|
[] |
no_license
|
HaKooNa-MaTaTa/IGONIN_JAVA_120
|
e2be8247450933d407dbfccb69c117498da2aa1d
|
dbb677ebd155214e85e1f31f1658f5cd1e106eb3
|
refs/heads/master
| 2020-05-15T06:22:13.515337
| 2019-10-08T19:34:24
| 2019-10-08T19:34:24
| 182,122,905
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 977
|
java
|
import java.util.Scanner;
class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please, enter size array");
int sizeArray = scanner.nextInt();
int array[] = new int[sizeArray];
int numbers = 0;
int maxDigits = 0;
int minDigits = 0;
int i = 0;
while ( i < sizeArray) {
numbers = scanner.nextInt();
array[i] = numbers;
i++;
}
System.out.print("Amount local maximum: ");
for (i = 0; i <= sizeArray-2; i++) {
if ( i != 0) {
if (array[i-1] < array[i]) {
if(array[i] > array[i+1]) {
maxDigits = maxDigits + 1;
}
}
}
}
System.out.println(maxDigits);
System.out.print("Amount local minimum: ");
for (i = 0; i <= sizeArray-2; i++) {
if ( i != 0) {
if (array[i-1] > array[i]) {
if (array[i] < array[i+1]) {
minDigits = minDigits + 1;
}
}
}
}
System.out.println(minDigits);
}
}
|
[
"oleg_in_l@mail.ru"
] |
oleg_in_l@mail.ru
|
1125bdac1b1f8f451c6f31ac99ead326e27847f8
|
395ac8ead306020f338495b6f44a52bffb919a92
|
/Ch7/OOP2/Composition/Main.java
|
84c341ef1d3cb3a76bb13c24fbc4ddea1ee08c35
|
[] |
no_license
|
cstoicescu/JavaCourse
|
77f12d91a420b391e2f01ec648e16806f946d81f
|
3f01862479eaae9ea682f14fb9b8ad0f68601969
|
refs/heads/master
| 2021-05-17T17:30:48.202483
| 2020-04-22T17:41:32
| 2020-04-22T17:41:32
| 250,896,937
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 701
|
java
|
package Ch7.OOP2.Composition;
public class Main {
public static void main(String[] args) {
Dimensions dimensions = new Dimensions(20,20,5);
Case theCase = new Case("2208","Dell","240V",dimensions);
Monitor theMonitor = new Monitor("27 inch","Acer",27,new Resolution(2540,1440));
Motherboard theMotherboard = new Motherboard("BJ-200","Asus",4,6,"v.2.44");
Computer pc = new Computer(theCase,theMonitor,theMotherboard);
pc.getTheCase().powerButton();
pc.powerUpAndDown();
pc.getTheMotherboard().loadProgram("Windows 10");
pc.openPaint();
pc.powerUpAndDown();
// Idea : Implement a menu , pc specs
}
}
|
[
"stoicescu.catalinn97@gmail.com"
] |
stoicescu.catalinn97@gmail.com
|
9013e722da43c1dac6e53876d48a63dd56c903b1
|
2650d565255cf7f5c0192599cb69650aba91fdb8
|
/java/src/main/java/com/ciaoshen/leetcode/MaxAreaOfIsland.java
|
67cfb443d89c115dfd19351b6038aac15322a187
|
[
"MIT"
] |
permissive
|
helloShen/leetcode
|
78ded31b16cfc0ca4d0618d90bb0ef3a8b10377a
|
5bba26f0612d785800c990947db8dae3af4bad81
|
refs/heads/master
| 2021-06-03T14:44:57.256143
| 2019-04-06T19:06:15
| 2019-04-06T19:06:15
| 96,709,063
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,950
|
java
|
/**
* Leetcode - Algorithm - MaxAreaOfIsland
*/
package com.ciaoshen.leetcode;
import java.util.*;
import com.ciaoshen.leetcode.myUtils.*;
/**
* Each problem is initialized with 3 solutions.
* You can expand more solutions.
* Before using your new solutions, don't forget to register them to the solution registry.
*/
class MaxAreaOfIsland implements Problem {
private Map<Integer,Solution> solutions = new HashMap<>(); // solutions registry
// register solutions HERE...
private MaxAreaOfIsland() {
register(new Solution1());
register(new Solution2());
register(new Solution3());
}
private abstract class Solution {
private int id = 0;
abstract public int maxAreaOfIsland(int[][] grid); // 主方法接口
protected void sometest() { return; } // 预留的一些小测试的接口
}
private class Solution1 extends Solution {
{ super.id = 1; }
private int[] count = new int[0];
private int[] board = new int[0];
private void init(int[][] grid) {
int height = grid.length;
int width = grid[0].length;
count = new int[height * width + 1];
board = new int[height * width + 1];
}
public int maxAreaOfIsland(int[][] grid) {
int height = grid.length;
if (height == 0) { return 0; }
int width = grid[0].length;
init(grid);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == 1) {
int posCurr = j+1 + width * i, posLeft = -1, posUpper = -1;
create(posCurr);
if (j > 0 && grid[i][j-1] == 1) {
posLeft = j + width * i;
merge(posCurr,posLeft); // 当前树嫁接到左树
}
if (i > 0 && grid[i-1][j] == 1) {
posUpper = j+1 + width * (i-1);
merge(posCurr,posUpper); // 当前树嫁接到上树
}
}
}
}
int max = 0;
for (int i = 0; i < count.length; i++) {
max = Math.max(max,count[i]);
}
// System.out.println(Arrays.toString(count));
// System.out.println(Arrays.toString(board));
return max;
}
private void create(int pos) {
board[pos] = pos;
count[pos] = 1;
}
private int find(int pos) {
if (board[pos] == pos) {
return pos;
} else {
int root = find(board[pos]);
board[pos] = root; // path compression
return root;
}
}
// root1嫁接到root2上
private void merge(int pos1, int pos2) {
int root1 = find(pos1);
int root2 = find(pos2);
if (root1 != root2) {
board[root1] = board[root2];
// System.out.println("Merge Group " + root1 + " to Group " + root2);
// System.out.println(count[root1] + " members from Group " + root1 + " merged to Group " + root2 + " with " + count[root2] + " members.");
count[root2] += count[root1];
count[root1] = 0;
}
}
}
private class Solution2 extends Solution {
{ super.id = 2; }
public int maxAreaOfIsland(int[][] grid) {
return 2;
}
}
private class Solution3 extends Solution {
{ super.id = 3; }
public int maxAreaOfIsland(int[][] grid) {
return 3;
}
}
// you can expand more solutions HERE if you want...
/**
* register a solution in the solution registry
* return false if this type of solution already exist in the registry.
*/
private boolean register(Solution s) {
return (solutions.put(s.id,s) == null)? true : false;
}
/**
* chose one of the solution to test
* return null if solution id does not exist
*/
private Solution solution(int id) {
return solutions.get(id);
}
private static class Test {
private MaxAreaOfIsland problem = new MaxAreaOfIsland();
private Solution solution = null;
// call method in solution
private void call(int[][] grid, int ans) {
Matrix.print(grid);
System.out.println("Max Area = " + solution.maxAreaOfIsland(grid) + "\t [Answer: " + ans + "]\n");
}
// public API of Test interface
public void test(int id) {
solution = problem.solution(id);
if (solution == null) { System.out.println("Sorry, [id:" + id + "] doesn't exist!"); return; }
System.out.println("\nCall Solution" + solution.id);
/** initialize your testcases HERE... */
int[][] grid1 = new int[][]{
{0,0,1,0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,1,1,0,1,0,0,0,0,0,0,0,0},
{0,1,0,0,1,1,0,0,1,0,1,0,0},
{0,1,0,0,1,1,0,0,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,1,1,0,0,0,0}
};
int ans1 = 6;
int[][] grid2 = new int[][] {
{1,1,0,0,0},
{1,1,0,0,0},
{0,0,0,1,1},
{0,0,0,1,1}
};
int ans2 = 4;
/** involk call() method HERE */
call(grid1,ans1);
call(grid2,ans2);
}
}
public static void main(String[] args) {
Test test = new Test();
test.test(1);
// test.test(2);
// test.test(3);
}
}
|
[
"symantec__@hotmail.com"
] |
symantec__@hotmail.com
|
dcffefa9a45342cbc812c1be0ea7b8c0fccb550f
|
eb2d7a70f5cf06ece65c3621a61f5d7a250cf277
|
/src/main/java/bitoflife/chatterbean/aiml/Em.java
|
499f255aa73ba7f3338ef125bbc2b9db2778b09d
|
[
"Apache-2.0"
] |
permissive
|
daicx/alice-bot-cn
|
6115f6cd71a7f7fe8ceeca708b83c4e8561b4553
|
3b86605f1aaaeb209fb8e6bdb72acd28830790be
|
refs/heads/master
| 2020-07-16T17:30:24.426115
| 2019-12-17T02:42:07
| 2019-12-17T02:42:07
| 205,832,823
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 363
|
java
|
package bitoflife.chatterbean.aiml;
import bitoflife.chatterbean.Match;
import org.xml.sax.Attributes;
public class Em extends TemplateElement
{
/*
Constructors
*/
public Em(Attributes attributes)
{
}
public Em(Object... children)
{
super(children);
}
/*
Methods
*/
public String process(Match match)
{
return "";
}
}
|
[
"807404400@qq.com"
] |
807404400@qq.com
|
7dacb4c9f86000cdc14a5f5789f011b34663cc5b
|
17999f59adae137d2a9366e3db2a8a91b8509fca
|
/src/main/java/org/killbill/billing/plugin/adyen/client/payment/builder/ModificationRequestBuilder.java
|
597c208a8fb293fdb42345a33320c21ce88cd633
|
[
"Apache-2.0"
] |
permissive
|
BLangendorf/killbill-adyen-plugin
|
731016e8294824cdf5163cbdf0e7910715d38ef3
|
fcae848332f1ddfafed6a0586b7f0cd6e0a7dda0
|
refs/heads/master
| 2021-01-18T13:10:15.438166
| 2016-03-01T22:29:37
| 2016-03-01T22:29:37
| 39,011,192
| 0
| 0
| null | 2015-07-13T12:38:32
| 2015-07-13T12:38:31
| null |
UTF-8
|
Java
| false
| false
| 2,626
|
java
|
/*
* Copyright 2014 Groupon, Inc
*
* Groupon licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.plugin.adyen.client.payment.builder;
import java.util.List;
import org.killbill.adyen.common.Amount;
import org.killbill.adyen.payment.AnyType2AnyTypeMap;
import org.killbill.adyen.payment.ModificationRequest;
import org.killbill.billing.plugin.adyen.client.model.SplitSettlementData;
public class ModificationRequestBuilder extends RequestBuilder<ModificationRequest> {
public ModificationRequestBuilder() {
super(new ModificationRequest());
}
public ModificationRequestBuilder withOriginalReference(final String value) {
request.setOriginalReference(value);
return this;
}
public ModificationRequestBuilder withMerchantAccount(final String value) {
request.setMerchantAccount(value);
return this;
}
public ModificationRequestBuilder withAuthorisationCode(final String value) {
request.setAuthorisationCode(value);
return this;
}
public ModificationRequestBuilder withAmount(final String currency, final Long value) {
if (value != null) {
final Amount amount = new Amount();
amount.setCurrency(currency);
amount.setValue(value);
return withAmount(amount);
}
return this;
}
public ModificationRequestBuilder withAmount(final Amount amount) {
request.setModificationAmount(amount);
return this;
}
public ModificationRequestBuilder withSplitSettlementData(final SplitSettlementData splitSettlementData) {
final List<AnyType2AnyTypeMap.Entry> entries = new SplitSettlementParamsBuilder().createEntriesFrom(splitSettlementData);
addAdditionalData(entries);
return this;
}
@Override
protected List<AnyType2AnyTypeMap.Entry> getAdditionalData() {
if (request.getAdditionalData() == null) {
request.setAdditionalData(new AnyType2AnyTypeMap());
}
return request.getAdditionalData().getEntry();
}
}
|
[
"pierre@mouraf.org"
] |
pierre@mouraf.org
|
cc8c4aa8c70d47e3dbbb88bea5cfcfb216aefded
|
7dfb1538fd074b79a0f6a62674d4979c7c55fd6d
|
/src/day35/StringToIntegerparsing.java
|
7d3b678f663d9ab25e905c95c9c8682a55524c6a
|
[] |
no_license
|
kutluduman/Java-Programming
|
424a4ad92e14f2d4cc700c8a9352ff7408aa993f
|
d55b8a61ab3a654f954e33db1cb244e36bbcc7da
|
refs/heads/master
| 2022-04-18T03:54:50.219846
| 2020-04-18T05:45:45
| 2020-04-18T05:45:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,753
|
java
|
package day35;
public class StringToIntegerparsing {
public static void main(String[] args) {
/**
* I have a employee ID : "FB-457"
* give me the employee number and store it into a number
*/
// String strNum = "100";
// int num = Integer.parseInt(strNum);
//
// System.out.println("num = " + num);
//
// String empID = "FB-457";
// int empID = Integer.parseInt(empID);
/**
* Integer class is class coming from java.lang package
* It's primarily used for wrapping up primitive value and treat it object
* what we will focus here i s though
* many useful static methods it provide already
* parseInt is a static method of Integer class
* It will turn a String that has only numbers and return int result
* if we have any non-numerical character ---> It will throw NumberFormatException
*/
// String[] empIDSplit = empID.s("-");
// String idStr = IDSplit[1];
// int id = Integer.parseInt(idStr);
//
// System.out.println("id = " + id);
// I have a String called twoNumbers
String twoNumbers = "100,600";
// I want to add them and give the result
String[] twoNumbersSplit = twoNumbers.split(",");
int num1 = Integer.parseInt(twoNumbersSplit[0]);
int num2 = Integer.parseInt(twoNumbersSplit[1]);
int sum = num1 + num2;
System.out.println("sum = " + sum);
int num1_1 = Integer.valueOf(twoNumbers.substring(0,3)) ;
int num2_1= Integer.valueOf(twoNumbers.substring(4));
int sum_1 = num1_1+num2_1;
System.out.println("sum_1 = " + sum_1);
}
}
|
[
"58450274+kutluduman@users.noreply.github.com"
] |
58450274+kutluduman@users.noreply.github.com
|
40f0f74281bd65c68490ffe80c3fa3b897abb2e1
|
ec9d221cea6eac53d902970149fda556ab457ca3
|
/src/main/java/com/orasystems/libs/utils/preferences/PreferencesUtil.java
|
07319e6ae0b268177d8d94ff7f2cad0535d81f35
|
[] |
no_license
|
orasystems/OrasystemsUtilLibrary
|
528696e6015cec8564d2a45e53baa3edb9c73943
|
61913851c3e53b0f4d8a43ba47009f2061e6b33b
|
refs/heads/master
| 2021-01-10T05:58:16.052064
| 2016-02-25T14:34:58
| 2016-02-25T14:34:58
| 52,529,795
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 521
|
java
|
package com.orasystems.libs.utils.preferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class PreferencesUtil {
public static SharedPreferences.Editor getPrefEditor(Context context){
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
return preference.edit();
}
public static SharedPreferences getPref(Context context){
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
|
[
"alan.echer@gmail.com"
] |
alan.echer@gmail.com
|
51ecc5071568c7183d9ec9ab538d2121f4be5b95
|
f4762a908e49f7aaa177378c2ebdf7b985180e2b
|
/sources/android/support/constraint/solver/Cache.java
|
355eee08d6a474708838500be9f5b4cbc8783ae6
|
[
"MIT"
] |
permissive
|
PixalTeam/receiver_android
|
76f5b0a7a8c54d83e49ad5921f640842547a171f
|
d4aa75f9021a66262a9a267edd5bc25509677248
|
refs/heads/master
| 2020-12-03T08:49:57.484377
| 2020-01-01T20:38:04
| 2020-01-01T20:38:04
| 231,260,295
| 0
| 0
|
MIT
| 2020-11-15T12:46:40
| 2020-01-01T20:25:18
|
Java
|
UTF-8
|
Java
| false
| false
| 254
|
java
|
package android.support.constraint.solver;
public class Cache {
Pool<ArrayRow> arrayRowPool = new SimplePool(256);
SolverVariable[] mIndexedVariables = new SolverVariable[32];
Pool<SolverVariable> solverVariablePool = new SimplePool(256);
}
|
[
"34947108+Gumbraise@users.noreply.github.com"
] |
34947108+Gumbraise@users.noreply.github.com
|
833b773af07f452e878aafe78760534b21e0440b
|
9399d8807299c10505472903f4836913c78f4fa8
|
/app/src/main/java/com/example/jackle91/myposservice/CreateTicket.java
|
7a1a0e7a8a7857dcc319b8806620f10591588dfe
|
[] |
no_license
|
jackle991/MyPOSservice
|
97244af36cf376a0c2b1941b3b1793d2ba7bdb3f
|
d9a30b44062f3c4d2d367b981ac7e414d462ed73
|
refs/heads/master
| 2022-12-12T22:42:14.522267
| 2020-09-02T20:31:00
| 2020-09-02T20:31:00
| 291,882,124
| 0
| 0
| null | 2020-09-01T18:46:08
| 2020-09-01T03:04:57
|
Java
|
UTF-8
|
Java
| false
| false
| 3,470
|
java
|
package com.example.jackle91.myposservice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.jackle91.myposservice.R;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class CreateTicket extends AppCompatActivity {
TextView responseText;
EditText ticketNumberText;
EditText storeIdText;
EditText businessDateText;
EditText totalPriceText;
Button submitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_ticket);
responseText = findViewById(R.id.responseText);
ticketNumberText = (EditText)findViewById(R.id.ticketNumber);
storeIdText = (EditText)findViewById(R.id.storeId);
businessDateText = (EditText)findViewById(R.id.businessDate);
totalPriceText = (EditText)findViewById(R.id.totalPrice);
submitButton = (Button)findViewById(R.id.submitButton);
// Log.i("****ticketNumber**** ", ticketNumberText.getText().toString());
// Log.i("****StoreID**** ", storeIdText.getText().toString());
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ticketNumber = ticketNumberText.getText().toString();
String storeId = storeIdText.getText().toString();
String businessDate = businessDateText.getText().toString();
String totalPrice = totalPriceText.getText().toString();
// System.out.println("****ticketNumber**** " + ticketNumber);
// System.out.println("****StoreId**** " + storeId);
// System.out.println("****BusinessDate**** " + businessDate);
// System.out.println("****TotalPrice**** " + totalPrice);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.28:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
TicketApi ticketApi = retrofit.create(TicketApi.class);
Ticket ticket = new Ticket(ticketNumber, storeId, businessDate, totalPrice);
Call<Ticket> call = ticketApi.postTicket(ticket);
call.enqueue(new Callback<Ticket>() {
@Override
public void onResponse(Call<Ticket> call, Response<Ticket> response) {
if (!response.isSuccessful()) {
responseText.setText("Code: " + response.code());
// responseText.setText("Code: " + ticketNumberText.getText().toString());
return;
}
// Ticket t = response.body();
responseText.setText("Ticket Created Successful");
}
@Override
public void onFailure(Call<Ticket> call, Throwable t) {
responseText.setText(t.getMessage());
}
});
}
});
}
}
|
[
"hieu6@gatech.edu"
] |
hieu6@gatech.edu
|
ddb433af9a97c18f6bf05ae9d8cee26e8e7378a0
|
788c95f6c757e8e01b8b8f51bda68f770e15689c
|
/src/com/moviesite/hibernate/entity/Review.java
|
d98c32d76bc0f26544daeda8ae06ffa8cb4053a8
|
[] |
no_license
|
methmal1997/HIbernate
|
ec6ca430204afbef4480fe369fa5a43e0c5fed19
|
5f6f733b224b3f6edd209b9e5292a5ecb356eb41
|
refs/heads/main
| 2023-07-05T17:17:18.305098
| 2021-08-23T15:07:07
| 2021-08-23T15:07:07
| 399,141,112
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,344
|
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.moviesite.hibernate.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
/**
*
* @author ASUS
*/
@Entity
public class Review implements Serializable {
private int idreview;
private int rate;
private Purchased purchased;
private Date rateDate;
private String discription;
private Movie movie;
public Review() {
}
public Review(int rate, String discription, Movie movie) {
this.rate = rate;
this.discription = discription;
this.movie = movie;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
@ManyToOne
@JoinColumn(name = "Id")
public Purchased getPurchased() {
return purchased;
}
public void setPurchased(Purchased purchased) {
this.purchased = purchased;
}
@Temporal(javax.persistence.TemporalType.DATE)
public Date getRateDate() {
return rateDate;
}
public void setRateDate(Date rateDate) {
this.rateDate = rateDate;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="MovieId")
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getIdreview() {
return idreview;
}
public void setIdreview(int idreview) {
this.idreview = idreview;
}
}
|
[
"methmaludan@gmail.com"
] |
methmaludan@gmail.com
|
4d6d7f9487f46b4e645c5f82c55ebb80f58e906a
|
21d2cee9c448e466092559501900b32a96ce9748
|
/edu.uci.isr.bna4/src/edu/uci/isr/bna4/things/labels/BoxedLabelThingPeer.java
|
bdf7288ba54a4cd7b5701c76b9465d5df4b36404
|
[] |
no_license
|
zheng3/AS
|
aa89acf9dc260442dee6b9816e2c5e9ecf001324
|
9549eb811fc0e1ff6bade062a933485edb919e4d
|
refs/heads/master
| 2020-05-19T21:56:26.979488
| 2015-07-01T12:19:41
| 2015-07-01T12:19:41
| 38,369,692
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,450
|
java
|
package edu.uci.isr.bna4.things.labels;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.TextLayout;
import edu.uci.isr.bna4.AbstractThingPeer;
import edu.uci.isr.bna4.BNAUtils;
import edu.uci.isr.bna4.IBNAView;
import edu.uci.isr.bna4.IThing;
import edu.uci.isr.bna4.ResourceUtils;
import edu.uci.isr.widgets.swt.constants.FontStyle;
import edu.uci.isr.widgets.swt.constants.HorizontalAlignment;
import edu.uci.isr.widgets.swt.constants.VerticalAlignment;
public class BoxedLabelThingPeer
extends AbstractThingPeer{
protected BoxedLabelThing t;
protected TextLayoutCache textLayoutCache = null;
public BoxedLabelThingPeer(IThing t){
super(t);
if(!(t instanceof BoxedLabelThing)){
throw new IllegalArgumentException("BoxedLabelThingPeer can only peer for BoxedLabelThing");
}
this.t = (BoxedLabelThing)t;
}
@Override
public void draw(IBNAView view, GC g){
Rectangle localBoundingBox = BNAUtils.worldToLocal(view.getCoordinateMapper(), BNAUtils.normalizeRectangle(t.getBoundingBox()));
if(!g.getClipping().intersects(localBoundingBox)){
return;
}
String text = t.getText();
if(text == null || text.trim().length() == 0){
return;
}
Color fg = ResourceUtils.getColor(getDisplay(), t.getColor());
if(fg == null){
fg = g.getDevice().getSystemColor(SWT.COLOR_BLACK);
}
g.setForeground(fg);
String fontName = t.getFontName();
int fontSize = t.getFontSize();
FontStyle fontStyle = t.getFontStyle();
boolean dontIncreaseFontSize = t.getDontIncreaseFontSize();
VerticalAlignment verticalAlignment = t.getVerticalAlignment();
HorizontalAlignment horizontalAlignment = t.getHorizontalAlignment();
if(textLayoutCache == null){
textLayoutCache = new TextLayoutCache(getDisplay());
}
textLayoutCache.setIncreaseFontSize(!dontIncreaseFontSize);
textLayoutCache.setText(text);
textLayoutCache.setFont(ResourceUtils.getFont(getDisplay(), fontName, fontSize, fontStyle));
{
/*
* The size of the local bounding box may differ slightly depending
* on the world origin. This causes excessive recalculation of the
* text layout, which is not really necessary. To overcome this, the
* width and height of the layout are only changed if they differ
* significantly from what they were before.
*/
Point oldSize = textLayoutCache.getSize();
Point size = new Point(localBoundingBox.width, localBoundingBox.height);
int dx = size.x - oldSize.x;
int dy = size.y - oldSize.y;
if(0 <= dx && dx <= 1 && 0 <= dy && dy <= 1){
size = oldSize;
}
textLayoutCache.setSize(size);
}
textLayoutCache.setAlignment(horizontalAlignment.toSWT());
TextLayout tl = textLayoutCache.getTextLayout();
if(tl != null){
Rectangle tlBounds = tl.getBounds();
int x = localBoundingBox.x;
switch(horizontalAlignment){
case LEFT:
break;
case CENTER:
x += (localBoundingBox.width - tlBounds.width) / 2;
break;
case RIGHT:
x += localBoundingBox.width - tlBounds.width;
break;
}
int y = localBoundingBox.y;
switch(verticalAlignment){
case TOP:
break;
case MIDDLE:
y += (localBoundingBox.height - tlBounds.height) / 2;
break;
case BOTTOM:
y += localBoundingBox.height - tlBounds.height;
break;
}
tl.draw(g, x, y);
}
else{
drawFakeLines(g, localBoundingBox);
}
}
private void drawFakeLines(GC g, Rectangle localBoundingBox){
g.setLineStyle(SWT.LINE_DASHDOT);
if(localBoundingBox.width >= 3){
if(localBoundingBox.height >= 1){
int y = localBoundingBox.y + localBoundingBox.height / 2;
g.drawLine(localBoundingBox.x + 1, y, localBoundingBox.x + localBoundingBox.width - 2, y);
}
if(localBoundingBox.height > 5){
int y = localBoundingBox.y + localBoundingBox.height / 2 - 2;
g.drawLine(localBoundingBox.x + 1, y, localBoundingBox.x + localBoundingBox.width - 2, y);
y += 4;
g.drawLine(localBoundingBox.x + 1, y, localBoundingBox.x + localBoundingBox.width - 2, y);
}
}
}
@Override
public boolean isInThing(IBNAView view, int worldX, int worldY){
return BNAUtils.isWithin(t.getBoundingBox(), worldX, worldY);
}
}
|
[
"zheng3@Yongjies-MacBook-Pro-2.local"
] |
zheng3@Yongjies-MacBook-Pro-2.local
|
ecdc3d2a215a3fd8b5dcb0dbb55709f61c14b753
|
dc79d4747f95827dad5519554a77bc597de05cc5
|
/app/src/main/java/com/tao/xiaoyuanyuan/view/colorpicker/builder/PaintBuilder.java
|
90b2a86e81a44eb110765dc4ff35a47534c953c3
|
[] |
no_license
|
lt594963425/xiaoyuanyuan2
|
46247076caff88ff2fc18367a0a335c6dc727ea6
|
108b8cfc0c6f50262d3c436e5c77730e00f76397
|
refs/heads/master
| 2021-07-22T00:32:38.875787
| 2020-07-30T10:01:04
| 2020-07-30T10:01:04
| 202,462,807
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,645
|
java
|
package com.tao.xiaoyuanyuan.view.colorpicker.builder;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
/**
* @author vondear
* @date 2018/6/11 11:36:40 整合修改
*/
public class PaintBuilder {
public static PaintHolder newPaint() {
return new PaintHolder();
}
public static Shader createAlphaPatternShader(int size) {
size /= 2;
size = Math.max(8, size * 2);
return new BitmapShader(createAlphaBackgroundPattern(size), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
}
private static Bitmap createAlphaBackgroundPattern(int size) {
Paint alphaPatternPaint = PaintBuilder.newPaint().build();
Bitmap bm = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
int s = Math.round(size / 2f);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if ((i + j) % 2 == 0) {
alphaPatternPaint.setColor(0xffffffff);
} else {
alphaPatternPaint.setColor(0xffd0d0d0);
}
c.drawRect(i * s, j * s, (i + 1) * s, (j + 1) * s, alphaPatternPaint);
}
}
return bm;
}
public static class PaintHolder {
private Paint paint;
private PaintHolder() {
this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
public PaintHolder color(int color) {
this.paint.setColor(color);
return this;
}
public PaintHolder antiAlias(boolean flag) {
this.paint.setAntiAlias(flag);
return this;
}
public PaintHolder style(Paint.Style style) {
this.paint.setStyle(style);
return this;
}
public PaintHolder mode(PorterDuff.Mode mode) {
this.paint.setXfermode(new PorterDuffXfermode(mode));
return this;
}
public PaintHolder stroke(float width) {
this.paint.setStrokeWidth(width);
return this;
}
public PaintHolder xPerMode(PorterDuff.Mode mode) {
this.paint.setXfermode(new PorterDuffXfermode(mode));
return this;
}
public PaintHolder shader(Shader shader) {
this.paint.setShader(shader);
return this;
}
public Paint build() {
return this.paint;
}
}
}
|
[
"594963425@qq.com"
] |
594963425@qq.com
|
eee475a3756f4725773fb3e1d90316b785a86895
|
482bce12fe1566586bffaf618dcb38d0ca5431b7
|
/app/src/test/java/de/triology/universeadm/mail/MailSenderTest.java
|
a8ff73a1d7c7baddf6ae5c85feab76ae491965aa
|
[
"MIT"
] |
permissive
|
cloudogu/usermgt
|
d0868b25e0b4a810e93414e25c51bd3254733a89
|
0e3f88fd9acd52dd6b7718ffd193a0c4c1f74a17
|
refs/heads/develop
| 2023-09-02T16:49:03.096688
| 2023-08-09T10:50:57
| 2023-08-09T10:50:57
| 39,503,636
| 1
| 2
|
MIT
| 2023-09-11T12:28:55
| 2015-07-22T11:59:23
|
Java
|
UTF-8
|
Java
| false
| false
| 3,004
|
java
|
package de.triology.universeadm.mail;
import de.triology.universeadm.configuration.ApplicationConfiguration;
import de.triology.universeadm.user.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import java.io.IOException;
import java.util.ArrayList;
import static org.mockito.Mockito.*;
public class MailSenderTest {
public static final String TEST = "test";
private static final String MAIL_CONTENT = "Willkommen zum Cloudogu Ecosystem!\n" +
"Dies ist ihr Benutzeraccount\n" +
"Benutzername = %s\n" +
"Passwort = %s\n" +
"Bei der ersten Anmeldung müssen sie ihr Passwort ändern\n";
private MailSender.MessageBuilder messageBuilder;
private MailSender.TransportSender transportSender;
private Message message;
private MailSender mailSender;
private ApplicationConfiguration applicationConfig;
private final User user = new User(
"Tester",
"Tester",
"Tes",
"Ter",
"test@test.com",
"temp",
true,
new ArrayList<String>());
@Before
public void setUp() {
this.message = mock(Message.class);
this.messageBuilder = mock(MailSender.MessageBuilder.class);
this.transportSender = mock(MailSender.TransportSender.class);
this.applicationConfig = mock(ApplicationConfiguration.class);
this.mailSender = new MailSender(this.messageBuilder, this.transportSender, this.applicationConfig);
when(this.messageBuilder.build(Matchers.<Session>any())).thenReturn(this.message);
when(applicationConfig.getHost()).thenReturn("postifx");
when(applicationConfig.getPort()).thenReturn("25");
}
@Test
public void sendMailSuccessful() throws MessagingException, IOException {
String content = String.format(MAIL_CONTENT, user.getUsername(), TEST);
this.mailSender.sendMail(TEST, content, user.getMail());
ArgumentCaptor<Multipart> argument = ArgumentCaptor.forClass(Multipart.class);
verify(message).setContent(argument.capture());
String actualMsgBodyContent = argument.getValue().getBodyPart(0).getContent().toString();
Assert.assertEquals(content, actualMsgBodyContent);
verify(this.transportSender, times(1)).send(Matchers.<Message>any());
}
@Test(expected = NullPointerException.class)
public void nullValueInMethodCall() throws MessagingException {
this.mailSender.sendMail(null, null, null);
}
@Test(expected = IllegalArgumentException.class)
public void InvalidMailMethodCall() throws MessagingException {
String content = String.format(MAIL_CONTENT, user.getUsername(), TEST);
this.mailSender.sendMail(TEST, content, TEST);
}
}
|
[
"nico.franzeck@cloudogu.com"
] |
nico.franzeck@cloudogu.com
|
70dec8a8013d710a0031f3a04dfc33f90a962b7a
|
243979a80371e53e57b284d321caa78054fa9eb6
|
/Leyou-item/Leyou-item-service/src/main/java/com/leyou/item/service/SpecificationService.java
|
1ac7ec08bdabf1a0c57a3831da656ab275ad7f4e
|
[] |
no_license
|
ForeverAndy/Reserch_LeYouMarket
|
ee53f9c985f044775e7da1c2f0234f4da4789be9
|
3794bcd2ebb71e60693c5266e314620b66773d23
|
refs/heads/master
| 2022-11-10T06:13:54.375423
| 2020-04-29T10:39:15
| 2020-04-29T10:39:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 725
|
java
|
package com.leyou.item.service;
import com.leyou.item.pojo.Specification;
/**
* @Author: 98050
* Time: 2018-08-14 15:26
* Feature:
*/
public interface SpecificationService {
/**
* 根据category id查询规格参数模板
* @param cid
* @return
*/
Specification queryById(Long cid);
/**
* 添加规格参数模板
* @param specification
*/
void saveSpecification(Specification specification);
/**
* 修改规格参数模板
* @param specification
*/
void updateSpecification(Specification specification);
/**
* 删除规格参数模板
* @param specification
*/
void deleteSpecification(Specification specification);
}
|
[
"332450461@qq.com"
] |
332450461@qq.com
|
551d57817c2688ccae2e599c1b4f160ef8ab6e96
|
ddac11ed921cf1b6a8b4f8eb037ef69fe632b183
|
/src/main/java/org/java/spring/boot/demo/controller/DemoController.java
|
878f0dfd815151b8c8a73e334de6d8b01fa83fb1
|
[] |
no_license
|
a969146049/springTest
|
014b71bc4a5fbaac67f538a4d5cd2580751e1ef3
|
664dc4933bc393cc0fdd2718bae9a013e0fc43a2
|
refs/heads/master
| 2020-03-22T19:57:06.495054
| 2018-07-11T10:40:43
| 2018-07-11T10:40:43
| 140,563,147
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 390
|
java
|
package org.java.spring.boot.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Administrator on 18/7/9.
*/
@RestController
public class DemoController {
@RequestMapping(value = "hi")
public String sayHi(){
return "Hellor Spring Boot";
}
}
|
[
"969146049@qq.com"
] |
969146049@qq.com
|
4fbbf78e2425e5f4dcbef3c6641b225998eae3e7
|
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
|
/eclipsejdt_cluster/16417/src_0.java
|
047c44068b94c2d94ae66dcae3f891e74a70aa9a
|
[] |
no_license
|
martinezmatias/GenPat-data-C3
|
63cfe27efee2946831139747e6c20cf952f1d6f6
|
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
|
refs/heads/master
| 2022-04-25T17:59:03.905613
| 2020-04-15T14:41:34
| 2020-04-15T14:41:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 52,512
|
java
|
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.lookup;
import java.util.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class ClassScope extends Scope {
public TypeDeclaration referenceContext;
public TypeReference superTypeReference;
public ClassScope(Scope parent, TypeDeclaration context) {
super(CLASS_SCOPE, parent);
this.referenceContext = context;
}
void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) {
LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage);
SourceTypeBinding sourceType = referenceContext.binding;
if (supertype.isInterface()) {
sourceType.superclass = getJavaLangObject();
sourceType.superInterfaces = new ReferenceBinding[] { supertype };
} else {
sourceType.superclass = supertype;
sourceType.superInterfaces = Binding.NO_SUPERINTERFACES;
}
connectMemberTypes();
buildFieldsAndMethods();
anonymousType.faultInTypesForFieldsAndMethods();
sourceType.verifyMethods(environment().methodVerifier());
}
private void buildFields() {
if (referenceContext.fields == null) {
referenceContext.binding.setFields(Binding.NO_FIELDS);
return;
}
// count the number of fields vs. initializers
FieldDeclaration[] fields = referenceContext.fields;
int size = fields.length;
int count = 0;
for (int i = 0; i < size; i++) {
switch (fields[i].getKind()) {
case AbstractVariableDeclaration.FIELD:
case AbstractVariableDeclaration.ENUM_CONSTANT:
count++;
}
}
// iterate the field declarations to create the bindings, lose all duplicates
FieldBinding[] fieldBindings = new FieldBinding[count];
HashtableOfObject knownFieldNames = new HashtableOfObject(count);
boolean duplicate = false;
count = 0;
for (int i = 0; i < size; i++) {
FieldDeclaration field = fields[i];
if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
if (referenceContext.binding.isInterface())
problemReporter().interfaceCannotHaveInitializers(referenceContext.binding, field);
} else {
FieldBinding fieldBinding = new FieldBinding(field, null, field.modifiers | ExtraCompilerModifiers.AccUnresolved, referenceContext.binding);
fieldBinding.id = count;
// field's type will be resolved when needed for top level types
checkAndSetModifiersForField(fieldBinding, field);
if (knownFieldNames.containsKey(field.name)) {
duplicate = true;
FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(field.name);
if (previousBinding != null) {
for (int f = 0; f < i; f++) {
FieldDeclaration previousField = fields[f];
if (previousField.binding == previousBinding) {
problemReporter().duplicateFieldInType(referenceContext.binding, previousField);
previousField.binding = null;
break;
}
}
}
knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed
problemReporter().duplicateFieldInType(referenceContext.binding, field);
field.binding = null;
} else {
knownFieldNames.put(field.name, fieldBinding);
// remember that we have seen a field with this name
if (fieldBinding != null)
fieldBindings[count++] = fieldBinding;
}
}
}
// remove duplicate fields
if (duplicate) {
FieldBinding[] newFieldBindings = new FieldBinding[fieldBindings.length];
// we know we'll be removing at least 1 duplicate name
size = count;
count = 0;
for (int i = 0; i < size; i++) {
FieldBinding fieldBinding = fieldBindings[i];
if (knownFieldNames.get(fieldBinding.name) != null) {
fieldBinding.id = count;
newFieldBindings[count++] = fieldBinding;
}
}
fieldBindings = newFieldBindings;
}
if (count != fieldBindings.length)
System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count);
referenceContext.binding.setFields(fieldBindings);
}
void buildFieldsAndMethods() {
buildFields();
buildMethods();
SourceTypeBinding sourceType = referenceContext.binding;
if (sourceType.isMemberType() && !sourceType.isLocalType())
((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields();
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++)
((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods();
}
private LocalTypeBinding buildLocalType(SourceTypeBinding enclosingType, PackageBinding packageBinding) {
referenceContext.scope = this;
referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
// build the binding or the local type
LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType, this.innermostSwitchCase());
referenceContext.binding = localType;
checkAndSetModifiers();
buildTypeVariables();
// Look at member types
ReferenceBinding[] memberTypeBindings = Binding.NO_MEMBER_TYPES;
if (referenceContext.memberTypes != null) {
int size = referenceContext.memberTypes.length;
memberTypeBindings = new ReferenceBinding[size];
int count = 0;
nextMember : for (int i = 0; i < size; i++) {
TypeDeclaration memberContext = referenceContext.memberTypes[i];
switch(TypeDeclaration.kind(memberContext.modifiers)) {
case TypeDeclaration.INTERFACE_DECL :
case TypeDeclaration.ANNOTATION_TYPE_DECL :
problemReporter().illegalLocalTypeDeclaration(memberContext);
continue nextMember;
}
ReferenceBinding type = localType;
// check that the member does not conflict with an enclosing type
do {
if (CharOperation.equals(type.sourceName, memberContext.name)) {
problemReporter().hidingEnclosingType(memberContext);
continue nextMember;
}
type = type.enclosingType();
} while (type != null);
// check the member type does not conflict with another sibling member type
for (int j = 0; j < i; j++) {
if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
problemReporter().duplicateNestedType(memberContext);
continue nextMember;
}
}
ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]);
LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding);
memberBinding.setAsMemberType();
memberTypeBindings[count++] = memberBinding;
}
if (count != size)
System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
}
localType.memberTypes = memberTypeBindings;
return localType;
}
void buildLocalTypeBinding(SourceTypeBinding enclosingType) {
LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage);
connectTypeHierarchy();
buildFieldsAndMethods();
localType.faultInTypesForFieldsAndMethods();
referenceContext.binding.verifyMethods(environment().methodVerifier());
}
private void buildMemberTypes(AccessRestriction accessRestriction) {
SourceTypeBinding sourceType = referenceContext.binding;
ReferenceBinding[] memberTypeBindings = Binding.NO_MEMBER_TYPES;
if (referenceContext.memberTypes != null) {
int length = referenceContext.memberTypes.length;
memberTypeBindings = new ReferenceBinding[length];
int count = 0;
nextMember : for (int i = 0; i < length; i++) {
TypeDeclaration memberContext = referenceContext.memberTypes[i];
switch(TypeDeclaration.kind(memberContext.modifiers)) {
case TypeDeclaration.INTERFACE_DECL :
case TypeDeclaration.ANNOTATION_TYPE_DECL :
if (sourceType.isNestedType()
&& sourceType.isClass() // no need to check for enum, since implicitly static
&& !sourceType.isStatic()) {
problemReporter().illegalLocalTypeDeclaration(memberContext);
continue nextMember;
}
break;
}
ReferenceBinding type = sourceType;
// check that the member does not conflict with an enclosing type
do {
if (CharOperation.equals(type.sourceName, memberContext.name)) {
problemReporter().hidingEnclosingType(memberContext);
continue nextMember;
}
type = type.enclosingType();
} while (type != null);
// check that the member type does not conflict with another sibling member type
for (int j = 0; j < i; j++) {
if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
problemReporter().duplicateNestedType(memberContext);
continue nextMember;
}
}
ClassScope memberScope = new ClassScope(this, memberContext);
memberTypeBindings[count++] = memberScope.buildType(sourceType, sourceType.fPackage, accessRestriction);
}
if (count != length)
System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
}
sourceType.memberTypes = memberTypeBindings;
}
private void buildMethods() {
boolean isEnum = TypeDeclaration.kind(referenceContext.modifiers) == TypeDeclaration.ENUM_DECL;
if (referenceContext.methods == null && !isEnum) {
referenceContext.binding.setMethods(Binding.NO_METHODS);
return;
}
// iterate the method declarations to create the bindings
AbstractMethodDeclaration[] methods = referenceContext.methods;
int size = methods == null ? 0 : methods.length;
// look for <clinit> method
int clinitIndex = -1;
for (int i = 0; i < size; i++) {
if (methods[i].isClinit()) {
clinitIndex = i;
break;
}
}
int count = isEnum ? 2 : 0; // reserve 2 slots for special enum methods: #values() and #valueOf(String)
MethodBinding[] methodBindings = new MethodBinding[(clinitIndex == -1 ? size : size - 1) + count];
// create special methods for enums
SourceTypeBinding sourceType = referenceContext.binding;
if (isEnum) {
methodBindings[0] = sourceType.addSyntheticEnumMethod(TypeConstants.VALUES); // add <EnumType>[] values()
methodBindings[1] = sourceType.addSyntheticEnumMethod(TypeConstants.VALUEOF); // add <EnumType> valueOf()
}
// create bindings for source methods
for (int i = 0; i < size; i++) {
if (i != clinitIndex) {
MethodScope scope = new MethodScope(this, methods[i], false);
MethodBinding methodBinding = scope.createMethod(methods[i]);
if (methodBinding != null) // is null if binding could not be created
methodBindings[count++] = methodBinding;
}
}
if (count != methodBindings.length)
System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count);
sourceType.tagBits &= ~TagBits.AreMethodsSorted; // in case some static imports reached already into this type
sourceType.setMethods(methodBindings);
}
SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
// provide the typeDeclaration with needed scopes
referenceContext.scope = this;
referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
if (enclosingType == null) {
char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name);
referenceContext.binding = new SourceTypeBinding(className, packageBinding, this);
} else {
char[][] className = CharOperation.deepCopy(enclosingType.compoundName);
className[className.length - 1] =
CharOperation.concat(className[className.length - 1], referenceContext.name, '$');
referenceContext.binding = new MemberTypeBinding(className, this, enclosingType);
}
SourceTypeBinding sourceType = referenceContext.binding;
environment().setAccessRestriction(sourceType, accessRestriction);
sourceType.fPackage.addType(sourceType);
checkAndSetModifiers();
buildTypeVariables();
buildMemberTypes(accessRestriction);
return sourceType;
}
private void buildTypeVariables() {
SourceTypeBinding sourceType = referenceContext.binding;
TypeParameter[] typeParameters = referenceContext.typeParameters;
// do not construct type variables if source < 1.5
if (typeParameters == null || compilerOptions().sourceLevel < ClassFileConstants.JDK1_5) {
sourceType.typeVariables = Binding.NO_TYPE_VARIABLES;
return;
}
sourceType.typeVariables = Binding.NO_TYPE_VARIABLES; // safety
if (sourceType.id == T_JavaLangObject) { // handle the case of redefining java.lang.Object up front
problemReporter().objectCannotBeGeneric(referenceContext);
return;
}
sourceType.typeVariables = createTypeVariables(typeParameters, sourceType);
sourceType.modifiers |= ExtraCompilerModifiers.AccGenericSignature;
}
private void checkAndSetModifiers() {
SourceTypeBinding sourceType = referenceContext.binding;
int modifiers = sourceType.modifiers;
if ((modifiers & ExtraCompilerModifiers.AccAlternateModifierProblem) != 0)
problemReporter().duplicateModifierForType(sourceType);
ReferenceBinding enclosingType = sourceType.enclosingType();
boolean isMemberType = sourceType.isMemberType();
if (isMemberType) {
modifiers |= (enclosingType.modifiers & (ExtraCompilerModifiers.AccGenericSignature|ClassFileConstants.AccStrictfp));
// checks for member types before local types to catch local members
if (enclosingType.isInterface())
modifiers |= ClassFileConstants.AccPublic;
if (sourceType.isEnum()) {
if (!enclosingType.isStatic())
problemReporter().nonStaticContextForEnumMemberType(sourceType);
else
modifiers |= ClassFileConstants.AccStatic;
}
} else if (sourceType.isLocalType()) {
if (sourceType.isEnum()) {
problemReporter().illegalLocalTypeDeclaration(referenceContext);
sourceType.modifiers = 0;
return;
}
if (sourceType.isAnonymousType()) {
modifiers |= ClassFileConstants.AccFinal;
// set AccEnum flag for anonymous body of enum constants
if (referenceContext.allocation.type == null)
modifiers |= ClassFileConstants.AccEnum;
}
Scope scope = this;
do {
switch (scope.kind) {
case METHOD_SCOPE :
MethodScope methodScope = (MethodScope) scope;
if (methodScope.isInsideInitializer()) {
SourceTypeBinding type = ((TypeDeclaration) methodScope.referenceContext).binding;
// inside field declaration ? check field modifier to see if deprecated
if (methodScope.initializedField != null) {
// currently inside this field initialization
if (methodScope.initializedField.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
} else {
if (type.isStrictfp())
modifiers |= ClassFileConstants.AccStrictfp;
if (type.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
}
} else {
MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding;
if (method != null) {
if (method.isStrictfp())
modifiers |= ClassFileConstants.AccStrictfp;
if (method.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
}
}
break;
case CLASS_SCOPE :
// local member
if (enclosingType.isStrictfp())
modifiers |= ClassFileConstants.AccStrictfp;
if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
break;
}
scope = scope.parent;
} while (scope != null);
}
// after this point, tests on the 16 bits reserved.
int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
if ((realModifiers & ClassFileConstants.AccInterface) != 0) { // interface and annotation type
// detect abnormal cases for interfaces
if (isMemberType) {
final int UNEXPECTED_MODIFIERS =
~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccStatic | ClassFileConstants.AccAbstract | ClassFileConstants.AccInterface | ClassFileConstants.AccStrictfp | ClassFileConstants.AccAnnotation);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0) {
if ((realModifiers & ClassFileConstants.AccAnnotation) != 0)
problemReporter().illegalModifierForAnnotationMemberType(sourceType);
else
problemReporter().illegalModifierForMemberInterface(sourceType);
}
/*
} else if (sourceType.isLocalType()) { //interfaces cannot be defined inside a method
int unexpectedModifiers = ~(AccAbstract | AccInterface | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForLocalInterface(sourceType);
*/
} else {
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract | ClassFileConstants.AccInterface | ClassFileConstants.AccStrictfp | ClassFileConstants.AccAnnotation);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0) {
if ((realModifiers & ClassFileConstants.AccAnnotation) != 0)
problemReporter().illegalModifierForAnnotationType(sourceType);
else
problemReporter().illegalModifierForInterface(sourceType);
}
}
modifiers |= ClassFileConstants.AccAbstract;
} else if ((realModifiers & ClassFileConstants.AccEnum) != 0) {
// detect abnormal cases for enums
if (isMemberType) { // includes member types defined inside local types
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccStatic | ClassFileConstants.AccStrictfp | ClassFileConstants.AccEnum);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForMemberEnum(sourceType);
} else if (sourceType.isLocalType()) { // each enum constant is an anonymous local type
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccStrictfp | ClassFileConstants.AccFinal | ClassFileConstants.AccEnum); // add final since implicitly set for anonymous type
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForLocalEnum(sourceType);
} else {
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccStrictfp | ClassFileConstants.AccEnum);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForEnum(sourceType);
}
// what about inherited interface methods?
if ((referenceContext.bits & ASTNode.HasAbstractMethods) != 0) {
modifiers |= ClassFileConstants.AccAbstract;
} else if (!sourceType.isAnonymousType()) {
// body of enum constant must implement any inherited abstract methods
// enum type needs to implement abstract methods if one of its constants does not supply a body
checkAbstractEnum: {
TypeDeclaration typeDeclaration = this.referenceContext;
FieldDeclaration[] fields = typeDeclaration.fields;
int fieldsLength = fields == null ? 0 : fields.length;
if (fieldsLength == 0) break checkAbstractEnum; // has no constants so must implement the method itself
AbstractMethodDeclaration[] methods = typeDeclaration.methods;
int methodsLength = methods == null ? 0 : methods.length;
// TODO (kent) cannot tell that the superinterfaces are empty or that their methods are implemented
boolean definesAbstractMethod = typeDeclaration.superInterfaces != null;
for (int i = 0; i < methodsLength && !definesAbstractMethod; i++)
definesAbstractMethod = methods[i].isAbstract();
if (!definesAbstractMethod) break checkAbstractEnum; // all methods have bodies
for (int i = 0; i < fieldsLength; i++) {
FieldDeclaration fieldDecl = fields[i];
if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT)
if (!(fieldDecl.initialization instanceof QualifiedAllocationExpression))
break checkAbstractEnum;
}
// tag this enum as abstract since an abstract method must be implemented AND all enum constants define an anonymous body
// as a result, each of its anonymous constants will see it as abstract and must implement each inherited abstract method
modifiers |= ClassFileConstants.AccAbstract;
}
}
modifiers |= ClassFileConstants.AccFinal;
} else {
// detect abnormal cases for classes
if (isMemberType) { // includes member types defined inside local types
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccStatic | ClassFileConstants.AccAbstract | ClassFileConstants.AccFinal | ClassFileConstants.AccStrictfp);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForMemberClass(sourceType);
} else if (sourceType.isLocalType()) {
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccAbstract | ClassFileConstants.AccFinal | ClassFileConstants.AccStrictfp);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForLocalClass(sourceType);
} else {
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract | ClassFileConstants.AccFinal | ClassFileConstants.AccStrictfp);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0)
problemReporter().illegalModifierForClass(sourceType);
}
// check that Final and Abstract are not set together
if ((realModifiers & (ClassFileConstants.AccFinal | ClassFileConstants.AccAbstract)) == (ClassFileConstants.AccFinal | ClassFileConstants.AccAbstract))
problemReporter().illegalModifierCombinationFinalAbstractForClass(sourceType);
}
if (isMemberType) {
// test visibility modifiers inconsistency, isolate the accessors bits
if (enclosingType.isInterface()) {
if ((realModifiers & (ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate)) != 0) {
problemReporter().illegalVisibilityModifierForInterfaceMemberType(sourceType);
// need to keep the less restrictive
if ((realModifiers & ClassFileConstants.AccProtected) != 0)
modifiers &= ~ClassFileConstants.AccProtected;
if ((realModifiers & ClassFileConstants.AccPrivate) != 0)
modifiers &= ~ClassFileConstants.AccPrivate;
}
} else {
int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
if ((accessorBits & (accessorBits - 1)) > 1) {
problemReporter().illegalVisibilityModifierCombinationForMemberType(sourceType);
// need to keep the less restrictive so disable Protected/Private as necessary
if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
if ((accessorBits & ClassFileConstants.AccProtected) != 0)
modifiers &= ~ClassFileConstants.AccProtected;
if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
modifiers &= ~ClassFileConstants.AccPrivate;
} else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
modifiers &= ~ClassFileConstants.AccPrivate;
}
}
}
// static modifier test
if ((realModifiers & ClassFileConstants.AccStatic) == 0) {
if (enclosingType.isInterface())
modifiers |= ClassFileConstants.AccStatic;
} else if (!enclosingType.isStatic()) {
// error the enclosing type of a static field must be static or a top-level type
problemReporter().illegalStaticModifierForMemberType(sourceType);
}
}
sourceType.modifiers = modifiers;
}
/* This method checks the modifiers of a field.
*
* 9.3 & 8.3
* Need to integrate the check for the final modifiers for nested types
*
* Note : A scope is accessible by : fieldBinding.declaringClass.scope
*/
private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) {
int modifiers = fieldBinding.modifiers;
final ReferenceBinding declaringClass = fieldBinding.declaringClass;
if ((modifiers & ExtraCompilerModifiers.AccAlternateModifierProblem) != 0)
problemReporter().duplicateModifierForField(declaringClass, fieldDecl);
if (declaringClass.isInterface()) {
final int IMPLICIT_MODIFIERS = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic | ClassFileConstants.AccFinal;
// set the modifiers
modifiers |= IMPLICIT_MODIFIERS;
// and then check that they are the only ones
if ((modifiers & ExtraCompilerModifiers.AccJustFlag) != IMPLICIT_MODIFIERS) {
if ((declaringClass.modifiers & ClassFileConstants.AccAnnotation) != 0)
problemReporter().illegalModifierForAnnotationField(fieldDecl);
else
problemReporter().illegalModifierForInterfaceField(fieldDecl);
}
fieldBinding.modifiers = modifiers;
return;
} else if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
// check that they are not modifiers in source
if ((modifiers & ExtraCompilerModifiers.AccJustFlag) != 0)
problemReporter().illegalModifierForEnumConstant(declaringClass, fieldDecl);
// set the modifiers
final int IMPLICIT_MODIFIERS = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccEnum;
if (fieldDecl.initialization instanceof QualifiedAllocationExpression)
declaringClass.modifiers &= ~ClassFileConstants.AccFinal;
fieldBinding.modifiers|= IMPLICIT_MODIFIERS;
return;
}
// after this point, tests on the 16 bits reserved.
int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
final int UNEXPECTED_MODIFIERS = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccFinal | ClassFileConstants.AccStatic | ClassFileConstants.AccTransient | ClassFileConstants.AccVolatile);
if ((realModifiers & UNEXPECTED_MODIFIERS) != 0) {
problemReporter().illegalModifierForField(declaringClass, fieldDecl);
modifiers &= ~ExtraCompilerModifiers.AccJustFlag | ~UNEXPECTED_MODIFIERS;
}
int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
if ((accessorBits & (accessorBits - 1)) > 1) {
problemReporter().illegalVisibilityModifierCombinationForField(declaringClass, fieldDecl);
// need to keep the less restrictive so disable Protected/Private as necessary
if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
if ((accessorBits & ClassFileConstants.AccProtected) != 0)
modifiers &= ~ClassFileConstants.AccProtected;
if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
modifiers &= ~ClassFileConstants.AccPrivate;
} else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
modifiers &= ~ClassFileConstants.AccPrivate;
}
}
if ((realModifiers & (ClassFileConstants.AccFinal | ClassFileConstants.AccVolatile)) == (ClassFileConstants.AccFinal | ClassFileConstants.AccVolatile))
problemReporter().illegalModifierCombinationFinalVolatileForField(declaringClass, fieldDecl);
if (fieldDecl.initialization == null && (modifiers & ClassFileConstants.AccFinal) != 0)
modifiers |= ExtraCompilerModifiers.AccBlankFinal;
fieldBinding.modifiers = modifiers;
}
public void checkParameterizedSuperTypeCollisions() {
// check for parameterized interface collisions (when different parameterizations occur)
SourceTypeBinding sourceType = referenceContext.binding;
ReferenceBinding[] interfaces = sourceType.superInterfaces;
int count = interfaces.length;
Map invocations = new HashMap(2);
ReferenceBinding itsSuperclass = sourceType.isInterface() ? null : sourceType.superclass;
nextInterface: for (int i = 0, length = count; i < length; i++) {
ReferenceBinding one = interfaces[i];
if (one == null) continue nextInterface;
if (itsSuperclass != null && hasErasedCandidatesCollisions(itsSuperclass, one, invocations, sourceType, referenceContext)) {
interfaces[i] = null;
count--;
continue nextInterface;
}
nextOtherInterface: for (int j = 0; j < i; j++) {
ReferenceBinding two = interfaces[j];
if (two == null) continue nextOtherInterface;
if (hasErasedCandidatesCollisions(one, two, invocations, sourceType, referenceContext)) {
interfaces[i] = null;
count--;
continue nextInterface;
}
}
}
if (count < interfaces.length) {
if (count == 0) {
sourceType.superInterfaces = Binding.NO_SUPERINTERFACES;
} else {
ReferenceBinding[] newInterfaceBindings = new ReferenceBinding[count];
for (int i = 0, j = 0, l = interfaces.length; i < l; i++)
if (interfaces[i] != null)
newInterfaceBindings[j++] = interfaces[i];
sourceType.superInterfaces = newInterfaceBindings;
}
}
TypeParameter[] typeParameters = this.referenceContext.typeParameters;
nextVariable : for (int i = 0, paramLength = typeParameters == null ? 0 : typeParameters.length; i < paramLength; i++) {
TypeParameter typeParameter = typeParameters[i];
TypeVariableBinding typeVariable = typeParameter.binding;
if (typeVariable == null || !typeVariable.isValidBinding()) continue nextVariable;
TypeReference[] boundRefs = typeParameter.bounds;
if (boundRefs != null) {
boolean checkSuperclass = typeVariable.firstBound == typeVariable.superclass;
for (int j = 0, boundLength = boundRefs.length; j < boundLength; j++) {
TypeReference typeRef = boundRefs[j];
TypeBinding superType = typeRef.resolvedType;
if (superType == null || !superType.isValidBinding()) continue;
// check against superclass
if (checkSuperclass)
if (hasErasedCandidatesCollisions(superType, typeVariable.superclass, invocations, typeVariable, typeRef))
continue nextVariable;
// check against superinterfaces
for (int index = typeVariable.superInterfaces.length; --index >= 0;)
if (hasErasedCandidatesCollisions(superType, typeVariable.superInterfaces[index], invocations, typeVariable, typeRef))
continue nextVariable;
}
}
}
ReferenceBinding[] memberTypes = referenceContext.binding.memberTypes;
if (memberTypes != null && memberTypes != Binding.NO_MEMBER_TYPES)
for (int i = 0, size = memberTypes.length; i < size; i++)
((SourceTypeBinding) memberTypes[i]).scope.checkParameterizedSuperTypeCollisions();
}
private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) {
// search up the hierarchy of the sourceType to see if any superType defines a member type
// when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit
// assumes super types have already been checked & tagged
ReferenceBinding currentType = sourceType;
ReferenceBinding[] interfacesToVisit = null;
int nextPosition = 0;
do {
if (currentType.hasMemberTypes()) // avoid resolving member types eagerly
return;
ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
if (itsInterfaces != Binding.NO_SUPERINTERFACES) {
if (itsInterfaces == null)
return; // in code assist cases when source types are added late, may not be finished connecting hierarchy
if (interfacesToVisit == null) {
interfacesToVisit = itsInterfaces;
nextPosition = interfacesToVisit.length;
} else {
int itsLength = itsInterfaces.length;
if (nextPosition + itsLength >= interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[nextPosition + itsLength + 5], 0, nextPosition);
nextInterface : for (int a = 0; a < itsLength; a++) {
ReferenceBinding next = itsInterfaces[a];
for (int b = 0; b < nextPosition; b++)
if (next == interfacesToVisit[b]) continue nextInterface;
interfacesToVisit[nextPosition++] = next;
}
}
}
} while ((currentType = currentType.superclass()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0);
if (interfacesToVisit != null) {
// contains the interfaces between the sourceType and any superclass, which was tagged as having no member types
boolean needToTag = false;
for (int i = 0; i < nextPosition; i++) {
ReferenceBinding anInterface = interfacesToVisit[i];
if ((anInterface.tagBits & TagBits.HasNoMemberTypes) == 0) { // skip interface if it already knows it has no member types
if (anInterface.hasMemberTypes()) // avoid resolving member types eagerly
return;
needToTag = true;
ReferenceBinding[] itsInterfaces = anInterface.superInterfaces();
if (itsInterfaces != Binding.NO_SUPERINTERFACES) {
int itsLength = itsInterfaces.length;
if (nextPosition + itsLength >= interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[nextPosition + itsLength + 5], 0, nextPosition);
nextInterface : for (int a = 0; a < itsLength; a++) {
ReferenceBinding next = itsInterfaces[a];
for (int b = 0; b < nextPosition; b++)
if (next == interfacesToVisit[b]) continue nextInterface;
interfacesToVisit[nextPosition++] = next;
}
}
}
}
if (needToTag) {
for (int i = 0; i < nextPosition; i++)
interfacesToVisit[i].tagBits |= TagBits.HasNoMemberTypes;
}
}
// tag the sourceType and all of its superclasses, unless they have already been tagged
currentType = sourceType;
do {
currentType.tagBits |= TagBits.HasNoMemberTypes;
} while ((currentType = currentType.superclass()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0);
}
// Perform deferred bound checks for parameterized type references (only done after hierarchy is connected)
public void checkParameterizedTypeBounds() {
TypeReference superclass = referenceContext.superclass;
if (superclass != null)
superclass.checkBounds(this);
TypeReference[] superinterfaces = referenceContext.superInterfaces;
if (superinterfaces != null)
for (int i = 0, length = superinterfaces.length; i < length; i++)
superinterfaces[i].checkBounds(this);
TypeParameter[] typeParameters = referenceContext.typeParameters;
if (typeParameters != null)
for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++)
typeParameters[i].checkBounds(this);
ReferenceBinding[] memberTypes = referenceContext.binding.memberTypes;
if (memberTypes != null && memberTypes != Binding.NO_MEMBER_TYPES)
for (int i = 0, size = memberTypes.length; i < size; i++)
((SourceTypeBinding) memberTypes[i]).scope.checkParameterizedTypeBounds();
}
private void connectMemberTypes() {
SourceTypeBinding sourceType = referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
if (memberTypes != null && memberTypes != Binding.NO_MEMBER_TYPES) {
for (int i = 0, size = memberTypes.length; i < size; i++)
((SourceTypeBinding) memberTypes[i]).scope.connectTypeHierarchy();
}
}
/*
Our current belief based on available JCK tests is:
inherited member types are visible as a potential superclass.
inherited interfaces are not visible when defining a superinterface.
Error recovery story:
ensure the superclass is set to java.lang.Object if a problem is detected
resolving the superclass.
Answer false if an error was reported against the sourceType.
*/
private boolean connectSuperclass() {
SourceTypeBinding sourceType = referenceContext.binding;
if (sourceType.id == T_JavaLangObject) { // handle the case of redefining java.lang.Object up front
sourceType.superclass = null;
sourceType.superInterfaces = Binding.NO_SUPERINTERFACES;
if (!sourceType.isClass())
problemReporter().objectMustBeClass(sourceType);
if (referenceContext.superclass != null || (referenceContext.superInterfaces != null && referenceContext.superInterfaces.length > 0))
problemReporter().objectCannotHaveSuperTypes(sourceType);
return true; // do not propagate Object's hierarchy problems down to every subtype
}
if (referenceContext.superclass == null) {
if (sourceType.isEnum() && compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) // do not connect if source < 1.5 as enum already got flagged as syntax error
return connectEnumSuperclass();
sourceType.superclass = getJavaLangObject();
return !detectHierarchyCycle(sourceType, sourceType.superclass, null);
}
TypeReference superclassRef = referenceContext.superclass;
ReferenceBinding superclass = findSupertype(superclassRef);
if (superclass != null) { // is null if a cycle was detected cycle or a problem
if (!superclass.isClass()) {
problemReporter().superclassMustBeAClass(sourceType, superclassRef, superclass);
} else if (superclass.isFinal()) {
problemReporter().classExtendFinalClass(sourceType, superclassRef, superclass);
} else if ((superclass.tagBits & TagBits.HasDirectWildcard) != 0) {
problemReporter().superTypeCannotUseWildcard(sourceType, superclassRef, superclass);
} else if (superclass.erasure().id == T_JavaLangEnum) {
problemReporter().cannotExtendEnum(sourceType, superclassRef, superclass);
} else {
// only want to reach here when no errors are reported
sourceType.superclass = superclass;
return true;
}
}
sourceType.tagBits |= TagBits.HierarchyHasProblems;
sourceType.superclass = getJavaLangObject();
if ((sourceType.superclass.tagBits & TagBits.BeginHierarchyCheck) == 0)
detectHierarchyCycle(sourceType, sourceType.superclass, null);
return false; // reported some error against the source type
}
/**
* enum X (implicitly) extends Enum<X>
*/
private boolean connectEnumSuperclass() {
SourceTypeBinding sourceType = referenceContext.binding;
ReferenceBinding rootEnumType = getJavaLangEnum();
boolean foundCycle = detectHierarchyCycle(sourceType, rootEnumType, null);
// arity check for well-known Enum<E>
TypeVariableBinding[] refTypeVariables = rootEnumType.typeVariables();
if (refTypeVariables == Binding.NO_TYPE_VARIABLES) { // check generic
problemReporter().nonGenericTypeCannotBeParameterized(null, rootEnumType, new TypeBinding[]{ sourceType });
return false; // cannot reach here as AbortCompilation is thrown
} else if (1 != refTypeVariables.length) { // check arity
problemReporter().incorrectArityForParameterizedType(null, rootEnumType, new TypeBinding[]{ sourceType });
return false; // cannot reach here as AbortCompilation is thrown
}
// check argument type compatibility
ParameterizedTypeBinding superType = environment().createParameterizedType(rootEnumType, new TypeBinding[]{ environment().convertToRawType(sourceType) } , null);
sourceType.superclass = superType;
// bound check (in case of bogus definition of Enum type)
if (refTypeVariables[0].boundCheck(superType, sourceType) != TypeConstants.OK) {
problemReporter().typeMismatchError(rootEnumType, refTypeVariables[0], sourceType, null);
}
return !foundCycle;
}
/*
Our current belief based on available JCK 1.3 tests is:
inherited member types are visible as a potential superclass.
inherited interfaces are visible when defining a superinterface.
Error recovery story:
ensure the superinterfaces contain only valid visible interfaces.
Answer false if an error was reported against the sourceType.
*/
private boolean connectSuperInterfaces() {
SourceTypeBinding sourceType = referenceContext.binding;
sourceType.superInterfaces = Binding.NO_SUPERINTERFACES;
if (referenceContext.superInterfaces == null) {
if (sourceType.isAnnotationType() && compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) { // do not connect if source < 1.5 as annotation already got flagged as syntax error) {
ReferenceBinding annotationType = getJavaLangAnnotationAnnotation();
boolean foundCycle = detectHierarchyCycle(sourceType, annotationType, null);
sourceType.superInterfaces = new ReferenceBinding[] { annotationType };
return !foundCycle;
}
return true;
}
if (sourceType.id == T_JavaLangObject) // already handled the case of redefining java.lang.Object
return true;
boolean noProblems = true;
int length = referenceContext.superInterfaces.length;
ReferenceBinding[] interfaceBindings = new ReferenceBinding[length];
int count = 0;
nextInterface : for (int i = 0; i < length; i++) {
TypeReference superInterfaceRef = referenceContext.superInterfaces[i];
ReferenceBinding superInterface = findSupertype(superInterfaceRef);
if (superInterface == null) { // detected cycle
sourceType.tagBits |= TagBits.HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
superInterfaceRef.resolvedType = superInterface; // hold onto the problem type
// check for simple interface collisions
// Check for a duplicate interface once the name is resolved, otherwise we may be confused (ie : a.b.I and c.d.I)
for (int j = 0; j < i; j++) {
if (interfaceBindings[j] == superInterface) {
problemReporter().duplicateSuperinterface(sourceType, superInterfaceRef, superInterface);
continue nextInterface;
}
}
if (!superInterface.isInterface()) {
problemReporter().superinterfaceMustBeAnInterface(sourceType, superInterfaceRef, superInterface);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
noProblems = false;
continue nextInterface;
} else if (superInterface.isAnnotationType()){
problemReporter().annotationTypeUsedAsSuperinterface(sourceType, superInterfaceRef, superInterface);
}
if ((superInterface.tagBits & TagBits.HasDirectWildcard) != 0) {
problemReporter().superTypeCannotUseWildcard(sourceType, superInterfaceRef, superInterface);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
// only want to reach here when no errors are reported
interfaceBindings[count++] = superInterface;
}
// hold onto all correctly resolved superinterfaces
if (count > 0) {
if (count != length)
System.arraycopy(interfaceBindings, 0, interfaceBindings = new ReferenceBinding[count], 0, count);
sourceType.superInterfaces = interfaceBindings;
}
return noProblems;
}
void connectTypeHierarchy() {
SourceTypeBinding sourceType = referenceContext.binding;
if ((sourceType.tagBits & TagBits.BeginHierarchyCheck) == 0) {
sourceType.tagBits |= TagBits.BeginHierarchyCheck;
boolean noProblems = connectSuperclass();
noProblems &= connectSuperInterfaces();
sourceType.tagBits |= TagBits.EndHierarchyCheck;
noProblems &= connectTypeVariables(referenceContext.typeParameters, false);
sourceType.tagBits |= TagBits.TypeVariablesAreConnected;
if (noProblems && sourceType.isHierarchyInconsistent())
problemReporter().hierarchyHasProblems(sourceType);
}
connectMemberTypes();
try {
checkForInheritedMemberTypes(sourceType);
} catch (AbortCompilation e) {
e.updateContext(referenceContext, referenceCompilationUnit().compilationResult);
throw e;
}
}
private void connectTypeHierarchyWithoutMembers() {
// must ensure the imports are resolved
if (parent instanceof CompilationUnitScope) {
if (((CompilationUnitScope) parent).imports == null)
((CompilationUnitScope) parent).checkAndSetImports();
} else if (parent instanceof ClassScope) {
// ensure that the enclosing type has already been checked
((ClassScope) parent).connectTypeHierarchyWithoutMembers();
}
// double check that the hierarchy search has not already begun...
SourceTypeBinding sourceType = referenceContext.binding;
if ((sourceType.tagBits & TagBits.BeginHierarchyCheck) != 0)
return;
sourceType.tagBits |= TagBits.BeginHierarchyCheck;
boolean noProblems = connectSuperclass();
noProblems &= connectSuperInterfaces();
sourceType.tagBits |= TagBits.EndHierarchyCheck;
noProblems &= connectTypeVariables(referenceContext.typeParameters, false);
sourceType.tagBits |= TagBits.TypeVariablesAreConnected;
if (noProblems && sourceType.isHierarchyInconsistent())
problemReporter().hierarchyHasProblems(sourceType);
}
public boolean detectHierarchyCycle(TypeBinding superType, TypeReference reference, TypeBinding[] argTypes) {
if (!(superType instanceof ReferenceBinding)) return false;
if (reference == this.superTypeReference) { // see findSuperType()
if (superType.isTypeVariable())
return false; // error case caught in resolveSuperType()
// abstract class X<K,V> implements java.util.Map<K,V>
// static abstract class M<K,V> implements Entry<K,V>
if (superType.isParameterizedType())
superType = ((ParameterizedTypeBinding) superType).type;
compilationUnitScope().recordSuperTypeReference(superType); // to record supertypes
return detectHierarchyCycle(referenceContext.binding, (ReferenceBinding) superType, reference);
}
if ((superType.tagBits & TagBits.BeginHierarchyCheck) == 0 && superType instanceof SourceTypeBinding)
// ensure if this is a source superclass that it has already been checked
((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers();
return false;
}
// Answer whether a cycle was found between the sourceType & the superType
private boolean detectHierarchyCycle(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) {
if (superType.isRawType())
superType = ((RawTypeBinding) superType).type;
// by this point the superType must be a binary or source type
if (sourceType == superType) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
return true;
}
// No longer believe this code is necessary, since we changed supertype lookup to use TypeReference resolution
// if (superType.isMemberType()) {
// ReferenceBinding current = superType.enclosingType();
// do {
// if (current.isHierarchyBeingConnected()) {
// problemReporter().hierarchyCircularity(sourceType, current, reference);
// sourceType.tagBits |= TagBits.HierarchyHasProblems;
// current.tagBits |= TagBits.HierarchyHasProblems;
// return true;
// }
// } while ((current = current.enclosingType()) != null);
// }
if (superType.isBinaryBinding()) {
// force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of:
// - a binary type... this case MUST be caught & reported here
// - another source type... this case is reported against the other source type
boolean hasCycle = false;
ReferenceBinding parentType = superType.superclass();
if (parentType != null) {
if (sourceType == parentType) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
superType.tagBits |= TagBits.HierarchyHasProblems;
return true;
}
if (parentType.isParameterizedType())
parentType = ((ParameterizedTypeBinding) parentType).type;
hasCycle |= detectHierarchyCycle(sourceType, parentType, reference);
if ((parentType.tagBits & TagBits.HierarchyHasProblems) != 0) {
sourceType.tagBits |= TagBits.HierarchyHasProblems;
parentType.tagBits |= TagBits.HierarchyHasProblems; // propagate down the hierarchy
}
}
ReferenceBinding[] itsInterfaces = superType.superInterfaces();
if (itsInterfaces != Binding.NO_SUPERINTERFACES) {
for (int i = 0, length = itsInterfaces.length; i < length; i++) {
ReferenceBinding anInterface = itsInterfaces[i];
if (sourceType == anInterface) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
superType.tagBits |= TagBits.HierarchyHasProblems;
return true;
}
if (anInterface.isParameterizedType())
anInterface = ((ParameterizedTypeBinding) anInterface).type;
hasCycle |= detectHierarchyCycle(sourceType, anInterface, reference);
if ((anInterface.tagBits & TagBits.HierarchyHasProblems) != 0) {
sourceType.tagBits |= TagBits.HierarchyHasProblems;
superType.tagBits |= TagBits.HierarchyHasProblems;
}
}
}
return hasCycle;
}
if (superType.isHierarchyBeingConnected()) {
org.eclipse.jdt.internal.compiler.ast.TypeReference ref = ((SourceTypeBinding) superType).scope.superTypeReference;
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=133071
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=121734
if (ref != null && (ref.resolvedType == null || ((ReferenceBinding) ref.resolvedType).isHierarchyBeingConnected())) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= TagBits.HierarchyHasProblems;
superType.tagBits |= TagBits.HierarchyHasProblems;
return true;
}
}
if ((superType.tagBits & TagBits.BeginHierarchyCheck) == 0)
// ensure if this is a source superclass that it has already been checked
((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers();
if ((superType.tagBits & TagBits.HierarchyHasProblems) != 0)
sourceType.tagBits |= TagBits.HierarchyHasProblems;
return false;
}
private ReferenceBinding findSupertype(TypeReference typeReference) {
try {
typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes
compilationUnitScope().recordQualifiedReference(typeReference.getTypeName());
this.superTypeReference = typeReference;
ReferenceBinding superType = (ReferenceBinding) typeReference.resolveSuperType(this);
this.superTypeReference = null;
return superType;
} catch (AbortCompilation e) {
e.updateContext(typeReference, referenceCompilationUnit().compilationResult);
throw e;
}
}
/* Answer the problem reporter to use for raising new problems.
*
* Note that as a side-effect, this updates the current reference context
* (unit, type or method) in case the problem handler decides it is necessary
* to abort.
*/
public ProblemReporter problemReporter() {
MethodScope outerMethodScope;
if ((outerMethodScope = outerMostMethodScope()) == null) {
ProblemReporter problemReporter = referenceCompilationUnit().problemReporter;
problemReporter.referenceContext = referenceContext;
return problemReporter;
}
return outerMethodScope.problemReporter();
}
/* Answer the reference type of this scope.
* It is the nearest enclosing type of this scope.
*/
public TypeDeclaration referenceType() {
return referenceContext;
}
public String toString() {
if (referenceContext != null)
return "--- Class Scope ---\n\n" //$NON-NLS-1$
+ referenceContext.binding.toString();
return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$
}
}
|
[
"375833274@qq.com"
] |
375833274@qq.com
|
2062399a825ecbf03c777a3e2f787d29d7264317
|
7c2f0c60697b395c7b51a517d78f7c0066b549e0
|
/src/main/java/cn/zhanhuarecao/rediscluster/config/RedissonEntity.java
|
f0482b1ff5c84433846154762260f6d1a2b3008e
|
[] |
no_license
|
missaouib/redis-cluster-1
|
508c0ac8d6a9646128a27d124b71e93d27d7cb39
|
94f361a78a6ac8177d53cc004ee96835556ce0a9
|
refs/heads/master
| 2023-03-02T14:24:07.386321
| 2021-02-08T08:17:01
| 2021-02-08T08:17:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,416
|
java
|
package cn.zhanhuarecao.rediscluster.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
@ConfigurationProperties(prefix = "redisson")
@PropertySource(value = "classpath:application.yml")
@Configuration
public class RedissonEntity {
private List<String> nodeAddresses;
private int connectionMinimumIdleSize = 10;
private int idleConnectionTimeout = 10000;
private int pingTimeout = 1000;
private int connectTimeout = 10000;
private int timeout = 3000;
private int retryAttempts = 3;
private int retryInterval = 1500;
private int reconnectionTimeout = 3000;
private int failedAttempts = 3;
private String password;
private int subscriptionsPerConnection = 5;
private String clientName = null;
private int subscriptionConnectionMinimumIdleSize = 1;
private int subscriptionConnectionPoolSize = 50;
private int connectionPoolSize = 64;
private int database = 0;
private boolean dnsMonitoring = false;
private int dnsMonitoringInterval = 5000;
private int thread = 4; //当前处理核数量 * 2
private String codec;
public List<String> getNodeAddresses() {
return nodeAddresses;
}
public void setNodeAddresses(List<String> nodeAddresses) {
this.nodeAddresses = nodeAddresses;
}
public int getConnectionMinimumIdleSize() {
return connectionMinimumIdleSize;
}
public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) {
this.connectionMinimumIdleSize = connectionMinimumIdleSize;
}
public int getIdleConnectionTimeout() {
return idleConnectionTimeout;
}
public void setIdleConnectionTimeout(int idleConnectionTimeout) {
this.idleConnectionTimeout = idleConnectionTimeout;
}
public int getPingTimeout() {
return pingTimeout;
}
public void setPingTimeout(int pingTimeout) {
this.pingTimeout = pingTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getRetryAttempts() {
return retryAttempts;
}
public void setRetryAttempts(int retryAttempts) {
this.retryAttempts = retryAttempts;
}
public int getRetryInterval() {
return retryInterval;
}
public void setRetryInterval(int retryInterval) {
this.retryInterval = retryInterval;
}
public int getReconnectionTimeout() {
return reconnectionTimeout;
}
public void setReconnectionTimeout(int reconnectionTimeout) {
this.reconnectionTimeout = reconnectionTimeout;
}
public int getFailedAttempts() {
return failedAttempts;
}
public void setFailedAttempts(int failedAttempts) {
this.failedAttempts = failedAttempts;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getSubscriptionsPerConnection() {
return subscriptionsPerConnection;
}
public void setSubscriptionsPerConnection(int subscriptionsPerConnection) {
this.subscriptionsPerConnection = subscriptionsPerConnection;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public int getSubscriptionConnectionMinimumIdleSize() {
return subscriptionConnectionMinimumIdleSize;
}
public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) {
this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize;
}
public int getSubscriptionConnectionPoolSize() {
return subscriptionConnectionPoolSize;
}
public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) {
this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize;
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public boolean isDnsMonitoring() {
return dnsMonitoring;
}
public void setDnsMonitoring(boolean dnsMonitoring) {
this.dnsMonitoring = dnsMonitoring;
}
public int getDnsMonitoringInterval() {
return dnsMonitoringInterval;
}
public void setDnsMonitoringInterval(int dnsMonitoringInterval) {
this.dnsMonitoringInterval = dnsMonitoringInterval;
}
public int getThread() {
return thread;
}
public void setThread(int thread) {
this.thread = thread;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
}
|
[
"kun_zhan1989@163.com"
] |
kun_zhan1989@163.com
|
b6f62cf1d89cc7c50631ec43fb81a3fe9e1bf660
|
516b00f0af7e8949e48b4bd3c17cd2151fd4dd56
|
/src/BaiTap2/ThanhToanOnline.java
|
ab2a32aec7115dfd1e16e4012c5444272528fb40
|
[] |
no_license
|
letandat-59130276/LeTanDat_59130276_StrateryPattern
|
4b633e79af352df98e2881e567e49d39d987a916
|
74112a79b247822399991a0d401e7a6963c69f2c
|
refs/heads/master
| 2022-04-20T23:05:43.006452
| 2020-04-19T03:59:22
| 2020-04-19T03:59:22
| 255,846,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 495
|
java
|
/*
* 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 BaiTap2;
/**
*
* @author Con Meo Cutee
*/
public class ThanhToanOnline implements IThanhToan{
@Override
public double thanhToan(int tienHang) {
if(tienHang < 1000000)
return 0.95*tienHang;
else
return 0.93*tienHang;
}
}
|
[
"Con Meo Cutee@DESKTOP-024VCJP"
] |
Con Meo Cutee@DESKTOP-024VCJP
|
ca2745587e0028e3d21062da5f8e2f05ca8568dc
|
401c228cf3672c8754330711af7a7e5128f1cf19
|
/kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-case-mgmt/kie-wb-common-stunner-case-mgmt-client/src/main/java/org/kie/workbench/common/stunner/cm/client/command/util/CaseManagementCommandUtil.java
|
4b40c7cb38f659f7f5af660f9d66f4e30ebdc3ef
|
[
"Apache-2.0"
] |
permissive
|
gitgabrio/kie-wb-common
|
f2fb145536a2c5bd60ddbaf1cb41dec5e93912ec
|
57ffa0afc6819d784e60bd675bbdee5d0660ad1b
|
refs/heads/master
| 2020-03-21T08:00:52.572728
| 2019-05-13T13:03:14
| 2019-05-13T13:03:14
| 138,314,007
| 0
| 0
|
Apache-2.0
| 2019-09-27T12:27:30
| 2018-06-22T14:46:16
|
Java
|
UTF-8
|
Java
| false
| false
| 1,441
|
java
|
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.cm.client.command.util;
import java.util.List;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
public class CaseManagementCommandUtil {
@SuppressWarnings("unchecked")
public static int getChildIndex(final Node parent,
final Node child) {
if (parent != null && child != null) {
List<Edge> outEdges = parent.getOutEdges();
if (null != outEdges && !outEdges.isEmpty()) {
for (int i = 0, n = outEdges.size(); i < n; i++) {
if (child.equals(outEdges.get(i).getTargetNode())) {
return i;
}
}
}
}
return -1;
}
}
|
[
"roger600@gmail.com"
] |
roger600@gmail.com
|
e08b59e5a9931c1343be5a6749f69b47e43b5795
|
6c41774581737c295c21d2bcd5dac96b98de9a74
|
/src/main/java/com/eb/server/controllers/v1/UserController.java
|
56f7a95d14690836e50f53486976d49e78608c49
|
[] |
no_license
|
Rastikko/old-erudite-battles-server
|
d81c007781de13d18c95c7a274c029733b588cba
|
33fb2e1b264bee706545a0b6bf0499d9061543d2
|
refs/heads/master
| 2021-03-19T14:53:42.824496
| 2018-08-28T15:33:25
| 2018-08-28T15:33:25
| 115,243,203
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,133
|
java
|
package com.eb.server.controllers.v1;
import com.eb.server.api.v1.model.RequestLoginDTO;
import com.eb.server.api.v1.model.UserDTO;
import com.eb.server.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin
@RequestMapping(UserController.BASE_URL)
public class UserController {
public static final String BASE_URL = "/api/v1/users";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
public UserDTO getUserById(@PathVariable Long id) {
return userService.findUserDTOById(id);
}
@PostMapping("/login")
@ResponseStatus(HttpStatus.OK)
public UserDTO login(@RequestBody RequestLoginDTO requestLoginDTO ) {
return userService.findUserDTOByName(requestLoginDTO.getName());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void createNewUser(@RequestBody UserDTO userDTO) {
userService.createNewUser(userDTO);
}
}
|
[
"rastikko@gmail.com"
] |
rastikko@gmail.com
|
d31ff55f899122d883222e55a5271e499086bc2c
|
cba56340735b3347c3fae1b46b747668e5d027f8
|
/src/tss/tpm/TPM2_NV_Certify_REQUEST.java
|
7ffcb6796a2fabda02f59d9d8ec5595be389336f
|
[
"MIT"
] |
permissive
|
kvnmlr/tpm2.0-playground
|
7cadd974ff27c231cfc6165056bca5b97e9db1fa
|
9b423b5ef8fc8e697b9276ff6bfcb118be45573f
|
refs/heads/master
| 2021-07-04T22:05:18.745386
| 2017-09-25T20:32:21
| 2017-09-25T20:32:21
| 104,788,255
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,092
|
java
|
package tss.tpm;
import tss.*;
// -----------This is an auto-generated file: do not edit
//>>>
/**
* The purpose of this command is to certify the contents of an NV Index or portion of an NV Index.
*/
public class TPM2_NV_Certify_REQUEST extends TpmStructure
{
/**
* The purpose of this command is to certify the contents of an NV Index or portion of an NV Index.
*
* @param _signHandle handle of the key used to sign the attestation structure Auth Index: 1 Auth Role: USER
* @param _authHandle handle indicating the source of the authorization value for the NV Index Auth Index: 2 Auth Role: USER
* @param _nvIndex Index for the area to be certified Auth Index: None
* @param _qualifyingData user-provided qualifying data
* @param _inScheme signing scheme to use if the scheme for signHandle is TPM_ALG_NULL (One of TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME)
* @param _size number of octets to certify
* @param _offset octet offset into the NV area This value shall be less than or equal to the size of the nvIndex data.
*/
public TPM2_NV_Certify_REQUEST(TPM_HANDLE _signHandle,TPM_HANDLE _authHandle,TPM_HANDLE _nvIndex,byte[] _qualifyingData,TPMU_SIG_SCHEME _inScheme,int _size,int _offset)
{
signHandle = _signHandle;
authHandle = _authHandle;
nvIndex = _nvIndex;
qualifyingData = _qualifyingData;
inScheme = _inScheme;
size = (short)_size;
offset = (short)_offset;
}
/**
* The purpose of this command is to certify the contents of an NV Index or portion of an NV Index.
*/
public TPM2_NV_Certify_REQUEST() {};
/**
* handle of the key used to sign the attestation structure Auth Index: 1 Auth Role: USER
*/
public TPM_HANDLE signHandle;
/**
* handle indicating the source of the authorization value for the NV Index Auth Index: 2 Auth Role: USER
*/
public TPM_HANDLE authHandle;
/**
* Index for the area to be certified Auth Index: None
*/
public TPM_HANDLE nvIndex;
/**
* size in octets of the buffer field; may be 0
*/
// private short qualifyingDataSize;
/**
* user-provided qualifying data
*/
public byte[] qualifyingData;
/**
* scheme selector
*/
// private TPM_ALG_ID inSchemeScheme;
/**
* signing scheme to use if the scheme for signHandle is TPM_ALG_NULL
*/
public TPMU_SIG_SCHEME inScheme;
/**
* number of octets to certify
*/
public short size;
/**
* octet offset into the NV area This value shall be less than or equal to the size of the nvIndex data.
*/
public short offset;
public int GetUnionSelector_inScheme()
{
if(inScheme instanceof TPMS_SIG_SCHEME_RSASSA){return 0x0014; }
if(inScheme instanceof TPMS_SIG_SCHEME_RSAPSS){return 0x0016; }
if(inScheme instanceof TPMS_SIG_SCHEME_ECDSA){return 0x0018; }
if(inScheme instanceof TPMS_SIG_SCHEME_ECDAA){return 0x001A; }
if(inScheme instanceof TPMS_SIG_SCHEME_SM2){return 0x001B; }
if(inScheme instanceof TPMS_SIG_SCHEME_ECSCHNORR){return 0x001C; }
if(inScheme instanceof TPMS_SCHEME_HMAC){return 0x0005; }
if(inScheme instanceof TPMS_SCHEME_HASH){return 0x7FFF; }
if(inScheme instanceof TPMS_NULL_SIG_SCHEME){return 0x0010; }
throw new RuntimeException("Unrecognized type");
}
@Override
public void toTpm(OutByteBuf buf)
{
signHandle.toTpm(buf);
authHandle.toTpm(buf);
nvIndex.toTpm(buf);
buf.writeInt((qualifyingData!=null)?qualifyingData.length:0, 2);
buf.write(qualifyingData);
buf.writeInt(GetUnionSelector_inScheme(), 2);
((TpmMarshaller)inScheme).toTpm(buf);
buf.write(size);
buf.write(offset);
return;
}
@Override
public void initFromTpm(InByteBuf buf)
{
signHandle = TPM_HANDLE.fromTpm(buf);
authHandle = TPM_HANDLE.fromTpm(buf);
nvIndex = TPM_HANDLE.fromTpm(buf);
int _qualifyingDataSize = buf.readInt(2);
qualifyingData = new byte[_qualifyingDataSize];
buf.readArrayOfInts(qualifyingData, 1, _qualifyingDataSize);
int _inSchemeScheme = buf.readInt(2);
inScheme=null;
if(_inSchemeScheme==TPM_ALG_ID.RSASSA.toInt()) {inScheme = new TPMS_SIG_SCHEME_RSASSA();}
else if(_inSchemeScheme==TPM_ALG_ID.RSAPSS.toInt()) {inScheme = new TPMS_SIG_SCHEME_RSAPSS();}
else if(_inSchemeScheme==TPM_ALG_ID.ECDSA.toInt()) {inScheme = new TPMS_SIG_SCHEME_ECDSA();}
else if(_inSchemeScheme==TPM_ALG_ID.ECDAA.toInt()) {inScheme = new TPMS_SIG_SCHEME_ECDAA();}
// code generator workaround BUGBUG >> (probChild)else if(_inSchemeScheme==TPM_ALG_ID.SM2.toInt()) {inScheme = new TPMS_SIG_SCHEME_SM2();}
// code generator workaround BUGBUG >> (probChild)else if(_inSchemeScheme==TPM_ALG_ID.ECSCHNORR.toInt()) {inScheme = new TPMS_SIG_SCHEME_ECSCHNORR();}
else if(_inSchemeScheme==TPM_ALG_ID.HMAC.toInt()) {inScheme = new TPMS_SCHEME_HMAC();}
else if(_inSchemeScheme==TPM_ALG_ID.ANY.toInt()) {inScheme = new TPMS_SCHEME_HASH();}
else if(_inSchemeScheme==TPM_ALG_ID.NULL.toInt()) {inScheme = new TPMS_NULL_SIG_SCHEME();}
if(inScheme==null)throw new RuntimeException("Unexpected type selector");
inScheme.initFromTpm(buf);
size = (short) buf.readInt(2);
offset = (short) buf.readInt(2);
}
@Override
public byte[] toTpm()
{
OutByteBuf buf = new OutByteBuf();
toTpm(buf);
return buf.getBuf();
}
public static TPM2_NV_Certify_REQUEST fromTpm (byte[] x)
{
TPM2_NV_Certify_REQUEST ret = new TPM2_NV_Certify_REQUEST();
InByteBuf buf = new InByteBuf(x);
ret.initFromTpm(buf);
if (buf.bytesRemaining()!=0)
throw new AssertionError("bytes remaining in buffer after object was de-serialized");
return ret;
}
public static TPM2_NV_Certify_REQUEST fromTpm (InByteBuf buf)
{
TPM2_NV_Certify_REQUEST ret = new TPM2_NV_Certify_REQUEST();
ret.initFromTpm(buf);
return ret;
}
@Override
public String toString()
{
TpmStructurePrinter _p = new TpmStructurePrinter("TPM2_NV_Certify_REQUEST");
toStringInternal(_p, 1);
_p.endStruct();
return _p.toString();
}
@Override
public void toStringInternal(TpmStructurePrinter _p, int d)
{
_p.add(d, "TPM_HANDLE", "signHandle", signHandle);
_p.add(d, "TPM_HANDLE", "authHandle", authHandle);
_p.add(d, "TPM_HANDLE", "nvIndex", nvIndex);
_p.add(d, "byte", "qualifyingData", qualifyingData);
_p.add(d, "TPMU_SIG_SCHEME", "inScheme", inScheme);
_p.add(d, "ushort", "size", size);
_p.add(d, "ushort", "offset", offset);
};
};
//<<<
|
[
"kevin.mueller1@live.de"
] |
kevin.mueller1@live.de
|
bb4be98a0b07336c30ad953435ff2107db152385
|
ab2fd960a295be52786b8d9394a7fd63e379b340
|
/common/message/src/main/java/org/thingsboard/server/common/msg/session/ex/ProcessingTimeoutException.java
|
2bf7033d39f6af10e3f82288f9aa9de435080945
|
[
"Apache-2.0"
] |
permissive
|
ltcong1411/SmartDeviceFrameworkV2
|
654f7460baa00d8acbc483dddf46b62ce6657eea
|
6f1bbbf3a2a15d5c0527e68feebea370967bce8a
|
refs/heads/master
| 2020-04-22T02:46:44.240516
| 2019-02-25T08:19:43
| 2019-02-25T08:19:43
| 170,062,547
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 810
|
java
|
/**
* Copyright © 2016-2019 The Thingsboard 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.thingsboard.server.common.msg.session.ex;
public class ProcessingTimeoutException extends Exception {
private static final long serialVersionUID = 1L;
}
|
[
"ltcong1411@gmail.com"
] |
ltcong1411@gmail.com
|
64cc33529236b51326d63261241dee17948a6e0b
|
28c2a2db61a5e3b0f516a64a199fead08cdb9571
|
/src/de/benpicco/libchan/handler/PostCountHandler.java
|
18c00a6f205d1f863f172947f9df47c214a2978c
|
[
"Apache-2.0",
"WTFPL"
] |
permissive
|
bumba420/libchan
|
bf4acf255fa32000edfbd87a6c8127788f633e8f
|
7b1aaf1e1dfe428b514345f563d0c61895842afe
|
refs/heads/master
| 2021-01-01T05:03:57.478208
| 2013-05-23T16:16:01
| 2013-05-23T16:16:01
| 55,990,471
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 913
|
java
|
package de.benpicco.libchan.handler;
import de.benpicco.libchan.clichan.PostArchiver;
import de.benpicco.libchan.imageboards.Post;
import de.benpicco.libchan.interfaces.PostProcessor;
import de.benpicco.libchan.util.Logger;
public class PostCountHandler implements PostProcessor {
final int treshold;
final PostArchiver archiver;
public PostCountHandler(PostArchiver archiver, int treshold) {
this.treshold = treshold;
this.archiver = archiver;
}
@Override
public void onAddPost(Post post) {
if (archiver.getPostCount() > treshold)
Logger.get().println("Thread " + archiver.getThreadId() + " has " + archiver.getPostCount() + " replies.");
}
@Override
public void onPostsParsingDone() {
Logger.get().println(
"Thread " + archiver.getThreadId() + " with " + archiver.getPostCount() + " posts received.");
}
@Override
public void onPostModified(Post oldPost, Post newPost) {
}
}
|
[
"benpicco@googlemail.com"
] |
benpicco@googlemail.com
|
045430535301fb48895423fc93a68ee4d30cf8de
|
13db4a1d034aa9dc3b97ba5a4c758eb37ef254df
|
/opserv-sp-service-impl/src/main/java/com/cognizant/opserv/sp/service/internal/MetricIntService.java
|
a83cacfe16af5499c0504bb586209bb8c196c067
|
[] |
no_license
|
deepthikamaraj/javaCode
|
3436c539c0abcaeb3fbec87ccd1b79b543dffbc6
|
7634d01d5553496c7f5549382651ae63f371f8cc
|
refs/heads/master
| 2021-04-06T08:54:22.184740
| 2018-03-13T09:57:40
| 2018-03-13T09:57:40
| 125,029,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,341
|
java
|
package com.cognizant.opserv.sp.service.internal;
import java.util.List;
import com.cognizant.opserv.sp.exception.MetricServiceException;
import com.cognizant.opserv.sp.model.auth.UserDetails;
import com.cognizant.opserv.sp.model.metric.RangeDetails;
/**
* ****************************************************************************.
*
* @class MetricIntService contains all the metric internal services
* @author Cognizant Technology Solutions
* @version OpServ 3.0
* @since 30/03/2016
* ***************************************************************************
*/
public interface MetricIntService {
/**
* Gets the range details for salespos metrics.
*
* @param mtrId the mtr id
* @param userDetails the user details
* @return the range details by metric
* @throws MetricServiceException the metric service exception
*/
List<RangeDetails> getRangeDetailsForSalesPosMetrics(long mtrId, UserDetails userDetails) throws MetricServiceException;
/**
* Gets the range details for geo metrics.
*
* @param mtrId the mtr id
* @param userDetails the user details
* @return the range details for geo metrics
* @throws MetricServiceException the metric service exception
*/
public List<RangeDetails> getRangeDetailsForGeoMetrics(Long mtrId,UserDetails userDetails) throws MetricServiceException;
}
|
[
"deepthi.k2@cognizant.com"
] |
deepthi.k2@cognizant.com
|
da8030c75b3783ca885c38a46cf5ad1a0cd077b5
|
bbe5eff2e9a63e4945bbde6b6d96f662ba7d1af7
|
/app/src/androidTest/java/com/blogspot/progectoscaseiros/movies_app/ExampleInstrumentedTest.java
|
aa65680b7e144fca8028c61537551308765c6ed9
|
[] |
no_license
|
edsna/Movies_App
|
5882af45209316e1deaf334bab5346b94a5b1f59
|
414a7320d95cec286189bf22f0ebe5345288dddf
|
refs/heads/master
| 2021-06-14T19:35:39.433829
| 2021-02-16T04:06:37
| 2021-02-16T04:06:37
| 139,759,466
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 766
|
java
|
package com.blogspot.progectoscaseiros.movies_app;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.blogspot.progectoscaseiros.movies_app", appContext.getPackageName());
}
}
|
[
"edsonaguiar17@gmail.com"
] |
edsonaguiar17@gmail.com
|
a5f0d2bee7dc1687def1f59eeb82595117b98e80
|
efca855f83be608cc5fcd5f9976b820f09f11243
|
/consensus/qbft/src/integration-test/java/org/enterchain/enter/consensus/qbft/test/SpuriousBehaviourTest.java
|
df827f98b106cf9d6e7840bbadfaa7bbf5e9464c
|
[
"Apache-2.0"
] |
permissive
|
enterpact/enterchain
|
5438e127c851597cbd7e274526c3328155483e58
|
d8b272fa6885e5d263066da01fff3be74a6357a0
|
refs/heads/master
| 2023-05-28T12:48:02.535365
| 2021-06-09T20:44:01
| 2021-06-09T20:44:01
| 375,483,000
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,337
|
java
|
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.enterchain.enter.consensus.qbft.test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.enterchain.enter.consensus.qbft.support.IntegrationTestHelpers.createSignedCommitPayload;
import org.enterchain.enter.consensus.common.bft.ConsensusRoundIdentifier;
import org.enterchain.enter.consensus.common.bft.inttest.NodeParams;
import org.enterchain.enter.consensus.qbft.messagedata.QbftV1;
import org.enterchain.enter.consensus.qbft.messagewrappers.Commit;
import org.enterchain.enter.consensus.qbft.messagewrappers.Prepare;
import org.enterchain.enter.consensus.qbft.payload.MessageFactory;
import org.enterchain.enter.consensus.qbft.support.RoundSpecificPeers;
import org.enterchain.enter.consensus.qbft.support.TestContext;
import org.enterchain.enter.consensus.qbft.support.TestContextBuilder;
import org.enterchain.enter.consensus.qbft.support.ValidatorPeer;
import org.enterchain.enter.crypto.NodeKey;
import org.enterchain.enter.crypto.NodeKeyUtils;
import org.enterchain.enter.crypto.SECPSignature;
import org.enterchain.enter.ethereum.core.Block;
import org.enterchain.enter.ethereum.core.Hash;
import org.enterchain.enter.ethereum.core.Util;
import org.enterchain.enter.ethereum.p2p.rlpx.wire.MessageData;
import org.enterchain.enter.ethereum.p2p.rlpx.wire.RawMessage;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Before;
import org.junit.Test;
public class SpuriousBehaviourTest {
private final long blockTimeStamp = 100;
private final Clock fixedClock =
Clock.fixed(Instant.ofEpochSecond(blockTimeStamp), ZoneId.systemDefault());
// Test is configured such that a remote peer is responsible for proposing a block
private final int NETWORK_SIZE = 5;
// Configuration ensures remote peer will provide proposal for first block
private final TestContext context =
new TestContextBuilder()
.validatorCount(NETWORK_SIZE)
.indexOfFirstLocallyProposedBlock(0)
.clock(fixedClock)
.buildAndStart();
private final ConsensusRoundIdentifier roundId = new ConsensusRoundIdentifier(1, 0);
private final RoundSpecificPeers peers = context.roundSpecificPeers(roundId);
private final Block proposedBlock =
context.createBlockForProposalFromChainHead(30, peers.getProposer().getNodeAddress());
private Prepare expectedPrepare;
private Commit expectedCommit;
@Before
public void setup() {
expectedPrepare =
context.getLocalNodeMessageFactory().createPrepare(roundId, proposedBlock.getHash());
expectedCommit =
new Commit(
createSignedCommitPayload(
roundId, proposedBlock, context.getLocalNodeParams().getNodeKey()));
}
@Test
public void badlyFormedRlpDoesNotPreventOngoingBftOperation() {
final MessageData illegalCommitMsg = new RawMessage(QbftV1.PREPARE, Bytes.EMPTY);
peers.getNonProposing(0).injectMessage(illegalCommitMsg);
peers.getProposer().injectProposal(roundId, proposedBlock);
peers.verifyMessagesReceived(expectedPrepare);
}
@Test
public void messageWithIllegalMessageCodeAreDiscardedAndDoNotPreventOngoingBftOperation() {
final MessageData illegalCommitMsg = new RawMessage(QbftV1.MESSAGE_SPACE, Bytes.EMPTY);
peers.getNonProposing(0).injectMessage(illegalCommitMsg);
peers.getProposer().injectProposal(roundId, proposedBlock);
peers.verifyMessagesReceived(expectedPrepare);
}
@Test
public void nonValidatorsCannotTriggerResponses() {
final NodeKey nonValidatorNodeKey = NodeKeyUtils.generate();
final NodeParams nonValidatorParams =
new NodeParams(
Util.publicKeyToAddress(nonValidatorNodeKey.getPublicKey()), nonValidatorNodeKey);
final ValidatorPeer nonvalidator =
new ValidatorPeer(
nonValidatorParams,
new MessageFactory(nonValidatorParams.getNodeKey()),
context.getEventMultiplexer());
nonvalidator.injectProposal(new ConsensusRoundIdentifier(1, 0), proposedBlock);
peers.verifyNoMessagesReceived();
}
@Test
public void preparesWithMisMatchedDigestAreNotRespondedTo() {
peers.getProposer().injectProposal(roundId, proposedBlock);
peers.verifyMessagesReceived(expectedPrepare);
peers.prepareForNonProposing(roundId, Hash.ZERO);
peers.verifyNoMessagesReceived();
peers.prepareForNonProposing(roundId, proposedBlock.getHash());
peers.verifyMessagesReceived(expectedCommit);
peers.prepareForNonProposing(roundId, Hash.ZERO);
assertThat(context.getCurrentChainHeight()).isEqualTo(0);
peers.commitForNonProposing(roundId, proposedBlock);
assertThat(context.getCurrentChainHeight()).isEqualTo(1);
}
@Test
public void oneCommitSealIsIllegalPreventsImport() {
peers.getProposer().injectProposal(roundId, proposedBlock);
peers.verifyMessagesReceived(expectedPrepare);
peers.prepareForNonProposing(roundId, proposedBlock.getHash());
// for a network of 5, 4 seals are required (local + 3 remote)
peers.getNonProposing(0).injectCommit(roundId, proposedBlock);
peers.getNonProposing(1).injectCommit(roundId, proposedBlock);
// nonProposer-2 will generate an invalid seal
final ValidatorPeer badSealPeer = peers.getNonProposing(2);
final SECPSignature illegalSeal = badSealPeer.getnodeKey().sign(Hash.ZERO);
badSealPeer.injectCommit(roundId, proposedBlock.getHash(), illegalSeal);
assertThat(context.getCurrentChainHeight()).isEqualTo(0);
// Now inject the REAL commit message
badSealPeer.injectCommit(roundId, proposedBlock);
assertThat(context.getCurrentChainHeight()).isEqualTo(1);
}
}
|
[
"webframes@gmail.com"
] |
webframes@gmail.com
|
99827a2281cfe0f3ea7a2f1228fb6497eec2a5de
|
852006975748f9e2aec0e851730bd8e3af555f91
|
/flink/src/main/java/com/logicalclocks/hsfs/constructor/Query.java
|
0cfc9ede6031351abd9c36722a6e2da2bacac062
|
[] |
no_license
|
davitbzh/FlinkAggJob
|
34c6531c6602128b1846c20ad4b37201fc7b9f75
|
e5a4ce91adccdde3ed1f5f262c4133be5ad5d271
|
refs/heads/master
| 2023-08-17T00:59:45.862350
| 2021-09-16T23:12:46
| 2021-09-16T23:12:46
| 407,335,151
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 10,703
|
java
|
/*
* Copyright (c) 2020 Logical Clocks AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.logicalclocks.hsfs.constructor;
import com.logicalclocks.hsfs.Feature;
import com.logicalclocks.hsfs.FeatureGroup;
import com.logicalclocks.hsfs.FeatureStoreException;
import com.logicalclocks.hsfs.OnDemandFeatureGroup;
import com.logicalclocks.hsfs.Storage;
import com.logicalclocks.hsfs.engine.Utils;
import com.logicalclocks.hsfs.metadata.FeatureGroupBase;
import com.logicalclocks.hsfs.metadata.QueryConstructorApi;
import com.logicalclocks.hsfs.metadata.StorageConnectorApi;
import lombok.Getter;
import lombok.Setter;
//import org.apache.spark.sql.Dataset;
//import org.apache.spark.sql.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Query {
private static final Logger LOGGER = LoggerFactory.getLogger(FeatureGroup.class);
@Getter
@Setter
private FeatureGroupBase leftFeatureGroup;
@Getter
@Setter
private List<Feature> leftFeatures;
@Getter
@Setter
private Long leftFeatureGroupStartTime;
@Getter
@Setter
private Long leftFeatureGroupEndTime;
@Getter
@Setter
private List<Join> joins = new ArrayList<>();
@Getter
@Setter
private FilterLogic filter;
@Getter
@Setter
private Boolean hiveEngine = false;
private QueryConstructorApi queryConstructorApi;
private StorageConnectorApi storageConnectorApi;
private Utils utils = new Utils();
public Query(FeatureGroupBase leftFeatureGroup, List<Feature> leftFeatures) {
this.leftFeatureGroup = leftFeatureGroup;
this.leftFeatures = leftFeatures;
this.queryConstructorApi = new QueryConstructorApi();
this.storageConnectorApi = new StorageConnectorApi();
}
public Query join(Query subquery) {
return join(subquery, JoinType.INNER);
}
public Query join(Query subquery, String prefix) {
return join(subquery, JoinType.INNER, prefix);
}
public Query join(Query subquery, List<String> on) {
return joinFeatures(subquery, on.stream().map(Feature::new).collect(Collectors.toList()), JoinType.INNER);
}
public Query join(Query subquery, List<String> leftOn, List<String> rightOn) {
return joinFeatures(subquery, leftOn.stream().map(Feature::new).collect(Collectors.toList()),
rightOn.stream().map(Feature::new).collect(Collectors.toList()), JoinType.INNER);
}
public Query join(Query subquery, List<String> leftOn, List<String> rightOn, String prefix) {
return joinFeatures(subquery, leftOn.stream().map(Feature::new).collect(Collectors.toList()),
rightOn.stream().map(Feature::new).collect(Collectors.toList()), JoinType.INNER, prefix);
}
public Query join(Query subquery, JoinType joinType) {
joins.add(new Join(subquery, joinType, null));
return this;
}
public Query join(Query subquery, JoinType joinType, String prefix) {
joins.add(new Join(subquery, joinType, prefix));
return this;
}
public Query join(Query subquery, List<String> on, JoinType joinType) {
joins.add(new Join(subquery, on.stream().map(Feature::new).collect(Collectors.toList()), joinType, null));
return this;
}
public Query join(Query subquery, List<String> on, JoinType joinType, String prefix) {
joins.add(new Join(subquery, on.stream().map(Feature::new).collect(Collectors.toList()), joinType, prefix));
return this;
}
public Query join(Query subquery, List<String> leftOn, List<String> rightOn, JoinType joinType) {
joins.add(new Join(subquery, leftOn.stream().map(Feature::new).collect(Collectors.toList()),
rightOn.stream().map(Feature::new).collect(Collectors.toList()), joinType, null));
return this;
}
public Query join(Query subquery, List<String> leftOn, List<String> rightOn, JoinType joinType, String prefix) {
joins.add(new Join(subquery, leftOn.stream().map(Feature::new).collect(Collectors.toList()),
rightOn.stream().map(Feature::new).collect(Collectors.toList()), joinType, prefix));
return this;
}
public Query joinFeatures(Query subquery, List<Feature> on) {
return joinFeatures(subquery, on, JoinType.INNER);
}
public Query joinFeatures(Query subquery, List<Feature> on, String prefix) {
return joinFeatures(subquery, on, JoinType.INNER, prefix);
}
public Query joinFeatures(Query subquery, List<Feature> leftOn, List<Feature> rightOn) {
return joinFeatures(subquery, leftOn, rightOn, JoinType.INNER);
}
public Query joinFeatures(Query subquery, List<Feature> leftOn, List<Feature> rightOn, String prefix) {
return joinFeatures(subquery, leftOn, rightOn, JoinType.INNER, prefix);
}
public Query joinFeatures(Query subquery, List<Feature> on, JoinType joinType) {
joins.add(new Join(subquery, on, joinType, null));
return this;
}
public Query joinFeatures(Query subquery, List<Feature> on, JoinType joinType, String prefix) {
joins.add(new Join(subquery, on, joinType, prefix));
return this;
}
public Query joinFeatures(Query subquery, List<Feature> leftOn, List<Feature> rightOn, JoinType joinType) {
joins.add(new Join(subquery, leftOn, rightOn, joinType, null));
return this;
}
public Query joinFeatures(Query subquery, List<Feature> leftOn, List<Feature> rightOn, JoinType joinType,
String prefix) {
joins.add(new Join(subquery, leftOn, rightOn, joinType, prefix));
return this;
}
/**
* Reads Feature group data at a specific point in time.
*
* @param wallclockTime point in time
* @return Query
* @throws FeatureStoreException
* @throws ParseException
*/
public Query asOf(String wallclockTime) throws FeatureStoreException, ParseException {
Long wallclockTimestamp = utils.getTimeStampFromDateString(wallclockTime);
for (Join join : this.joins) {
Query queryWithTimeStamp = join.getQuery();
queryWithTimeStamp.setLeftFeatureGroupEndTime(wallclockTimestamp);
join.setQuery(queryWithTimeStamp);
}
this.setLeftFeatureGroupEndTime(wallclockTimestamp);
return this;
}
/**
* Reads changes that occurred between specified points in time.
*
* @param wallclockStartTime start date.
* @param wallclockEndTime end date.
* @return Query
* @throws FeatureStoreException
* @throws IOException
* @throws ParseException
*/
public Query pullChanges(String wallclockStartTime, String wallclockEndTime)
throws FeatureStoreException, ParseException {
this.setLeftFeatureGroupStartTime(utils.getTimeStampFromDateString(wallclockStartTime));
this.setLeftFeatureGroupEndTime(utils.getTimeStampFromDateString(wallclockEndTime));
return this;
}
/*
public Dataset<Row> read() throws FeatureStoreException, IOException {
return read(false, null);
}
public Dataset<Row> read(boolean online) throws FeatureStoreException, IOException {
return read(online, null);
}
public Dataset<Row> read(boolean online, Map<String, String> readOptions) throws FeatureStoreException, IOException {
FsQuery fsQuery = queryConstructorApi.constructQuery(leftFeatureGroup.getFeatureStore(), this);
if (online) {
LOGGER.info("Executing query: " + fsQuery.getStorageQuery(Storage.ONLINE));
StorageConnector onlineConnector =
storageConnectorApi.getOnlineStorageConnector(leftFeatureGroup.getFeatureStore());
return onlineConnector.read(fsQuery.getStorageQuery(Storage.ONLINE),null, null, null);
} else {
registerOnDemandFeatureGroups(fsQuery.getOnDemandFeatureGroups());
registerHudiFeatureGroups(fsQuery.getHudiCachedFeatureGroups(), readOptions);
LOGGER.info("Executing query: " + fsQuery.getStorageQuery(Storage.OFFLINE));
return SparkEngine.getInstance().sql(fsQuery.getStorageQuery(Storage.OFFLINE));
}
}
public void show(int numRows) throws FeatureStoreException, IOException {
show(false, numRows);
}
public void show(boolean online, int numRows) throws FeatureStoreException, IOException {
read(online).show(numRows);
}
*/
public String toString() {
return toString(Storage.OFFLINE);
}
public String toString(Storage storage) {
try {
return queryConstructorApi
.constructQuery(leftFeatureGroup.getFeatureStore(), this)
.getStorageQuery(storage);
} catch (FeatureStoreException | IOException e) {
return e.getMessage();
}
}
/*
private void registerOnDemandFeatureGroups(List<OnDemandFeatureGroupAlias> onDemandFeatureGroups)
throws FeatureStoreException, IOException {
if (onDemandFeatureGroups == null || onDemandFeatureGroups.isEmpty()) {
return;
}
for (OnDemandFeatureGroupAlias onDemandFeatureGroupAlias : onDemandFeatureGroups) {
String alias = onDemandFeatureGroupAlias.getAlias();
OnDemandFeatureGroup onDemandFeatureGroup = onDemandFeatureGroupAlias.getOnDemandFeatureGroup();
SparkEngine.getInstance().registerOnDemandTemporaryTable(onDemandFeatureGroup, alias);
}
}
private void registerHudiFeatureGroups(List<HudiFeatureGroupAlias> hudiFeatureGroups,
Map<String, String> readOptions) {
for (HudiFeatureGroupAlias hudiFeatureGroupAlias : hudiFeatureGroups) {
String alias = hudiFeatureGroupAlias.getAlias();
FeatureGroup featureGroup = hudiFeatureGroupAlias.getFeatureGroup();
SparkEngine.getInstance().registerHudiTemporaryTable(featureGroup, alias,
hudiFeatureGroupAlias.getLeftFeatureGroupStartTimestamp(),
hudiFeatureGroupAlias.getLeftFeatureGroupEndTimestamp(),
readOptions);
}
}
*/
public Query filter(Filter filter) {
if (this.filter == null) {
this.filter = new FilterLogic(filter);
} else {
this.filter = this.filter.and(filter);
}
return this;
}
public Query filter(FilterLogic filter) {
if (this.filter == null) {
this.filter = filter;
} else {
this.filter = this.filter.and(filter);
}
return this;
}
}
|
[
"davit@logicalclocks.com"
] |
davit@logicalclocks.com
|
183d5e45e23c2dec84ab88cb505aab92e4b3af19
|
a8dab0659ad38e4f98730e4f246a83a859666fc0
|
/LeetCode/com/chin/leetcode/solutions/InvertBinaryTree.java
|
6a4cae08449aa02015ce6e8a560246fe0816cc54
|
[] |
no_license
|
DZDcyj/Java
|
02c9a29c565b03f0214c7bd7b7b3cb9a4eacce77
|
493c60d15a65e53c4cb7e57cc625e4c368944db3
|
refs/heads/master
| 2021-09-18T12:37:12.543910
| 2020-05-08T06:58:59
| 2020-05-08T06:58:59
| 156,069,233
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 555
|
java
|
package com.chin.leetcode.solutions;
import com.chin.leetcode.TreeNode;
/**
* @author Chin
*/
public class InvertBinaryTree {
private static TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
if (root.left != null) {
root.left = invertTree(root.left);
}
if (root.right != null) {
root.right = invertTree(root.right);
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
|
[
"cyjdtxz@gmail.com"
] |
cyjdtxz@gmail.com
|
d63bc5a52d870d9c607fe1633d946d8893666895
|
1eea24a6aa39ba093508df4c724feaed296a25c5
|
/src/com/egame/src/main/displays/Display.java
|
21d27e0d98554ecf38fcc109b43ba866c67a307c
|
[] |
no_license
|
EdwardEddyEd/Shooter
|
388baec4459d5196aa13f57c2cdc5173f598fa14
|
70ab8a1db4873645d55ee1f970a6c6f3d952219e
|
refs/heads/master
| 2021-01-10T17:11:39.823636
| 2015-12-09T22:30:54
| 2015-12-09T22:30:54
| 47,722,875
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 685
|
java
|
package com.egame.src.main.displays;
import java.awt.Graphics2D;
import com.egame.src.main.entities.Player;
public abstract class Display {
protected Player player;
protected double x, y;
protected int movementCounter = 0;
protected int displayCounter = 0;
protected boolean visible = false;
protected boolean completedDisplay = false;
protected boolean triggered = false;
public Display(Player player){
this.player = player;
}
public abstract void tick();
public abstract void render(Graphics2D g2d);
public void triggerDisplay(Byte event){
visible = true;
triggered = true;
displayCounter = 0;
}
public boolean isVisible(){
return visible;
}
}
|
[
"Edward.J.Camp.18@dartmouth.edu"
] |
Edward.J.Camp.18@dartmouth.edu
|
6416c1537ebc115c8e9e964bf15acaac6d0b955f
|
952ae1b3768c503de64849ea628e1d4d37e0400c
|
/consumer/src/main/java/com/longxw/ConsumerApplication.java
|
3e20a6cf746a619205bf30af92d0e5008d16e620
|
[] |
no_license
|
crysbcat/spring-cloud-demo
|
2ea933994034548352cbe24dbb36072a940e1d3a
|
bc1389e5135ab97d435d2dc63e8ca66af6dcdde4
|
refs/heads/master
| 2020-07-03T07:56:36.564403
| 2019-08-12T02:02:17
| 2019-08-12T02:02:17
| 201,845,004
| 0
| 0
| null | 2019-08-12T02:40:29
| 2019-08-12T02:40:29
| null |
UTF-8
|
Java
| false
| false
| 624
|
java
|
package com.longxw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableFeignClients(basePackages = {"com.longxw.demo.feign.client"})
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}
|
[
"longxw@minstone.com.cn"
] |
longxw@minstone.com.cn
|
7961a4f3bae1366caa6b08d3a5df8212baca061b
|
85b098fb578d9988c830f1ca6c7b6fceec96054a
|
/Info8000/src/br/com/nfe/comunicador/XMotivo.java
|
5ab24a6f051663fb5fbe282134ef4484354948ea
|
[] |
no_license
|
Blasterprateado/info8000
|
35c728eda8d23f9fb6ea4493bcbca0cbb0753170
|
181adc214e253ce6075a8a2be79e104637b39a78
|
refs/heads/master
| 2021-01-18T17:48:50.135101
| 2016-09-28T05:39:33
| 2016-09-28T05:39:33
| 69,123,172
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,673
|
java
|
/*
* 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.nfe.comunicador;
/**
*
* @author Edson
*/
public class XMotivo {
private String Versao;
private String TpAmb;
private String VerAplic;
private String CStat;
private String XMotivo;
private String CUF;
private String DhRecbto;
public XMotivo(String re) {
setCamposXMotivo(re);
}
public XMotivo(XMotivo re) {
setCamposXMotivo(re);
}
public String getVersao() {
return Versao;
}
public void setVersao(String Versao) {
this.Versao = Versao;
}
public String getTpAmb() {
return TpAmb;
}
public void setTpAmb(String TpAmb) {
this.TpAmb = TpAmb;
}
public String getVerAplic() {
return VerAplic;
}
public void setVerAplic(String VerAplic) {
this.VerAplic = VerAplic;
}
public String getCStat() {
return CStat;
}
public void setCStat(String CStat) {
this.CStat = CStat;
}
public String getXMotivo() {
return XMotivo;
}
public void setXMotivo(String XMotivo) {
this.XMotivo = XMotivo;
}
public String getCUF() {
return CUF;
}
public void setCUF(String CUF) {
this.CUF = CUF;
}
public String getDhRecbto() {
return DhRecbto;
}
public void setDhRecbto(String DhRecbto) {
this.DhRecbto = DhRecbto;
}
private void setCamposXMotivo(XMotivo xMotivo) {
this.setCStat(xMotivo.getCStat());
this.setCUF(xMotivo.getCUF());
this.setDhRecbto(xMotivo.getDhRecbto());
this.setTpAmb(xMotivo.getTpAmb());
this.setVerAplic(xMotivo.getVerAplic());
this.setVersao(xMotivo.getVersao());
this.setXMotivo(xMotivo.getXMotivo());
}
private void setCamposXMotivo(String s) {
this.setCStat(TextUtils.lerTagIni("CStat", s));
this.setCUF(TextUtils.lerTagIni("CUF", s));
this.setDhRecbto(TextUtils.lerTagIni("DhRecbto", s));
this.setTpAmb(TextUtils.lerTagIni("TpAmb", s));
this.setVerAplic(TextUtils.lerTagIni("VerAplic", s));
this.setVersao(TextUtils.lerTagIni("Versao", s));
this.setXMotivo(TextUtils.lerTagIni("XMotivo", s));
}
@Override
public String toString() {
return "XMotivo{" + "Versao=" + Versao + ", TpAmb=" + TpAmb + ", VerAplic=" + VerAplic + ", CStat=" + CStat + ", XMotivo=" + XMotivo + ", CUF=" + CUF + ", DhRecbto=" + DhRecbto + '}';
}
}
|
[
"junior000638@gmail.com"
] |
junior000638@gmail.com
|
f480c1ed940fb59916589b70b8498357d3697a24
|
bf640d825debde2b8b3fd993b80d1f30c69db6af
|
/server/src/main/java/com/cezarykluczynski/stapi/server/comicStrip/reader/ComicStripRestReader.java
|
560540ba046d5164cc382494645e1e14538fb65f
|
[
"MIT"
] |
permissive
|
mastermind1981/stapi
|
6b8395a18a0097312d33780f6cd5e203f20acf99
|
5e9251e0ca800c6b5d607a7977554675231d785c
|
refs/heads/master
| 2021-01-20T12:49:17.620368
| 2017-05-05T17:18:53
| 2017-05-05T17:18:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,901
|
java
|
package com.cezarykluczynski.stapi.server.comicStrip.reader;
import com.cezarykluczynski.stapi.client.v1.rest.model.ComicStripBaseResponse;
import com.cezarykluczynski.stapi.client.v1.rest.model.ComicStripFullResponse;
import com.cezarykluczynski.stapi.model.comicStrip.entity.ComicStrip;
import com.cezarykluczynski.stapi.server.comicStrip.dto.ComicStripRestBeanParams;
import com.cezarykluczynski.stapi.server.comicStrip.mapper.ComicStripBaseRestMapper;
import com.cezarykluczynski.stapi.server.comicStrip.mapper.ComicStripFullRestMapper;
import com.cezarykluczynski.stapi.server.comicStrip.query.ComicStripRestQuery;
import com.cezarykluczynski.stapi.server.common.mapper.PageMapper;
import com.cezarykluczynski.stapi.server.common.reader.BaseReader;
import com.cezarykluczynski.stapi.server.common.reader.FullReader;
import com.cezarykluczynski.stapi.server.common.validator.StaticValidator;
import com.google.common.collect.Iterables;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
@Service
public class ComicStripRestReader implements BaseReader<ComicStripRestBeanParams, ComicStripBaseResponse>,
FullReader<String, ComicStripFullResponse> {
private ComicStripRestQuery comicStripRestQuery;
private ComicStripBaseRestMapper comicStripBaseRestMapper;
private ComicStripFullRestMapper comicStripFullRestMapper;
private PageMapper pageMapper;
@Inject
public ComicStripRestReader(ComicStripRestQuery comicStripRestQuery, ComicStripBaseRestMapper comicStripBaseRestMapper,
ComicStripFullRestMapper comicStripFullRestMapper, PageMapper pageMapper) {
this.comicStripRestQuery = comicStripRestQuery;
this.comicStripBaseRestMapper = comicStripBaseRestMapper;
this.comicStripFullRestMapper = comicStripFullRestMapper;
this.pageMapper = pageMapper;
}
@Override
public ComicStripBaseResponse readBase(ComicStripRestBeanParams comicStripRestBeanParams) {
Page<ComicStrip> comicStripPage = comicStripRestQuery.query(comicStripRestBeanParams);
ComicStripBaseResponse comicStripResponse = new ComicStripBaseResponse();
comicStripResponse.setPage(pageMapper.fromPageToRestResponsePage(comicStripPage));
comicStripResponse.getComicStrips().addAll(comicStripBaseRestMapper.mapBase(comicStripPage.getContent()));
return comicStripResponse;
}
@Override
public ComicStripFullResponse readFull(String uid) {
StaticValidator.requireUid(uid);
ComicStripRestBeanParams comicStripRestBeanParams = new ComicStripRestBeanParams();
comicStripRestBeanParams.setUid(uid);
Page<ComicStrip> comicStripPage = comicStripRestQuery.query(comicStripRestBeanParams);
ComicStripFullResponse comicStripResponse = new ComicStripFullResponse();
comicStripResponse.setComicStrip(comicStripFullRestMapper.mapFull(Iterables.getOnlyElement(comicStripPage.getContent(), null)));
return comicStripResponse;
}
}
|
[
"cezary.kluczynski@gmail.com"
] |
cezary.kluczynski@gmail.com
|
3aaec629e3edb096b1bb51b814d9a61340fc2409
|
0790c45dc122c8b6d988862818868dd617f2d9ef
|
/src/main/java/com/dtl/gemini/widget/MorePopWindow.java
|
83344b658a319e84ef55011df918c48af8338c41
|
[] |
no_license
|
wanlihua/Androidgit
|
07034ae50c13df0b85070208012ceb8081e86d75
|
2c0767940e341d0db0ec7ad2cf42c0dc912876d2
|
refs/heads/master
| 2022-12-21T07:36:15.374736
| 2020-09-24T09:00:49
| 2020-09-24T09:00:49
| 298,209,185
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,570
|
java
|
package com.dtl.gemini.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.dtl.gemini.R;
/**
* 大图灵
* 2019/2/18
* 左上角弹窗
**/
public class MorePopWindow extends PopupWindow {
Context context;
public RelativeLayout rl1;
public RelativeLayout rl2;
public RelativeLayout rl3;
public RelativeLayout rl4;
public RelativeLayout rl5;
public TextView textView1;
public TextView textView2;
public TextView textView3;
public TextView textView4;
public TextView textView5;
@SuppressLint("InflateParams")
public MorePopWindow(Context context, Object tv1, Object tv2, Object tv3, Object tv4, Object tv5) {
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View content = inflater.inflate(R.layout.popupwindow_add, null);
// 设置SelectPicPopupWindow的View
this.setContentView(content);
// 设置SelectPicPopupWindow弹出窗体的宽
this.setWidth(LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow弹出窗体的高
this.setHeight(LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow弹出窗体可点击
this.setFocusable(true);
this.setOutsideTouchable(true);
// 刷新状态
this.update();
// 实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0000000000);
// 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ,设置其他控件变化等操作
this.setBackgroundDrawable(dw);
// 设置SelectPicPopupWindow弹出窗体动画效果
this.setAnimationStyle(R.style.AnimationPreview);
rl1 = (RelativeLayout) content.findViewById(R.id.rl1);
rl2 = (RelativeLayout) content.findViewById(R.id.rl2);
rl3 = (RelativeLayout) content.findViewById(R.id.rl3);
rl4 = (RelativeLayout) content.findViewById(R.id.rl4);
rl5 = (RelativeLayout) content.findViewById(R.id.rl5);
textView1 = (TextView) content.findViewById(R.id.tv1);
textView2 = (TextView) content.findViewById(R.id.tv2);
textView3 = (TextView) content.findViewById(R.id.tv3);
textView4 = (TextView) content.findViewById(R.id.tv4);
textView5 = (TextView) content.findViewById(R.id.tv5);
if (tv1 != null)
rl1.setVisibility(View.VISIBLE);
else
rl1.setVisibility(View.GONE);
if (tv2 != null)
rl2.setVisibility(View.VISIBLE);
else
rl2.setVisibility(View.GONE);
if (tv3 != null)
rl3.setVisibility(View.VISIBLE);
else
rl3.setVisibility(View.GONE);
if (tv4 != null)
rl4.setVisibility(View.VISIBLE);
else
rl4.setVisibility(View.GONE);
if (tv5 != null)
rl5.setVisibility(View.VISIBLE);
else
rl5.setVisibility(View.GONE);
textView1.setText(tv1 + "");
textView2.setText(tv2 + "");
textView3.setText(tv3 + "");
textView4.setText(tv4 + "");
textView5.setText(tv5 + "");
}
public void tv1Btn(View.OnClickListener clickListener) {
textView1.setOnClickListener(clickListener);
}
public void tv2Btn(View.OnClickListener clickListener) {
textView2.setOnClickListener(clickListener);
}
public void tv3Btn(View.OnClickListener clickListener) {
textView3.setOnClickListener(clickListener);
}
public void tv4Btn(View.OnClickListener clickListener) {
textView4.setOnClickListener(clickListener);
}
public void tv5Btn(View.OnClickListener clickListener) {
textView5.setOnClickListener(clickListener);
}
public void dismissDialog() {
if (this.isShowing())
MorePopWindow.this.dismiss();
else
return;
}
/**
* 显示popupWindow
*
* @param parent
*/
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
// 以下拉方式显示popupwindow
this.showAsDropDown(parent, 0, 0);
} else {
this.dismiss();
}
}
}
|
[
"838231074@qq.com"
] |
838231074@qq.com
|
ef58a66a48caa010cc4c625309d2d470265e48c7
|
3728dca6b824c22d9d5c0d36de12449234a2c9dd
|
/JAVA-MYSQL/src/main/java/TEST.java
|
4e5f34949031abde0e7824875aafd5a64b67c698
|
[] |
no_license
|
anjnpul/JAVA
|
a7311d682c4e9b67851fe1b1a476af5e544208f1
|
8a8488e03b8125df17ed53c741c6b28384810df4
|
refs/heads/master
| 2022-06-27T11:42:34.590714
| 2020-01-08T20:13:43
| 2020-01-08T20:13:43
| 229,389,379
| 0
| 0
| null | 2022-06-21T02:32:20
| 2019-12-21T06:49:36
|
Java
|
UTF-8
|
Java
| false
| false
| 2,715
|
java
|
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
* @author ANJAN
*/
public class TEST extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try
{
Connection conn=null;
conn = MYSQL_CONNECT.ConnectDB();
out.println("Remote DataBase Connected");
}
catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
[
"anjan.paul3@gmail.com"
] |
anjan.paul3@gmail.com
|
2191e3a84cbc65874032002627bb9484fad606d6
|
25cbef7afa8bd3da7957cf68c09fb4d8b32df1a0
|
/sem6-p6-jsp-one-servlet-jstl-jdbc/src/main/controller/RequestHelper.java
|
d84e6bb70ce0efd37306bd198520bcb005fe7df6
|
[] |
no_license
|
boba-alex/sem-6
|
474578f6fcf09a3ba1ab7d6f82ef35383b14b975
|
786e9e2e950f3321390e14e77db66767bbb06f5e
|
refs/heads/master
| 2021-04-30T04:39:21.909668
| 2018-07-15T20:15:44
| 2018-07-15T20:15:44
| 121,540,898
| 4
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,052
|
java
|
package main.controller;
import main.controller.commands.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
public class RequestHelper {
private static RequestHelper instance = null;
HashMap<String, Command> commands = new HashMap<>();
private RequestHelper() {
commands.put("add-receipt-customer", new AddReceiptCustomerCommand());
commands.put("add-receipt", new AddReceiptCommand());
commands.put("delete-receipt", new DeleteReceiptCommand());
commands.put("analyze-receipts", new AnalyzeReceiptsCommand());
}
public Command getCommand(HttpServletRequest request) {
String action = request.getParameter("command");
Command command = commands.get(action);
if (command == null) {
command = new NoCommand();
}
return command;
}
//Singleton
public static RequestHelper getInstance() {
if (instance == null) {
instance = new RequestHelper();
}
return instance;
}
}
|
[
"099@tut.by"
] |
099@tut.by
|
54ff78c998a22162fab26d9e7e443193eb39e9be
|
f7fbc015359f7e2a7bae421918636b608ea4cef6
|
/base/branches/odbcproto1/src/org/hsqldb/ParserBase.java
|
80a76274d1c288bbdbf942996ab7cfcc9e56e431
|
[] |
no_license
|
svn2github/hsqldb
|
cdb363112cbdb9924c816811577586f0bf8aba90
|
52c703b4d54483899d834b1c23c1de7173558458
|
refs/heads/master
| 2023-09-03T10:33:34.963710
| 2019-01-18T23:07:40
| 2019-01-18T23:07:40
| 155,365,089
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 20,146
|
java
|
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb;
import java.math.BigDecimal;
import org.hsqldb.HsqlNameManager.HsqlName;
import org.hsqldb.lib.ArrayUtil;
import org.hsqldb.lib.HsqlArrayList;
import org.hsqldb.lib.IntKeyIntValueHashMap;
import org.hsqldb.types.IntervalType;
import org.hsqldb.types.NumberType;
import org.hsqldb.types.TimeData;
import org.hsqldb.types.Type;
/**
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.9.0
*/
public class ParserBase {
private Scanner scanner;
protected Token token;
//
protected boolean isRecording;
protected HsqlArrayList recordedStatement;
//
protected boolean isCheckOrTriggerCondition;
protected boolean isSchemaDefinition;
protected int parsePosition;
static final BigDecimal LONG_MAX_VALUE_INCREMENT =
BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.valueOf(1));
/**
* Constructs a new BaseParser object with the given context.
*
* @param t the token source from which to parse commands
*/
ParserBase(Scanner t) {
scanner = t;
token = scanner.token;
}
public Scanner getScanner() {
return scanner;
}
public int getParsePosition() {
return parsePosition;
}
public void setParsePosition(int parsePosition) {
this.parsePosition = parsePosition;
}
/**
* Resets this parse context with the given SQL character sequence.
*
* Internal structures are reset as though a new parser were created
* with the given sql and the originally specified database and session
*
* @param sql a new SQL character sequence to replace the current one
*/
void reset(String sql) {
scanner.reset(sql);
//
parsePosition = 0;
isCheckOrTriggerCondition = false;
isSchemaDefinition = false;
isRecording = false;
recordedStatement = null;
}
int getPosition() {
return scanner.getTokenPosition();
}
void rewind(int position) throws HsqlException {
if (position == scanner.getTokenPosition()) {
return;
}
scanner.position(position);
if (isRecording) {
int i = recordedStatement.size() - 1;
for (; i >= 0; i--) {
Token token = (Token) recordedStatement.get(i);
if (token.position < position) {
break;
}
}
recordedStatement.setSize(i + 1);
}
read();
}
String getLastPart() {
return scanner.getPart(parsePosition, scanner.getTokenPosition());
}
String getLastPart(int position) {
return scanner.getPart(position, scanner.getTokenPosition());
}
String getLastPartAndCurrent(int position) {
return scanner.getPart(position, scanner.getPosition());
}
String getStatement(int startPosition,
short[] startTokens) throws HsqlException {
while (true) {
if (ArrayUtil.find(startTokens, token.tokenType) != -1) {
break;
}
read();
}
String sql = scanner.getPart(startPosition, scanner.getPosition());
return sql;
}
//
void startRecording() {
recordedStatement = new HsqlArrayList();
recordedStatement.add(token.duplicate());
isRecording = true;
}
void recordExpressionForToken(ExpressionColumn expression)
throws HsqlException {
if (isRecording) {
Token recordToken =
(Token) recordedStatement.get(recordedStatement.size() - 1);
recordToken.columnExpression = expression;
}
}
Token[] getRecordedStatement() {
isRecording = false;
recordedStatement.remove(recordedStatement.size() - 1);
Token[] tokens = new Token[recordedStatement.size()];
recordedStatement.toArray(tokens);
recordedStatement = null;
return tokens;
}
void read() throws HsqlException {
scanner.scanNext();
if (token.isMalformed) {
int errorCode = -1;
switch (token.tokenType) {
case Tokens.X_MALFORMED_BINARY_STRING :
errorCode = ErrorCode.X_42587;
break;
case Tokens.X_MALFORMED_BIT_STRING :
errorCode = ErrorCode.X_42588;
break;
case Tokens.X_MALFORMED_UNICODE_STRING :
errorCode = ErrorCode.X_42586;
break;
case Tokens.X_MALFORMED_STRING :
errorCode = ErrorCode.X_42584;
break;
case Tokens.X_UNKNOWN_TOKEN :
errorCode = ErrorCode.X_42582;
break;
case Tokens.X_MALFORMED_NUMERIC :
errorCode = ErrorCode.X_42585;
break;
case Tokens.X_MALFORMED_COMMENT :
errorCode = ErrorCode.X_42589;
break;
case Tokens.X_MALFORMED_IDENTIFIER :
errorCode = ErrorCode.X_42583;
break;
}
throw Error.error(errorCode);
}
if (isRecording) {
Token dup = token.duplicate();
dup.position = scanner.getTokenPosition();
recordedStatement.add(dup);
}
}
boolean isReservedKey() {
return scanner.token.isReservedIdentifier;
}
boolean isCoreReservedKey() {
return scanner.token.isCoreReservedIdentifier;
}
boolean isNonReservedIdentifier() {
return !scanner.token.isReservedIdentifier
&& (scanner.token.isUndelimitedIdentifier
|| scanner.token.isDelimitedIdentifier);
}
void checkIsNonReservedIdentifier() throws HsqlException {
if (!isNonReservedIdentifier()) {
throw unexpectedToken();
}
}
boolean isNonCoreReservedIdentifier() {
return !scanner.token.isCoreReservedIdentifier
&& (scanner.token.isUndelimitedIdentifier
|| scanner.token.isDelimitedIdentifier);
}
void checkIsNonCoreReservedIdentifier() throws HsqlException {
if (!isNonCoreReservedIdentifier()) {
throw unexpectedToken();
}
}
boolean isIdentifier() {
return scanner.token.isUndelimitedIdentifier
|| scanner.token.isDelimitedIdentifier;
}
void checkIsIdentifier() throws HsqlException {
if (!isIdentifier()) {
throw unexpectedToken();
}
}
boolean isDelimitedIdentifier() {
return scanner.token.isDelimitedIdentifier;
}
void checkIsDelimitedIdentifier() throws HsqlException {
if (token.tokenType != Tokens.X_DELIMITED_IDENTIFIER) {
throw Error.error(ErrorCode.X_42569);
}
}
void checkIsNotQuoted() throws HsqlException {
if (token.tokenType == Tokens.X_DELIMITED_IDENTIFIER) {
throw unexpectedToken();
}
}
void checkIsValue() throws HsqlException {
if (token.tokenType != Tokens.X_VALUE) {
throw unexpectedToken();
}
}
void checkIsValue(int dataTypeCode) throws HsqlException {
if (token.tokenType != Tokens.X_VALUE
|| token.dataType.typeCode != dataTypeCode) {
throw unexpectedToken();
}
}
void checkIsThis(int type) throws HsqlException {
if (token.tokenType != type) {
throw unexpectedToken();
}
}
boolean isUndelimitedSimpleName() {
return token.isUndelimitedIdentifier && token.namePrefix == null;
}
boolean isDelimitedSimpleName() {
return token.isDelimitedIdentifier && token.namePrefix == null;
}
boolean isSimpleName() {
return isNonReservedIdentifier() && token.namePrefix == null;
}
void checkIsSimpleName() throws HsqlException {
if (!isSimpleName()) {
throw unexpectedToken();
}
}
void readQuotedString() throws HsqlException {
if (token.dataType.typeCode != Types.SQL_CHAR) {
throw Error.error(ErrorCode.X_42565);
}
}
void readThis(int tokenId) throws HsqlException {
if (token.tokenType != tokenId) {
String required = Tokens.getKeyword(tokenId);
throw unexpectedTokenRequire(required);
}
read();
}
boolean readIfThis(int tokenId) throws HsqlException {
if (token.tokenType == tokenId) {
read();
return true;
}
return false;
}
int readInteger() throws HsqlException {
boolean minus = false;
if (token.tokenType == Tokens.MINUS) {
minus = true;
read();
}
checkIsValue();
if (minus && token.dataType.typeCode == Types.SQL_BIGINT
&& ((Number) token.tokenValue).longValue()
== -(long) Integer.MIN_VALUE) {
read();
return Integer.MIN_VALUE;
}
if (token.dataType.typeCode != Types.SQL_INTEGER) {
throw Error.error(ErrorCode.X_42565);
}
int val = ((Number) token.tokenValue).intValue();
if (minus) {
val = -val;
}
read();
return val;
}
long readBigint() throws HsqlException {
boolean minus = false;
if (token.tokenType == Tokens.MINUS) {
minus = true;
read();
}
checkIsValue();
if (minus && token.dataType.typeCode == Types.SQL_NUMERIC
&& LONG_MAX_VALUE_INCREMENT.equals(token.tokenValue)) {
read();
return Long.MIN_VALUE;
}
if (token.dataType.typeCode != Types.SQL_INTEGER
&& token.dataType.typeCode != Types.SQL_BIGINT) {
throw Error.error(ErrorCode.X_42565);
}
long val = ((Number) token.tokenValue).longValue();
if (minus) {
val = -val;
}
read();
return val;
}
Expression readDateTimeIntervalLiteral() throws HsqlException {
int pos = getPosition();
switch (token.tokenType) {
case Tokens.DATE : {
read();
if (token.tokenType != Tokens.X_VALUE
|| token.dataType.typeCode != Types.SQL_CHAR) {
break;
}
String s = token.tokenString;
read();
Object date = scanner.newDate(s);
return new ExpressionValue(date, Type.SQL_DATE);
}
case Tokens.TIME : {
read();
if (token.tokenType != Tokens.X_VALUE
|| token.dataType.typeCode != Types.SQL_CHAR) {
break;
}
String s = token.tokenString;
read();
TimeData value = scanner.newTime(s);
Type dataType = scanner.dateTimeType;
return new ExpressionValue(value, dataType);
}
case Tokens.TIMESTAMP : {
read();
if (token.tokenType != Tokens.X_VALUE
|| token.dataType.typeCode != Types.SQL_CHAR) {
break;
}
String s = token.tokenString;
read();
Object date = scanner.newTimestamp(s);
Type dataType = scanner.dateTimeType;
return new ExpressionValue(date, dataType);
}
case Tokens.INTERVAL : {
boolean minus = false;
read();
if (token.tokenType == Tokens.MINUS) {
read();
minus = true;
} else if (token.tokenType == Tokens.PLUS) {
read();
}
if (token.tokenType != Tokens.X_VALUE
|| token.dataType.typeCode != Types.SQL_CHAR) {
break;
}
String s = token.tokenString;
read();
IntervalType dataType = readIntervalType();
Object interval = scanner.newInterval(s, dataType);
dataType = (IntervalType) scanner.dateTimeType;
if (minus) {
interval = dataType.negate(interval);
}
return new ExpressionValue(interval, dataType);
}
default :
throw Error.runtimeError(ErrorCode.U_S0500, "Parser");
}
rewind(pos);
return null;
}
IntervalType readIntervalType() throws HsqlException {
int precision = -1;
int scale = -1;
int startToken;
int endToken;
startToken = endToken = token.tokenType;
read();
if (token.tokenType == Tokens.OPENBRACKET) {
read();
precision = readInteger();
if (precision <= 0) {
throw Error.error(ErrorCode.X_42592);
}
if (token.tokenType == Tokens.COMMA) {
if (startToken != Tokens.SECOND) {
throw unexpectedToken();
}
read();
scale = readInteger();
if (scale < 0) {
throw Error.error(ErrorCode.X_42592);
}
}
readThis(Tokens.CLOSEBRACKET);
}
if (token.tokenType == Tokens.TO) {
read();
endToken = token.tokenType;
read();
}
if (token.tokenType == Tokens.OPENBRACKET) {
if (endToken != Tokens.SECOND || endToken == startToken) {
throw unexpectedToken();
}
read();
scale = readInteger();
if (scale < 0) {
throw Error.error(ErrorCode.X_42592);
}
readThis(Tokens.CLOSEBRACKET);
}
int startIndex = ArrayUtil.find(Tokens.SQL_INTERVAL_FIELD_CODES,
startToken);
int endIndex = ArrayUtil.find(Tokens.SQL_INTERVAL_FIELD_CODES,
endToken);
return IntervalType.getIntervalType(startIndex, endIndex, precision,
scale);
}
static int getExpressionType(int tokenT) {
int type = expressionTypeMap.get(tokenT, -1);
if (type == -1) {
throw Error.runtimeError(ErrorCode.U_S0500, "Parser");
}
return type;
}
private static final IntKeyIntValueHashMap expressionTypeMap =
new IntKeyIntValueHashMap(37);
static {
// comparison
expressionTypeMap.put(Tokens.EQUALS, OpTypes.EQUAL);
expressionTypeMap.put(Tokens.GREATER, OpTypes.GREATER);
expressionTypeMap.put(Tokens.LESS, OpTypes.SMALLER);
expressionTypeMap.put(Tokens.GREATER_EQUALS, OpTypes.GREATER_EQUAL);
expressionTypeMap.put(Tokens.LESS_EQUALS, OpTypes.SMALLER_EQUAL);
expressionTypeMap.put(Tokens.NOT_EQUALS, OpTypes.NOT_EQUAL);
// aggregates
expressionTypeMap.put(Tokens.COUNT, OpTypes.COUNT);
expressionTypeMap.put(Tokens.MAX, OpTypes.MAX);
expressionTypeMap.put(Tokens.MIN, OpTypes.MIN);
expressionTypeMap.put(Tokens.SUM, OpTypes.SUM);
expressionTypeMap.put(Tokens.AVG, OpTypes.AVG);
expressionTypeMap.put(Tokens.EVERY, OpTypes.EVERY);
expressionTypeMap.put(Tokens.ANY, OpTypes.SOME);
expressionTypeMap.put(Tokens.SOME, OpTypes.SOME);
expressionTypeMap.put(Tokens.STDDEV_POP, OpTypes.STDDEV_POP);
expressionTypeMap.put(Tokens.STDDEV_SAMP, OpTypes.STDDEV_SAMP);
expressionTypeMap.put(Tokens.VAR_POP, OpTypes.VAR_POP);
expressionTypeMap.put(Tokens.VAR_SAMP, OpTypes.VAR_SAMP);
}
HsqlException unexpectedToken(String tokenS) {
return Error.error(ErrorCode.X_42581, tokenS);
}
HsqlException unexpectedTokenRequire(String required) {
if (token.tokenType == Tokens.X_ENDPARSE) {
return Error.error(ErrorCode.X_42590, ErrorCode.TOKEN_REQUIRED,
new Object[] {
"", required
});
}
String tokenS = token.namePrePrefix != null ? token.namePrePrefix
: token.namePrefix != null
? token.namePrefix
: token.tokenString;
return Error.error(ErrorCode.X_42581, ErrorCode.TOKEN_REQUIRED,
new Object[] {
tokenS, required
});
}
HsqlException unexpectedToken() {
if (token.tokenType == Tokens.X_ENDPARSE) {
return Error.error(ErrorCode.X_42590);
}
String tokenS = token.namePrePrefix != null ? token.namePrePrefix
: token.namePrefix != null
? token.namePrefix
: token.tokenString;
return Error.error(ErrorCode.X_42581, tokenS);
}
HsqlException tooManyIdentifiers() {
String tokenS = token.namePrePrefix != null ? token.namePrePrefix
: token.namePrefix != null
? token.namePrefix
: token.tokenString;
return Error.error(ErrorCode.X_42551, tokenS);
}
HsqlException unsupportedFeature() {
return Error.error(ErrorCode.X_0A501, token.tokenString);
}
HsqlException unsupportedFeature(String string) {
return Error.error(ErrorCode.X_0A501, string);
}
public Number convertToNumber(String s,
NumberType type) throws HsqlException {
return scanner.convertToNumber(s, type);
}
}
|
[
"unsaved@7c7dc5f5-a22d-0410-a3af-b41755a11667"
] |
unsaved@7c7dc5f5-a22d-0410-a3af-b41755a11667
|
95073d738433c40a573df2b882c549636d071c3a
|
9138b43f3a1424e4a8abcafcabf27a6bfcbce006
|
/Opdracht7EJBInheritance/src/java/Entity/Hond.java
|
c073e3896bb0a793669e32c500e21b7543a43866
|
[] |
no_license
|
tiboke1992/Opdracht7
|
189c676646effd0e96e0b847c25cf649a364bc64
|
b0a90f31ad7d8b468573f888b0cdc897494bbaa9
|
refs/heads/master
| 2016-09-11T04:01:31.504500
| 2012-12-03T09:47:28
| 2012-12-03T09:47:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 491
|
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Entity;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
/**
*
* @author stinson
*/
@Entity
@Inheritance
public class Hond extends Huisdier {
private int aantalHoofden;
public int getAantalHoofden() {
return aantalHoofden;
}
public void setAantalHoofden(int aantalHoofden) {
this.aantalHoofden = aantalHoofden;
}
}
|
[
"tibo_hulens@hotmail.com"
] |
tibo_hulens@hotmail.com
|
7e492e8fbc343f0b094c1db520ef615bfbcf198e
|
352c66d36acd18c2f868904f50a5110128e712b9
|
/src/com/alexandragurova/swing1/model/EmploymentCategory.java
|
73fba9136a51dd57802c9eee074e421892922825
|
[] |
no_license
|
alexandragurova/Swing1
|
78527ed4fa34fddb18c7b0abdd614723cf51dde5
|
a4087ce66057a5fed8079e6aaee051f2f886a72d
|
refs/heads/master
| 2020-04-30T05:09:27.214753
| 2015-03-10T19:36:52
| 2015-03-10T19:36:52
| 31,892,607
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 180
|
java
|
package com.alexandragurova.swing1.model;
/**
* Created by Gurova on 09.03.2015.
*/
public enum EmploymentCategory {
employed,
selfemployed,
unemployed,
other
}
|
[
"alexandragurova@yandex.ru"
] |
alexandragurova@yandex.ru
|
b4739714758c486fbc35e8ebbbfe76db2a25ce97
|
754ef0f07410bd7ae7627901efae3376fd361249
|
/10_Board_reply/src/com/reply/model/BbsDAO.java
|
217951ae3951391e22ac831f34e38f5655f967bf
|
[] |
no_license
|
Hoan1993/JSP_Servlet
|
148da69084e809b7db712504a022e72620ba1c42
|
1bb601ee2350dc9e5f448298473180b629881b1e
|
refs/heads/master
| 2021-02-04T16:48:52.238014
| 2020-03-24T08:49:21
| 2020-03-24T08:49:21
| 243,688,258
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,610
|
java
|
package com.reply.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class BbsDAO {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
private BbsDAO() {
// TODO Auto-generated constructor stub
}
private static BbsDAO instance = new BbsDAO();
public static BbsDAO getInstance() {
return instance;
}
public Connection openConn() {
try {
// 1. JNDI 서버 객체 생성
InitialContext ic = new InitialContext();
// 2. lookup() 메서드를 이용하여 매칭되는 커넥션을 찾는다.
DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/myoracle");
// 3. DataSource 객체를 이용하여 커넥션 객체를 하나 가져온다.
conn = ds.getConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void close(Connection conn, Statement stmt, ResultSet rs) {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(Connection conn, Statement stmt) {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<BbsDTO> getBbsList() {
sql = "select * from jsp_bbs order by board_group desc, board_step asc";
conn = openConn();
List<BbsDTO> list = new ArrayList<BbsDTO>();
BbsDTO dto = null;
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
dto = new BbsDTO();
dto.setBoard_no(rs.getInt(1));
dto.setBoard_writer(rs.getString(2));
dto.setBoard_title(rs.getString(3));
dto.setBoard_cont(rs.getString(4));
dto.setBoard_pwd(rs.getString(5));
dto.setBoard_hit(rs.getInt(6));
dto.setBoard_date(rs.getString(7));
dto.setBoard_group(rs.getInt(8));
dto.setBoard_step(rs.getInt(9));
dto.setBoard_indent(rs.getInt(10));
list.add(dto);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt, rs);
}
return list;
}
public int insertRecord(BbsDTO dto) {
sql = "insert into jsp_bbs values(bbs_seq.nextval, ?,?,?,?,default, sysdate, bbs_seq.currval, 0, 0)";
conn = openConn();
int result = 0;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getBoard_writer());
pstmt.setString(2, dto.getBoard_title());
pstmt.setString(3, dto.getBoard_cont());
pstmt.setString(4, dto.getBoard_pwd());
result = pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt);
}
return result;
}
public BbsDTO selectOneRecordByNum(int board_no) {
sql = "select * from jsp_bbs where board_no = ?";
conn = openConn();
BbsDTO dto = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, board_no);
rs = pstmt.executeQuery();
if(rs.next()) {
dto = new BbsDTO();
dto.setBoard_no(rs.getInt(1));
dto.setBoard_writer(rs.getString(2));
dto.setBoard_title(rs.getString(3));
dto.setBoard_cont(rs.getString(4));
dto.setBoard_pwd(rs.getString(5));
dto.setBoard_hit(rs.getInt(6));
dto.setBoard_date(rs.getString(7));
dto.setBoard_group(rs.getInt(8));
dto.setBoard_step(rs.getInt(9));
dto.setBoard_indent(rs.getInt(10));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt, rs);
}
return dto;
}
public void boardHit(int board_no) {
sql = "update jsp_bbs set board_hit = board_hit +1 where board_no=?";
conn = openConn();
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, board_no);
pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt);
}
}
// jsp_bbs 테이블의 게시판의 글에 step을 하나 증가시키는 메서드
public void replyUpdate(int board_group, int board_step) {
sql = "update jsp_bbs set board_step = board_step +1 where board_group = ? and board_step > ?";
conn = openConn();
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, board_group);
pstmt.setInt(2, board_step);
pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt);
}
}
// jsp_bbs 테이블의 게시판 원글에 답변글을 추가하는 메서드
public int replyBoard(BbsDTO dto) {
int result = 0;
try {
conn = openConn();
sql = "insert into jsp_bbs "
+ "values(bbs_seq.nextval, ?,?,?,?, default, sysdate, ?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getBoard_writer());
pstmt.setString(2, dto.getBoard_title());
pstmt.setString(3, dto.getBoard_cont());
pstmt.setString(4, dto.getBoard_pwd());
pstmt.setInt(5, dto.getBoard_group());
pstmt.setInt(6, dto.getBoard_step()+1);
pstmt.setInt(7, dto.getBoard_indent()+1);
result = pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, pstmt);
}
return result;
}
}
|
[
"sist@DESKTOP-3J6RDRE"
] |
sist@DESKTOP-3J6RDRE
|
e7a65506152fba9956f3eea09265686410c6d15c
|
96342d1091241ac93d2d59366b873c8fedce8137
|
/java/com/l2jolivia/gameserver/model/entity/FortSiege.java
|
c2d442a12bc29bc5b6416a9fc248709147e41cb3
|
[] |
no_license
|
soultobe/L2JOlivia_EpicEdition
|
c97ac7d232e429fa6f91d21bb9360cf347c7ee33
|
6f9b3de9f63d70fa2e281b49d139738e02d97cd6
|
refs/heads/master
| 2021-01-10T03:42:04.091432
| 2016-03-09T06:55:59
| 2016-03-09T06:55:59
| 53,468,281
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 33,214
|
java
|
/*
* This file is part of the L2J Olivia project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jolivia.gameserver.model.entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jolivia.Config;
import com.l2jolivia.commons.database.DatabaseFactory;
import com.l2jolivia.gameserver.ThreadPoolManager;
import com.l2jolivia.gameserver.data.sql.impl.ClanTable;
import com.l2jolivia.gameserver.enums.ChatType;
import com.l2jolivia.gameserver.enums.FortTeleportWhoType;
import com.l2jolivia.gameserver.enums.SiegeClanType;
import com.l2jolivia.gameserver.instancemanager.FortManager;
import com.l2jolivia.gameserver.instancemanager.FortSiegeGuardManager;
import com.l2jolivia.gameserver.instancemanager.FortSiegeManager;
import com.l2jolivia.gameserver.model.CombatFlag;
import com.l2jolivia.gameserver.model.FortSiegeSpawn;
import com.l2jolivia.gameserver.model.L2Clan;
import com.l2jolivia.gameserver.model.L2Object;
import com.l2jolivia.gameserver.model.L2SiegeClan;
import com.l2jolivia.gameserver.model.L2Spawn;
import com.l2jolivia.gameserver.model.PcCondOverride;
import com.l2jolivia.gameserver.model.TeleportWhereType;
import com.l2jolivia.gameserver.model.actor.L2Npc;
import com.l2jolivia.gameserver.model.actor.instance.L2DoorInstance;
import com.l2jolivia.gameserver.model.actor.instance.L2FortCommanderInstance;
import com.l2jolivia.gameserver.model.actor.instance.L2PcInstance;
import com.l2jolivia.gameserver.model.events.EventDispatcher;
import com.l2jolivia.gameserver.model.events.impl.sieges.fort.OnFortSiegeFinish;
import com.l2jolivia.gameserver.model.events.impl.sieges.fort.OnFortSiegeStart;
import com.l2jolivia.gameserver.network.NpcStringId;
import com.l2jolivia.gameserver.network.SystemMessageId;
import com.l2jolivia.gameserver.network.serverpackets.NpcSay;
import com.l2jolivia.gameserver.network.serverpackets.SystemMessage;
public class FortSiege implements Siegable
{
protected static final Logger _log = Logger.getLogger(FortSiege.class.getName());
// SQL
private static final String DELETE_FORT_SIEGECLANS_BY_CLAN_ID = "DELETE FROM fortsiege_clans WHERE fort_id = ? AND clan_id = ?";
private static final String DELETE_FORT_SIEGECLANS = "DELETE FROM fortsiege_clans WHERE fort_id = ?";
public class ScheduleEndSiegeTask implements Runnable
{
@Override
public void run()
{
if (!isInProgress())
{
return;
}
try
{
_siegeEnd = null;
endSiege();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: ScheduleEndSiegeTask() for Fort: " + _fort.getName() + " " + e.getMessage(), e);
}
}
}
public class ScheduleStartSiegeTask implements Runnable
{
private final Fort _fortInst;
private final int _time;
public ScheduleStartSiegeTask(int time)
{
_fortInst = _fort;
_time = time;
}
@Override
public void run()
{
if (isInProgress())
{
return;
}
try
{
final SystemMessage sm;
if (_time == 3600) // 1hr remains
{
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(600), 3000000); // Prepare task for 10 minutes left.
}
else if (_time == 600) // 10min remains
{
getFort().despawnSuspiciousMerchant();
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(10);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(300), 300000); // Prepare task for 5 minutes left.
}
else if (_time == 300) // 5min remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(5);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(60), 240000); // Prepare task for 1 minute left.
}
else if (_time == 60) // 1min remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(1);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(30), 30000); // Prepare task for 30 seconds left.
}
else if (_time == 30) // 30seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(30);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(10), 20000); // Prepare task for 10 seconds left.
}
else if (_time == 10) // 10seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(10);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(5), 5000); // Prepare task for 5 seconds left.
}
else if (_time == 5) // 5seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(5);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(1), 4000); // Prepare task for 1 seconds left.
}
else if (_time == 1) // 1seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(1);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(0), 1000); // Prepare task start siege.
}
else if (_time == 0)// start siege
{
_fortInst.getSiege().startSiege();
}
else
{
_log.warning("Exception: ScheduleStartSiegeTask(): unknown siege time: " + String.valueOf(_time));
}
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: ScheduleStartSiegeTask() for Fort: " + _fortInst.getName() + " " + e.getMessage(), e);
}
}
}
public class ScheduleSuspiciousMerchantSpawn implements Runnable
{
@Override
public void run()
{
if (isInProgress())
{
return;
}
try
{
_fort.spawnSuspiciousMerchant();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: ScheduleSuspicoiusMerchantSpawn() for Fort: " + _fort.getName() + " " + e.getMessage(), e);
}
}
}
public class ScheduleSiegeRestore implements Runnable
{
@Override
public void run()
{
if (!isInProgress())
{
return;
}
try
{
_siegeRestore = null;
resetSiege();
announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.THE_BARRACKS_FUNCTION_HAS_BEEN_RESTORED));
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: ScheduleSiegeRestore() for Fort: " + _fort.getName() + " " + e.getMessage(), e);
}
}
}
private final List<L2SiegeClan> _attackerClans = new CopyOnWriteArrayList<>();
// Fort setting
protected List<L2Spawn> _commanders = new CopyOnWriteArrayList<>();
protected final Fort _fort;
private boolean _isInProgress = false;
private FortSiegeGuardManager _siegeGuardManager;
ScheduledFuture<?> _siegeEnd = null;
ScheduledFuture<?> _siegeRestore = null;
ScheduledFuture<?> _siegeStartTask = null;
public FortSiege(Fort fort)
{
_fort = fort;
checkAutoTask();
FortSiegeManager.getInstance().addSiege(this);
}
/**
* When siege ends.
*/
@Override
public void endSiege()
{
if (isInProgress())
{
_isInProgress = false; // Flag so that siege instance can be started
removeFlags(); // Removes all flags. Note: Remove flag before teleporting players
unSpawnFlags();
updatePlayerSiegeStateFlags(true);
int ownerId = -1;
if (getFort().getOwnerClan() != null)
{
ownerId = getFort().getOwnerClan().getId();
}
getFort().getZone().banishForeigners(ownerId);
getFort().getZone().setIsActive(false);
getFort().getZone().updateZoneStatusForCharactersInside();
getFort().getZone().setSiegeInstance(null);
saveFortSiege(); // Save fort specific data
clearSiegeClan(); // Clear siege clan from db
removeCommanders(); // Remove commander from this fort
getFort().spawnNpcCommanders(); // Spawn NPC commanders
getSiegeGuardManager().unspawnSiegeGuard(); // Remove all spawned siege guard from this fort
getFort().resetDoors(); // Respawn door to fort
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSuspiciousMerchantSpawn(), FortSiegeManager.getInstance().getSuspiciousMerchantRespawnDelay() * 60 * 1000L); // Prepare 3hr task for suspicious merchant respawn
setSiegeDateTime(true); // store suspicious merchant spawn in DB
if (_siegeEnd != null)
{
_siegeEnd.cancel(true);
_siegeEnd = null;
}
if (_siegeRestore != null)
{
_siegeRestore.cancel(true);
_siegeRestore = null;
}
if ((getFort().getOwnerClan() != null) && (getFort().getFlagPole().getMeshIndex() == 0))
{
getFort().setVisibleFlag(true);
}
_log.info("Siege of " + getFort().getName() + " fort finished.");
// Notify to scripts.
EventDispatcher.getInstance().notifyEventAsync(new OnFortSiegeFinish(this), getFort());
}
}
/**
* When siege starts
*/
@Override
public void startSiege()
{
if (!isInProgress())
{
if (_siegeStartTask != null) // used admin command "admin_startfortsiege"
{
_siegeStartTask.cancel(true);
getFort().despawnSuspiciousMerchant();
}
_siegeStartTask = null;
if (getAttackerClans().isEmpty())
{
return;
}
_isInProgress = true; // Flag so that same siege instance cannot be started again
loadSiegeClan(); // Load siege clan from db
updatePlayerSiegeStateFlags(false);
teleportPlayer(FortTeleportWhoType.Attacker, TeleportWhereType.TOWN); // Teleport to the closest town
getFort().despawnNpcCommanders(); // Despawn NPC commanders
spawnCommanders(); // Spawn commanders
getFort().resetDoors(); // Spawn door
spawnSiegeGuard(); // Spawn siege guard
getFort().setVisibleFlag(false);
getFort().getZone().setSiegeInstance(this);
getFort().getZone().setIsActive(true);
getFort().getZone().updateZoneStatusForCharactersInside();
// Schedule a task to prepare auto siege end
_siegeEnd = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(), FortSiegeManager.getInstance().getSiegeLength() * 60 * 1000L); // Prepare auto end task
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THE_FORTRESS_BATTLE_S1_HAS_BEGUN);
sm.addCastleId(getFort().getResidenceId());
announceToPlayer(sm);
saveFortSiege();
_log.info("Siege of " + getFort().getName() + " fort started.");
// Notify to scripts.
EventDispatcher.getInstance().notifyEventAsync(new OnFortSiegeStart(this), getFort());
}
}
/**
* Announce to player.
* @param sm the system message to send to player
*/
public void announceToPlayer(SystemMessage sm)
{
// announce messages only for participants
L2Clan clan;
for (L2SiegeClan siegeclan : getAttackerClans())
{
clan = ClanTable.getInstance().getClan(siegeclan.getClanId());
for (L2PcInstance member : clan.getOnlineMembers(0))
{
member.sendPacket(sm);
}
}
if (getFort().getOwnerClan() != null)
{
clan = ClanTable.getInstance().getClan(getFort().getOwnerClan().getId());
for (L2PcInstance member : clan.getOnlineMembers(0))
{
if (member != null)
{
member.sendPacket(sm);
}
}
}
}
public void announceToPlayer(SystemMessage sm, String s)
{
sm.addString(s);
announceToPlayer(sm);
}
public void updatePlayerSiegeStateFlags(boolean clear)
{
L2Clan clan;
for (L2SiegeClan siegeclan : getAttackerClans())
{
clan = ClanTable.getInstance().getClan(siegeclan.getClanId());
for (L2PcInstance member : clan.getOnlineMembers(0))
{
if (clear)
{
member.setSiegeState((byte) 0);
member.setSiegeSide(0);
member.setIsInSiege(false);
member.stopFameTask();
}
else
{
member.setSiegeState((byte) 1);
member.setSiegeSide(getFort().getResidenceId());
if (checkIfInZone(member))
{
member.setIsInSiege(true);
member.startFameTask(Config.FORTRESS_ZONE_FAME_TASK_FREQUENCY * 1000, Config.FORTRESS_ZONE_FAME_AQUIRE_POINTS);
}
}
member.broadcastUserInfo();
}
}
if (getFort().getOwnerClan() != null)
{
clan = ClanTable.getInstance().getClan(getFort().getOwnerClan().getId());
for (L2PcInstance member : clan.getOnlineMembers(0))
{
if (member == null)
{
continue;
}
if (clear)
{
member.setSiegeState((byte) 0);
member.setSiegeSide(0);
member.setIsInSiege(false);
member.stopFameTask();
}
else
{
member.setSiegeState((byte) 2);
member.setSiegeSide(getFort().getResidenceId());
if (checkIfInZone(member))
{
member.setIsInSiege(true);
member.startFameTask(Config.FORTRESS_ZONE_FAME_TASK_FREQUENCY * 1000, Config.FORTRESS_ZONE_FAME_AQUIRE_POINTS);
}
}
member.broadcastUserInfo();
}
}
}
/**
* @param object
* @return true if object is inside the zone
*/
public boolean checkIfInZone(L2Object object)
{
return checkIfInZone(object.getX(), object.getY(), object.getZ());
}
/**
* @param x
* @param y
* @param z
* @return true if object is inside the zone
*/
public boolean checkIfInZone(int x, int y, int z)
{
return (isInProgress() && (getFort().checkIfInZone(x, y, z))); // Fort zone during siege
}
/**
* @param clan The L2Clan of the player
* @return true if clan is attacker
*/
@Override
public boolean checkIsAttacker(L2Clan clan)
{
return (getAttackerClan(clan) != null);
}
/**
* @param clan The L2Clan of the player
* @return true if clan is defender
*/
@Override
public boolean checkIsDefender(L2Clan clan)
{
if ((clan != null) && (getFort().getOwnerClan() == clan))
{
return true;
}
return false;
}
/** Clear all registered siege clans from database for fort */
public void clearSiegeClan()
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("DELETE FROM fortsiege_clans WHERE fort_id=?"))
{
ps.setInt(1, getFort().getResidenceId());
ps.execute();
if (getFort().getOwnerClan() != null)
{
try (PreparedStatement delete = con.prepareStatement("DELETE FROM fortsiege_clans WHERE clan_id=?"))
{
delete.setInt(1, getFort().getOwnerClan().getId());
delete.execute();
}
}
getAttackerClans().clear();
// if siege is in progress, end siege
if (isInProgress())
{
endSiege();
}
// if siege isn't in progress (1hr waiting time till siege starts), cancel waiting time
if (_siegeStartTask != null)
{
_siegeStartTask.cancel(true);
_siegeStartTask = null;
}
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: clearSiegeClan(): " + e.getMessage(), e);
}
}
/** Set the date for the next siege. */
private void clearSiegeDate()
{
getFort().getSiegeDate().setTimeInMillis(0);
}
/**
* @return list of L2PcInstance registered as attacker in the zone.
*/
@Override
public List<L2PcInstance> getAttackersInZone()
{
final List<L2PcInstance> players = new LinkedList<>();
for (L2SiegeClan siegeclan : getAttackerClans())
{
final L2Clan clan = ClanTable.getInstance().getClan(siegeclan.getClanId());
for (L2PcInstance player : clan.getOnlineMembers(0))
{
if (player.isInSiege())
{
players.add(player);
}
}
}
return players;
}
/**
* @return list of L2PcInstance in the zone.
*/
public List<L2PcInstance> getPlayersInZone()
{
return getFort().getZone().getPlayersInside();
}
/**
* @return list of L2PcInstance owning the fort in the zone.
*/
public List<L2PcInstance> getOwnersInZone()
{
final List<L2PcInstance> players = new LinkedList<>();
if (getFort().getOwnerClan() != null)
{
final L2Clan clan = ClanTable.getInstance().getClan(getFort().getOwnerClan().getId());
if (clan != getFort().getOwnerClan())
{
return null;
}
for (L2PcInstance player : clan.getOnlineMembers(0))
{
if (player.isInSiege())
{
players.add(player);
}
}
}
return players;
}
/**
* TODO: To DP AI<br>
* Commander was killed
* @param instance
*/
public void killedCommander(L2FortCommanderInstance instance)
{
if (!_commanders.isEmpty() && (getFort() != null))
{
final L2Spawn spawn = instance.getSpawn();
if (spawn != null)
{
final List<FortSiegeSpawn> commanders = FortSiegeManager.getInstance().getCommanderSpawnList(getFort().getResidenceId());
for (FortSiegeSpawn spawn2 : commanders)
{
if (spawn2.getId() == spawn.getId())
{
NpcStringId npcString = null;
switch (spawn2.getMessageId())
{
case 1:
{
npcString = NpcStringId.YOU_MAY_HAVE_BROKEN_OUR_ARROWS_BUT_YOU_WILL_NEVER_BREAK_OUR_WILL_ARCHERS_RETREAT;
break;
}
case 2:
{
npcString = NpcStringId.AIIEEEE_COMMAND_CENTER_THIS_IS_GUARD_UNIT_WE_NEED_BACKUP_RIGHT_AWAY;
break;
}
case 3:
{
npcString = NpcStringId.AT_LAST_THE_MAGIC_CIRCLE_THAT_PROTECTS_THE_FORTRESS_HAS_WEAKENED_VOLUNTEERS_STAND_BACK;
break;
}
case 4:
{
npcString = NpcStringId.I_FEEL_SO_MUCH_GRIEF_THAT_I_CAN_T_EVEN_TAKE_CARE_OF_MYSELF_THERE_ISN_T_ANY_REASON_FOR_ME_TO_STAY_HERE_ANY_LONGER;
break;
}
}
if (npcString != null)
{
instance.broadcastPacket(new NpcSay(instance.getObjectId(), ChatType.NPC_SHOUT, instance.getId(), npcString));
}
}
}
_commanders.remove(spawn);
if (_commanders.isEmpty())
{
// spawn fort flags
spawnFlag(getFort().getResidenceId());
// cancel door/commanders respawn
if (_siegeRestore != null)
{
_siegeRestore.cancel(true);
}
// open doors in main building
for (L2DoorInstance door : getFort().getDoors())
{
if (door.getIsShowHp())
{
continue;
}
// TODO this also opens control room door at big fort
door.openMe();
}
getFort().getSiege().announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.ALL_BARRACKS_ARE_OCCUPIED));
}
// schedule restoring doors/commanders respawn
else if (_siegeRestore == null)
{
getFort().getSiege().announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.THE_BARRACKS_HAVE_BEEN_SEIZED));
_siegeRestore = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSiegeRestore(), FortSiegeManager.getInstance().getCountDownLength() * 60 * 1000L);
}
else
{
getFort().getSiege().announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.THE_BARRACKS_HAVE_BEEN_SEIZED));
}
}
else
{
_log.warning("FortSiege.killedCommander(): killed commander, but commander not registered for fortress. NpcId: " + instance.getId() + " FortId: " + getFort().getResidenceId());
}
}
}
/**
* Remove the flag that was killed
* @param flag
*/
public void killedFlag(L2Npc flag)
{
if (flag == null)
{
return;
}
for (L2SiegeClan clan : getAttackerClans())
{
if (clan.removeFlag(flag))
{
return;
}
}
}
/**
* Register clan as attacker.<BR>
* @param player The L2PcInstance of the player trying to register.
* @param checkConditions True if should be checked conditions, false otherwise
* @return Number that defines what happened. <BR>
* 0 - Player don't have clan.<BR>
* 1 - Player don't have enough adena to register.<BR>
* 2 - Is not right time to register Fortress now.<BR>
* 3 - Players clan is already registered to siege.<BR>
* 4 - Players clan is successfully registered to siege.
*/
public int addAttacker(L2PcInstance player, boolean checkConditions)
{
if (player.getClan() == null)
{
return 0; // Player dont have clan
}
if (checkConditions)
{
if (getFort().getSiege().getAttackerClans().isEmpty() && (player.getInventory().getAdena() < 250000))
{
return 1; // Player don't have enough adena to register
}
for (Fort fort : FortManager.getInstance().getForts())
{
if (fort.getSiege().getAttackerClan(player.getClanId()) != null)
{
return 3; // Players clan is already registered to siege
}
if ((fort.getOwnerClan() == player.getClan()) && (fort.getSiege().isInProgress() || (fort.getSiege()._siegeStartTask != null)))
{
return 3; // Players clan is already registered to siege
}
}
}
saveSiegeClan(player.getClan());
if (getAttackerClans().size() == 1)
{
if (checkConditions)
{
player.reduceAdena("FortressSiege", 250000, null, true);
}
startAutoTask(true);
}
return 4; // Players clan is successfully registered to siege
}
/**
* Remove clan from siege
* @param clan The clan being removed
*/
public void removeAttacker(L2Clan clan)
{
if ((clan == null) || (clan.getFortId() == getFort().getResidenceId()) || !FortSiegeManager.getInstance().checkIsRegistered(clan, getFort().getResidenceId()))
{
return;
}
removeSiegeClan(clan.getId());
}
/**
* This function does not do any checks and should not be called from bypass !
* @param clanId
*/
private void removeSiegeClan(int clanId)
{
final String query = (clanId != 0) ? DELETE_FORT_SIEGECLANS_BY_CLAN_ID : DELETE_FORT_SIEGECLANS;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement(query))
{
ps.setInt(1, getFort().getResidenceId());
if (clanId != 0)
{
ps.setInt(2, clanId);
}
ps.execute();
loadSiegeClan();
if (getAttackerClans().isEmpty())
{
if (isInProgress())
{
endSiege();
}
else
{
saveFortSiege(); // Clear siege time in DB
}
if (_siegeStartTask != null)
{
_siegeStartTask.cancel(true);
_siegeStartTask = null;
}
}
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception on removeSiegeClan: " + e.getMessage(), e);
}
}
/**
* Start the auto tasks
*/
public void checkAutoTask()
{
if (_siegeStartTask != null)
{
return;
}
final long delay = getFort().getSiegeDate().getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
if (delay < 0)
{
// siege time in past
saveFortSiege();
clearSiegeClan(); // remove all clans
// spawn suspicious merchant immediately
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
}
else
{
loadSiegeClan();
if (getAttackerClans().isEmpty())
{
// no attackers - waiting for suspicious merchant spawn
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSuspiciousMerchantSpawn(), delay);
}
else
{
// preparing start siege task
if (delay > 3600000) // more than hour, how this can happens ? spawn suspicious merchant
{
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(3600), delay - 3600000);
}
if (delay > 600000) // more than 10 min, spawn suspicious merchant
{
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(600), delay - 600000);
}
else if (delay > 300000)
{
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(300), delay - 300000);
}
else if (delay > 60000)
{
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(60), delay - 60000);
}
else
{
// lower than 1 min, set to 1 min
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(60), 0);
}
_log.info("Siege of " + getFort().getName() + " fort: " + getFort().getSiegeDate().getTime());
}
}
}
/**
* Start the auto task
* @param setTime
*/
public void startAutoTask(boolean setTime)
{
if (_siegeStartTask != null)
{
return;
}
if (setTime)
{
setSiegeDateTime(false);
}
if (getFort().getOwnerClan() != null)
{
getFort().getOwnerClan().broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.A_FORTRESS_IS_UNDER_ATTACK));
}
// Execute siege auto start
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(3600), 0);
}
/**
* Teleport players
* @param teleportWho
* @param teleportWhere
*/
public void teleportPlayer(FortTeleportWhoType teleportWho, TeleportWhereType teleportWhere)
{
List<L2PcInstance> players;
switch (teleportWho)
{
case Owner:
{
players = getOwnersInZone();
break;
}
case Attacker:
{
players = getAttackersInZone();
break;
}
default:
{
players = getPlayersInZone();
}
}
for (L2PcInstance player : players)
{
if (player.canOverrideCond(PcCondOverride.FORTRESS_CONDITIONS) || player.isJailed())
{
continue;
}
player.teleToLocation(teleportWhere);
}
}
/**
* Add clan as attacker<
* @param clanId
*/
private void addAttacker(int clanId)
{
getAttackerClans().add(new L2SiegeClan(clanId, SiegeClanType.ATTACKER)); // Add registered attacker to attacker list
}
/**
* @param clan
* @return {@code true} if the clan has already registered to a siege for the same day, {@code false} otherwise.
*/
public boolean checkIfAlreadyRegisteredForSameDay(L2Clan clan)
{
for (FortSiege siege : FortSiegeManager.getInstance().getSieges())
{
if (siege == this)
{
continue;
}
if (siege.getSiegeDate().get(Calendar.DAY_OF_WEEK) == getSiegeDate().get(Calendar.DAY_OF_WEEK))
{
if (siege.checkIsAttacker(clan))
{
return true;
}
if (siege.checkIsDefender(clan))
{
return true;
}
}
}
return false;
}
private void setSiegeDateTime(boolean merchant)
{
final Calendar newDate = Calendar.getInstance();
if (merchant)
{
newDate.add(Calendar.MINUTE, FortSiegeManager.getInstance().getSuspiciousMerchantRespawnDelay());
}
else
{
newDate.add(Calendar.MINUTE, 60);
}
getFort().setSiegeDate(newDate);
saveSiegeDate();
}
/** Load siege clans. */
private void loadSiegeClan()
{
getAttackerClans().clear();
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT clan_id FROM fortsiege_clans WHERE fort_id=?"))
{
ps.setInt(1, getFort().getResidenceId());
try (ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
addAttacker(rs.getInt("clan_id"));
}
}
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: loadSiegeClan(): " + e.getMessage(), e);
}
}
/** Remove commanders. */
private void removeCommanders()
{
if ((_commanders != null) && !_commanders.isEmpty())
{
// Remove all instance of commanders for this fort
for (L2Spawn spawn : _commanders)
{
if (spawn != null)
{
spawn.stopRespawn();
if (spawn.getLastSpawn() != null)
{
spawn.getLastSpawn().deleteMe();
}
}
}
_commanders.clear();
}
}
/** Remove all flags. */
private void removeFlags()
{
for (L2SiegeClan sc : getAttackerClans())
{
if (sc != null)
{
sc.removeFlags();
}
}
}
/** Save fort siege related to database. */
private void saveFortSiege()
{
clearSiegeDate(); // clear siege date
saveSiegeDate(); // Save the new date
}
/** Save siege date to database. */
private void saveSiegeDate()
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("UPDATE fort SET siegeDate = ? WHERE id = ?"))
{
ps.setLong(1, getSiegeDate().getTimeInMillis());
ps.setInt(2, getFort().getResidenceId());
ps.execute();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: saveSiegeDate(): " + e.getMessage(), e);
}
}
/**
* Save registration to database.
* @param clan
*/
private void saveSiegeClan(L2Clan clan)
{
if (getAttackerClans().size() >= FortSiegeManager.getInstance().getAttackerMaxClans())
{
return;
}
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO fortsiege_clans (clan_id,fort_id) values (?,?)"))
{
ps.setInt(1, clan.getId());
ps.setInt(2, getFort().getResidenceId());
ps.execute();
addAttacker(clan.getId());
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: saveSiegeClan(L2Clan clan): " + e.getMessage(), e);
}
}
/** Spawn commanders. */
private void spawnCommanders()
{
// Set commanders array size if one does not exist
try
{
_commanders.clear();
for (FortSiegeSpawn _sp : FortSiegeManager.getInstance().getCommanderSpawnList(getFort().getResidenceId()))
{
final L2Spawn spawnDat = new L2Spawn(_sp.getId());
spawnDat.setAmount(1);
spawnDat.setX(_sp.getLocation().getX());
spawnDat.setY(_sp.getLocation().getY());
spawnDat.setZ(_sp.getLocation().getZ());
spawnDat.setHeading(_sp.getLocation().getHeading());
spawnDat.setRespawnDelay(60);
spawnDat.doSpawn();
spawnDat.stopRespawn();
_commanders.add(spawnDat);
}
}
catch (Exception e)
{
// problem with initializing spawn, go to next one
_log.log(Level.WARNING, "FortSiege.spawnCommander: Spawn could not be initialized: " + e.getMessage(), e);
}
}
private void spawnFlag(int Id)
{
for (CombatFlag cf : FortSiegeManager.getInstance().getFlagList(Id))
{
cf.spawnMe();
}
}
private void unSpawnFlags()
{
if (FortSiegeManager.getInstance().getFlagList(getFort().getResidenceId()) == null)
{
return;
}
for (CombatFlag cf : FortSiegeManager.getInstance().getFlagList(getFort().getResidenceId()))
{
cf.unSpawnMe();
}
}
/**
* Spawn siege guard.
*/
private void spawnSiegeGuard()
{
getSiegeGuardManager().spawnSiegeGuard();
}
@Override
public final L2SiegeClan getAttackerClan(L2Clan clan)
{
if (clan == null)
{
return null;
}
return getAttackerClan(clan.getId());
}
@Override
public final L2SiegeClan getAttackerClan(int clanId)
{
for (L2SiegeClan sc : getAttackerClans())
{
if ((sc != null) && (sc.getClanId() == clanId))
{
return sc;
}
}
return null;
}
@Override
public final List<L2SiegeClan> getAttackerClans()
{
return _attackerClans;
}
public final Fort getFort()
{
return _fort;
}
public final boolean isInProgress()
{
return _isInProgress;
}
@Override
public final Calendar getSiegeDate()
{
return getFort().getSiegeDate();
}
@Override
public List<L2Npc> getFlag(L2Clan clan)
{
if (clan != null)
{
final L2SiegeClan sc = getAttackerClan(clan);
if (sc != null)
{
return sc.getFlag();
}
}
return null;
}
public final FortSiegeGuardManager getSiegeGuardManager()
{
if (_siegeGuardManager == null)
{
_siegeGuardManager = new FortSiegeGuardManager(getFort());
}
return _siegeGuardManager;
}
public void resetSiege()
{
// reload commanders and repair doors
removeCommanders();
spawnCommanders();
getFort().resetDoors();
}
public List<L2Spawn> getCommanders()
{
return _commanders;
}
@Override
public L2SiegeClan getDefenderClan(int clanId)
{
return null;
}
@Override
public L2SiegeClan getDefenderClan(L2Clan clan)
{
return null;
}
@Override
public List<L2SiegeClan> getDefenderClans()
{
return null;
}
@Override
public boolean giveFame()
{
return true;
}
@Override
public int getFameFrequency()
{
return Config.FORTRESS_ZONE_FAME_TASK_FREQUENCY;
}
@Override
public int getFameAmount()
{
return Config.FORTRESS_ZONE_FAME_AQUIRE_POINTS;
}
@Override
public void updateSiege()
{
}
}
|
[
"kim@tsnet-j.co.jp"
] |
kim@tsnet-j.co.jp
|
ae3562129673ea6fd443ad9351d36e5715fe6cd8
|
a4cfe7314e5c38538149d9fa639b304360f13afd
|
/Java_Level1/Task2/lesson7/src/Plate.java
|
771a1df7c011893d3980e5c15cbb3e32b2021566
|
[] |
no_license
|
KwakYV/Study
|
dec2a57eb4390cd905c453a4e4e5e65f365552d3
|
144bf5abe3eef0cc8211c4e102b138e112a4624b
|
refs/heads/master
| 2022-09-28T07:41:38.863554
| 2021-11-14T18:28:28
| 2021-11-14T18:28:28
| 117,089,389
| 0
| 0
| null | 2022-09-08T01:14:10
| 2018-01-11T11:07:58
|
Java
|
UTF-8
|
Java
| false
| false
| 397
|
java
|
public class Plate {
private int food;
public Plate(int food) {
this.food = food;
}
public void info() {
System.out.println("plate: " + food);
}
public void decreaseFood(int n) {
if (n <= food)
food -= n;
}
public void increaseFood(int n){
food += n;
}
public int getFood() {
return this.food;
}
}
|
[
"yury.kvak@leroymerlin.ru"
] |
yury.kvak@leroymerlin.ru
|
3d3caa2df0e9493d80f00c2c455d08ae43df1be3
|
de3d5289dd998ab3e2d1551d8fb14825f22247a5
|
/app/src/main/java/com/calyx/pointmobiledemo/api/model/Location.java
|
b9d69acf28ecc847e3a0cf98d66b97f8a7715d2f
|
[] |
no_license
|
skiw9841/PointMobileDemo
|
98ec0133eb9f8176b41bb8e45ddc1cefed8aef15
|
325a03abd9802ba21923e9711a77d7ab58e0cc2c
|
refs/heads/master
| 2020-12-14T21:05:14.442433
| 2020-01-27T11:01:26
| 2020-01-27T11:01:26
| 234,868,490
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 457
|
java
|
package com.calyx.pointmobiledemo.api.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Location implements Serializable {
@SerializedName("street1") public String street1 = "street";
@SerializedName("city") public String city;
@SerializedName("state") public String state;
@SerializedName("country") public String country;
@SerializedName("postcode") public String postcode;
}
|
[
"skiw9841@gmail.com"
] |
skiw9841@gmail.com
|
6d0c722bea456ff973e8b056dc9a66df7c28620c
|
0faf4e5aef423441a2d669879960e63c678d9f8c
|
/src/lsibanda/aircraft/Coordinates.java
|
71be242047e539cfd43298a9d8c939195d3aa491
|
[] |
no_license
|
lsibanda/Avaj-launcher
|
56df9512ca2b7e947ffec811782bddd7fc7e4cdd
|
85d5a9d1efd7fcf2f5762093822a6d3cd14e5fcf
|
refs/heads/master
| 2020-06-15T22:30:47.454356
| 2019-07-05T12:56:43
| 2019-07-05T12:56:43
| 195,409,047
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 568
|
java
|
package lsibanda.aircraft;
public class Coordinates {
Coordinates(int longitude, int latitude, int height)
{
this.longitude = longitude;
this.latitude = latitude;
this.height = height > 100 ? 100 : height;
// if (height > 100)
}
public int getLongitude()
{
return this.longitude;
}
public int getLatitude()
{
return this.latitude;
}
public int getHeight()
{
return this.height;
}
private int longitude;
private int latitude;
private int height;
}
|
[
"lsibanda@c4r12s8.wethinkcode.co.za"
] |
lsibanda@c4r12s8.wethinkcode.co.za
|
46f13e71dc6b76938a9951c5fbc68d961518d544
|
1ac0c3219e44db71950e79acac8ecf370f8e2a7b
|
/src/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java
|
5f35e3ad7b521abbe6f30361e38df96fc09845dd
|
[
"BSD-3-Clause"
] |
permissive
|
yeahhhhhhhh/chromium_quic
|
5383c74ca3665c4639899a2aa5741ca2efa39ffb
|
217d9cdd739b3cc9a440ecea38813c0ce85ef251
|
refs/heads/master
| 2022-12-08T04:12:54.583056
| 2019-08-19T15:03:52
| 2019-08-19T15:03:52
| 203,185,892
| 1
| 3
| null | 2022-11-19T05:44:25
| 2019-08-19T14:09:51
| null |
UTF-8
|
Java
| false
| false
| 94,366
|
java
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences.password;
import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.Intents.intending;
import static android.support.test.espresso.intent.matcher.BundleMatchers.hasEntry;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasData;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasExtras;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasType;
import static android.support.test.espresso.intent.matcher.UriMatchers.hasHost;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.isEnabled;
import static android.support.test.espresso.matcher.ViewMatchers.isRoot;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.chromium.chrome.test.util.ViewUtils.VIEW_GONE;
import static org.chromium.chrome.test.util.ViewUtils.VIEW_INVISIBLE;
import static org.chromium.chrome.test.util.ViewUtils.VIEW_NULL;
import static org.chromium.chrome.test.util.ViewUtils.waitForView;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.support.annotation.IdRes;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.intent.Intents;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.filters.SmallTest;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.view.menu.ActionMenuItemView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.chromium.base.Callback;
import org.chromium.base.CollectionUtil;
import org.chromium.base.IntStringCallback;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeFeatureList;
import org.chromium.chrome.browser.history.HistoryActivity;
import org.chromium.chrome.browser.history.HistoryManager;
import org.chromium.chrome.browser.history.StubbedHistoryProvider;
import org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference;
import org.chromium.chrome.browser.preferences.ChromeSwitchPreference;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.Preferences;
import org.chromium.chrome.browser.preferences.PreferencesTest;
import org.chromium.chrome.browser.sync.ProfileSyncService;
import org.chromium.chrome.test.ChromeBrowserTestRule;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.components.signin.ChromeSigninController;
import org.chromium.components.sync.ModelType;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
* Tests for the "Save Passwords" settings screen.
*/
@RunWith(BaseJUnit4ClassRunner.class)
public class SavePasswordsPreferencesTest {
private static final long UI_UPDATING_TIMEOUT_MS = 3000;
@Rule
public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule();
@Rule
public TestRule mProcessor = new Features.InstrumentationProcessor();
@Rule
public IntentsTestRule<HistoryActivity> mHistoryActivityTestRule =
new IntentsTestRule<>(HistoryActivity.class, false, false);
private static final class FakePasswordManagerHandler implements PasswordManagerHandler {
// This class has exactly one observer, set on construction and expected to last at least as
// long as this object (a good candidate is the owner of this object).
private final PasswordListObserver mObserver;
// The faked contents of the password store to be displayed.
private ArrayList<SavedPasswordEntry> mSavedPasswords = new ArrayList<SavedPasswordEntry>();
// The faked contents of the saves password exceptions to be displayed.
private ArrayList<String> mSavedPasswordExeptions = new ArrayList<>();
// The following three data members are set once {@link #serializePasswords()} is called.
@Nullable
private IntStringCallback mExportSuccessCallback;
@Nullable
private Callback<String> mExportErrorCallback;
@Nullable
private String mExportTargetPath;
public void setSavedPasswords(ArrayList<SavedPasswordEntry> savedPasswords) {
mSavedPasswords = savedPasswords;
}
public void setSavedPasswordExceptions(ArrayList<String> savedPasswordExceptions) {
mSavedPasswordExeptions = savedPasswordExceptions;
}
public IntStringCallback getExportSuccessCallback() {
return mExportSuccessCallback;
}
public Callback<String> getExportErrorCallback() {
return mExportErrorCallback;
}
public String getExportTargetPath() {
return mExportTargetPath;
}
/**
* Constructor.
* @param PasswordListObserver The only observer.
*/
public FakePasswordManagerHandler(PasswordListObserver observer) {
mObserver = observer;
}
// Pretends that the updated lists are |mSavedPasswords| for the saved passwords and an
// empty list for exceptions and immediately calls the observer.
@Override
public void updatePasswordLists() {
mObserver.passwordListAvailable(mSavedPasswords.size());
mObserver.passwordExceptionListAvailable(mSavedPasswordExeptions.size());
}
@Override
public SavedPasswordEntry getSavedPasswordEntry(int index) {
return mSavedPasswords.get(index);
}
@Override
public String getSavedPasswordException(int index) {
return mSavedPasswordExeptions.get(index);
}
@Override
public void changeSavedPasswordEntry(int index, String newUsername, String newPassword) {
mSavedPasswords.set(index,
new SavedPasswordEntry(
mSavedPasswords.get(index).getUrl(), newUsername, newPassword));
updatePasswordLists();
}
@Override
public void removeSavedPasswordEntry(int index) {
assert false : "Define this method before starting to use it in tests.";
}
@Override
public void removeSavedPasswordException(int index) {
assert false : "Define this method before starting to use it in tests.";
}
@Override
public void serializePasswords(String targetPath, IntStringCallback successCallback,
Callback<String> errorCallback) {
mExportSuccessCallback = successCallback;
mExportErrorCallback = errorCallback;
mExportTargetPath = targetPath;
}
}
private final static SavedPasswordEntry ZEUS_ON_EARTH =
new SavedPasswordEntry("http://www.phoenicia.gr", "Zeus", "Europa");
private final static SavedPasswordEntry ARES_AT_OLYMP =
new SavedPasswordEntry("https://1-of-12.olymp.gr", "Ares", "God-o'w@r");
private final static SavedPasswordEntry PHOBOS_AT_OLYMP =
new SavedPasswordEntry("https://visitor.olymp.gr", "Phobos-son-of-ares", "G0d0fF34r");
private final static SavedPasswordEntry DEIMOS_AT_OLYMP =
new SavedPasswordEntry("https://visitor.olymp.gr", "Deimops-Ares-son", "G0d0fT3rr0r");
private final static SavedPasswordEntry HADES_AT_UNDERWORLD =
new SavedPasswordEntry("https://underworld.gr", "", "C3rb3rus");
private final static SavedPasswordEntry[] GREEK_GODS = {
ZEUS_ON_EARTH, ARES_AT_OLYMP, PHOBOS_AT_OLYMP, DEIMOS_AT_OLYMP, HADES_AT_UNDERWORLD,
};
// Used to provide fake lists of stored passwords. Tests which need it can use setPasswordSource
// to instantiate it.
FakePasswordManagerHandler mHandler;
/**
* Delayer controling hiding the progress bar during exporting passwords. This replaces a time
* delay used in production.
*/
private final ManualCallbackDelayer mManualDelayer = new ManualCallbackDelayer();
private void overrideProfileSyncService(
final boolean usingPassphrase, final boolean syncingPasswords) {
TestThreadUtils.runOnUiThreadBlocking(() -> {
ProfileSyncService.overrideForTests(new ProfileSyncService() {
@Override
public boolean isUsingSecondaryPassphrase() {
return usingPassphrase;
}
@Override
public Set<Integer> getActiveDataTypes() {
if (syncingPasswords) return CollectionUtil.newHashSet(ModelType.PASSWORDS);
return CollectionUtil.newHashSet(ModelType.AUTOFILL);
}
});
});
}
@After
public void tearDown() throws Exception {
TestThreadUtils.runOnUiThreadBlocking(() -> ProfileSyncService.resetForTests());
}
/**
* Helper to set up a fake source of displayed passwords.
* @param entry An entry to be added to saved passwords. Can be null.
*/
private void setPasswordSource(SavedPasswordEntry entry) throws Exception {
SavedPasswordEntry[] entries = {};
if (entry != null) {
entries = new SavedPasswordEntry[] {entry};
}
setPasswordSourceWithMultipleEntries(entries);
}
/**
* Helper to set up a fake source of displayed passwords with multiple initial passwords.
* @param initialEntries All entries to be added to saved passwords. Can not be null.
*/
private void setPasswordSourceWithMultipleEntries(SavedPasswordEntry[] initialEntries)
throws Exception {
if (mHandler == null) {
mHandler = new FakePasswordManagerHandler(PasswordManagerHandlerProvider.getInstance());
}
ArrayList<SavedPasswordEntry> entries = new ArrayList<>(Arrays.asList(initialEntries));
mHandler.setSavedPasswords(entries);
TestThreadUtils.runOnUiThreadBlocking(
()
-> PasswordManagerHandlerProvider.getInstance()
.setPasswordManagerHandlerForTest(mHandler));
}
/**
* Helper to set up a fake source of displayed passwords without passwords but with exceptions.
* @param exceptions All exceptions to be added to saved exceptions. Can not be null.
*/
private void setPasswordExceptions(String[] exceptions) throws Exception {
if (mHandler == null) {
mHandler = new FakePasswordManagerHandler(PasswordManagerHandlerProvider.getInstance());
}
mHandler.setSavedPasswordExceptions(new ArrayList<>(Arrays.asList(exceptions)));
TestThreadUtils.runOnUiThreadBlocking(
()
-> PasswordManagerHandlerProvider.getInstance()
.setPasswordManagerHandlerForTest(mHandler));
}
/**
* Looks for the icon by id. If it cannot be found, it's probably hidden in the overflow
* menu. In that case, open the menu and search for its title.
* @return Returns either the icon button or the menu option.
*/
public static Matcher<View> withMenuIdOrText(@IdRes int actionId, @StringRes int actionLabel) {
Matcher<View> matcher = withId(actionId);
try {
Espresso.onView(matcher).check(matches(isDisplayed()));
return matcher;
} catch (Exception NoMatchingViewException) {
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
return withText(actionLabel);
}
}
/**
* Looks for the search icon by id or by its title.
* @return Returns either the icon button or the menu option.
*/
public static Matcher<View> withSearchMenuIdOrText() {
return withMenuIdOrText(R.id.menu_id_search, R.string.search);
}
/**
* Looks for the edit saved password icon by id or by its title.
* @return Returns either the icon button or the menu option.
*/
public static Matcher<View> withEditMenuIdOrText() {
return withMenuIdOrText(R.id.action_edit_saved_password,
R.string.password_entry_viewer_edit_stored_password_action_title);
}
/**
* Looks for the save edited password icon by id or by its title.
* @return Returns either the icon button or the menu option.
*/
public static Matcher<View> withSaveMenuIdOrText() {
return withMenuIdOrText(R.id.action_save_edited_password, R.string.save);
}
/**
* Taps the menu item to trigger exporting and ensures that reauthentication passes.
* It also disables the timer in {@link DialogManager} which is used to allow hiding the
* progress bar after an initial period. Hiding can be later allowed manually in tests with
* {@link #allowProgressBarToBeHidden}, to avoid time-dependent flakiness.
*/
private void reauthenticateAndRequestExport(Preferences preferences) {
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
// Avoid launching the Android-provided reauthentication challenge, which cannot be
// completed in the test.
ReauthenticationManager.setSkipSystemReauth(true);
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Now Chrome thinks it triggered the challenge and is waiting to be resumed. Once resumed
// it will check the reauthentication result. First, update the reauth timestamp to indicate
// a successful reauth:
ReauthenticationManager.recordLastReauth(
System.currentTimeMillis(), ReauthenticationManager.ReauthScope.BULK);
TestThreadUtils.runOnUiThreadBlocking(() -> {
// Disable the timer for progress bar.
SavePasswordsPreferences fragment =
(SavePasswordsPreferences) preferences.getMainFragment();
fragment.getExportFlowForTesting()
.getDialogManagerForTesting()
.replaceCallbackDelayerForTesting(mManualDelayer);
// Now call onResume to nudge Chrome into continuing the export flow.
preferences.getMainFragment().onResume();
});
}
@IntDef({MenuItemState.DISABLED, MenuItemState.ENABLED})
@Retention(RetentionPolicy.SOURCE)
private @interface MenuItemState {
/** Represents the state of an enabled menu item. */
int DISABLED = 0;
/** Represents the state of a disabled menu item. */
int ENABLED = 1;
}
/**
* Checks that the menu item for exporting passwords is enabled or disabled as expected.
* @param expectedState The expected state of the menu item.
*/
private void checkExportMenuItemState(@MenuItemState int expectedState) {
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
final Matcher<View> stateMatcher =
expectedState == MenuItemState.ENABLED ? isEnabled() : not(isEnabled());
// The text matches a text view, but the disabled entity is some wrapper two levels up in
// the view hierarchy, hence the two withParent matchers.
Espresso.onView(allOf(withText(R.string.save_password_preferences_export_action_title),
withParent(withParent(withParent(stateMatcher)))))
.check(matches(isDisplayed()));
}
/** Requests showing an arbitrary password export error. */
private void requestShowingExportError() {
TestThreadUtils.runOnUiThreadBlocking(
() -> { mHandler.getExportErrorCallback().onResult("Arbitrary error"); });
}
/**
* Requests showing an arbitrary password export error with a particular positive button to be
* shown. If you don't care about the button, just call {@link #requestShowingExportError}.
* @param preferences is the SavePasswordsPreferences instance being tested.
* @param positiveButtonLabelId controls which label the positive button ends up having.
*/
private void requestShowingExportErrorWithButton(
Preferences preferences, int positiveButtonLabelId) {
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences fragment =
(SavePasswordsPreferences) preferences.getMainFragment();
// To show an error, the error type for UMA needs to be specified. Because it is not
// relevant for cases when the error is forcibly displayed in tests,
// HistogramExportResult.NO_CONSUMER is passed as an arbitrarily chosen value.
fragment.getExportFlowForTesting().showExportErrorAndAbort(
R.string.save_password_preferences_export_no_app, null, positiveButtonLabelId,
ExportFlow.HistogramExportResult.NO_CONSUMER);
});
}
/**
* Sends the signal to {@link DialogManager} that the minimal time for showing the progress
* bar has passed. This results in the progress bar getting hidden as soon as requested.
*/
private void allowProgressBarToBeHidden(Preferences preferences) {
TestThreadUtils.runOnUiThreadBlocking(mManualDelayer::runCallbacksSynchronously);
}
/**
* Call after activity.finish() to wait for the wrap up to complete. If it was already completed
* or could be finished within |timeout_ms|, stop waiting anyways.
* @param activity The activity to wait for.
* @param timeout The timeout in ms after which the waiting will end anyways.
* @throws InterruptedException
*/
private void waitToFinish(Activity activity, long timeout) throws InterruptedException {
long start_time = System.currentTimeMillis();
while (activity.isFinishing() && (System.currentTimeMillis() - start_time < timeout))
Thread.sleep(100);
}
/**
* Create a temporary file in the cache sub-directory for exported passwords, which the test can
* try to use for sharing.
* @return The {@link File} handle for such temporary file.
*/
private File createFakeExportedPasswordsFile() throws IOException {
File passwordsDir = new File(ExportFlow.getTargetDirectory());
// Ensure that the directory exists.
passwordsDir.mkdir();
return File.createTempFile("test", ".csv", passwordsDir);
}
/**
* Ensure that resetting of empty passwords list works.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testResetListEmpty() throws Exception {
// Load the preferences, they should show the empty list.
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences savePasswordPreferences =
(SavePasswordsPreferences) preferences.getMainFragment();
// Emulate an update from PasswordStore. This should not crash.
savePasswordPreferences.passwordListAvailable(0);
});
}
/**
* Ensure that the on/off switch in "Save Passwords" settings actually enables and disables
* password saving.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSavePasswordsSwitch() throws Exception {
TestThreadUtils.runOnUiThreadBlocking(
() -> { PrefServiceBridge.getInstance().setRememberPasswordsEnabled(true); });
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
ChromeSwitchPreference onOffSwitch =
(ChromeSwitchPreference) savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_SAVE_PASSWORDS_SWITCH);
Assert.assertTrue(onOffSwitch.isChecked());
onOffSwitch.performClick();
Assert.assertFalse(PrefServiceBridge.getInstance().isRememberPasswordsEnabled());
onOffSwitch.performClick();
Assert.assertTrue(PrefServiceBridge.getInstance().isRememberPasswordsEnabled());
preferences.finish();
PrefServiceBridge.getInstance().setRememberPasswordsEnabled(false);
});
final Preferences preferences2 =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences2.getMainFragment();
ChromeSwitchPreference onOffSwitch =
(ChromeSwitchPreference) savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_SAVE_PASSWORDS_SWITCH);
Assert.assertFalse(onOffSwitch.isChecked());
});
}
/**
* Tests that the link pointing to managing passwords in the user's account is not displayed
* for non signed in users.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testManageAccountLinkNotSignedIn() throws Exception {
// Add a password entry, because the link is only displayed if the password list is not
// empty.
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
Assert.assertNull(savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_KEY_MANAGE_ACCOUNT_LINK));
}
/**
* Tests that the link pointing to managing passwords in the user's account is not displayed
* for signed in users, not syncing passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testManageAccountLinkSignedInNotSyncing() throws Exception {
// Add a password entry, because the link is only displayed if the password list is not
// empty.
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ChromeSigninController.get().setSignedInAccountName("Test Account");
overrideProfileSyncService(false, false);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
Assert.assertNull(savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_KEY_MANAGE_ACCOUNT_LINK));
}
/**
* Tests that the link pointing to managing passwords in the user's account is displayed for
* users syncing passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testManageAccountLinkSyncing() throws Exception {
// Add a password entry, because the link is only displayed if the password list is not
// empty.
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ChromeSigninController.get().setSignedInAccountName("Test Account");
overrideProfileSyncService(false, true);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
Assert.assertNotNull(savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_KEY_MANAGE_ACCOUNT_LINK));
}
/**
* Tests that the link pointing to managing passwords in the user's account is not displayed
* for users syncing passwords with custom passphrase.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testManageAccountLinkSyncingWithPassphrase() throws Exception {
// Add a password entry, because the link is only displayed if the password list is not
// empty.
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ChromeSigninController.get().setSignedInAccountName("Test Account");
overrideProfileSyncService(true, true);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
SavePasswordsPreferences savedPasswordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
Assert.assertNull(savedPasswordPrefs.findPreference(
SavePasswordsPreferences.PREF_KEY_MANAGE_ACCOUNT_LINK));
}
/**
* Ensure that the "Auto Sign-in" switch in "Save Passwords" settings actually enables and
* disables auto sign-in.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testAutoSignInCheckbox() throws Exception {
TestThreadUtils.runOnUiThreadBlocking(() -> {
PrefServiceBridge.getInstance().setPasswordManagerAutoSigninEnabled(true);
});
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences passwordPrefs =
(SavePasswordsPreferences) preferences.getMainFragment();
ChromeBaseCheckBoxPreference onOffSwitch =
(ChromeBaseCheckBoxPreference) passwordPrefs.findPreference(
SavePasswordsPreferences.PREF_AUTOSIGNIN_SWITCH);
Assert.assertTrue(onOffSwitch.isChecked());
onOffSwitch.performClick();
Assert.assertFalse(
PrefServiceBridge.getInstance().isPasswordManagerAutoSigninEnabled());
onOffSwitch.performClick();
Assert.assertTrue(PrefServiceBridge.getInstance().isPasswordManagerAutoSigninEnabled());
preferences.finish();
PrefServiceBridge.getInstance().setPasswordManagerAutoSigninEnabled(false);
});
final Preferences preferences2 =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
TestThreadUtils.runOnUiThreadBlocking(() -> {
SavePasswordsPreferences passwordPrefs =
(SavePasswordsPreferences) preferences2.getMainFragment();
ChromeBaseCheckBoxPreference onOffSwitch =
(ChromeBaseCheckBoxPreference) passwordPrefs.findPreference(
SavePasswordsPreferences.PREF_AUTOSIGNIN_SWITCH);
Assert.assertFalse(onOffSwitch.isChecked());
});
}
/**
* Check that the password data shown in the password editing activity matches the data of the
* password that was clicked.
*/
@Test
@SmallTest
@Feature({"Preferences"})
@Features.EnableFeatures(ChromeFeatureList.PASSWORD_EDITING_ANDROID)
public void testSelectedStoredPasswordDataIsSameAsEditedPasswordData() throws Exception {
setPasswordSourceWithMultipleEntries( // Initialize preferences
new SavedPasswordEntry[] {new SavedPasswordEntry("https://example.com",
"example user", "example password"),
new SavedPasswordEntry("https://test.com", "test user", "test password")});
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(withText(containsString("test user"))).perform(click());
Espresso.onView(withEditMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.site_edit)).check(matches(withText("https://test.com")));
}
/**
* Check that the changes of password data in the password editing activity are preserved and
* shown in the password viewing activity and in the list of passwords after the save button
* was clicked.
*/
@Test
@SmallTest
@Feature({"Preferences"})
@Features.EnableFeatures(ChromeFeatureList.PASSWORD_EDITING_ANDROID)
public void testChangeOfStoredPasswordDataIsPreserved() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(withText(containsString("test user"))).perform(click());
Espresso.onView(withEditMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.username_edit)).perform(typeText(" new"));
Espresso.onView(withSaveMenuIdOrText()).perform(click());
// Check if the password viewing activity has the updated data.
Espresso.onView(withText("test user new")).check(matches(isDisplayed()));
Espresso.pressBack();
// Check if the password preferences activity has the updated data in the list of passwords.
Espresso.onView(withText("test user new")).check(matches(isDisplayed()));
}
/**
* Check that if there are no saved passwords, the export menu item is disabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuDisabled() throws Exception {
// Ensure there are no saved passwords reported to settings.
setPasswordSource(null);
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
checkExportMenuItemState(MenuItemState.DISABLED);
}
/**
* Check that if there are saved passwords, the export menu item is enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuEnabled() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that tapping the export menu requests the passwords to be serialised in the background.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportTriggersSerialization() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
// Before tapping the menu item for export, pretend that the last successful
// reauthentication just happened. This will allow the export flow to continue.
ReauthenticationManager.recordLastReauth(
System.currentTimeMillis(), ReauthenticationManager.ReauthScope.BULK);
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
Assert.assertNotNull(mHandler.getExportTargetPath());
Assert.assertFalse(mHandler.getExportTargetPath().isEmpty());
}
/**
* Check that the export menu item is included and hidden behind the overflow menu. Check that
* the menu displays the warning before letting the user export passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuItem() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Check that the warning dialog is displayed.
Espresso.onView(withText(R.string.settings_passwords_export_description))
.check(matches(isDisplayed()));
}
/**
* Check that if export is canceled by the user after a successful reauthentication, then
* re-triggering the export and failing the second reauthentication aborts the export as well.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportReauthAfterCancel() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Hit the Cancel button on the warning dialog to cancel the flow.
Espresso.onView(withText(R.string.cancel)).perform(click());
// Now repeat the steps almost like in |reauthenticateAndRequestExport| but simulate failing
// the reauthentication challenge.
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
// Avoid launching the Android-provided reauthentication challenge, which cannot be
// completed in the test.
ReauthenticationManager.setSkipSystemReauth(true);
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Now Chrome thinks it triggered the challenge and is waiting to be resumed. Once resumed
// it will check the reauthentication result. First, update the reauth timestamp to indicate
// a cancelled reauth:
ReauthenticationManager.resetLastReauth();
// Now call onResume to nudge Chrome into continuing the export flow.
TestThreadUtils.runOnUiThreadBlocking(() -> { preferences.getMainFragment().onResume(); });
// Check that the warning dialog is not displayed.
Espresso.onView(withText(R.string.settings_passwords_export_description))
.check(doesNotExist());
// Check that the export menu item is enabled, because the current export was cancelled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check whether the user is asked to set up a screen lock if attempting to export passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuItemNoLock() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.UNAVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
View mainDecorView = preferences.getWindow().getDecorView();
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
Espresso.onView(withText(R.string.password_export_set_lock_screen))
.inRoot(withDecorView(not(is(mainDecorView))))
.check(matches(isDisplayed()));
}
/**
* Check that if exporting is cancelled for the absence of the screen lock, the menu item is
* enabled for a retry.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuItemReenabledNoLock() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.UNAVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Trigger exporting and let it fail on the unavailable lock.
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Check that for re-triggering, the export menu item is enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that if exporting is cancelled for the user's failure to reauthenticate, the menu item
* is enabled for a retry.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportMenuItemReenabledReauthFailure() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setSkipSystemReauth(true);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// The reauthentication dialog is skipped and the last reauthentication timestamp is not
// reset. This looks like a failed reauthentication to SavePasswordsPreferences' onResume.
TestThreadUtils.runOnUiThreadBlocking(() -> { preferences.getMainFragment().onResume(); });
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the export always requires a reauthentication, even if the last one happened
* recently.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportRequiresReauth() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Ensure that the last reauthentication time stamp is recent enough.
ReauthenticationManager.recordLastReauth(
System.currentTimeMillis(), ReauthenticationManager.ReauthScope.BULK);
// Start export.
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
// Avoid launching the Android-provided reauthentication challenge, which cannot be
// completed in the test.
ReauthenticationManager.setSkipSystemReauth(true);
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Check that Chrome indeed issued an (ignored) request to reauthenticate the user rather
// than re-using the recent reauthentication, by observing that the next step in the flow
// (progress bar) is not shown.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(doesNotExist());
}
/**
* Check that the export flow ends up with sending off a share intent with the exported
* passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportIntent() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Intents.init();
reauthenticateAndRequestExport(preferences);
File tempFile = createFakeExportedPasswordsFile();
// Pretend that passwords have been serialized to go directly to the intent.
mHandler.getExportSuccessCallback().onResult(123, tempFile.getPath());
// Before triggering the sharing intent chooser, stub it out to avoid leaving system UI open
// after the test is finished.
intending(hasAction(equalTo(Intent.ACTION_CHOOSER)))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
// Confirm the export warning to fire the sharing intent.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
intended(allOf(hasAction(equalTo(Intent.ACTION_CHOOSER)),
hasExtras(hasEntry(equalTo(Intent.EXTRA_INTENT),
allOf(hasAction(equalTo(Intent.ACTION_SEND)), hasType("text/csv"))))));
Intents.release();
tempFile.delete();
}
/**
* Check that the export flow ends up with sending off a share intent with the exported
* passwords, even if the flow gets interrupted by pausing Chrome.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportIntentPaused() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Intents.init();
reauthenticateAndRequestExport(preferences);
// Call onResume to simulate that the user put Chrome into background by opening "recent
// apps" and then restored Chrome by choosing it from the list.
TestThreadUtils.runOnUiThreadBlocking(() -> { preferences.getMainFragment().onResume(); });
File tempFile = createFakeExportedPasswordsFile();
// Pretend that passwords have been serialized to go directly to the intent.
mHandler.getExportSuccessCallback().onResult(56, tempFile.getPath());
// Before triggering the sharing intent chooser, stub it out to avoid leaving system UI open
// after the test is finished.
intending(hasAction(equalTo(Intent.ACTION_CHOOSER)))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
// Confirm the export warning to fire the sharing intent.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
intended(allOf(hasAction(equalTo(Intent.ACTION_CHOOSER)),
hasExtras(hasEntry(equalTo(Intent.EXTRA_INTENT),
allOf(hasAction(equalTo(Intent.ACTION_SEND)), hasType("text/csv"))))));
Intents.release();
tempFile.delete();
}
/**
* Check that the export flow can be canceled in the warning dialogue and that upon cancellation
* the export menu item gets re-enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportCancelOnWarning() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Cancel the export warning.
Espresso.onView(withText(R.string.cancel)).perform(click());
// Check that the cancellation succeeded by checking that the export menu is available and
// enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the export warning is not duplicated when onResume is called on the settings.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportWarningOnResume() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Call onResume to simulate that the user put Chrome into background by opening "recent
// apps" and then restored Chrome by choosing it from the list.
TestThreadUtils.runOnUiThreadBlocking(() -> { preferences.getMainFragment().onResume(); });
// Cancel the export warning.
Espresso.onView(withText(R.string.cancel)).perform(click());
// Check that export warning is not visible again.
Espresso.onView(withText(R.string.cancel)).check(doesNotExist());
// Check that the cancellation succeeded by checking that the export menu is available and
// enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the export warning is dismissed after onResume if the last reauthentication
* happened too long ago.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportWarningTimeoutOnResume() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
// Before exporting, pretend that the last successful reauthentication happend too long ago.
ReauthenticationManager.recordLastReauth(System.currentTimeMillis()
- ReauthenticationManager.VALID_REAUTHENTICATION_TIME_INTERVAL_MILLIS - 1,
ReauthenticationManager.ReauthScope.BULK);
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Call onResume to simulate that the user put Chrome into background by opening "recent
// apps" and then restored Chrome by choosing it from the list.
TestThreadUtils.runOnUiThreadBlocking(() -> { preferences.getMainFragment().onResume(); });
// Check that export warning is not visible again.
Espresso.onView(withText(R.string.cancel)).check(doesNotExist());
// Check that the export flow was cancelled automatically by checking that the export menu
// is available and enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the export flow can be canceled by dismissing the warning dialogue (tapping
* outside of it, as opposed to tapping "Cancel") and that upon cancellation the export menu
* item gets re-enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportCancelOnWarningDismissal() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Verify that the warning dialog is shown and then dismiss it through pressing back (as
// opposed to the cancel button).
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.check(matches(isDisplayed()));
Espresso.pressBack();
// Check that the cancellation succeeded by checking that the export menu is available and
// enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that a progressbar is displayed for a minimal time duration to avoid flickering.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportProgressMinimalTime() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Intents.init();
// This also disables the timer for keeping the progress bar up. The test can thus emulate
// that timer going off by calling {@link allowProgressBarToBeHidden}.
reauthenticateAndRequestExport(preferences);
// Before triggering the sharing intent chooser, stub it out to avoid leaving system UI open
// after the test is finished.
intending(hasAction(equalTo(Intent.ACTION_CHOOSER)))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
// Confirm the export warning to fire the sharing intent.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Before simulating the serialized passwords being received, check that the progress bar is
// shown.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(matches(isDisplayed()));
File tempFile = createFakeExportedPasswordsFile();
// Now pretend that passwords have been serialized.
mHandler.getExportSuccessCallback().onResult(12, tempFile.getPath());
// Check that the progress bar is still shown, though, because the timer has not gone off
// yet.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(matches(isDisplayed()));
// Now mark the timer as gone off and check that the progress bar is hidden.
allowProgressBarToBeHidden(preferences);
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(doesNotExist());
intended(allOf(hasAction(equalTo(Intent.ACTION_CHOOSER)),
hasExtras(hasEntry(equalTo(Intent.EXTRA_INTENT),
allOf(hasAction(equalTo(Intent.ACTION_SEND)), hasType("text/csv"))))));
Intents.release();
tempFile.delete();
}
/**
* Check that a progressbar is displayed when the user confirms the export and the serialized
* passwords are not ready yet.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportProgress() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Intents.init();
reauthenticateAndRequestExport(preferences);
// Before triggering the sharing intent chooser, stub it out to avoid leaving system UI open
// after the test is finished.
intending(hasAction(equalTo(Intent.ACTION_CHOOSER)))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
// Confirm the export warning to fire the sharing intent.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Before simulating the serialized passwords being received, check that the progress bar is
// shown.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(matches(isDisplayed()));
File tempFile = createFakeExportedPasswordsFile();
// Now pretend that passwords have been serialized.
allowProgressBarToBeHidden(preferences);
mHandler.getExportSuccessCallback().onResult(12, tempFile.getPath());
// After simulating the serialized passwords being received, check that the progress bar is
// hidden.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(doesNotExist());
intended(allOf(hasAction(equalTo(Intent.ACTION_CHOOSER)),
hasExtras(hasEntry(equalTo(Intent.EXTRA_INTENT),
allOf(hasAction(equalTo(Intent.ACTION_SEND)), hasType("text/csv"))))));
Intents.release();
tempFile.delete();
}
/**
* Check that the user can cancel exporting with the "Cancel" button on the progressbar.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportCancelOnProgress() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Confirm the export warning to fire the sharing intent.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Simulate the minimal time for showing the progress bar to have passed, to ensure that it
// is kept live because of the pending serialization.
allowProgressBarToBeHidden(preferences);
// Check that the progress bar is shown.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(matches(isDisplayed()));
// Hit the Cancel button.
Espresso.onView(withText(R.string.cancel)).perform(click());
// Check that the cancellation succeeded by checking that the export menu is available and
// enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the user can cancel exporting with the negative button on the error message.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportCancelOnError() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Confirm the export warning.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Show an arbitrary error. This should replace the progress bar if that has been shown in
// the meantime.
allowProgressBarToBeHidden(preferences);
requestShowingExportError();
// Check that the error prompt is showing.
Espresso.onView(withText(R.string.save_password_preferences_export_error_title))
.check(matches(isDisplayed()));
// Hit the negative button on the error prompt.
Espresso.onView(withText(R.string.close)).perform(click());
// Check that the cancellation succeeded by checking that the export menu is available and
// enabled.
checkExportMenuItemState(MenuItemState.ENABLED);
}
/**
* Check that the user can re-trigger the export from an error dialog which has a "retry"
* button.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportRetry() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Confirm the export warning.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Show an arbitrary error but ensure that the positive button label is the one for "try
// again".
allowProgressBarToBeHidden(preferences);
requestShowingExportErrorWithButton(preferences, R.string.try_again);
// Hit the positive button to try again.
Espresso.onView(withText(R.string.try_again)).perform(click());
// Check that there is again the export warning.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.check(matches(isDisplayed()));
}
/**
* Check that the error dialog lets the user visit a help page to install Google Drive if they
* need an app to consume the exported passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportHelpSite() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Confirm the export warning.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Show an arbitrary error but ensure that the positive button label is the one for the
// Google Drive help site.
allowProgressBarToBeHidden(preferences);
requestShowingExportErrorWithButton(
preferences, R.string.save_password_preferences_export_learn_google_drive);
Intents.init();
// Before triggering the viewing intent, stub it out to avoid cascading that into further
// intents and opening the web browser.
intending(hasAction(equalTo(Intent.ACTION_VIEW)))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
// Hit the positive button to navigate to the help site.
Espresso.onView(withText(R.string.save_password_preferences_export_learn_google_drive))
.perform(click());
intended(allOf(hasAction(equalTo(Intent.ACTION_VIEW)),
hasData(hasHost(equalTo("support.google.com")))));
Intents.release();
}
/**
* Check that if errors are encountered when user is busy confirming the export, the error UI is
* shown after the confirmation is completed, so that the user does not see UI changing
* unexpectedly under their fingers.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testExportErrorUiAfterConfirmation() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
reauthenticateAndRequestExport(preferences);
// Request showing an arbitrary error while the confirmation dialog is still up.
requestShowingExportError();
// Check that the confirmation dialog is showing and dismiss it.
Espresso.onView(withText(R.string.save_password_preferences_export_action_title))
.perform(click());
// Check that now the error is displayed, instead of the progress bar.
allowProgressBarToBeHidden(preferences);
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(doesNotExist());
Espresso.onView(withText(R.string.save_password_preferences_export_error_title))
.check(matches(isDisplayed()));
// Close the error dialog and abort the export.
Espresso.onView(withText(R.string.close)).perform(click());
// Ensure that there is still no progress bar.
Espresso.onView(withText(R.string.settings_passwords_preparing_export))
.check(doesNotExist());
}
/**
* Check whether the user is asked to set up a screen lock if attempting to view passwords.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testViewPasswordNoLock() throws Exception {
setPasswordSource(new SavedPasswordEntry("https://example.com", "test user", "password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.UNAVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
View mainDecorView = preferences.getWindow().getDecorView();
Espresso.onView(withText(containsString("test user"))).perform(click());
Espresso.onView(withContentDescription(R.string.password_entry_viewer_copy_stored_password))
.perform(click());
Espresso.onView(withText(R.string.password_entry_viewer_set_lock_screen))
.inRoot(withDecorView(not(is(mainDecorView))))
.check(matches(isDisplayed()));
}
/**
* Check whether the user can view a saved password.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testViewPassword() throws Exception {
setPasswordSource(
new SavedPasswordEntry("https://example.com", "test user", "test password"));
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
final Preferences preferences =
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(withText(containsString("test user"))).perform(click());
// Before tapping the view button, pretend that the last successful reauthentication just
// happened. This will allow showing the password.
ReauthenticationManager.recordLastReauth(
System.currentTimeMillis(), ReauthenticationManager.ReauthScope.ONE_AT_A_TIME);
Espresso.onView(withContentDescription(R.string.password_entry_viewer_view_stored_password))
.perform(click());
Espresso.onView(withText("test password")).check(matches(isDisplayed()));
}
/**
* Check that the search item is visible if the Feature is enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
@SuppressWarnings("AlwaysShowAction") // We need to ensure the icon is in the action bar.
public void testSearchIconVisibleInActionBarWithFeature() throws Exception {
setPasswordSource(null); // Initialize empty preferences.
SavePasswordsPreferences f =
(SavePasswordsPreferences) PreferencesTest
.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName())
.getMainFragment();
// Force the search option into the action bar.
TestThreadUtils.runOnUiThreadBlocking(
()
-> f.getMenuForTesting()
.findItem(R.id.menu_id_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS));
Espresso.onView(withId(R.id.menu_id_search)).check(matches(isDisplayed()));
}
/**
* Check that the icon for editing saved passwords is visible if the Feature is enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
@Features.EnableFeatures(ChromeFeatureList.PASSWORD_EDITING_ANDROID)
public void testEditSavedPasswordIconVisibleInActionBarWithFeature() throws Exception {
setPasswordSource( // Initialize preferences
new SavedPasswordEntry("https://example.com", "test user", "test password"));
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(withText(containsString("test user"))).perform(click());
Espresso.onView(withEditMenuIdOrText()).check(matches(isDisplayed()));
}
/**
* Check that the search item is visible if the Feature is enabled.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchTextInOverflowMenuVisibleWithFeature() throws Exception {
setPasswordSource(null); // Initialize empty preferences.
SavePasswordsPreferences f =
(SavePasswordsPreferences) PreferencesTest
.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName())
.getMainFragment();
// Force the search option into the overflow menu.
TestThreadUtils.runOnUiThreadBlocking(
()
-> f.getMenuForTesting()
.findItem(R.id.menu_id_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER));
// Open the overflow menu.
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.search)).check(matches(isDisplayed()));
}
/**
* Check that searching doesn't push the help icon into the overflow menu permanently.
* On screen sizes where the help item starts out in the overflow menu, ensure it stays there.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testTriggeringSearchRestoresHelpIcon() throws Exception {
setPasswordSource(null);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView(
(ViewGroup) root, withText(R.string.prefs_saved_passwords_title)));
// Retrieve the initial status and ensure that the help option is there at all.
final AtomicReference<Boolean> helpInOverflowMenu = new AtomicReference<>(false);
Espresso.onView(withId(R.id.menu_id_general_help)).check((helpMenuItem, e) -> {
ActionMenuItemView view = (ActionMenuItemView) helpMenuItem;
helpInOverflowMenu.set(view == null || !view.showsIcon());
});
if (helpInOverflowMenu.get()) {
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.menu_help)).check(matches(isDisplayed()));
Espresso.pressBack(); // to close the Overflow menu.
} else {
Espresso.onView(withId(R.id.menu_id_general_help)).check(matches(isDisplayed()));
}
// Trigger the search, close it and wait for UI to be restored.
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click());
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView(
(ViewGroup) root, withText(R.string.prefs_saved_passwords_title)));
// Check that the help option is exactly where it was to begin with.
if (helpInOverflowMenu.get()) {
openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext());
Espresso.onView(withText(R.string.menu_help)).check(matches(isDisplayed()));
Espresso.onView(withId(R.id.menu_id_general_help)).check(doesNotExist());
} else {
Espresso.onView(withText(R.string.menu_help)).check(doesNotExist());
Espresso.onView(withId(R.id.menu_id_general_help)).check(matches(isDisplayed()));
}
}
/**
* Check that the search filters the list by name.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchFiltersByUserName() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Search for a string matching multiple user names. Case doesn't need to match.
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.search_src_text))
.perform(click(), typeText("aREs"), closeSoftKeyboard());
Espresso.onView(withText(ARES_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(PHOBOS_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(DEIMOS_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).check(doesNotExist());
Espresso.onView(withText(HADES_AT_UNDERWORLD.getUrl())).check(doesNotExist());
}
/**
* Check that the search filters the list by URL.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchFiltersByUrl() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Search for a string that matches multiple URLs. Case doesn't need to match.
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.search_src_text))
.perform(click(), typeText("Olymp"), closeSoftKeyboard());
Espresso.onView(withText(ARES_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(PHOBOS_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(DEIMOS_AT_OLYMP.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).check(doesNotExist());
Espresso.onView(withText(HADES_AT_UNDERWORLD.getUrl())).check(doesNotExist());
}
/**
* Check that the search filters the list by URL.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchDisplaysBlankPageIfSearchTurnsUpEmpty() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Open the search which should hide the Account link.
Espresso.onView(withSearchMenuIdOrText()).perform(click());
// Search for a string that matches nothing which should leave the results entirely blank.
Espresso.onView(withId(R.id.search_src_text))
.perform(click(), typeText("Mars"), closeSoftKeyboard());
for (SavedPasswordEntry god : GREEK_GODS) {
Espresso.onView(allOf(withText(god.getUserName()), withText(god.getUrl())))
.check(doesNotExist());
}
Espresso.onView(withText(R.string.saved_passwords_none_text)).check(doesNotExist());
// Check that the section header for saved passwords is not present. Do not confuse it with
// the toolbar label which contains the same string, look for the one inside a linear
// layout.
Espresso.onView(allOf(withParent(isAssignableFrom(LinearLayout.class)),
withText(R.string.prefs_saved_passwords_title)))
.check(doesNotExist());
}
/**
* Check that triggering the search hides all non-password prefs.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchIconClickedHidesExceptionsTemporarily() throws Exception {
setPasswordExceptions(new String[] {"http://exclu.de", "http://not-inclu.de"});
final SavePasswordsPreferences savePasswordPreferences =
(SavePasswordsPreferences) PreferencesTest
.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName())
.getMainFragment();
Espresso.onView(withText(R.string.section_saved_passwords_exceptions))
.check(matches(isDisplayed()));
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.search_src_text)).perform(click(), closeSoftKeyboard());
Espresso.onView(withText(R.string.section_saved_passwords_exceptions))
.check(doesNotExist());
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click());
InstrumentationRegistry.getInstrumentation().waitForIdleSync(); // Close search view.
Espresso.onView(withText(R.string.section_saved_passwords_exceptions))
.check(matches(isDisplayed()));
}
/**
* Check that triggering the search hides all non-password prefs.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchIconClickedHidesGeneralPrefs() throws Exception {
setPasswordSource(ZEUS_ON_EARTH);
final SavePasswordsPreferences prefs =
(SavePasswordsPreferences) PreferencesTest
.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName())
.getMainFragment();
final AtomicReference<Boolean> menuInitiallyVisible = new AtomicReference<>();
TestThreadUtils.runOnUiThreadBlocking(
()
-> menuInitiallyVisible.set(
prefs.getToolbarForTesting().isOverflowMenuShowing()));
Espresso.onView(withText(R.string.passwords_auto_signin_title))
.check(matches(isDisplayed()));
if (menuInitiallyVisible.get()) { // Check overflow menu only on large screens that have it.
Espresso.onView(withContentDescription(R.string.abc_action_menu_overflow_description))
.check(matches(isDisplayed()));
}
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withText(R.string.passwords_auto_signin_title)).check(doesNotExist());
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView((ViewGroup) root,
withParent(withContentDescription(
R.string.abc_action_menu_overflow_description)),
VIEW_INVISIBLE | VIEW_GONE | VIEW_NULL));
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click());
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
if (menuInitiallyVisible.get()) { // If the overflow menu was there, it should be restored.
Espresso.onView(withContentDescription(R.string.abc_action_menu_overflow_description))
.check(matches(isDisplayed()));
}
}
/**
* Check that closing the search via back button brings back all non-password prefs.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchBarBackButtonRestoresGeneralPrefs() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(withId(R.id.search_src_text))
.perform(click(), typeText("Zeu"), closeSoftKeyboard());
Espresso.onView(withText(R.string.passwords_auto_signin_title)).check(doesNotExist());
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click());
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
Espresso.onView(withText(R.string.passwords_auto_signin_title))
.check(matches(isDisplayed()));
Espresso.onView(withId(R.id.menu_id_search)).check(matches(isDisplayed()));
}
/**
* Check that clearing the search also hides the clear button.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchViewCloseIconExistsOnlyToClearQueries() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Trigger search which shouldn't have the button yet.
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView((ViewGroup) root, withId(R.id.search_close_btn),
VIEW_INVISIBLE | VIEW_GONE | VIEW_NULL));
// Type something and see the button appear.
Espresso.onView(withId(R.id.search_src_text))
// Trigger search which shouldn't have the button yet.
.perform(click(), typeText("Zeu"), closeSoftKeyboard());
Espresso.onView(withId(R.id.search_close_btn)).check(matches(isDisplayed()));
// Clear the search which should hide the button again.
Espresso.onView(withId(R.id.search_close_btn)).perform(click()); // Clear search.
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView((ViewGroup) root, withId(R.id.search_close_btn),
VIEW_INVISIBLE | VIEW_GONE | VIEW_NULL));
}
/**
* Check that the changed color of the loaded Drawable does not persist for other uses of the
* drawable. This is not implicitly true as a loaded Drawable is by default only a reference to
* the globally defined resource.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchIconColorAffectsOnlyLocalSearchDrawable() throws Exception {
// Open the password preferences and remember the applied color filter.
final SavePasswordsPreferences f =
(SavePasswordsPreferences) PreferencesTest
.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName())
.getMainFragment();
Espresso.onView(withId(R.id.search_button)).check(matches(isDisplayed()));
final AtomicReference<ColorFilter> passwordSearchFilter = new AtomicReference<>();
TestThreadUtils.runOnUiThreadBlocking(() -> {
Drawable drawable = f.getMenuForTesting().findItem(R.id.menu_id_search).getIcon();
passwordSearchFilter.set(DrawableCompat.getColorFilter(drawable));
});
// Now launch a non-empty History activity.
StubbedHistoryProvider mHistoryProvider = new StubbedHistoryProvider();
mHistoryProvider.addItem(StubbedHistoryProvider.createHistoryItem(0, new Date().getTime()));
mHistoryProvider.addItem(StubbedHistoryProvider.createHistoryItem(1, new Date().getTime()));
HistoryManager.setProviderForTests(mHistoryProvider);
mHistoryActivityTestRule.launchActivity(null);
// Find the search view to ensure that the set color filter is different from the saved one.
final AtomicReference<ColorFilter> historySearchFilter = new AtomicReference<>();
Espresso.onView(withId(R.id.search_menu_id)).check(matches(isDisplayed()));
Espresso.onView(withId(R.id.search_menu_id)).check((searchMenuItem, e) -> {
Drawable drawable = ((ActionMenuItemView) searchMenuItem).getItemData().getIcon();
historySearchFilter.set(DrawableCompat.getColorFilter(drawable));
Assert.assertThat(historySearchFilter.get(),
anyOf(is(nullValue()), is(not(sameInstance(passwordSearchFilter.get())))));
});
// Close the activity and check that the icon in the password preferences has not changed.
mHistoryActivityTestRule.getActivity().finish();
TestThreadUtils.runOnUiThreadBlocking(() -> {
ColorFilter colorFilter = DrawableCompat.getColorFilter(
f.getMenuForTesting().findItem(R.id.menu_id_search).getIcon());
Assert.assertThat(colorFilter,
anyOf(is(nullValue()), is(sameInstance(passwordSearchFilter.get()))));
Assert.assertThat(colorFilter,
anyOf(is(nullValue()), is(not(sameInstance(historySearchFilter.get())))));
});
}
/**
* Check that the filtered password list persists after the user had inspected a single result.
*/
@Test
@SmallTest
@Feature({"Preferences"})
public void testSearchResultsPersistAfterEntryInspection() throws Exception {
setPasswordSourceWithMultipleEntries(GREEK_GODS);
setPasswordExceptions(new String[] {"http://exclu.de", "http://not-inclu.de"});
ReauthenticationManager.setApiOverride(ReauthenticationManager.OverrideState.AVAILABLE);
ReauthenticationManager.setScreenLockSetUpOverride(
ReauthenticationManager.OverrideState.AVAILABLE);
PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(),
SavePasswordsPreferences.class.getName());
// Open the search and filter all but "Zeus".
Espresso.onView(withSearchMenuIdOrText()).perform(click());
Espresso.onView(isRoot()).check(
(root, e) -> waitForView((ViewGroup) root, withId(R.id.search_src_text)));
Espresso.onView(withId(R.id.search_src_text))
.perform(click(), typeText("Zeu"), closeSoftKeyboard());
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
Espresso.onView(withText(R.string.passwords_auto_signin_title)).check(doesNotExist());
Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(PHOBOS_AT_OLYMP.getUserName())).check(doesNotExist());
Espresso.onView(withText(HADES_AT_UNDERWORLD.getUrl())).check(doesNotExist());
// Click "Zeus" to open edit field and verify the password. Pretend the user just passed the
// reauthentication challenge.
ReauthenticationManager.recordLastReauth(
System.currentTimeMillis(), ReauthenticationManager.ReauthScope.ONE_AT_A_TIME);
Instrumentation.ActivityMonitor monitor =
InstrumentationRegistry.getInstrumentation().addMonitor(
new IntentFilter(Intent.ACTION_VIEW), null, false);
Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).perform(click());
monitor.waitForActivityWithTimeout(UI_UPDATING_TIMEOUT_MS);
Assert.assertEquals("Monitor for has not been called", 1, monitor.getHits());
InstrumentationRegistry.getInstrumentation().removeMonitor(monitor);
Espresso.onView(withContentDescription(R.string.password_entry_viewer_view_stored_password))
.perform(click());
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
Espresso.onView(withText(ZEUS_ON_EARTH.getPassword())).check(matches(isDisplayed()));
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description))
.perform(click()); // Go back to the search list.
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
Espresso.onView(withText(R.string.passwords_auto_signin_title)).check(doesNotExist());
Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).check(matches(isDisplayed()));
Espresso.onView(withText(PHOBOS_AT_OLYMP.getUserName())).check(doesNotExist());
Espresso.onView(withText(HADES_AT_UNDERWORLD.getUrl())).check(doesNotExist());
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
// The search bar should still be open and still display the search query.
Espresso.onView(isRoot()).check(
(root, e)
-> waitForView((ViewGroup) root,
allOf(withId(R.id.search_src_text), withText("Zeu"))));
Espresso.onView(withId(R.id.search_src_text)).check(matches(withText("Zeu")));
}
}
|
[
"root@vultr.guest"
] |
root@vultr.guest
|
39c1deb96a28e0dd50e62de0253fb5dad6c2b44b
|
30438d60e37eb471932151d640a56381dc0238ed
|
/app/src/main/java/com/Store/www/entity/LookLogisticsResponse.java
|
3727c8ca9909e7f68359f04b6efdf31b2e6145e4
|
[] |
no_license
|
ChangeKiss/Store
|
27af74a2d382b23c745c390a201efc7e61315fd2
|
dce4cea0137eb63f567c43972b1cd7ad992aa9a0
|
refs/heads/master
| 2020-06-25T17:09:44.318255
| 2019-07-29T06:17:28
| 2019-07-29T06:17:54
| 199,373,409
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,068
|
java
|
package com.Store.www.entity;
import java.util.List;
/**
* Created by www on 2018/8/14.
* 查看物流响应体
*/
public class LookLogisticsResponse {
/**
* returnValue : 1
* data : [{"no":"3366969258232","info":["本人签收-已签收","福建厦门杏东公司-钟诗纬(18059297137,)-派件中","已到达-福建厦门杏东公司","福建厦门转运中心-已发往-福建厦门杏东公司","福建厦门转运中心-已发往-福建厦门杏东公司","广东佛山航空部-已进行装车扫描","广东佛山航空部-已发往-福建厦门转运中心","广东佛山公司--已收件"]}]
* errMsg : null
*/
private int returnValue;
private String errMsg;
private List<DataBean> data;
public int getReturnValue() {
return returnValue;
}
public void setReturnValue(int returnValue) {
this.returnValue = returnValue;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* no : 3366969258232
* info : ["本人签收-已签收","福建厦门杏东公司-钟诗纬(18059297137,)-派件中","已到达-福建厦门杏东公司","福建厦门转运中心-已发往-福建厦门杏东公司","福建厦门转运中心-已发往-福建厦门杏东公司","广东佛山航空部-已进行装车扫描","广东佛山航空部-已发往-福建厦门转运中心","广东佛山公司--已收件"]
*/
private String no;
private List<String> info;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public List<String> getInfo() {
return info;
}
public void setInfo(List<String> info) {
this.info = info;
}
}
}
|
[
"553765309@qq.com"
] |
553765309@qq.com
|
91f0f1159c3fa7ba6df62692a4b7faae4360accc
|
12fa67398f713849953e73f95d636c0493b40c3a
|
/project/src/castadiva/TrafficSchema.java
|
2d6e495e48eeec1f15249566fc7f09b897ca8809
|
[] |
no_license
|
GRCDEV/castadiva
|
b8612a370f2d34182cca7781e84d876fc38956d7
|
78a6f7e8516b97b7bf135ac6897d03642ac77b14
|
refs/heads/master
| 2023-08-31T13:11:13.739004
| 2011-01-11T11:23:57
| 2011-01-11T11:23:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,044
|
java
|
/*
* TrafficSchema.java
*
* Created on 6 de noviembre de 2006, 12:05
*
*
*/
package castadiva;
import java.io.Serializable;
/**
*
* @author jorge
*
*/
abstract class TrafficSchema implements Serializable{
String trafficKind;
Integer size;
Integer start;
Integer stop;
Integer packetPerSeconds;
Integer transferSize;
Integer totalPackets;
/**
* Return if the traffic declared is UDP or TCP.
*/
public String getTCPUDP(){
return trafficKind;
}
/**
* Return the size of the packet.
*/
public Integer getSize(){
return size;
}
/**
* Return the second when the traffic start to be sended.
*/
public Integer getStart(){
return start;
}
/**
* Return the second when the traffic ends.
*/
public Integer getStop(){
return stop;
}
/**
* Return how many packets must be sended by second.
*/
public Integer getPacketsSeconds(){
return packetPerSeconds;
}
/**
* Return the total traffic por TCP traffic.
*/
public Integer getTransferSize(){
return transferSize;
}
/**
* Return the total packets sended in the traffic flux.
*/
public Integer getMaxPackets(){
return totalPackets;
}
/**
* Set the traffic to a specified protocol (UDP or TCP).
* @param tcpudp Is a string containing the protocol.
*/
public void setTCPUDP(String tcpudp){
trafficKind = tcpudp;
}
/**
* Change the packet size.
* @param packetSize The number of the packet size.
*/
public void setSize(Integer packetSize){
size = packetSize;
}
/**
* Change the number of packets sended by second.
* @param packetNumber Define the packet burst.
*/
public void setPacketsSeconds(Integer packetNumber){
packetPerSeconds = packetNumber;
}
/**
* Obtain the max packets that can be sended in a determined time;
*/
public void CalculateMaxPackets(){
totalPackets = (start - stop)*packetPerSeconds;
}
/**
* Change the maxim number of packets sended.
* @param max Define the total packets desired.
*/
public void setMaxPackets(Integer max){
totalPackets = max;
}
/**
* Change the starting simulation second for this traffic flux.
* @param start Is the starting second.
*/
public void setStart(Integer start){
this.start = start;
}
/**
* Change the end simulation second for this traffic flow.
* @param stop Is the second when will end.
*/
public void setStop(Integer stop){
this.stop = stop;
}
/**
* Change the total traffic for TCP.
* @param transferSize The new TCP traffic between two selected nodes.
*/
public void setTransferSize(Integer transferSize){
this.transferSize = transferSize;
}
}
|
[
"jorge@7b4e6c59-6d95-4d52-ab24-47429ca55bdb"
] |
jorge@7b4e6c59-6d95-4d52-ab24-47429ca55bdb
|
ebf786cf80edc3472ac85dc20e98df12b5ce3741
|
b90a16dd9209bb1a93f08badd7f1b102676d59ec
|
/glacier-common/src/main/java/com/geektcp/alpha/common/base/context/SpringContext.java
|
7f97364c27b200ccbf2a6b9eedac4e262bb515f7
|
[
"Apache-2.0"
] |
permissive
|
jojofans/alpha-glacier
|
bc00e168724518393e685dce55d895cb5e35db3a
|
bcf37167ecbf68673bf8283e20592cdbff1c914d
|
refs/heads/master
| 2021-05-23T08:43:42.737533
| 2020-03-31T05:50:56
| 2020-03-31T05:50:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,438
|
java
|
package com.geektcp.alpha.common.base.context;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* @author tanghaiyang on 2017/11/13.
*/
@Component
public class SpringContext implements ApplicationContextAware {
public static ApplicationContext context;
public static Environment env;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContext.context = context;
SpringContext.env = context.getEnvironment();
}
public static <T> T getBean(String beanId, Class<T> clazz) {
return context.getBean(beanId, clazz);
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
public static ApplicationContext getContext() {
return context;
}
public static Environment getEnv() {
return env;
}
public static String getProperty(String key) {
return getProperty(key, "");
}
public static String getProperty(String key, String defaultValue) {
return env.getProperty(key, defaultValue);
}
public static <T> T getProperty(String key, Class<T> targetType) {
return env.getProperty(key, targetType);
}
}
|
[
"geektcp@163.com"
] |
geektcp@163.com
|
a7f7070918895529a633af0472b4fc38e304b91c
|
3dae89cd840011e75933218232f94aeac554cf63
|
/nio/src/main/java/jlibs/nio/PipedConnection.java
|
dc0cc8488a683f525c6cff9098e22ad6162020bd
|
[
"Apache-2.0"
] |
permissive
|
santhosh-tekuri/jlibs
|
73c851d453d11e2e57912233e4c56901bbf03c04
|
3fc29d2616be6b232aa82fa3c36b02779ef83389
|
refs/heads/master
| 2023-09-01T04:27:53.977246
| 2021-06-10T06:37:48
| 2021-06-10T06:37:48
| 32,234,412
| 62
| 31
|
Apache-2.0
| 2022-12-12T21:42:44
| 2015-03-14T22:08:44
|
Java
|
UTF-8
|
Java
| false
| false
| 1,653
|
java
|
/*
* JLibs: Common Utilities for Java
* Copyright (C) 2009 Santhosh Kumar T <santhosh.tekuri@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
package jlibs.nio;
import java.io.IOException;
import java.nio.channels.SelectableChannel;
/**
* @author Santhosh Kumar Tekuri
*/
public class PipedConnection extends Connection<SelectableChannel>{
private ReadPipe readPipe;
private WritePipe writePipe;
public PipedConnection(ReadPipe readPipe, WritePipe writePipe) throws IOException{
super(null, null);
this.readPipe = readPipe;
this.writePipe = writePipe;
}
@Override
protected void process(boolean timeout){
throw new UnsupportedOperationException();
}
@Override
protected void wakeupNow(){
throw new UnsupportedOperationException();
}
@Override
public Input in(){
return readPipe.in();
}
@Override
public Output out(){
return writePipe.out();
}
public boolean isOpen(){
return readPipe.isOpen() & writePipe.isOpen();
}
@Override
public void close(){
writePipe.close();
readPipe.close();
}
}
|
[
"santhosh.tekuri@gmail.com@c7b8b07c-c7ab-11dd-86c2-0f8696b7b6f9"
] |
santhosh.tekuri@gmail.com@c7b8b07c-c7ab-11dd-86c2-0f8696b7b6f9
|
8225f29cf21d800dd53105aeda732e42046d489c
|
e22250f541cef188371299e0097e2ccd5829ae15
|
/src/test/java/com/demo/DemoXmlRpcApplicationTests.java
|
8246b86d2fdc996d3375a23801f6b278746557e7
|
[] |
no_license
|
Giannelahc/xml-rpc
|
8f0f3d1f52571b677b416c386794d1e5512a386e
|
e3adef74393f507d606fcdfc2e8f9402a2e58475
|
refs/heads/main
| 2023-08-18T15:22:27.515264
| 2021-09-21T18:53:08
| 2021-09-21T18:53:08
| 408,904,421
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 204
|
java
|
package com.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoXmlRpcApplicationTests {
@Test
void contextLoads() {
}
}
|
[
"giannelahc@gmail.com"
] |
giannelahc@gmail.com
|
4e0a43bc6f1d325bedd0fd9272d9e80c62e8f383
|
df9730228bb225928a7569df10aa84df95fdc3e4
|
/android/src/com/freshplanet/inapppurchase/utils/Purchase.java
|
8d1240107f708562a992db9b06a74b43a6f0b353
|
[
"Apache-2.0"
] |
permissive
|
wastedabuser/ANE-In-App-Purchase
|
a3a5cdcf89dc09a2e2e0b4ef674cb30d5de1ac50
|
41456c8d9f593be2589ae24a924c94260e735d84
|
refs/heads/develop
| 2021-01-09T07:05:17.007066
| 2016-04-19T11:21:29
| 2016-04-19T11:21:29
| 33,926,489
| 0
| 0
| null | 2015-04-14T10:52:39
| 2015-04-14T10:52:39
| null |
UTF-8
|
Java
| false
| false
| 2,318
|
java
|
package com.freshplanet.inapppurchase.utils;
/* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.json.JSONException;
import org.json.JSONObject;
/**
* Represents an in-app billing purchase.
*/
public class Purchase {
String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS
String mOrderId;
String mPackageName;
String mSku;
long mPurchaseTime;
int mPurchaseState;
String mDeveloperPayload;
String mToken;
String mOriginalJson;
String mSignature;
public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
mItemType = itemType;
mOriginalJson = jsonPurchaseInfo;
JSONObject o = new JSONObject(mOriginalJson);
mOrderId = o.optString("orderId");
mPackageName = o.optString("packageName");
mSku = o.optString("productId");
mPurchaseTime = o.optLong("purchaseTime");
mPurchaseState = o.optInt("purchaseState");
mDeveloperPayload = o.optString("developerPayload");
mToken = o.optString("token", o.optString("purchaseToken"));
mSignature = signature;
}
public String getItemType() { return mItemType; }
public String getOrderId() { return mOrderId; }
public String getPackageName() { return mPackageName; }
public String getSku() { return mSku; }
public long getPurchaseTime() { return mPurchaseTime; }
public int getPurchaseState() { return mPurchaseState; }
public String getDeveloperPayload() { return mDeveloperPayload; }
public String getToken() { return mToken; }
public String getOriginalJson() { return mOriginalJson; }
public String getSignature() { return mSignature; }
@Override
public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; }
}
|
[
"alexis.taugeron@gmail.com"
] |
alexis.taugeron@gmail.com
|
441f13fbd2ce173d6bde43e4f90ddc0f85158483
|
72342b5d6e2764347e5a179daad6692b332292d3
|
/app/src/main/java/com/mt/artist/Contant.java
|
29f11c35c177e317680d499f6a8f0044594161e8
|
[] |
no_license
|
ZSK-CRS/Artist
|
5644b6d152799b1e08f13cee5ab7df12252558db
|
86eae1f952042fbac23c86cece130c1a4bb0ceda
|
refs/heads/master
| 2020-06-23T23:06:53.788735
| 2019-07-26T09:02:40
| 2019-07-26T09:02:40
| 198,780,036
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 173
|
java
|
package com.mt.artist;
/**
* Author : ZSK
* Date : 2019/7/22
* Description :
*/
public class Contant {
public static String APPID_WECHAT = "wxb6fd1fafd3a870fe";
}
|
[
"1625127317@qq.com"
] |
1625127317@qq.com
|
25e20e2b221c5c6a20f30c3bbfad27e7546f2b7a
|
92638a078fb7d6f2b2ee7112f69a75e991c68a20
|
/src/Offer/Rectangle_Arrange.java
|
23ec81a7979190327cd0d89b8994b945fb0f3fe2
|
[] |
no_license
|
showiproute/Algorithm
|
5a774e21e4d9c2d7a6712c04c5407cb82c6871ca
|
5f748c14d55de8884fbd5e59c96f3749834200e0
|
refs/heads/master
| 2020-04-19T11:40:32.675332
| 2019-06-28T12:39:22
| 2019-06-28T12:39:22
| 168,173,475
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 573
|
java
|
package Offer;
/*
* 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。
* 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
*/
public class Rectangle_Arrange {
public static int RectCover(int target) {
if(target==0) {
return 0;
}
if(target<=1) {
return 1;
}
if(target*2==2) {
return 1;
}else if(target*2==4) {
return 2;
}else {
return RectCover(target-1)+RectCover(target-2);
}
}
}
|
[
"m18752095913@163.com"
] |
m18752095913@163.com
|
a0dad507171e964c6757d75c68d18b3e2fd5b8fb
|
922cbfd75ee7f6597e12373be7e345af631906bc
|
/DremOne/src/com/example/domain/Curriculum.java
|
272117b028916b01a8105465aa2616daa52969eb
|
[] |
no_license
|
jameschinese/JIkeDream
|
f1d968894c5ccac9baefd3b6c07be2d0a1e2586f
|
e164f6605e9d5e6ca1f433babe8acd0c36457988
|
refs/heads/master
| 2021-01-17T22:04:58.542868
| 2015-05-22T12:11:16
| 2015-05-22T12:11:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,367
|
java
|
package com.example.domain;
import java.io.Serializable;
/**
* 课程实体
*
* @author Administrator
*
*/
public class Curriculum implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6709416980283370927L;
private Integer id; // Id
private String title; // 标题
private Integer durationCount; // 课时总数量
private String url; // 图片uri
private String briefIntroduction; // 简介
private Integer useFlag; // 是否是vip教程<0为普通用户,1为vip>
public Curriculum() {
super();
}
public Curriculum(Integer id, String title, Integer durationCount,
String url, String briefIntroduction, Integer useFlag) {
super();
this.id = id;
this.title = title;
this.durationCount = durationCount;
this.url = url;
this.briefIntroduction = briefIntroduction;
this.useFlag = useFlag;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title
* the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the durationCount
*/
public Integer getDurationCount() {
return durationCount;
}
/**
* @param durationCount
* the durationCount to set
*/
public void setDurationCount(Integer durationCount) {
this.durationCount = durationCount;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url
* the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the briefIntroduction
*/
public String getBriefIntroduction() {
return briefIntroduction;
}
/**
* @param briefIntroduction
* the briefIntroduction to set
*/
public void setBriefIntroduction(String briefIntroduction) {
this.briefIntroduction = briefIntroduction;
}
/**
* @return the useFlag
*/
public Integer getUseFlag() {
return useFlag;
}
/**
* @param useFlag
* the useFlag to set
*/
public void setUseFlag(Integer useFlag) {
this.useFlag = useFlag;
}
}
|
[
"929280059@qq.com"
] |
929280059@qq.com
|
256400c455f1e28c8219e86054ee37c8c200d752
|
79367d7a51a493c66b9c0dc9bcc9531f46ac151d
|
/src/test/java/com/IniciandoComSpringMVC/cobranca/CobrancaApplicationTests.java
|
b93e4185590b95bea52fe233bcb81744af20067f
|
[] |
no_license
|
vitorfelipep/SpringCobranca
|
de4a027213dda78f0abf0b9de5b3def040818dfa
|
ed5724301ecdc04797d00f71df25bd61d0865459
|
refs/heads/master
| 2021-01-10T01:33:10.757284
| 2016-01-31T22:40:47
| 2016-01-31T22:40:47
| 49,376,604
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 522
|
java
|
package com.IniciandoComSpringMVC.cobranca;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CobrancaApplication.class)
@WebAppConfiguration
public class CobrancaApplicationTests {
@Test
public void contextLoads() {
}
}
|
[
"vitorfelipep@gmail.com"
] |
vitorfelipep@gmail.com
|
dc0f2d20e67a019e7f0aa94eda753cc56ad30c43
|
0cd6efa364121ad5cfb0b948f242561848a311cc
|
/jdk1.8.0_161/src/main/java/com/sun/corba/se/PortableActivationIDL/ServerNotRegistered.java
|
ca5c07709f72c19ef1a5f0fe8be589b15df2a091
|
[] |
no_license
|
izbk/jdk1.8.0_161
|
0050c98a7aa19b42b162db91ec0123f9b33bc849
|
606a851668a0ebfb01f3777fa923ec257059a21e
|
refs/heads/master
| 2021-07-14T00:29:26.104001
| 2020-05-14T02:46:42
| 2020-05-14T02:46:42
| 130,954,214
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 952
|
java
|
package com.sun.corba.se.PortableActivationIDL;
/**
* com/sun/corba/se/PortableActivationIDL/ServerNotRegistered.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u161/10277/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl
* Tuesday, December 19, 2017 5:53:41 PM PST
*/
public final class ServerNotRegistered extends org.omg.CORBA.UserException
{
public String serverId = null;
public ServerNotRegistered ()
{
super(ServerNotRegisteredHelper.id());
} // ctor
public ServerNotRegistered (String _serverId)
{
super(ServerNotRegisteredHelper.id());
serverId = _serverId;
} // ctor
public ServerNotRegistered (String $reason, String _serverId)
{
super(ServerNotRegisteredHelper.id() + " " + $reason);
serverId = _serverId;
} // ctor
} // class ServerNotRegistered
|
[
"izbk@163.com"
] |
izbk@163.com
|
8f42c1a4f34ba4c8289945b576117f89851f3bd1
|
2fc26e1904b04f84f322afd4f9d6834363ab3c97
|
/src/engineer/enterprise/payroll/system/Edit_Trainee.java
|
01412e53d116437f05f12ce4ed55a563ecfd6e48
|
[] |
no_license
|
enjy609/Engineer-Enterprise-payroll-system
|
01fba9aad584fdc529dd3269a07f0222b01c5770
|
0630faaec301332b5436738ff68fc88e862f7c9a
|
refs/heads/master
| 2022-11-06T09:30:35.417354
| 2020-06-23T19:34:40
| 2020-06-23T19:34:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 19,848
|
java
|
/*
* 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 engineer.enterprise.payroll.system;
import javax.swing.JOptionPane;
/**
*
* @author Lap
*/
public class Edit_Trainee extends javax.swing.JFrame {
/**
* Creates new form Edit_Trainee
*/
public Edit_Trainee() {
initComponents();
this.setTitle("Edit data");
jComboBox1.setVisible(false);
jButton2.setVisible(false);
jLabel2.setVisible(false);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
jLabel5.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
jTextField4.setVisible(false);
jLabel6.setVisible(false);
jTextField5.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jTextField5 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLocation(new java.awt.Point(500, 200));
setPreferredSize(new java.awt.Dimension(1090, 720));
setResizable(false);
getContentPane().setLayout(null);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-identity-theft-48.png"))); // NOI18N
jLabel1.setText("ID");
getContentPane().add(jLabel1);
jLabel1.setBounds(130, 30, 110, 48);
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
getContentPane().add(jTextField1);
jTextField1.setBounds(300, 40, 154, 30);
jButton1.setBackground(new java.awt.Color(204, 204, 204));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-ok-24.png"))); // NOI18N
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(680, 40, 110, 37);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-compose-48.png"))); // NOI18N
jLabel2.setText("Edit");
getContentPane().add(jLabel2);
jLabel2.setBounds(120, 80, 110, 60);
jComboBox1.setBackground(new java.awt.Color(204, 204, 204));
jComboBox1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Age", "Univeristy_Name", "Days", "Edit all data" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
getContentPane().add(jComboBox1);
jComboBox1.setBounds(300, 100, 160, 28);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-autograph-48.png"))); // NOI18N
jLabel3.setText("Name");
getContentPane().add(jLabel3);
jLabel3.setBounds(100, 320, 140, 48);
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
getContentPane().add(jTextField2);
jTextField2.setBounds(330, 330, 170, 28);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-age-48.png"))); // NOI18N
jLabel4.setText("Age");
getContentPane().add(jLabel4);
jLabel4.setBounds(110, 250, 130, 48);
jTextField3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
getContentPane().add(jTextField3);
jTextField3.setBounds(330, 260, 170, 28);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-classroom-48.png"))); // NOI18N
jLabel5.setText("Univeristy_Name");
getContentPane().add(jLabel5);
jLabel5.setBounds(40, 190, 270, 40);
jTextField4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
getContentPane().add(jTextField4);
jTextField4.setBounds(330, 190, 170, 30);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-timetable-48.png"))); // NOI18N
jLabel6.setText("Days");
getContentPane().add(jLabel6);
jLabel6.setBounds(120, 390, 140, 48);
jTextField5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField5ActionPerformed(evt);
}
});
getContentPane().add(jTextField5);
jTextField5.setBounds(330, 400, 170, 28);
jButton2.setBackground(new java.awt.Color(204, 204, 204));
jButton2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-simple-arrow-24.png"))); // NOI18N
jButton2.setText("Save");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2);
jButton2.setBounds(330, 520, 180, 50);
jButton3.setBackground(new java.awt.Color(204, 204, 204));
jButton3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/icons8-go-back-24.png"))); // NOI18N
jButton3.setText("Return Back");
jButton3.setActionCommand("");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(660, 520, 210, 50);
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/engineer/enterprise/payroll/system/f153e729-628b-446c-a69c-217cde29c861.jpg"))); // NOI18N
getContentPane().add(jLabel7);
jLabel7.setBounds(0, 0, 1280, 690);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
boolean flag=false;
boolean day=true;
if(jTextField1.getText().length()!=0){
String id=jTextField1.getText();
for(int i=0;i<trainee.tra.size();i++){
if(id.equals(trainee.tra.get(i).getID())){
flag=true;
if (trainee.tra.get(i).getDays()>3){
day=false;
}
}
}
if(flag==true&&day==true){
jLabel2.setVisible(true);
jComboBox1.setVisible(true);
jButton2.setVisible(true);
}
if(flag==false){
jLabel2.setVisible(false);
jComboBox1.setVisible(false);
jButton2.setVisible(false);
JOptionPane.showMessageDialog(this,"the ID is not found ", "Error",JOptionPane.ERROR_MESSAGE);
}
if(day==false){
jLabel2.setVisible(false);
jComboBox1.setVisible(false);
jButton2.setVisible(false);
JOptionPane.showMessageDialog(this, "This Trainee is deleted as the his absence days is more than three days", "ERROR",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(this, "Please Enter the trainne id", "ERROR",JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
String choice=String.valueOf(jComboBox1.getSelectedItem());
if(choice.equals("Name")){
jButton2.setVisible(true);
jButton3.setVisible(true);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
jLabel4.setVisible(false);
jLabel5.setVisible(false);
jTextField2.setVisible(true);
jTextField3.setVisible(false);
jTextField4.setVisible(false);
jLabel6.setVisible(false);
}
else if(choice.equals("Age")){
jButton2.setVisible(true);
jButton3.setVisible(true);
jLabel2.setVisible(true);
jLabel3.setVisible(false);
jLabel4.setVisible(true);
jLabel5.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(true);
jTextField4.setVisible(false);
jLabel6.setVisible(false);
}
else if(choice.equals("Univeristy_Name")){
jButton2.setVisible(true);
jButton3.setVisible(true);
jLabel2.setVisible(true);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
jLabel5.setVisible(true);
jLabel6.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
jTextField5.setVisible(false);
jTextField4.setVisible(true);
}
else if (choice.equals("Days")){
jButton2.setVisible(true);
jButton3.setVisible(true);
jLabel2.setVisible(true);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
jLabel5.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
jTextField4.setVisible(false);
jLabel6.setVisible(true);
jTextField5.setVisible(true);
}
else if (choice.equals("Edit all data")){
jButton2.setVisible(true);
jButton3.setVisible(true);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
jLabel4.setVisible(true);
jLabel5.setVisible(true);
jTextField2.setVisible(true);
jTextField3.setVisible(true);
jTextField4.setVisible(true);
jLabel6.setVisible(true);
jTextField5.setVisible(true);
}
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
String id=jTextField1.getText();
trainee tempp;
if(jTextField2.getText().length()!=0||jTextField3.getText().length()!=0||jTextField4.getText().length()!=0||jTextField5.getText().length()!=0){
for(int i=0;i<trainee.tra.size();i++){
if(id.equals(trainee.tra.get(i).getID())){
tempp=trainee.tra.get(i);
String choice=String.valueOf(jComboBox1.getSelectedItem());
if(choice.equals("Name")){
tempp.setName(jTextField2.getText());
}
else if(choice.equals("Age")){
int age=Integer.parseInt(jTextField3.getText());
tempp.setAge(age);
}
else if (choice.equals("Univeristy_Name")){
tempp.setUniversty_name(jTextField4.getText());
}
else if (choice.equals("Days")){
int day=Integer.parseInt(jTextField5.getText());
tempp.setDays(day);
}
else if(choice.equals("Edit all data")){
tempp.setName(jTextField2.getText());
int age=Integer.parseInt(jTextField3.getText());
tempp.setAge(age);
tempp.setUniversty_name(jTextField4.getText());
int day=Integer.parseInt(jTextField5.getText());
tempp.setDays(day);
}
}
}
jTextField1.setText(null);
jTextField2.setText(null);
jTextField3.setText(null);
jTextField4.setText(null);
jTextField5.setText(null);
jComboBox1.setVisible(false);
jButton2.setVisible(false);
jButton3.setVisible(true);
jLabel2.setVisible(false);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
jLabel5.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
jTextField4.setVisible(false);
jLabel6.setVisible(false);
jTextField5.setVisible(false);
JOptionPane.showMessageDialog(this,"the new data has saved","Done", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this,"please enter the new data","Error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
Trainee_form F = new Trainee_form ();
F.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton3ActionPerformed
private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField5ActionPerformed
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed
/**
* @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(Edit_Trainee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Edit_Trainee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Edit_Trainee.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Edit_Trainee.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 Edit_Trainee().setVisible(true);
}
});
}
// 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.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
// End of variables declaration//GEN-END:variables
}
|
[
"mohomed.adel.26@gmail.com"
] |
mohomed.adel.26@gmail.com
|
1f64f26a49e3d988392bdfbdfac8134012bb6714
|
60eab9b092bb9d5a50b807f45cbe310774d0e456
|
/dataset/cl1/src/test/org/apache/commons/lang/builder/HashCodeBuilderTest.java
|
4e2897dbbf57c31c29d7b661561a7580763910f5
|
[
"Apache-1.1",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
SpoonLabs/nopol-experiments
|
7b691c39b09e68c3c310bffee713aae608db61bc
|
2cf383cb84a00df568a6e41fc1ab01680a4a9cc6
|
refs/heads/master
| 2022-02-13T19:44:43.869060
| 2022-01-22T22:06:28
| 2022-01-22T22:14:45
| 56,683,489
| 6
| 1
| null | 2019-03-05T11:02:20
| 2016-04-20T12:05:51
|
Java
|
UTF-8
|
Java
| false
| false
| 20,212
|
java
|
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.builder;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests {@link org.apache.commons.lang.HashCodeBuilder}.
*
* @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
* @version $Id: HashCodeBuilderTest.java,v 1.3 2003/01/19 17:35:20 scolebourne Exp $
*/
public class HashCodeBuilderTest extends TestCase {
public HashCodeBuilderTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(HashCodeBuilderTest.class);
suite.setName("HashCodeBuilder Tests");
return suite;
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
//-----------------------------------------------------------------------
public void testConstructorEx1() {
try {
new HashCodeBuilder(0, 0);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testConstructorEx2() {
try {
new HashCodeBuilder(2, 2);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
static class TestObject {
private int a;
public TestObject(int a) {
this.a = a;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TestObject)) {
return false;
}
TestObject rhs = (TestObject) o;
return (a == rhs.a);
}
public void setA(int a) {
this.a = a;
}
public int getA() {
return a;
}
}
static class TestSubObject extends TestObject {
private int b;
transient private int t;
public TestSubObject() {
super(0);
}
public TestSubObject(int a, int b, int t) {
super(a);
this.b = b;
this.t = t;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TestSubObject)) {
return false;
}
TestSubObject rhs = (TestSubObject) o;
return super.equals(o) && (b == rhs.b);
}
}
public void testReflectionHashCode() {
assertEquals(17 * 37, HashCodeBuilder.reflectionHashCode(new TestObject(0)));
assertEquals(17 * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestObject(123456)));
}
public void testReflectionHierarchyHashCode() {
assertEquals(17 * 37 * 37, HashCodeBuilder.reflectionHashCode(new TestSubObject(0, 0, 0)));
assertEquals(17 * 37 * 37 * 37, HashCodeBuilder.reflectionHashCode(new TestSubObject(0, 0, 0), true));
assertEquals((17 * 37 + 7890) * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestSubObject(123456, 7890, 0)));
assertEquals(((17 * 37 + 7890) * 37 + 0) * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestSubObject(123456, 7890, 0), true));
}
public void testReflectionHierarchyHashCodeEx1() {
try {
HashCodeBuilder.reflectionHashCode(0, 0, new TestSubObject(0, 0, 0), true);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testReflectionHierarchyHashCodeEx2() {
try {
HashCodeBuilder.reflectionHashCode(2, 2, new TestSubObject(0, 0, 0), true);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testReflectionHashCodeEx1() {
try {
HashCodeBuilder.reflectionHashCode(0, 0, new TestObject(0), true);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testReflectionHashCodeEx2() {
try {
HashCodeBuilder.reflectionHashCode(2, 2, new TestObject(0), true);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testReflectionHashCodeEx3() {
try {
HashCodeBuilder.reflectionHashCode(13, 19, null, true);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
public void testSuper() {
Object obj = new Object();
assertEquals(17 * 37 + (19 * 41 + obj.hashCode()), new HashCodeBuilder(17, 37).appendSuper(
new HashCodeBuilder(19, 41).append(obj).toHashCode()
).toHashCode());
}
public void testObject() {
Object obj = null;
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj = new Object();
assertEquals(17 * 37 + obj.hashCode(), new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testLong() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((long) 0L).toHashCode());
assertEquals(17 * 37 + (int) (123456789L ^ (123456789L >> 32)), new HashCodeBuilder(17, 37).append((long) 123456789L).toHashCode());
}
public void testInt() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((int) 0).toHashCode());
assertEquals(17 * 37 + 123456, new HashCodeBuilder(17, 37).append((int) 123456).toHashCode());
}
public void testShort() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((short) 0).toHashCode());
assertEquals(17 * 37 + 12345, new HashCodeBuilder(17, 37).append((short) 12345).toHashCode());
}
public void testChar() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((char) 0).toHashCode());
assertEquals(17 * 37 + 1234, new HashCodeBuilder(17, 37).append((char) 1234).toHashCode());
}
public void testByte() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((byte) 0).toHashCode());
assertEquals(17 * 37 + 123, new HashCodeBuilder(17, 37).append((byte) 123).toHashCode());
}
public void testDouble() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double) 0d).toHashCode());
double d = 1234567.89;
long l = Double.doubleToLongBits(d);
assertEquals(17 * 37 + (int) (l ^ (l >> 32)), new HashCodeBuilder(17, 37).append(d).toHashCode());
}
public void testFloat() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float) 0f).toHashCode());
float f = 1234.89f;
int i = Float.floatToIntBits(f);
assertEquals(17 * 37 + i, new HashCodeBuilder(17, 37).append(f).toHashCode());
}
public void testBoolean() {
assertEquals(17 * 37 + 0, new HashCodeBuilder(17, 37).append(true).toHashCode());
assertEquals(17 * 37 + 1, new HashCodeBuilder(17, 37).append(false).toHashCode());
}
public void testObjectArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((Object[]) null).toHashCode());
Object[] obj = new Object[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = new Object();
assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = new Object();
assertEquals( (17 * 37 + obj[0].hashCode()) * 37 + obj[1].hashCode(), new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testObjectArrayAsObject() {
Object[] obj = new Object[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = new Object();
assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = new Object();
assertEquals( (17 * 37 + obj[0].hashCode()) * 37 + obj[1].hashCode(), new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testLongArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((long[]) null).toHashCode());
long[] obj = new long[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = 5L;
int h1 = (int) (5L ^ (5L >> 32));
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = 6L;
int h2 = (int) (6L ^ (6L >> 32));
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testLongArrayAsObject() {
long[] obj = new long[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = 5L;
int h1 = (int) (5L ^ (5L >> 32));
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = 6L;
int h2 = (int) (6L ^ (6L >> 32));
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testIntArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((int[]) null).toHashCode());
int[] obj = new int[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testIntArrayAsObject() {
int[] obj = new int[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testShortArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((short[]) null).toHashCode());
short[] obj = new short[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = (short) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = (short) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testShortArrayAsObject() {
short[] obj = new short[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = (short) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = (short) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testCharArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((char[]) null).toHashCode());
char[] obj = new char[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = (char) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = (char) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testCharArrayAsObject() {
char[] obj = new char[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = (char) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = (char) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testByteArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((byte[]) null).toHashCode());
byte[] obj = new byte[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = (byte) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = (byte) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testByteArrayAsObject() {
byte[] obj = new byte[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = (byte) 5;
assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = (byte) 6;
assertEquals( (17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testDoubleArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double[]) null).toHashCode());
double[] obj = new double[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = 5.4d;
long l1 = Double.doubleToLongBits(5.4d);
int h1 = (int) (l1 ^ (l1 >> 32));
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = 6.3d;
long l2 = Double.doubleToLongBits(6.3d);
int h2 = (int) (l2 ^ (l2 >> 32));
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testDoubleArrayAsObject() {
double[] obj = new double[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = 5.4d;
long l1 = Double.doubleToLongBits(5.4d);
int h1 = (int) (l1 ^ (l1 >> 32));
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = 6.3d;
long l2 = Double.doubleToLongBits(6.3d);
int h2 = (int) (l2 ^ (l2 >> 32));
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testFloatArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float[]) null).toHashCode());
float[] obj = new float[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = 5.4f;
int h1 = Float.floatToIntBits(5.4f);
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = 6.3f;
int h2 = Float.floatToIntBits(6.3f);
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testFloatArrayAsObject() {
float[] obj = new float[2];
assertEquals((17 * 37) * 37 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = 5.4f;
int h1 = Float.floatToIntBits(5.4f);
assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = 6.3f;
int h2 = Float.floatToIntBits(6.3f);
assertEquals( (17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testBooleanArray() {
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((boolean[]) null).toHashCode());
boolean[] obj = new boolean[2];
assertEquals((17 * 37 + 1) * 37 + 1 , new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = true;
assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = false;
assertEquals( (17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
public void testBooleanArrayAsObject() {
boolean[] obj = new boolean[2];
assertEquals((17 * 37 + 1) * 37 + 1 , new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[0] = true;
assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
obj[1] = false;
assertEquals( (17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode());
}
public void testBooleanMultiArray() {
boolean[][] obj = new boolean[2][];
assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = new boolean[0];
assertEquals(17 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = new boolean[1];
assertEquals((17 * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0] = new boolean[2];
assertEquals(((17 * 37 + 1) * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[0][0] = true;
assertEquals(((17 * 37 + 0) * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode());
obj[1] = new boolean[1];
assertEquals( (((17 * 37 + 0) * 37 + 1) * 37 + 1), new HashCodeBuilder(17, 37).append(obj).toHashCode());
}
}
|
[
"durieuxthomas@hotmail.com"
] |
durieuxthomas@hotmail.com
|
01f2ca7da1b5a376b45b159297ab5b3cde8cf9ae
|
11218f02efbbe1ff9841998ed03b0448234bc6a5
|
/app/src/androidTest/java/com/example/msisdqa/ExampleInstrumentedTest.java
|
a874ccd532962451f2e91c980191ba36ad0ec76c
|
[] |
no_license
|
kentwx/msi.sdqa
|
e7012062bd9cb0cf5014a09c948d0cfa061ae1f9
|
d02ec244939770a241b1d35ca0b9f713f8b12a69
|
refs/heads/master
| 2022-11-23T05:24:19.224130
| 2020-08-04T01:30:12
| 2020-08-04T01:30:12
| 284,844,998
| 0
| 0
| null | 2020-08-04T01:20:05
| 2020-08-04T01:20:04
| null |
UTF-8
|
Java
| false
| false
| 752
|
java
|
package com.example.msisdqa;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.msisdqa", appContext.getPackageName());
}
}
|
[
"68135067+kentwx@users.noreply.github.com"
] |
68135067+kentwx@users.noreply.github.com
|
4a0da75cdfc23c8682796896cc045c01a7e9ba1e
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/8/8_c35c0071965ffa2a49cabadc2a29a69aa9158202/RubeScene/8_c35c0071965ffa2a49cabadc2a29a69aa9158202_RubeScene_s.java
|
0dbbb05da2ec3a295b4c1d4b327e09e4f447bb15
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 9,558
|
java
|
package com.mangecailloux.rube;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.mangecailloux.rube.loader.serializers.utils.RubeImage;
/**
* A simple encapsulation of a {@link World}. Plus the data needed to run the simulation.
* @author clement.vayer
*
*/
public class RubeScene
{
public class CustomProperties {
Map<String, Integer> m_customPropertyMap_int;
Map<String, Float> m_customPropertyMap_float;
Map<String, String> m_customPropertyMap_string;
Map<String, Vector2> m_customPropertyMap_Vector2;
Map<String, Boolean> m_customPropertyMap_bool;
public CustomProperties() {
m_customPropertyMap_int = new HashMap<String, Integer>();
m_customPropertyMap_float = new HashMap<String, Float>();
m_customPropertyMap_string = new HashMap<String, String>();
m_customPropertyMap_Vector2 = new HashMap<String, Vector2>();
m_customPropertyMap_bool = new HashMap<String, Boolean>();
}
}
/** Box2D {@link World} */
public World world;
public static RubeScene mScene; // singleton reference. Initialized by RubeWorldSerializer.
private Array<Body> mBodies;
private Array<Fixture> mFixtures;
private Array<Joint> mJoints;
private Array<RubeImage> mImages;
public Map<Object,CustomProperties> mCustomPropertiesMap;
public Map<Body,Array<RubeImage>> mBodyImageMap;
/** Simulation steps wanted per second */
public int stepsPerSecond;
/** Iteration steps done in the simulation to calculates positions */
public int positionIterations;
/** Iteration steps done in the simulation to calculates velocities */
public int velocityIterations;
public RubeScene()
{
stepsPerSecond = RubeDefaults.World.stepsPerSecond;
positionIterations = RubeDefaults.World.positionIterations;
velocityIterations = RubeDefaults.World.velocityIterations;
mCustomPropertiesMap = new HashMap<Object, CustomProperties>();
mBodyImageMap = new HashMap<Body,Array<RubeImage>>();
}
@SuppressWarnings("unchecked")
public void parseCustomProperties(Json json,Object item, Object jsonData)
{
Array<Map<String,?>> customProperties = json.readValue("customProperties", Array.class, HashMap.class, jsonData);
if (customProperties != null)
{
for (int i = 0; i < customProperties.size; i++)
{
Map<String, ?> property = customProperties.get(i);
String propertyName = (String)property.get("name");
if (property.containsKey("string"))
{
setCustom(item, propertyName, (String)property.get("string"));
}
else if (property.containsKey("int"))
{
// Json stores things as Floats. Convert to integer here.
setCustom(item, propertyName,(Integer)((Float)property.get("int")).intValue());
}
else if (property.containsKey("float"))
{
setCustom(item, propertyName, (Float) property.get("float"));
}
else if (property.containsKey("vec2"))
{
setCustom(item, propertyName, (Vector2)json.readValue("vec2", Vector2.class,property));
}
else if (property.containsKey("bool"))
{
setCustom(item, propertyName, (Boolean)property.get("bool"));
}
}
}
}
public CustomProperties getCustomPropertiesForItem(Object item, boolean createIfNotExisting)
{
if (mCustomPropertiesMap.containsKey(item))
return mCustomPropertiesMap.get(item);
if (!createIfNotExisting)
return null;
CustomProperties props = new CustomProperties();
mCustomPropertiesMap.put(item, props);
return props;
}
public void setCustom(Object item, String propertyName, String val)
{
getCustomPropertiesForItem(item, true).m_customPropertyMap_string.put(propertyName, val);
}
public void setCustom(Object item, String propertyName, Integer val)
{
getCustomPropertiesForItem(item, true).m_customPropertyMap_int.put(propertyName, val);
}
public void setCustom(Object item, String propertyName, Float val)
{
getCustomPropertiesForItem(item, true).m_customPropertyMap_float.put(propertyName, val);
}
public void setCustom(Object item, String propertyName, Boolean val)
{
getCustomPropertiesForItem(item, true).m_customPropertyMap_bool.put(propertyName, val);
}
public void setCustom(Object item, String propertyName, Vector2 val)
{
getCustomPropertiesForItem(item, true).m_customPropertyMap_Vector2.put(propertyName, val);
}
public String getCustom(Object item, String propertyName, String defaultVal)
{
CustomProperties props = getCustomPropertiesForItem(item, false);
if (null == props)
return defaultVal;
if (props.m_customPropertyMap_string.containsKey(propertyName))
return props.m_customPropertyMap_string.get(propertyName);
return defaultVal;
}
public int getCustom(Object item, String propertyName, int defaultVal)
{
CustomProperties props = getCustomPropertiesForItem(item, false);
if (null == props)
return defaultVal;
if (props.m_customPropertyMap_int.containsKey(propertyName))
return props.m_customPropertyMap_int.get(propertyName);
return defaultVal;
}
public boolean getCustom(Object item, String propertyName, boolean defaultVal)
{
CustomProperties props = getCustomPropertiesForItem(item, false);
if (null == props)
return defaultVal;
if (props.m_customPropertyMap_bool.containsKey(propertyName))
return props.m_customPropertyMap_bool.get(propertyName);
return defaultVal;
}
public float getCustom(Object item, String propertyName, float defaultVal)
{
CustomProperties props = getCustomPropertiesForItem(item, false);
if (null == props)
return defaultVal;
if (props.m_customPropertyMap_float.containsKey(propertyName))
return props.m_customPropertyMap_float.get(propertyName);
return defaultVal;
}
public Vector2 getCustom(Object item, String propertyName, Vector2 defaultVal)
{
CustomProperties props = getCustomPropertiesForItem(item, false);
if (null == props)
return defaultVal;
if (props.m_customPropertyMap_Vector2.containsKey(propertyName))
return props.m_customPropertyMap_Vector2.get(propertyName);
return defaultVal;
}
public void clear()
{
if (mBodies != null)
{
mBodies.clear();
}
if (mFixtures != null)
{
mFixtures.clear();
}
if (mJoints != null)
{
mJoints.clear();
}
if (mImages != null)
{
mImages.clear();
}
if (mCustomPropertiesMap != null)
{
mCustomPropertiesMap.clear();
}
if (mBodyImageMap != null)
{
mBodyImageMap.clear();
}
}
/**
* Convenience method to update the Box2D simulation with the parameters read from the scene.
*/
public void step()
{
if(world != null)
{
float dt = 1.0f/stepsPerSecond;
world.step(dt, velocityIterations, positionIterations);
}
}
public void setBodies(Array<Body> mBodies)
{
this.mBodies = mBodies;
}
public Array<Body> getBodies()
{
return mBodies;
}
public void addFixtures(Array<Fixture> fixtures)
{
if (fixtures != null)
{
if (mFixtures == null)
{
mFixtures = new Array<Fixture>();
}
mFixtures.addAll(fixtures);
}
}
public Array<Fixture> getFixtures()
{
return mFixtures;
}
public void setJoints(Array<Joint> mJoints)
{
this.mJoints = mJoints;
}
public Array<Joint> getJoints()
{
return mJoints;
}
public void setImages(Array<RubeImage> images)
{
mImages = images;
}
public Array<RubeImage> getImages()
{
return mImages;
}
public void setMappedImage(Body body, RubeImage image)
{
Array<RubeImage> images = mBodyImageMap.get(body);
// if the mapping hasn't been created yet...
if (images == null)
{
// initialize the key's value...
images = new Array<RubeImage>(false,1); // expectation is that most, if not all, bodies will have a single image.
images.add(image);
mBodyImageMap.put(body, images);
}
else
{
//TODO: Sort based on render order of the image
images.add(image);
}
}
public Array<RubeImage> getMappedImage(Body body)
{
return mBodyImageMap.get(body);
}
public void printStats() {
System.out.println("Body count: " + ((mBodies != null) ? mBodies.size : 0));
System.out.println("Fixture count: " + ((mFixtures != null) ? mFixtures.size : 0));
System.out.println("Joint count: " + ((mJoints != null) ? mJoints.size : 0));
System.out.println("Image count: " + ((mImages != null) ? mImages.size : 0));
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
4bb39328a709fc1cfdb65a9109cbe28b35cb2386
|
421f0a75a6b62c5af62f89595be61f406328113b
|
/generated_tests/no_seeding/8_gfarcegestionfa-fr.unice.gfarce.interGraph.CreerUnEtudiantAction-1.0-7/fr/unice/gfarce/interGraph/CreerUnEtudiantAction_ESTest_scaffolding.java
|
d3740eea38187357846377692b223f1195c233c2
|
[] |
no_license
|
tigerqiu712/evosuite-model-seeding-empirical-evaluation
|
c78c4b775e5c074aaa5e6ca56bc394ec03c2c7c6
|
11a920b8213d9855082d3946233731c843baf7bc
|
refs/heads/master
| 2020-12-23T21:04:12.152289
| 2019-10-30T08:02:29
| 2019-10-30T08:02:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 554
|
java
|
/**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Mon Oct 28 20:32:23 GMT 2019
*/
package fr.unice.gfarce.interGraph;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class CreerUnEtudiantAction_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
|
[
"pderakhshanfar@bsr01.win.tue.nl"
] |
pderakhshanfar@bsr01.win.tue.nl
|
acaa86c497731e4071fb3f348118183e8cc9b2fc
|
88c90014ab4685f419a181a76fabdfb257a7b57c
|
/core/src/main/java/me/kolek/ecommerce/dsgw/repository/CatalogRepository.java
|
4f77a99529c63d6cbe9cc4b6caff019734da8c51
|
[] |
no_license
|
ckolek/dropship-gateway
|
987ae365496b6e84b9baf95958b3d2634a2cadd3
|
298f06f8549aab14309a8a52bf5566b5b01d2f1c
|
refs/heads/main
| 2023-09-01T20:50:11.250068
| 2021-10-10T18:06:23
| 2021-10-10T18:06:23
| 393,224,520
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 238
|
java
|
package me.kolek.ecommerce.dsgw.repository;
import me.kolek.ecommerce.dsgw.model.Catalog;
import org.springframework.stereotype.Repository;
@Repository
public interface CatalogRepository extends ExtendedJpaRepository<Catalog, Long> {
}
|
[
"christopher.w@kolek.me"
] |
christopher.w@kolek.me
|
0a0bb05273b5615a1969c6c30e51078cbcbb2053
|
9290655536e7ec1bb79f2646395f9b882be254ec
|
/djmall_provider/djmall_auth_provider/src/main/java/com/dj/mall/auth/service/address/impl/AreaServiceImpl.java
|
5ba6e9ea93eefd58a8edfbd28197c65c2df80207
|
[] |
no_license
|
CF1024/djmall
|
6ff074d681c0ef6c114420bbcfb1ee816e5cad51
|
8ed8315f65a4b2dba1eef0602b55d895a8297237
|
refs/heads/master
| 2022-12-27T08:49:44.588877
| 2020-09-28T14:14:18
| 2020-09-28T14:14:18
| 299,317,891
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 953
|
java
|
/*
* 作者:CF
* 日期:2020-07-28 15:24
* 项目:djmall
* 模块:djmall_auth_provider
* 类名:UserAddressService
* 版权所有(C), 2020. 所有权利保留
*/
package com.dj.mall.auth.service.address.impl;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dj.mall.auth.dto.address.AreaDTO;
import com.dj.mall.auth.entity.address.AreaEntity;
import com.dj.mall.auth.mapper.address.AreaMapper;
import com.dj.mall.auth.service.address.AreaService;
import com.dj.mall.model.base.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author chengf
* @date 2020/7/28 15:28
* 不暴露服务 省市县
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class AreaServiceImpl extends ServiceImpl<AreaMapper, AreaEntity> implements AreaService {
}
|
[
"chengfan0905@163.com"
] |
chengfan0905@163.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.