text
stringlengths
10
2.72M
package swing; import java.awt.*; import javax.swing.*; public class JLabelDemo extends JLabel { public JLabelDemo() { super("NVH", new ImageIcon("JLabel.jpg"), JLabel.CENTER); JFrame f = new JFrame("JLabel Demo"); f.setSize(300, 300); f.setLayout(null); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(this); setBounds(20, 20, 200, 200); System.out.println(getFont()); } public static void main(String[] args) { new JLabelDemo(); } }
package PA165.language_school_manager.Dao; import PA165.language_school_manager.Entities.Lecturer; import PA165.language_school_manager.Enums.Language; import java.util.List; /** * @author Viktor Slaný */ public interface LecturerDAO { /** * Find lecturer by Id. * * @param id identification number. * @return Lecturer with this identification number. */ Lecturer findById(Long id); /** * Create and add lecturer to database. * * @param lecturer lecturer in language school. */ void create(Lecturer lecturer); /** * Update lecturer in database. * * @param lecturer lecturer in language school. */ void update(Lecturer lecturer); /** * Update lecturer from database. * * @param lecturer lecturer in language school. */ void delete(Lecturer lecturer); /** * Find all lecturers in database. * * @return List of all lecturers in database. */ List<Lecturer> findAll(); /** * Find all lecturers who speak with this language. * * @param language lecturers language. * @return List of all lecturers in database who speak with this language. */ List<Lecturer> findByLanguage(Language language); /** * Find lecturers by first name * * @param firstName first name * @return List<Lecturer> */ List<Lecturer> findByFirstName(String firstName); /** * Find lecturers by last name * * @param lastName last name * @return List<Lecturer> */ List<Lecturer> findByLastName(String lastName); /** * Find lecture by lecture * * @param lectureId lecture id * @return Lecturer */ Lecturer findByLecture(Long lectureId); }
package com.example.demo.util; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) class ObjectArrayTest { @Mock ObjectArray objectArray; @BeforeEach void setup(){ MockitoAnnotations.initMocks(this); objectArray = new ObjectArray(); } @Test void creatCart() { Product[] arr = objectArray.creatCart(); for ( Product e : arr){ System.out.println(e.toString()); } assertEquals("Coffee",arr[0].getDescription()); } }
package com.maliang.core.arithmetic.function; import java.util.HashMap; import java.util.Map; import com.maliang.core.arithmetic.ArithmeticExpression; import com.maliang.core.service.MapHelper; public class AddToParams { public static void main(String[] args) { String paramStr = "{product:{id:'111111',name:'Product',brand:'aaaa',price:335.8,expiry_date:'2015-03-26'}," + "brands:[{id:'aaaa',name:'雪花秀'},{id:'bbbb',name:'希思黎'},{id:'cccc',name:'Pola'}]," + "products:[{id:'1111',name:'Bioeffect EGF生长因子精华',brand:'Bioeffect',price:850.00,picture:'0-item_pic.jpg'}," + "{id:'2222',name:'Aminogenesis活力再生胶囊 ',brand:'Aminogenesis',price:275.00,picture:'0-item_pic.jpg'}]}"; Map<String,Object> params = MapHelper.buildAndExecuteMap(paramStr, null); params = new HashMap(); String str = "{code:addToParams({product:{id:'111111',name:'Product',brand:'aaaa',price:335.8,expiry_date:'2015-03-26'},edit_form:{id:'edit_'+product.id}})}"; Object formMap = ArithmeticExpression.execute(str, params); System.out.println(params); String s = "{name:'product.brand',label:'品牌',type:'select',value:product.brand.id,options:each(brands){{value:this.id,text:this.name}}}"; } public static Map<String,Object> execute(Function function,Map<String,Object> params){ //System.out.println("addToParams expression : " + function.getExpression()); new MapCompiler(function.getExpression(),1,params,true,true); return params; } }
/** * Copyright 2008 The European Bioinformatics Institute, and others. * * 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 uk.ac.ebi.intact.view.webapp.controller.list; import org.apache.commons.lang.StringUtils; import org.apache.myfaces.orchestra.conversation.annotations.ConversationName; import org.primefaces.context.RequestContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import uk.ac.ebi.intact.model.CvDatabase; import uk.ac.ebi.intact.model.CvXrefQualifier; import uk.ac.ebi.intact.model.InteractorXref; import uk.ac.ebi.intact.view.webapp.model.InteractorWrapper; import javax.faces.event.ActionEvent; import java.util.*; /** * Controller for ProteinList View * * @author Bruno Aranda (baranda@ebi.ac.uk) * @version $Id$ * @since 0.9 */ @Controller @Scope( "conversation.access" ) @ConversationName( "general" ) public class ProteinListController extends InteractorListController { public ProteinListController() { } public String[] getSelectedUniprotIds() { final InteractorWrapper[] selected = getSelected(); if (selected == null) { return new String[0]; } final List<InteractorWrapper> interactorWrappers = Arrays.asList(selected); Set<String> uniprotIds = new HashSet<String>(); for (InteractorWrapper interactorWrapper : interactorWrappers) { if (interactorWrapper != null) { Collection<InteractorXref> interactorXrefs = interactorWrapper.getXrefs(); InteractorXref interactorXref = getUniprotXrefFrom(interactorXrefs); if (interactorXref != null) { uniprotIds.add(interactorXref.getPrimaryId()); } } } return uniprotIds.toArray( new String[uniprotIds.size()] ); } private InteractorXref getUniprotXrefFrom(Collection<InteractorXref> interactorXrefs) { for (InteractorXref xref : interactorXrefs) { CvXrefQualifier qualifier = xref.getCvXrefQualifier(); if (qualifier != null) { String qualifierIdentity = qualifier.getIdentifier(); if (qualifierIdentity != null && CvXrefQualifier.IDENTITY_MI_REF.equals(qualifierIdentity)) { CvDatabase database = xref.getCvDatabase(); String databaseIdentity = database.getIdentifier(); if (databaseIdentity != null && CvDatabase.UNIPROT_MI_REF.equals(databaseIdentity)) { return xref; } } } } return null; } public void openInReactome(ActionEvent evt) { RequestContext context = RequestContext.getCurrentInstance(); if (getSelected().length > 0) { context.execute("reactomeAnalysisList(['"+ StringUtils.join(getSelectedUniprotIds(), "','")+"'])"); } else { alertNoSelection(); } } private void alertNoSelection() { RequestContext context = RequestContext.getCurrentInstance(); context.execute("alert('Select at least a protein in the table below')"); } public void openInInterpro(ActionEvent evt) { String url = "http://www.ebi.ac.uk/interpro/IProtein?ac="+StringUtils.join(getSelectedUniprotIds(), ","); executeUrlRedirection(url); } public void openInEnsembl(ActionEvent evt) { String url = "http://www.ensembl.org/Homo_sapiens/featureview?type=ProteinAlignFeature;id="+StringUtils.join(getSelectedUniprotIds(), ";id="); executeUrlRedirection(url); } public void openInArrayExpress(ActionEvent evt) { String url = "http://www.ebi.ac.uk/gxa/query?geneQuery="+StringUtils.join(getSelectedUniprotIds(), "+"); executeUrlRedirection(url); } private void executeUrlRedirection(String url) { RequestContext context = RequestContext.getCurrentInstance(); if (getSelected().length > 0) { context.execute("var win = window.open('','_blank'); win.location='" + url + "';"); } else { alertNoSelection(); } } }
package com.jic.libin.leaderus.study003; import java.util.Spliterator; import java.util.concurrent.CountedCompleter; import java.util.concurrent.ForkJoinPool; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.DoubleStream; /** * Created by Administrator on 2016/12/24 0024. */ public class P <T>{ private final Spliterator<T> st; public P(Spliterator<T> st) { this.st = st; } public <R> P<R> map(Function<T, R> f) { Spliterator<R> stMap = new Spliterator<R>() { @Override public boolean tryAdvance(Consumer<? super R> action) { return st.tryAdvance((x)->{ System.out.println("-" + x + "-"); action.accept(f.apply(x)); }); } @Override public Spliterator<R> trySplit() { return (Spliterator<R>) st.trySplit(); } @Override public long estimateSize() { return st.estimateSize(); } @Override public int characteristics() { return st.characteristics(); } }; return new P(stMap); } public P<T> filter(Predicate<T> p) { Spliterator<T> stFilter = new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return st.tryAdvance((x)-> { if (p.test(x)) { action.accept(x); } }); } @Override public Spliterator<T> trySplit() { return st.trySplit(); } @Override public long estimateSize() { return st.estimateSize(); } @Override public int characteristics() { return st.characteristics(); } }; return new P(stFilter); } public void forEach(Consumer<T> t) { if ((st.characteristics() & Spliterator.SIZED) != 0){ parEach(t); } else { while (st.tryAdvance(t)); } } void parEach(Consumer<T> action) { long targetBatchSize = st.estimateSize() / (ForkJoinPool.getCommonPoolParallelism() * 8); new ParEach(null, st, action, targetBatchSize).invoke(); } static class ParEach<T> extends CountedCompleter<Void> { final Spliterator<T> spliterator; final Consumer<T> action; final long targetBatchSize; ParEach(ParEach<T> parent, Spliterator<T> spliterator, Consumer<T> action, long targetBatchSize) { super(parent); this.spliterator = spliterator; this.action = action; this.targetBatchSize = targetBatchSize; } @Override public void compute() { Spliterator<T> sub; while (spliterator.estimateSize() > targetBatchSize && (sub = spliterator.trySplit()) != null) { addToPendingCount(1); new ParEach<>(this, sub, action, targetBatchSize).fork(); } spliterator.forEachRemaining(action); propagateCompletion(); } } public static void main(String[] args) { int size = 3; Integer[] t = new Integer[size]; for(int i = 0; i < size; i++) { t[i] = Integer.valueOf(i); } TheArraySpliterator<Integer> sp = new TheArraySpliterator<>(t, 0, size); P<Integer> p = new P(sp); p.map(x -> x * 2) .forEach(System.out::println); } }
package com.meehoo.biz.core.basic.vo.security; import lombok.Getter; import lombok.Setter; import java.util.Date; /** * Created by qx on 2019/4/1. */ @Getter @Setter public class UserLoginRecordVO { private String id; private String userId; private Integer status; private Date loginTime; private Date availableTime; private String device; }
package com.padeltrophy.util.json; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.padeltrophy.entity.Player; //import com.padeltrophy.service.PlayerService; import com.padeltrophy.util.log.Tracer; import java.io.IOException; /** * Created by JLRB002 on 03/11/2015. */ public class TournamentOrganizerDeserializer extends JsonDeserializer<Player> { private Tracer tracer = new Tracer(TournamentOrganizerDeserializer.class.getName()); @Override public Player deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { /*try { PlayerService playerUtil = ApplicationContextHolder.getContext().getBean(PlayerService.class); String organizerId = jsonParser.getText(); tracer.trace("deserialize() : organizerId: "+organizerId); Player organizer=null; if(playerUtil!=null) { tracer.trace("deserialize() : getPlayerById: "+organizerId); organizer = playerUtil.getSimplePlayerById(organizerId); }else{ tracer.trace("deserialize() : playerUtil null!"); } return organizer; }catch (Exception e){ tracer.trace("deserialize() : error:> ",Tracer.LEVEL_ERROR,e); return null; }*/ return null; } }
package stratergy; import models.Post; import java.util.Date; import java.util.List; public interface RankingStratergyI { List<Post> rankFeeds(List<Post> feeds, Date timeStamp); }
package com.bofsoft.laio.laiovehiclegps.Database; /** * @author admin * */ public class DBRequestParam<T> { /** * @author yedong */ public final static int One_PENDING = 0x01; // 初始状态 public final static int TWO_GETTING_UPDATE_LIST = 0x02; // 获取服务器数据库更新时间 public final static int THREE_CHECK_IS_UPDATE = 0x03; // 比较本地更新时间 public final static int FOUR_GETTING_UPDATE = 0x04; // 获取更新的数据 public final static int FIVE_FINISH = 0x05; // 更新完成 // private int id = 0; /** * 是否有超时等问题(true-不更新本地更新时间) */ private boolean isHasException = false; private int curStatus = One_PENDING; public DBCallBackImp<T> dbCallBack; /** * 请求的表的Id */ private int tableNum; /** * 请求的表名 */ private String tableName; /** * 请求的数据类型 */ private Class<T> dataClass; /** * 查询的条件 */ private String selection; /** * 查询的条件参数 */ private String[] selectionArgs; /** * 分组 */ private String groupBy; /** * 过滤 */ private String having; /** * 排序 */ private String orderBy; public DBRequestParam(int tableNum, Class<T> dataClass, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, DBCallBackImp<T> callBack) { this.tableNum = tableNum; this.tableName = TableManager.getNameByNum(tableNum); this.dataClass = dataClass; this.selection = selection; this.selectionArgs = selectionArgs; this.groupBy = groupBy; this.having = having; this.orderBy = orderBy; this.dbCallBack = callBack; // this.id = AtomicIntegerUtil.getIncrementID(); } public DBRequestParam(String tableName, Class<T> dataClass, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, DBCallBackImp<T> callBack) { this.tableNum = TableManager.getNumByName(tableName); this.tableName = tableName; this.dataClass = dataClass; this.selection = selection; this.selectionArgs = selectionArgs; this.groupBy = groupBy; this.having = having; this.orderBy = orderBy; this.dbCallBack = callBack; // this.id = AtomicIntegerUtil.getIncrementID(); } /** * 获取是否有超时等问题 * * @return */ public boolean isHasException() { return isHasException; } /** * 设置是否有超时等问题 * * @return */ public void setHasException(boolean isHasException) { this.isHasException = isHasException; } /** * 获取当前请求的状态 * * @return */ public int getCurStatus() { return curStatus; } /** * 设置当前请求的状态 * * @return */ public void setCurStatus(int curStatus) { this.curStatus = curStatus; } public int getTableNum() { return tableNum; } public void setTableNum(int tableNum) { this.tableNum = tableNum; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public Class<T> getDataClass() { return dataClass; } public void setDataClass(Class<T> dataClass) { this.dataClass = dataClass; } public String getSelection() { return selection; } public void setSelection(String selection) { this.selection = selection; } public String[] getSelectionArgs() { return selectionArgs; } public void setSelectionArgs(String[] selectionArgs) { this.selectionArgs = selectionArgs; } public String getGroupBy() { return groupBy; } public void setGroupBy(String groupBy) { this.groupBy = groupBy; } public String getHaving() { return having; } public void setHaving(String having) { this.having = having; } public String getOrderBy() { return orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } }
package com.lxj.leaf; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.border.EmptyBorder; @SuppressWarnings("serial") public class MainFrame extends JFrame implements ActionListener { private JPanel contentPane; private DataCollector dc; private PicPanel picPane; private ThreeDPanel threeDPanel; private JScrollPane jsPane; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrame frame = new MainFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public MainFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JMenuBar menuBar = new JMenuBar(); contentPane.add(menuBar, BorderLayout.NORTH); JMenu dataMenu = new JMenu("Data"); menuBar.add(dataMenu); JMenuItem initItem = new JMenuItem("Init"); dataMenu.add(initItem); initItem.addActionListener(this); JSeparator separator = new JSeparator(); dataMenu.add(separator); JMenuItem startItem = new JMenuItem("Start"); dataMenu.add(startItem); startItem.addActionListener(this); JMenuItem stopItem = new JMenuItem("Stop"); dataMenu.add(stopItem); stopItem.addActionListener(this); JSeparator separator_1 = new JSeparator(); dataMenu.add(separator_1); JMenuItem startGetOutlineItem = new JMenuItem("Start Get Outline"); dataMenu.add(startGetOutlineItem); startGetOutlineItem.addActionListener(this); JMenuItem finishGetOutlineItem = new JMenuItem("Finish Get Outline"); dataMenu.add(finishGetOutlineItem); finishGetOutlineItem.addActionListener(this); JSeparator separator_2 = new JSeparator(); dataMenu.add(separator_2); JMenuItem saveItem = new JMenuItem("Save"); dataMenu.add(saveItem); saveItem.addActionListener(this); JMenuItem loadItem = new JMenuItem("Load"); dataMenu.add(loadItem); loadItem.addActionListener(this); JMenu showMenu = new JMenu("Show"); menuBar.add(showMenu); JMenuItem picItem = new JMenuItem("PicPanel"); showMenu.add(picItem); picItem.addActionListener(this); JMenuItem threeDItem = new JMenuItem("ThreeDPanel"); showMenu.add(threeDItem); threeDItem.addActionListener(this); dc = new DataCollector(); picPane = new PicPanel(dc); jsPane = new JScrollPane(picPane); contentPane.add(jsPane, BorderLayout.CENTER); } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); switch (command) { case "Init": picPane.loadPic(); picPane.repaint(); break; case "Start": picPane.startGet(); break; case "Stop": picPane.stopGet(); break; case "Start Get Outline": picPane.startGetOutline(); break; case "Finish Get Outline": picPane.finishGetOutline(); break; case "Save": try { dc.saveLines(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } break; case "Load": try { dc.loadLines(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } break; case "PicPanel": contentPane.remove(1); contentPane.add(jsPane, BorderLayout.CENTER); this.repaint(); break; case "ThreeDPanel": threeDPanel = new ThreeDPanel(dc); contentPane.remove(1); contentPane.add(threeDPanel.getCanvas(), BorderLayout.CENTER); this.repaint(); break; default: break; } } }
package cz.muni.fi.pa165.monsterslayers.frontend.security; import org.springframework.context.annotation.Import; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * Initializer for security stuff * * @author Ondrej Budai */ @Import(SecurityConfiguration.class) public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
package com.qa.hubspot.pages; import org.openqa.selenium.WebDriver; import com.qa.hubspot.BasePage.basePage; public class Sales_TasksPage extends basePage{ WebDriver driver; public Sales_TasksPage(WebDriver driver) { this.driver=driver; } }
package uk.co.mtford.jalp.abduction.logic.instance; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.mtford.jalp.abduction.AbductiveFramework; import uk.co.mtford.jalp.abduction.logic.instance.equalities.EqualityInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.CharConstantInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance; import uk.co.mtford.jalp.abduction.rules.E2RuleNode; import uk.co.mtford.jalp.abduction.rules.E2bRuleNode; import uk.co.mtford.jalp.abduction.rules.E2cRuleNode; import java.util.HashMap; import java.util.LinkedList; import static org.junit.Assert.assertTrue; /** Checks that the correct types of E rule nodes are produced depending on quantification etc. * */ public class ETest { public ETest() { } @Before public void noSetup() { } @After public void noTearDown() { } // ForAll X . <- X = u should produce an E2 node. @Test public void test1() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance X = new VariableInstance("X"); VariableInstance Y = new VariableInstance("Y"); EqualityInstance E = new EqualityInstance(X,Y); DenialInstance d = new DenialInstance(E); d.getUniversalVariables().add(X); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); } /* // ForAll X . <- p(X)=p(Y) should produce an E2 node with X=Y as head. @Test public void test2() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance X = new VariableInstance("X"); VariableInstance Y = new VariableInstance("Y"); PredicateInstance p1 = new PredicateInstance("p",X); PredicateInstance p2 = new PredicateInstance("p",Y); EqualityInstance E = new EqualityInstance(p1,p2); DenialInstance d = new DenialInstance(E); d.getUniversalVariables().add(X); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); assertTrue(goals.get(0).equals(new EqualityInstance(X,Y))); } */ // <- Z = X should produce an E2b node. @Test public void test3() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance Z = new VariableInstance("Z"); VariableInstance X = new VariableInstance("X"); EqualityInstance E = new EqualityInstance(Z,X); DenialInstance d = new DenialInstance(E); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2bRuleNode); } // <- Z = c should produce an E2b node. @Test public void test10() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance Z = new VariableInstance("Z"); CharConstantInstance c = new CharConstantInstance("c"); EqualityInstance E = new EqualityInstance(Z,c); DenialInstance d = new DenialInstance(E); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2bRuleNode); } // <- Z = p(X) should produce an E2b node. @Test public void test4() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance Z = new VariableInstance("Z"); VariableInstance X = new VariableInstance("X"); PredicateInstance p1 = new PredicateInstance("p",X); EqualityInstance E = new EqualityInstance(Z,p1); DenialInstance d = new DenialInstance(E); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2bRuleNode); } // for all Y <- Z = Y should produce an E2c node. @Test public void test5() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); VariableInstance Z = new VariableInstance("Z"); VariableInstance Y = new VariableInstance("Y"); EqualityInstance E = new EqualityInstance(Z,Y); DenialInstance d = new DenialInstance(E); d.getUniversalVariables().add(Y); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2cRuleNode); } // for all Y <- c = Y should produce an E2 node. @Test public void test6() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); CharConstantInstance c = new CharConstantInstance("c"); VariableInstance Y = new VariableInstance("Y"); EqualityInstance E = new EqualityInstance(c,Y); DenialInstance d = new DenialInstance(E); d.getUniversalVariables().add(Y); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); } // for all Y <- Y = c should produce an E2 node. @Test public void test7() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); CharConstantInstance c = new CharConstantInstance("c"); VariableInstance Y = new VariableInstance("Y"); EqualityInstance E = new EqualityInstance(Y,c); DenialInstance d = new DenialInstance(E); d.getUniversalVariables().add(Y); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); } // <- c = c should produce an E2 node. @Test public void test8() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); CharConstantInstance c = new CharConstantInstance("c"); EqualityInstance E = new EqualityInstance(c,c); DenialInstance d = new DenialInstance(E); goals.add(d); assertTrue(d.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); } // <- c = d should produce an E2 node. @Test public void test9() { AbductiveFramework f = new AbductiveFramework(); LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>(); CharConstantInstance c = new CharConstantInstance("c"); CharConstantInstance d = new CharConstantInstance("d"); EqualityInstance E = new EqualityInstance(c,d); DenialInstance de = new DenialInstance(E); goals.add(de); assertTrue(de.getPositiveRootRuleNode(f,null,goals) instanceof E2RuleNode); } }
package com.esum.framework.security.crypto.encrypt; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.util.Hashtable; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import com.esum.framework.security.SecurityConstants; import com.esum.framework.security.pki.manager.PKIException; import com.esum.framework.security.pki.manager.info.PKIStoreInfo; abstract public class DataEncrypt { private static Hashtable<String, DataEncrypt> mDataEncryptMap = new Hashtable<String, DataEncrypt>(); public static DataEncrypt getInstance(String toolkitName) { if (!mDataEncryptMap.containsKey(toolkitName)) { return newInstance(toolkitName); } return mDataEncryptMap.get(toolkitName); } private static synchronized DataEncrypt newInstance(String toolkitName) { if (!mDataEncryptMap.containsKey(toolkitName)) { if (toolkitName.equals(SecurityConstants.TOOLKIT_TRADE_SIGN)) { mDataEncryptMap.put(toolkitName, new DataEncryptWithTradeSign()); } else if (toolkitName.equals(SecurityConstants.TOOLKIT_SIGN_GATE)) { mDataEncryptMap.put(toolkitName, new DataEncryptWithSignGate()); } else { mDataEncryptMap.put(toolkitName, new DataEncryptWithBC()); } } return mDataEncryptMap.get(toolkitName); } /** * 비대칭키 기반의 암호화를 수행하고, 그 결과를 리턴한다. * 암호화 키로 사용되는 인증서(cert)를 받아서 사용한다. 암호화된 데이터는 입력받은 cert의 다른 키를 통해 복호화할 수 있다. */ abstract public byte[] encryptWithAsymmetric(byte[] data, Certificate cert) throws NoSuchPaddingException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, CertificateException, IllegalStateException, IllegalBlockSizeException, BadPaddingException; /** * 암호화된 데이터를 pkiStoreInfo를 통해 복호화한다. */ abstract public byte[] decryptWithAsymmetric(byte[] encryptedData, PKIStoreInfo pkiStoreInfo) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, PKIException; /** * 특정 symetricKey를 이용하여 data를 암호화 한다. symetricKey는 복호화를 위해 사용된다. */ abstract public byte[] encryptWithSymmetric(byte[] data, byte[] symmetricKey, String encryptMethod) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, PKIException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException; /** * 특정 symetricKey로 암호화된 데이터를 복호화한다. */ abstract public byte[] decryptWithSymmetric(byte[] encryptedData, byte[] symmetricKey, String encryptMethod) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, PKIException; }
package redbusdemo; import org.openqa.selenium.By; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class UploadFiles { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe"); InternetExplorerDriver driver=new InternetExplorerDriver(); driver.get("http://leaftaps.com/opentaps/control/main"); driver.findElementById("username").sendKeys("DemoSalesManager"); driver.findElementById("password").sendKeys("crmsfa"); driver.findElementByClassName("decorativeSubmit").click(); driver.findElementByLinkText("CRM/SFA").click(); driver.findElementByLinkText("Leads").click(); driver.findElementByLinkText("Upload Leads").click(); driver.findElementById("uploadedFile").sendKeys("D:\\sample.pdf"); WebDriverWait wait=new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("smallSubmit"))); driver.findElementByClassName("smallSubmit").click(); } }
package com.kywpcm.problem.bm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class P04 { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input; List<String> list = new ArrayList<>(); try { while (true) { input = br.readLine(); if (input.equals("END")) { break; } list.add(input); } } catch (IOException e) { e.printStackTrace(); } int tabSize = Integer.parseInt(list.get(0)); list.remove(0); List<String> replacedCode = replaceTabToSpace(tabSize, list); for (String rCodeLine : replacedCode) { System.out.println(rCodeLine); } } public static List<String> replaceTabToSpace(int tabSize, List<String> code) { StringBuilder sb = new StringBuilder(); List<String> replaceCode = new ArrayList<>(); int spaceCnt = 0; for (String codeLine : code) { for (int i = 0; i < codeLine.length(); i++) { char c = codeLine.charAt(i); if (c == 32) { // space spaceCnt++; sb.append(c); } else if (c == 9) { // tab int diff = tabSize - (spaceCnt % tabSize); // tab 만큼 space 생성 StringBuilder space = new StringBuilder(); for (int j = 1; j <= diff; j++) { space.append(" "); } sb.append(space); spaceCnt = 0; } else { // other character // 나머지 전부 append 후 탈출 sb.append(codeLine.substring(i)); break; } } // 오른쪽 trim 후, list add replaceCode.add(sb.toString().replaceAll("(\\s|\t)*$", "")); sb.setLength(0); // StringBuilder 초기화 } return replaceCode; } @Test public void replaceTabToSpaceTest() { List<String> code = new ArrayList<>(); code.add("2"); code.add("\tprintf"); code.add(" \tprintf"); code.add(" \tprintf"); code.add(" \tprintf"); code.add(" \tprintf"); code.add("\tprintf printf\t\tprintf"); code.add("\tprintf printf\t\tprintf "); code.add("\tprintf printf\t\tprintf\t"); code.add("\tprintf printf\t\tprintf \t"); code.add("\tprintf printf\t\tprintf \t\t\t\t\t"); int tabSize = Integer.parseInt(code.get(0)); code.remove(0); List<String> replacedCode = replaceTabToSpace(tabSize, code); for (String rCodeLine : replacedCode) { System.out.println(rCodeLine); } } }
package com.jiacaizichan.baselibrary.utils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; public class AlertDialogUtil { private View view; private AlertDialog alertDialog; private int resourceId; private Activity activity; private InitDialog initDialog; //显示等级(是否可以点击外面取消) private int showGrade; public int getShowGrade() { return showGrade; } public void setShowGrade(int showGrade) { this.showGrade = showGrade; } public InitDialog getInitDialog() { return initDialog; } public void setInitDialog(InitDialog initDialog) { this.initDialog = initDialog; } public AlertDialogUtil(Activity activity, int resourceId){ this.activity = activity; this.resourceId = resourceId; } public void init(int flag){ if (initDialog==null){ throw new NullPointerException("请先实现接口"); }else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); view = LayoutInflater.from(activity).inflate(resourceId,null,false); initDialog.initDialog(view,flag); alertDialog = builder.create(); switch (showGrade){ case 0: break; case 1: alertDialog.setCanceledOnTouchOutside(false); // alertDialog.setCancelable(false); break; case 2: // alertDialog.setCanceledOnTouchOutside(false); alertDialog.setCancelable(false); break; } // alertDialog = (AlertDialog) new Dialog(activity); alertDialog.setView((activity).getLayoutInflater().inflate(resourceId, null)); alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); alertDialog.show(); alertDialog.getWindow().setContentView(view); view.post(new Runnable() { @Override public void run() { int width = view.getWidth(); WindowManager.LayoutParams attributes = alertDialog.getWindow().getAttributes(); attributes.width = width; alertDialog.getWindow().setAttributes(attributes); alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); } }); } } public void setIsDismiss(boolean isDismiss){ alertDialog.setCanceledOnTouchOutside(isDismiss); } public void showDialog(){ alertDialog.show(); } public void dismissDialog(){ if (alertDialog!=null&&alertDialog.isShowing()){ alertDialog.dismiss(); } } public interface InitDialog{ void initDialog(View view,int flag); } }
public class ChessKingCheck { /** * @RAKESH YADAV * 27TH FEBRUARY 2015 * Check whether a king is in safe position or not. If he is not, find possible moves. * Matrix is not necessary to be of 8*8. It can be of any size. * King, Queen, Bishop(Wazir), Rook(Elephant), Knight(Horse), Pawn(Pyade). * * We will have to check "Check Condition" from Left, Right, Up, Down, all 4 diagonal directions and from the Knight */ static char [][]board = {{'K','_','_','k','_','_','_','_'}, {'_','_','_','_','_','_','_','_'}, {'q','n','_','_','_','_','_','q'}, {'_','_','_','_','_','_','_','_'}, {'_','_','_','_','_','_','_','_'}, {'_','_','_','_','_','_','_','_'} }; static int row; static int col; public static void main(String[] args) { printMatrix(); boolean safe = isKingSafe(board); if(safe == true){ System.out.println("\nKing is safe"); } else{ // System.out.println("\nKing is not safe"); } } //Finding position of the King and Printing Matrix static void printMatrix(){ for(int i = 0; i < board.length; i ++){ for(int j = 0; j< board[i].length; j ++){ System.out.print(board[i][j] + " "); if(board[i][j] == 'K'){ row = i; col = j; } } System.out.println(); } System.out.println("\nKing is at Position board(" +row + ", "+ col + ")"); } static boolean isKingSafe(char [][]board){ System.out.println("\n" + checkKnight()); return false; } //Checking from Left Direction static boolean checkLeft(){ int c = 0; int check = 0; for(int i = col-1; i >= 0; i --){ //Checking if there is rook or queen of opponent in the left of King if(board[row][i] == 'q' || board[row][i] == 'r'){ c = i; check = 1; break; } } //if there is no rook or queen of opponent in the left of King if(check == 0) return true; //if there is rook or queen in left if(check == 1){ for(int i = c+1; i < col; i++){ //check if there is anything else between our King and queen or rook if(board[row][i] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from Right Direction static boolean checkRight(){ int c = 0; int check = 0; for(int i = col+1; i < board[0].length; i ++){ //Checking if there is rook or queen of opponent in the right of King if(board[row][i] == 'q' || board[row][i] == 'r'){ c = i; check = 1; break; } } //if there is no rook or queen of opponent in the left of King if(check == 0) return true; //if there is rook or queen in left if(check == 1){ for(int i = c-1; i > col; i--){ //check if there is anything else between our King and queen or rook if(board[row][i] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from Upward Direction static boolean checkUp(){ int r = 0; int check = 0; for(int i = row-1; i >= 0; i --){ //Checking if there is rook or queen of opponent in upward direction of King if(board[i][col] == 'q' || board[i][col] == 'r'){ r = i; check = 1; break; } } //if there is no rook or queen of opponent in upward direction of King if(check == 0) return true; //if there is rook or queen in left if(check == 1){ for(int i = row-1; i > r; i--){ //check if there is anything else between our King and queen or rook if(board[i][col] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from Downward Direction static boolean checkDown(){ int r = 0; int check = 0; for(int i = row+1; i < board.length; i ++){ //Checking if there is rook or queen of opponent in downward direction of King if(board[i][col] == 'q' || board[i][col] == 'r'){ r = i; check = 1; break; } } //if there is no rook or queen of opponent in downward direction of King if(check == 0) return true; //if there is rook or queen in left if(check == 1){ for(int i = row+1; i < r; i++){ //check if there is anything else between our King and queen or rook if(board[i][col] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from diagonal Left Up Direction static boolean checkDiagonalLeftUp(){ int r = 0; int c = col; int check = 0; //Checking for pawn of the opponent in the diagonal left up direction if(row > 0 && col > 0){ if(board[row-1][col-1] == 'p'){ return false; } } for(int i = row-1; i >= 0; i --){ //Checking if there is bishop or queen of opponent in diagonal left up direction of King c--; if(c < 0) //Checking for column bound break; if(board[i][c] == 'q' || board[i][c] == 'b'){ r = i; check = 1; break; } } //if there is no bishop or queen of opponent in diagonal left up direction of King if(check == 0) return true; if(check == 1){ c = col; for(int i = row-1; i > r; i--){ //check if there is anything else between our King and queen or bishop of opponenet c--; if(board[i][c] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from diagonal Right Up Direction static boolean checkDiagonalRightUp(){ int r = 0; int c = col; int check = 0; //Checking for pawn of the opponent if(row > 0 && col < board[0].length){ if(board[row-1][col+1] == 'p'){ return false; } } for(int i = row-1; i >= 0; i --){ //Checking if there is bishop or queen of opponent c++; if(c == board[0].length) //Checking for column bound break; if(board[i][c] == 'q' || board[i][c] == 'b'){ r = i; check = 1; break; } } //if there is no bishop or queen of opponent in diagonal left up direction of King if(check == 0) return true; if(check == 1){ c = col; for(int i = row-1; i > r; i--){ //check if there is anything else between our King and queen or bishop of opponenet c++; if(board[i][c] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from diagonal Left Down Direction static boolean checkDiagonalLeftDown(){ int r = row; int c = 0; int check = 0; for(int i = col-1; i >= 0; i --){ //Checking if there is bishop or queen of opponent r++; if(r == board.length){ //Checking for row bound break; } if(board[r][i] == 'q' || board[r][i] == 'b'){ c = i; check = 1; break; } } //if there is no bishop or queen of opponent in diagonal left up direction of King if(check == 0) return true; if(check == 1){ r = row; for(int i = col-1; i > c; i--){ //check if there is anything else between our King and queen or bishop of opponenet r++; if(board[r][i] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking from diagonal Right Down Direction static boolean checkDiagonalRightDown(){ int r = row; int c = 0; int check = 0; for(int i = col+1; i < board[0].length; i ++){ //Checking if there is bishop or queen of opponent r++; if(r == board.length){ //Checking for row bound break; } if(board[r][i] == 'q' || board[r][i] == 'b'){ c = i; check = 1; break; } } //if there is no bishop or queen of opponent in diagonal left up direction of King if(check == 0) return true; if(check == 1){ r = row; for(int i = col+1; i < c; i ++){ //check if there is anything else between our King and queen or bishop of opponenet r++; if(board[r][i] != '_'){ check++; break; } } } if(check == 2) return true; else return false; } //Checking for Knight static boolean checkKnight(){ int flag = 0; int r = 0; int c = 0; outer: for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[i].length; j ++){ if(board[i][j] == 'n'){ r = i; c = j; break outer; } } } System.out.println("Knight is at position (" + r + "," + c + ")"); if(((row-2) >= 0) && ((col-1) >= 0)){ if(board[row-2][col-1] == 'n') flag = 1; } else if(((row-2) >= 0) && ((col+1) >= 0)){ if(board[row-2][col+1] == 'n') flag = 1; } else if(((row-1) >= 0) && ((col+2) >= 0)){ if(board[row-1][col+2] == 'n') flag = 1; } else if(((row+1) >= 0) && ((col+2) >= 0)){ if(board[row+1][col+2] == 'n') flag = 1; } else if(((row+2) >= 0) && ((col+1) >= 0)){ if(board[row+2][col+1] == 'n') flag = 1; } else if(((row+2) >= 0) && ((col-1) >= 0)){ if(board[row+2][col-1] == 'n') flag = 1; } else if(((row+1) >= 0) && ((col-2) >= 0)){ if(board[row+1][col-2] == 'n') flag = 1; } else if(((row-1) >= 0) && ((col-2) >= 0)){ if(board[row-1][col-2] == 'n') flag = 1; } if(flag == 1) return false; else return true; } }
/* * Created on Mar 1, 2007 * */ package com.citibank.ods.entity.pl.valueobject; import java.util.Date; /** * @author fernando.salgado * */ public class TplProdQlfyPrvtHistEntityVO extends BaseTplProdQlfyPrvtEntityVO { /** * Data de referencia do registro no historico * * Comment for <code>m_prodQlfyRefDate</code> * @generated "UML to Java * (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ private Date m_prodQlfyRefDate; /** * Codigo do usuario (SOE ID) que aprovou a ultima alteração do registro * * Comment for <code>m_lastAuthUserId</code> * @generated "UML to Java * (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ private String m_lastAuthUserId; /** * Data e Hora que o usuario aprovou a alteração do registro * * Comment for <code>m_lastAuthDate</code> * @generated "UML to Java * (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ private Date m_lastAuthDate; /** * Status Registro - Identifica se o registro esta ativo, inativo ou aguar * dando aprovacao" * * Comment for <code>m_recStatCode</code> * @generated "UML to Java * (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ private String m_recStatCode; /** * @return Returns lastAuthDate. */ public Date getLastAuthDate() { return m_lastAuthDate; } /** * @param lastAuthDate_ Field lastAuthDate to be setted. */ public void setLastAuthDate( Date lastAuthDate_ ) { m_lastAuthDate = lastAuthDate_; } /** * @return Returns lastAuthUserId. */ public String getLastAuthUserId() { return m_lastAuthUserId; } /** * @param lastAuthUserId_ Field lastAuthUserId to be setted. */ public void setLastAuthUserId( String lastAuthUserId_ ) { m_lastAuthUserId = lastAuthUserId_; } /** * @return Returns prodQlfyRefDate. */ public Date getProdQlfyRefDate() { return m_prodQlfyRefDate; } /** * @param prodQlfyRefDate_ Field prodQlfyRefDate to be setted. */ public void setProdQlfyRefDate( Date prodQlfyRefDate_ ) { m_prodQlfyRefDate = prodQlfyRefDate_; } /** * @return Returns recStatCode. */ public String getRecStatCode() { return m_recStatCode; } /** * @param recStatCode_ Field recStatCode to be setted. */ public void setRecStatCode( String recStatCode_ ) { m_recStatCode = recStatCode_; } }
package com.example.androidhomework3.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.androidhomework3.R; import com.example.androidhomework3.interfaces.IFirebaseAdapterComunication; import com.example.androidhomework3.interfaces.IFragmentActivityCommunication; import com.example.androidhomework3.models.Book; import java.util.ArrayList; public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> { private ArrayList<Book> books; private IFragmentActivityCommunication iFragmentActivityCommunication; private IFirebaseAdapterComunication iFirebaseAdapterComunication; public BookAdapter(ArrayList<Book> books) { this.books = books; } @NonNull @Override public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.item_book,parent,false); BookViewHolder bookViewHolder = new BookViewHolder(view); return bookViewHolder; } @Override public void onBindViewHolder(@NonNull BookViewHolder holder, int position) { Book book = books.get(position); holder.bind(book); ImageView arrow = holder.itemView.findViewById(R.id.arrow_image); TextView title = holder.itemView.findViewById(R.id.book_title); TextView author = holder.itemView.findViewById(R.id.book_author); TextView description = holder.itemView.findViewById(R.id.book_description); arrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (iFirebaseAdapterComunication != null){ Book newBook = new Book(title.getText().toString(), author.getText().toString(), description.getText().toString()); iFirebaseAdapterComunication.deleteItem(newBook); } } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (iFragmentActivityCommunication != null){ iFragmentActivityCommunication.onFullItemFragment(title.getText().toString(), author.getText().toString(),description.getText().toString()); } } }); } @Override public int getItemCount() { return books.size(); } @Override public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); if (recyclerView.getContext() instanceof IFragmentActivityCommunication){ iFragmentActivityCommunication = (IFragmentActivityCommunication) recyclerView.getContext(); } if (recyclerView.getContext() instanceof IFirebaseAdapterComunication){ iFirebaseAdapterComunication = (IFirebaseAdapterComunication) recyclerView.getContext(); } } class BookViewHolder extends RecyclerView.ViewHolder{ private TextView bookTitle; private TextView bookAuthor; private TextView bookDescription; private ImageView arrow; public BookViewHolder(View view) { super(view); bookTitle = view.findViewById(R.id.book_title); bookAuthor = view.findViewById(R.id.book_author); bookDescription = view.findViewById(R.id.book_description); arrow = view.findViewById(R.id.arrow_image); } public void bind(Book book) { bookTitle.setText(book.getTitle()); bookAuthor.setText(book.getAuthor()); bookDescription.setText(book.getDescription()); } public void setVisibility(boolean vis) { } } }
package com.arthur.leetcode; /** * @program: leetcode * @description: 解码方法 _ 二刷 * @title: No91_2 * @Author hengmingji * @Date: 2021/12/28 14:16 * @Version 1.0 */ public class No91_2 { public int numDecodings(String s) { int len = s.length(); int[] dp = new int[len + 1]; int[] nums = new int[len + 1]; for (int i = 1; i <= s.length(); i++) { nums[i] = Integer.valueOf(s.charAt(i - 1) - '0'); } dp[0] = 1; for (int i = 1; i <= len; i++) { int n = nums[i - 1] * 10 + nums[i]; if (nums[i] >= 1 && nums[i] <= 9) { dp[i] = dp[i - 1]; } if (n >= 10 && n <= 26) { dp[i] += dp[i - 2]; } } return dp[len]; } }
import java.awt.*; import javax.swing.*; import javax.swing.text.AttributeSet.ColorAttribute; public class TelaListaIoTs extends JPanel{ private JPanel telaListaIoTs; private JLabel lblID; private JLabel lblFabricante; private JLabel lblCategoriaIoT; private JLabel lblNome; private JLabel lblLocal; private JLabel lblEstado; public TelaListaIoTs(){ telaListaIoTs = new JPanel(new BorderLayout()); telaListaIoTs.setSize(500, 500); MontarTela(); } public void MontarTela(){ Box cabecalho = Box.createHorizontalBox(); cabecalho.setSize(50, 25); // cabecalho.setLayout(null); lblID = new JLabel("ID"); // lblID.setSize(100, 25); // cabecalho.add(lblID, BorderLayout.PAGE_START); lblID.setBounds(0, 10, 10, 25); cabecalho.add(lblID); lblFabricante = new JLabel("FABRICANTE"); // lblFabricante.setSize(30, 25); lblID.setBounds(0, 25, 10, 25); cabecalho.add(lblFabricante); // lblCategoriaIoT = new JLabel("CATEGORIA"); // // lblFabricante.setSize(30, 25); // lblID.setBounds(0, 40, 10, 25); // cabecalho.add(lblCategoriaIoT); // lblNome = new JLabel("NOME"); // // lblFabricante.setSize(30, 25); // lblID.setBounds(0, 55, 10, 25); // cabecalho.add(lblNome); // lblLocal = new JLabel("LOCAL"); // // lblFabricante.setSize(30, 25); // lblID.setBounds(0, 70, 10, 25); // cabecalho.add(lblLocal); // lblEstado = new JLabel("ESTADO"); // // lblFabricante.setSize(30, 25); // lblID.setBounds(0, 85, 10, 25); // cabecalho.add(lblEstado); // telaListaIoTs.add(cabecalho, BorderLayout.PAGE_START); telaListaIoTs.add(cabecalho, BorderLayout.PAGE_START); } public JComponent getTelaListaIoTs(){ return telaListaIoTs; } }
package com.wangzhu.proxy; import com.wangzhu.spring.beanannotation.injection.service.InjectionService; import com.wangzhu.utils.ReflectionUtil; /** * Created by wang.zhu on 2020-01-09 14:25. **/ public class MessageTestMain { public static void main(String[] args) { System.out.println(ReflectionUtil.getMethods(MessageProxy.class)); System.out.println(ReflectionUtil.getMethods(InjectionService.class)); Class<?> clazz = IMessageTest.class; IMessageTest messageTest = new MessageProxy().bind(); System.out.println(messageTest); System.out.println(clazz.isInterface()); System.out.println(clazz.isInstance(messageTest)); } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.lang; import xyz.noark.core.converter.impl.LocalTimeSectionConverter; import java.time.LocalDateTime; /** * 时间范围,主要用于指定时间区间的条件判定. * <p> * 格式:[年][月][日][星期][时间]<br> * 例:<br> * [*][*][*][*][00:00-24:00]<br> * [2020][5-6][11,12,15-19][w1,w5-w7][12:00-13:00]<br> * 前4个区,都可以使用逗号和连接号来实现多段效果, 判定规则是所有段内条件都满足 * * @author 小流氓[176543888@qq.com] * @since 3.4 */ public class TimeRange implements ValidTime { /** * 年 */ private IntRange year; /** * 月 */ private IntRange month; /** * 日 */ private IntRange day; /** * 星期 */ private IntRange dayOfWeek; /** * 时间区间 */ private LocalTimeSection timeSection; public TimeRange(String expression) { BracketParser parser = new BracketParser(expression); this.year = new IntRange(parser.readString()); this.month = new IntRange(parser.readString()); this.day = new IntRange(parser.readString()); this.dayOfWeek = new IntRange(parser.readString()); this.timeSection = new LocalTimeSectionConverter().convert(parser.readString()); } @Override public boolean isValid(LocalDateTime time) { // 年份 if (!year.contains(time.getYear())) { return false; } // 月份 if (!month.contains(time.getMonthValue())) { return false; } // 日 if (!day.contains(time.getDayOfMonth())) { return false; } // 星期 if (!dayOfWeek.contains(time.getDayOfWeek().getValue())) { return false; } // 时间 return timeSection.isValid(time.toLocalTime()); } }
package com.smartlead.common.vo; public class ProjectStageVO { private int projectStageId; private String projectStageName; public int getProjectStageId() { return projectStageId; } public void setProjectStageId(int projectStageId) { this.projectStageId = projectStageId; } public String getProjectStageName() { return projectStageName; } public void setProjectStageName(String projectStageName) { this.projectStageName = projectStageName; } @Override public String toString() { return "ProjectStage{" + "projectStageId=" + projectStageId + ", projectStageName='" + projectStageName + '\'' + '}'; } }
package com.sailaminoak.saiii; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.rtugeek.android.colorseekbar.ColorSeekBar; import worker8.com.github.radiogroupplus.RadioGroupPlus; /** * A simple {@link Fragment} subclass. * Use the {@link Setting#newInstance} factory method to * create an instance of this fragment. */ public class Setting extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; RadioGroupPlus radioGroupPlus; Button button; SharedPreferences sharedPreferences; ColorSeekBar colorSeekBar; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public Setting() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment Setting. */ // TODO: Rename and change types and number of parameters public static Setting newInstance(String param1, String param2) { Setting fragment = new Setting(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_setting, container, false); sharedPreferences =this.getActivity().getSharedPreferences("Saii", Context.MODE_PRIVATE); radioGroupPlus=view.findViewById(R.id.radio_group); button=view.findViewById(R.id.apply); colorSeekBar=view.findViewById(R.id.color_seek_bar); colorSeekBar.setOnColorChangeListener(new ColorSeekBar.OnColorChangeListener() { @Override public void onColorChangeListener(int colorBarPosition, int alphaBarPosition, int color) { SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putInt("textColor",color); editor.apply(); button.setTextColor(color); } }); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int number=0; try{ number=radioGroupPlus.getCheckedRadioButtonId(); switch (number){ case R.id.ironman: SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putInt("BackgroundColor",0); editor.apply(); // Toast.makeText(getActivity(),"iron man",Toast.LENGTH_SHORT).show(); jump(); break; case R.id.batman: SharedPreferences.Editor editor1=sharedPreferences.edit(); editor1.putInt("BackgroundColor",2); editor1.apply(); //Toast.makeText(getActivity(),"batman",Toast.LENGTH_SHORT).show(); jump(); break; case R.id.statue: SharedPreferences.Editor editor2=sharedPreferences.edit(); editor2.putInt("BackgroundColor",3); editor2.apply(); //Toast.makeText(getActivity(),"Statue",Toast.LENGTH_SHORT).show(); jump(); break; case R.id.technology: SharedPreferences.Editor editor3=sharedPreferences.edit(); editor3.putInt("BackgroundColor",4); editor3.apply(); // Toast.makeText(getActivity()," 0 1 ",Toast.LENGTH_SHORT).show(); jump(); break; case R.id.latkhalal: SharedPreferences.Editor editor4=sharedPreferences.edit(); editor4.putInt("BackgroundColor",1); editor4.apply(); jump(); //Toast.makeText(getActivity(),"Fuck You abcdefg ",Toast.LENGTH_SHORT).show(); break; case R.id.robert: SharedPreferences.Editor editor5=sharedPreferences.edit(); editor5.putInt("BackgroundColor",5); editor5.apply(); jump(); // Toast.makeText(getActivity(),"Robert",Toast.LENGTH_SHORT).show(); break; case R.id.depressionkaungsoelay: SharedPreferences.Editor editor6=sharedPreferences.edit(); editor6.putInt("BackgroundColor",6); editor6.apply(); jump(); // Toast.makeText(getActivity(),"Depression Kaung Soe Lay",Toast.LENGTH_SHORT).show(); break; case R.id.girl: SharedPreferences.Editor editor7=sharedPreferences.edit(); editor7.putInt("BackgroundColor",7); editor7.apply(); jump(); break; default:Display("Color will change when new note page created"); jump(); break; } }catch (Exception e){ Toast.makeText(getActivity(),"not checking yet",Toast.LENGTH_SHORT).show(); } } }); return view; } public void jump(){ Intent intent=new Intent(getActivity(),MainActivity.class); getActivity().finish(); startActivity(intent); Display("Applied Successful"); } public void Display(String str){ Toast.makeText(getActivity(),str,Toast.LENGTH_SHORT).show(); } }
package com.sinosoft.mobileshop.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import com.sinosoft.gyicPlat.MainActivity; import com.sinosoft.gyicPlat.R; import com.sinosoft.mobileshop.appwidget.dialog.StytledDialog; import com.sinosoft.mobileshop.util.CommonUtil; import com.sinosoft.mobileshop.util.TDevice; import com.sinosoft.util.Utils; /** * 应用启动界面 * */ public class WelcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View view = View.inflate(this, R.layout.activity_welcome, null); setContentView(view); // 渐变展示启动屏 AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f); aa.setDuration(800); view.startAnimation(aa); aa.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation arg0) { if(!Utils.isNetConnect()) { AlertDialog.Builder builder=new AlertDialog.Builder(WelcomeActivity.this); //先得到构造器 builder.setTitle("提示"); //设置标题 builder.setMessage("当前设备没有开启任何网络,请开启后重新启动移动应用平台。"); //设置内容 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮 @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.create().show(); } else { redirectTo(); } } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } }); } @Override protected void onResume() { super.onResume(); } /** * 跳转到... */ private void redirectTo() { // String readTxtFile = CommonUtil.ReadTxtFile(); // if(TextUtils.isEmpty(readTxtFile)){ // Intent intent = new Intent(this, RegisterActivity.class); // startActivity(intent); // finish(); // }else { // userLogin(); // } // 开启服务 Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } /** * 自动登陆 */ private void userLogin() { } }
package xtrus.ex.tcs.channel.client; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.io.IOUtils; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xtrus.ex.tcs.TcsCode; import xtrus.ex.tcs.TcsConfig; import xtrus.ex.tcs.TcsException; import xtrus.ex.tcs.message.RequestTypes; import xtrus.ex.tcs.message.TcsFrameMessage; import xtrus.ex.tcs.message.TcsMessage; import xtrus.ex.tcs.message.TcsMessageUtils; import xtrus.ex.tcs.table.TcsInfoRecord; /** * TCS 통신 프로토콜 포맷에 맞게 데이터를 전송하는 클라이언트 모듈. */ public final class TcsClient { private Logger logger = LoggerFactory.getLogger(TcsClient.class); private ClientBootstrap bootstrap; private Channel channel; private TcsInfoRecord infoRecord; private String traceId; private Timer timer; public TcsClient(TcsInfoRecord infoRecord) { this.infoRecord = infoRecord; this.traceId = "["+infoRecord.getInterfaceId()+"]["+infoRecord.getClientHost()+"] "; timer = new HashedWheelTimer(); } /** * 특정 TCS 서버의 host, port정보로 접속한다. */ public void connect() throws TcsException { if(isConnected()) shutdown(); if(timer == null) timer = new HashedWheelTimer(); final String host = infoRecord.getClientHost(); final int port = infoRecord.getClientPort(); final int connectionTimeout = infoRecord.getClientConnTimeout(); if(logger.isDebugEnabled()) logger.debug(traceId+"Initalizing TCS Client. host : "+host+", port : "+port); if(this.bootstrap==null) { this.bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new TcsClientChannelPipelineFactory("["+host+"] ", infoRecord, timer)); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("receiveBufferSize", 1048576); bootstrap.setOption("sendBufferSize", 1048576); if(connectionTimeout!=-1) bootstrap.setOption("connectTimeoutMillis", connectionTimeout); if(logger.isDebugEnabled()) logger.debug(traceId+"Connecting to TCS Server..."); final AtomicInteger reconnect = new AtomicInteger(1); while(reconnect.get()<=3) { try { ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.await(TcsConfig.DEFAULT_CONN_TIMEOUT, TimeUnit.SECONDS); channel = future.getChannel(); if(future.isSuccess()) { break; } logger.info(traceId+"Retry connect to...("+reconnect.get()+"/3)"); } catch (InterruptedException e) { throw new TcsException(TcsCode.ERROR_CLIENT_CONNECT, "connect()", "Connection failed. host : "+host+", port : "+port); } finally { reconnect.incrementAndGet(); } } if(!isConnected()) throw new TcsException(TcsCode.ERROR_CLIENT_CONNECT, "connect()", "Connection failed. host : "+host+", port : "+port); } logger.info(traceId+"connected to TCS Server."); } /** * 서버와 연결이 되어 있는지 여부를 리턴한다. */ public boolean isConnected() { if(bootstrap==null || channel==null) return false; if(channel!=null) return channel.isConnected(); return false; } public TcsMessage process(String fileName, byte[] fileBytes) throws TcsException { if(!isConnected()) connect(); if(logger.isDebugEnabled()) logger.debug(traceId+"TCS File sending start. fileName["+fileName+"], size["+fileBytes.length+"]"); TcsFrameMessage message = new TcsFrameMessage(); message.setSequence(1); message.setFileName(fileName); message.setOffset(0); message.setFileSize(fileBytes.length); message.setDocLength(0); int over = (fileBytes.length%TcsMessage.DEFAULT_PACKET_SIZE)==0?0:1; int maxPacketCount = fileBytes.length/TcsMessage.DEFAULT_PACKET_SIZE+over; if(!ready(message)) throw new TcsException(TcsCode.ERROR_MESSAGE, "process()", "Header packet sent. but not received response header from server."); return sendFileData(message, fileBytes, TcsMessage.DEFAULT_PACKET_SIZE, maxPacketCount); } private boolean ready(TcsFrameMessage message) throws TcsException { message.setRequestType(new RequestTypes(RequestTypes.EOF)); // add crc check message.getRequestType().addRequestType(RequestTypes.CRC_CHECK); TcsClientMessageHandler handler = channel.getPipeline().get(TcsClientMessageHandler.class); TcsFrameMessage responseMessage = handler.sendSync(TcsMessageUtils.toByteArray(message)); if(responseMessage!=null) { if(responseMessage.getFileName().equals(message.getFileName())) return true; } return false; } private TcsMessage sendFileData(TcsFrameMessage message, byte[] fileBytes, int packetSize, int maxPacketCount) throws TcsException { if(logger.isDebugEnabled()) logger.debug(traceId+"TCS Message. packetSize["+packetSize+"], maxPacketCount["+maxPacketCount+"], compressType["+infoRecord.getCompressType()+"]"); InputStream in = null; in = new ByteArrayInputStream(fileBytes); int packetCnt = 1; int sequenceNo = message.getSequence()+1; long totalLength = fileBytes.length; int offset = 0; TcsFrameMessage responseMessage = null; TcsClientMessageHandler handler = channel.getPipeline().get(TcsClientMessageHandler.class); try { while(packetCnt<=maxPacketCount) { if(!channel.isConnected()) break; message.setRequestType(new RequestTypes(0)); message.setSequence(sequenceNo); message.setOffset(offset); int readableLength = in.available()>packetSize?packetSize:in.available(); byte[] seqData = new byte[readableLength]; int dataLength = -1; try { dataLength = IOUtils.read(in, seqData, 0, readableLength); message.setDocLength(dataLength); message.setDataBytes(seqData); if(logger.isDebugEnabled()) logger.debug(traceId+"Reading data . data("+dataLength+"/"+totalLength+"), offset("+offset+"), seq("+message.getSequence()+"), packetSeq("+packetCnt+")"); offset += dataLength; } catch (IOException e) { logger.error(traceId+"File reading failed.", e); IOUtils.closeQuietly(in); throw e; } if(infoRecord.isUseCompress()) { message.getRequestType().addRequestType(RequestTypes.COMPRESSED); int compressedSize = doCompress(message); if(logger.isDebugEnabled()) logger.debug(traceId+"Compressed. compressed size : "+compressedSize); message.setDocLength(compressedSize); } /** EOF Process */ if(packetCnt==maxPacketCount) { if(logger.isDebugEnabled()) logger.debug(traceId+"Sending last packet."); message.getRequestType().addRequestType(RequestTypes.EOF); if(logger.isDebugEnabled()) logger.debug(traceId+"End of File."); message.getRequestType().addRequestType(RequestTypes.RESP_HEADER); if(logger.isDebugEnabled()) logger.debug(traceId+"Response Header requested."); responseMessage = handler.sendSync(TcsMessageUtils.toByteArray(message)); } else { boolean checkPacing = (packetCnt)%infoRecord.getClientPacingCount()==0?true:false; if(checkPacing) { message.getRequestType().addRequestType(RequestTypes.RESP_HEADER); if(logger.isDebugEnabled()) logger.debug(traceId+"Response Header requested."); responseMessage = handler.sendSync(TcsMessageUtils.toByteArray(message)); if(responseMessage==null) throw new TcsException(TcsCode.ERROR_WRITE_FILE, "sendFileData()", "No response message received."); } else { handler.sendAsync(TcsMessageUtils.toByteArray(message)); } } sequenceNo++; packetCnt++; } if(logger.isDebugEnabled()) logger.debug(traceId+"File data sending completed."); } catch(Exception e) { logger.error(traceId+"Reading failed.", e); shutdown(); throw new TcsException(TcsCode.ERROR_WRITE_FILE, "sendFileData()", e.getMessage(), e); } finally { IOUtils.closeQuietly(in); } return responseMessage; } private int doCompress(TcsFrameMessage message) { byte[] compressed = null; try { compressed = TcsMessageUtils.compress(message); message.setDataBytes(compressed); return compressed.length; } catch (TcsException e) { logger.error(traceId+"Compressiong failed.", e); return message.getDocLength(); } } public void closeChannel() { if(timer!=null) timer.stop(); timer = null; if(this.channel!=null) { try { this.channel.close().sync(); } catch (InterruptedException e) { } } this.channel =null; } /** * TCS 클라이언트를 종료한다. */ public void shutdown() throws TcsException { logger.info(traceId+"Shutdowning client."); closeChannel(); if(bootstrap!=null) bootstrap.releaseExternalResources(); logger.info(traceId+"Connection shutdown completed."); bootstrap = null; } }
package com.mercadolibre.bootcampmelifrescos.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; @Data @AllArgsConstructor @NoArgsConstructor public class WarehouseBatchDTO { @Positive(message = "The warehouse code must be a positive number") @NotNull(message = "The warehouse code can't be empty") private Long warehouseCode; @Positive(message = "The total quantity must be a positive number") @NotNull(message = "The total quantity can't be empty") private int totalQuantity; }
package com.wipro.flowcontrolstatements; public class Ex17 { public static void main(String[] args) { // TODO Auto-generated method stub int n=Integer.parseInt(args[0]),temp,rem,rev=0; temp=n; while(n!=0) { rem=n%10; rev=rev*10+rem; n/=10; } if(rev==temp) System.out.println(temp+" is a palindrome"); else System.out.println(temp+" is not a palindrome"); } }
package com.softserve.edu.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name = "ROLE", schema = "hostme", uniqueConstraints = { @UniqueConstraint(columnNames = { "role_id" }) }) public class Role { @Id @GeneratedValue @Column(name = "role_id", unique = true, nullable = false) private Integer id; @Column(name = "role", length = 10) private String role; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
package com._10_stream; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Example { public static void main(String[] args) { System.out.println("========== Example-1 ==========="); Stream.iterate(1, i ->i+1).filter(i -> i%2 ==0 ).limit(10).forEach(System.out::println); System.out.println("========== Example-2 ==========="); //list 1 List<String> list1 = Arrays.asList("Fenerbahce","Hatayspor","Besiktas"); //list 2 List<String> list2 = Arrays.asList("Huseyin","Ali","Ahmet"); Stream.concat(list1.stream(),list2.stream()).forEach(list -> System.out.println(list)); } }
package com.skyhorse.scs.Service; import java.util.ArrayList; import java.util.List; public interface UserService { public String insertData(String UserID,String Uname,String password,String UserEmail,String phone,String Address,String SecQue,String SecAns,String UserRole); public void updatePassword(String UserId,String oldPassword,String newPassword); }
package com.example.tgs.latte; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.MediaController; import android.widget.VideoView; /** * Created by TGS on 2016-06-12. */ public class MediaActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mediaactivity); VideoView videoViewExample = (VideoView)findViewById(R.id.videoView); MediaController mc = new MediaController(this); Uri videoUri = Uri.parse( "android.resource://" + getPackageName() + "/raw/dumb" ); videoViewExample.setMediaController(mc); videoViewExample.setVideoURI(videoUri); videoViewExample.start(); } }
package fr.aresrpg.tofumanchou.domain.event.player; import fr.aresrpg.commons.domain.event.Event; import fr.aresrpg.commons.domain.event.EventBus; import fr.aresrpg.tofumanchou.domain.data.Account; /** * * @since */ public class SpellOptionEvent implements Event<SpellOptionEvent> { private static final EventBus<SpellOptionEvent> BUS = new EventBus<>(SpellOptionEvent.class); private Account client; private boolean canUseAllSpells; /** * @param client * @param canUseAllSpells */ public SpellOptionEvent(Account client, boolean canUseAllSpells) { this.client = client; this.canUseAllSpells = canUseAllSpells; } public boolean canUseAllSpells() { return canUseAllSpells; } /** * @param client * the client to set */ public void setClient(Account client) { this.client = client; } /** * @param canUseAllSpells * the canUseAllSpells to set */ public void setCanUseAllSpells(boolean canUseAllSpells) { this.canUseAllSpells = canUseAllSpells; } /** * @return the client */ public Account getClient() { return client; } @Override public EventBus<SpellOptionEvent> getBus() { return BUS; } @Override public boolean isAsynchronous() { return false; } @Override public String toString() { return "SpellOptionEvent [client=" + client + ", canUseAllSpells=" + canUseAllSpells + "]"; } }
/* UiEngineImpl.java Purpose: Description: History: Thu Jun 9 13:05:28 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui.impl; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.IdentityHashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.LinkedList; import java.util.Collections; import java.util.Collection; import java.util.regex.Pattern; import java.io.Writer; import java.io.IOException; import javax.servlet.ServletRequest; import org.zkoss.lang.D; import org.zkoss.lang.Library; import org.zkoss.lang.Classes; import org.zkoss.lang.Objects; import org.zkoss.lang.Threads; import org.zkoss.lang.Exceptions; import org.zkoss.lang.Expectable; import org.zkoss.mesg.Messages; import org.zkoss.util.ArraysX; import org.zkoss.util.logging.Log; import org.zkoss.web.servlet.Servlets; import org.zkoss.json.*; import org.zkoss.zk.mesg.MZk; import org.zkoss.zk.ui.*; import org.zkoss.zk.ui.sys.*; import org.zkoss.zk.ui.sys.Attributes; import org.zkoss.zk.ui.event.*; import org.zkoss.zk.ui.metainfo.*; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zk.ui.ext.Native; import org.zkoss.zk.ui.ext.Scope; import org.zkoss.zk.ui.ext.Scopes; import org.zkoss.zk.ui.ext.render.PrologAllowed; import org.zkoss.zk.ui.util.*; import org.zkoss.zk.xel.Evaluators; import org.zkoss.zk.scripting.Interpreter; import org.zkoss.zk.au.*; import org.zkoss.zk.au.out.*; /** * An implementation of {@link UiEngine} to create and update components. * * @author tomyeh */ public class UiEngineImpl implements UiEngine { /*package*/ static final Log log = Log.lookup(UiEngineImpl.class); /** The Web application this engine belongs to. */ private WebApp _wapp; /** A pool of idle EventProcessingThreadImpl. */ private final List _idles = new LinkedList(); /** A map of suspended processing: * (Desktop desktop, IdentityHashMap(Object mutex, List(EventProcessingThreadImpl)). */ private final Map _suspended = new HashMap(); /** A map of resumed processing * (Desktop desktop, List(EventProcessingThreadImpl)). */ private final Map _resumed = new HashMap(); /** # of suspended event processing threads. */ private int _suspCnt; /** the extension. */ private Extension _ext; public UiEngineImpl() { } //-- UiEngine --// public void start(WebApp wapp) { _wapp = wapp; } public void stop(WebApp wapp) { synchronized (_idles) { for (Iterator it = _idles.iterator(); it.hasNext();) ((EventProcessingThreadImpl)it.next()).cease("Stop application"); _idles.clear(); } synchronized (_suspended) { for (Iterator it = _suspended.values().iterator(); it.hasNext();) { final Map map = (Map)it.next(); synchronized (map) { for (Iterator i2 = map.values().iterator(); i2.hasNext();) { final List list = (List)i2.next(); for (Iterator i3 = list.iterator(); i3.hasNext();) ((EventProcessingThreadImpl)i3.next()).cease("Stop application"); } } } _suspended.clear(); } synchronized (_resumed) { for (Iterator it = _resumed.values().iterator(); it.hasNext();) { final List list = (List)it.next(); synchronized (list) { for (Iterator i2 = list.iterator(); i2.hasNext();) ((EventProcessingThreadImpl)i2.next()).cease("Stop application"); } } _resumed.clear(); } } public boolean hasSuspendedThread() { if (!_suspended.isEmpty()) { synchronized (_suspended) { for (Iterator it = _suspended.values().iterator(); it.hasNext();) { final Map map = (Map)it.next(); if (!map.isEmpty()) return true; } } } return false; } public Collection getSuspendedThreads(Desktop desktop) { final Map map; synchronized (_suspended) { map = (Map)_suspended.get(desktop); } if (map == null || map.isEmpty()) return Collections.EMPTY_LIST; final List threads = new LinkedList(); synchronized (map) { for (Iterator it = map.values().iterator(); it.hasNext();) { threads.addAll((List)it.next()); } } return threads; } public boolean ceaseSuspendedThread(Desktop desktop, EventProcessingThread evtthd, String cause) { final Map map; synchronized (_suspended) { map = (Map)_suspended.get(desktop); } if (map == null) return false; boolean found = false; synchronized (map) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { final Map.Entry me = (Map.Entry)it.next(); final List list = (List)me.getValue(); found = list.remove(evtthd); //found if (found) { if (list.isEmpty()) it.remove(); //(mutex, list) no longer useful break; //DONE } } } if (found) ((EventProcessingThreadImpl)evtthd).cease(cause); return found; } public void desktopDestroyed(Desktop desktop) { // if (log.debugable()) log.debug("destroy "+desktop); Execution exec = Executions.getCurrent(); if (exec == null) { //Bug 2015878: exec is null if it is caused by session invalidated //while listener (ResumeAbort and so) might need it exec = new PhantomExecution(desktop); boolean activated = activate(exec, getDestroyTimeout()); try { desktopDestroyed0(desktop); } finally { if (activated) deactivate(exec); } } else { desktopDestroyed0(desktop); } } private void desktopDestroyed0(Desktop desktop) { final Configuration config = _wapp.getConfiguration(); if (!_suspended.isEmpty()) { //no need to sync (better performance) final Map map; synchronized (_suspended) { map = (Map)_suspended.remove(desktop); } if (map != null) { synchronized (map) { for (Iterator it = map.values().iterator(); it.hasNext();) { final List list = (List)it.next(); for (Iterator i2 = list.iterator(); i2.hasNext();) { final EventProcessingThreadImpl evtthd = (EventProcessingThreadImpl)i2.next(); evtthd.ceaseSilently("Destroy desktop "+desktop); config.invokeEventThreadResumeAborts( evtthd.getComponent(), evtthd.getEvent()); } } } } } if (!_resumed.isEmpty()) { //no need to sync (better performance) final List list; synchronized (_resumed) { list = (List)_resumed.remove(desktop); } if (list != null) { synchronized (list) { for (Iterator it = list.iterator(); it.hasNext();) { final EventProcessingThreadImpl evtthd = (EventProcessingThreadImpl)it.next(); evtthd.ceaseSilently("Destroy desktop "+desktop); config.invokeEventThreadResumeAborts( evtthd.getComponent(), evtthd.getEvent()); } } } } ((DesktopCtrl)desktop).destroy(); } private static UiVisualizer getCurrentVisualizer() { final ExecutionCtrl execCtrl = ExecutionsCtrl.getCurrentCtrl(); if (execCtrl == null) throw new IllegalStateException("Components can be accessed only in event listeners"); return (UiVisualizer)execCtrl.getVisualizer(); } public Component setOwner(Component comp) { return getCurrentVisualizer().setOwner(comp); } public boolean isInvalidated(Component comp) { return getCurrentVisualizer().isInvalidated(comp); } public void addInvalidate(Page page) { if (page == null) throw new IllegalArgumentException(); getCurrentVisualizer().addInvalidate(page); } public void addInvalidate(Component comp) { if (comp == null) throw new IllegalArgumentException(); getCurrentVisualizer().addInvalidate(comp); } /** @deprecated As of release 5.0.2, replaced with {@link #addSmartUpdate(Component comp, String, Object, boolean)}. */ public void addSmartUpdate(Component comp, String attr, Object value) { addSmartUpdate(comp, attr, value, false); } public void addSmartUpdate(Component comp, String attr, Object value, boolean append) { if (comp == null) throw new IllegalArgumentException(); getCurrentVisualizer().addSmartUpdate(comp, attr, value, append); } public void addResponse(AuResponse response) { getCurrentVisualizer().addResponse(response); } public void addResponse(String key, AuResponse response) { getCurrentVisualizer().addResponse(key, response); } public void addMoved(Component comp, Component oldparent, Page oldpg, Page newpg) { if (comp == null) throw new IllegalArgumentException(); getCurrentVisualizer().addMoved(comp, oldparent, oldpg, newpg); } public void addUuidChanged(Component comp) { if (comp == null) throw new IllegalArgumentException(); getCurrentVisualizer().addUuidChanged(comp); } public boolean disableClientUpdate(Component comp, boolean disable) { return getCurrentVisualizer().disableClientUpdate(comp, disable); } //-- Creating a new page --// public void execNewPage(Execution exec, Richlet richlet, Page page, Writer out) throws IOException { execNewPage0(exec, null, richlet, page, out); } public void execNewPage(Execution exec, PageDefinition pagedef, Page page, Writer out) throws IOException { execNewPage0(exec, pagedef, null, page, out); } /** It assumes exactly one of pagedef and richlet is not null. */ private void execNewPage0(final Execution exec, final PageDefinition pagedef, final Richlet richlet, final Page page, final Writer out) throws IOException { //Update the device type first. If this is the second page and not //belonging to the same device type, an exception is thrown final Desktop desktop = exec.getDesktop(); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; final LanguageDefinition langdef = //default page pagedef != null ? pagedef.getLanguageDefinition(): richlet != null ? richlet.getLanguageDefinition(): null; if (langdef != null) desktop.setDeviceType(langdef.getDeviceType()); //set and check! final WebApp wapp = desktop.getWebApp(); final Configuration config = wapp.getConfiguration(); PerformanceMeter pfmeter = config.getPerformanceMeter(); final long startTime = pfmeter != null ? System.currentTimeMillis(): 0; //snapshot time since activate might take time //It is possible this method is invoked when processing other exec final Execution oldexec = Executions.getCurrent(); final ExecutionCtrl oldexecCtrl = (ExecutionCtrl)oldexec; final UiVisualizer olduv = oldexecCtrl != null ? (UiVisualizer)oldexecCtrl.getVisualizer(): null; final UiVisualizer uv; if (olduv != null) { uv = doReactivate(exec, olduv); pfmeter = null; //don't count included pages } else { uv = doActivate(exec, false, false, null, -1); } final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; final Page old = execCtrl.getCurrentPage(); final PageDefinition olddef = execCtrl.getCurrentPageDefinition(); execCtrl.setCurrentPage(page); execCtrl.setCurrentPageDefinition(pagedef); final String pfReqId = pfmeter != null ? meterLoadStart(pfmeter, exec, startTime): null; AbortingReason abrn = null; try { config.invokeExecutionInits(exec, oldexec); desktopCtrl.invokeExecutionInits(exec, oldexec); if (olduv != null) { final Component owner = olduv.getOwner(); if (owner != null) { ((PageCtrl)page).setOwner(owner); // if (D.ON && log.finerable()) log.finer("Set owner of "+page+" to "+owner); } } //Cycle 1: Creates all components //Note: //1) stylesheet, tablib are inited in Page's contructor //2) we add variable resolvers before init because //init's zscirpt might depend on it. if (pagedef != null) { ((PageCtrl)page).preInit(); pagedef.initXelContext(page); final Initiators inits = Initiators.doInit( pagedef, page, config.getInitiators()); //F1472813: sendRedirect in init; test: redirectNow.zul try { pagedef.init(page, !uv.isEverAsyncUpdate() && !uv.isAborting()); final Component[] comps; final String uri = pagedef.getForwardURI(page); if (uri != null) { comps = new Component[0]; exec.forward(uri); } else { comps = uv.isAborting() || exec.isVoided() ? new Component[0]: execCreate(new CreateInfo( ((WebAppCtrl)wapp).getUiFactory(), exec, page, config.getComposer(page)), pagedef, null); } inits.doAfterCompose(page, comps); afterCreate(comps); } catch(Throwable ex) { if (!inits.doCatch(ex)) throw UiException.Aide.wrap(ex); } finally { inits.doFinally(); } } else { //FUTURE: a way to allow richlet to set page ID ((PageCtrl)page).preInit(); final Initiators inits = Initiators.doInit( null, page, config.getInitiators()); try { ((PageCtrl)page).init(new PageConfig() { public String getId() {return null;} public String getUuid() {return null;} public String getTitle() {return null;} public String getStyle() {return null;} public String getBeforeHeadTags() {return "";} public String getAfterHeadTags() {return "";} /** @deprecated */ public String getHeaders(boolean before) {return "";} /** @deprecated */ public String getHeaders() {return "";} public Collection getResponseHeaders() {return Collections.EMPTY_LIST;} }); final Composer composer = config.getComposer(page); try { richlet.service(page); for (Component root = page.getFirstRoot(); root != null; root = root.getNextSibling()) { if (composer != null) composer.doAfterCompose(root); afterCreate(new Component[] {root}); //root's next sibling might be changed } } catch (Throwable t) { if (composer instanceof ComposerExt) if (((ComposerExt)composer).doCatch(t)) t = null; //ignored if (t != null) throw t; } finally { if (composer instanceof ComposerExt) ((ComposerExt)composer).doFinally(); } } catch(Throwable ex) { if (!inits.doCatch(ex)) throw UiException.Aide.wrap(ex); } finally { inits.doFinally(); } } if (exec.isVoided()) return; //don't generate any output //Cycle 2: process pending events //Unlike execUpdate, execution is aborted here if any exception final List errs = new LinkedList(); Event event = nextEvent(uv); do { for (; event != null; event = nextEvent(uv)) { try { process(desktop, event); } catch (Throwable ex) { handleError(ex, uv, errs); } } resumeAll(desktop, uv, null); } while ((event = nextEvent(uv)) != null); //Cycle 2a: Handle aborting reason abrn = uv.getAbortingReason(); if (abrn != null) abrn.execute(); //always execute even if !isAborting //Cycle 3: Redraw the page (and responses) List responses = getResponses(exec, uv, errs); if (olduv != null && olduv.addToFirstAsyncUpdate(responses)) responses = null; //A new ZK page might be included by an async update //(example: ZUL's include). //If so, we cannot generate the responses in the page. //Rather, we shall add them to the async update. else execCtrl.setResponses(responses); ((PageCtrl)page).redraw(out); afterRenderNewPage(page); desktopCtrl.invokeExecutionCleanups(exec, oldexec, errs); config.invokeExecutionCleanups(exec, oldexec, errs); } catch (Throwable ex) { final List errs = new LinkedList(); errs.add(ex); desktopCtrl.invokeExecutionCleanups(exec, oldexec, errs); config.invokeExecutionCleanups(exec, oldexec, errs); if (!errs.isEmpty()) { ex = (Throwable)errs.get(0); if (ex instanceof IOException) throw (IOException)ex; throw UiException.Aide.wrap(ex); } } finally { if (abrn != null) { try { abrn.finish(); } catch (Throwable t) { log.warning(t); } } execCtrl.setCurrentPage(old); //restore it execCtrl.setCurrentPageDefinition(olddef); //restore it if (olduv != null) doDereactivate(exec, olduv); else doDeactivate(exec); if (pfmeter != null) meterLoadServerComplete(pfmeter, pfReqId, exec); } } public void recycleDesktop(Execution exec, Page page, Writer out) throws IOException { PerformanceMeter pfmeter = page.getDesktop().getWebApp().getConfiguration().getPerformanceMeter(); final long startTime = pfmeter != null ? System.currentTimeMillis(): 0; final String pfReqId = pfmeter != null ? meterLoadStart(pfmeter, exec, startTime): null; final UiVisualizer uv = doActivate(exec, false, false, null, -1); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; execCtrl.setCurrentPage(page); try { Events.postEvent(new Event(Events.ON_DESKTOP_RECYCLE)); final List errs = new LinkedList(); final Desktop desktop = exec.getDesktop(); Event event = nextEvent(uv); do { for (; event != null; event = nextEvent(uv)) { try { process(desktop, event); } catch (Throwable ex) { handleError(ex, uv, errs); } } resumeAll(desktop, uv, null); } while ((event = nextEvent(uv)) != null); execCtrl.setResponses(getResponses(exec, uv, errs)); ((PageCtrl)page).redraw(out); } finally { doDeactivate(exec); if (pfmeter != null) meterLoadServerComplete(pfmeter, pfReqId, exec); } } /** Called after the whole component tree has been created by * this engine. * @param comps the components being created. It is never null but * it might be a zero-length array. */ private void afterCreate(Component[] comps) { getExtension().afterCreate(comps); } /** Called after a new page has been redrawn ({@link PageCtrl#redraw} * has been called). */ private void afterRenderNewPage(Page page) { getExtension().afterRenderNewPage(page); } private Extension getExtension() { if (_ext == null) { synchronized (this) { if (_ext == null) { String clsnm = Library.getProperty("org.zkoss.zk.ui.impl.UiEngineImpl.extension"); if (clsnm != null) { try { _ext = (Extension)Classes.newInstanceByThread(clsnm); } catch (Throwable ex) { log.realCauseBriefly("Unable to instantiate "+clsnm, ex); } } if (_ext == null) _ext = new DefaultExtension(); } } } return _ext; } private static final Event nextEvent(UiVisualizer uv) { final Event evt = ((ExecutionCtrl)uv.getExecution()).getNextEvent(); return evt != null && !uv.isAborting() ? evt: null; } /** Cycle 1: * Creates all child components defined in the specified definition. * @return the first component being created. */ private static final Component[] execCreate( CreateInfo ci, NodeInfo parentInfo, Component parent) { String fulfillURI = null; if (parentInfo instanceof ComponentInfo) { final ComponentInfo pi = (ComponentInfo)parentInfo; String fulfill = pi.getFulfill(); if (fulfill != null) { //defer the creation of children fulfill = fulfill.trim(); if (fulfill.length() > 0) { if (fulfill.startsWith("=")) { fulfillURI = fulfill.substring(1).trim(); } else { new FulfillListener(fulfill, pi, parent); return new Component[0]; } } } } Component[] cs = execCreate0(ci, parentInfo, parent); if (fulfillURI != null) { fulfillURI = (String)Evaluators.evaluate( ((ComponentInfo)parentInfo).getEvaluator(), parent, fulfillURI, String.class); if (fulfillURI != null) { final Component c = ci.exec.createComponents(fulfillURI, parent, null); if (c != null) { cs = (Component[])ArraysX.resize(cs, cs.length + 1); cs[cs.length - 1] = c; } } } return cs; } private static final Component[] execCreate0( CreateInfo ci, NodeInfo parentInfo, Component parent) { final List created = new LinkedList(); final Page page = ci.page; final PageDefinition pagedef = parentInfo.getPageDefinition(); //note: don't use page.getDefinition because createComponents //might be called from a page other than instance's final ReplaceableText replaceableText = new ReplaceableText(); for (Iterator it = parentInfo.getChildren().iterator(); it.hasNext();) { final Object meta = it.next(); if (meta instanceof ComponentInfo) { final ComponentInfo childInfo = (ComponentInfo)meta; final ForEach forEach = childInfo.resolveForEach(page, parent); if (forEach == null) { if (isEffective(childInfo, page, parent)) { final Component[] children = execCreateChild(ci, parent, childInfo, replaceableText); for (int j = 0; j < children.length; ++j) created.add(children[j]); } } else { while (forEach.next()) { if (isEffective(childInfo, page, parent)) { final Component[] children = execCreateChild(ci, parent, childInfo, replaceableText); for (int j = 0; j < children.length; ++j) created.add(children[j]); } } } } else if (meta instanceof TextInfo) { //parent must be a native component final String s = ((TextInfo)meta).getValue(parent); if (s != null && s.length() > 0) parent.appendChild( ((Native)parent).getHelper().newNative(s)); } else { execNonComponent(ci, parent, meta); } } return (Component[])created.toArray(new Component[created.size()]); } private static Component[] execCreateChild( CreateInfo ci, Component parent, ComponentInfo childInfo, ReplaceableText replaceableText) { if (childInfo instanceof ZkInfo) { final ZkInfo zkInfo = (ZkInfo)childInfo; return zkInfo.withSwitch() ? execSwitch(ci, zkInfo, parent): execCreate0(ci, childInfo, parent); } final ComponentDefinition childdef = childInfo.getComponentDefinition(); if (childdef.isInlineMacro()) { final Map props = new HashMap(); props.put("includer", parent); childInfo.evalProperties(props, ci.page, parent, true); return new Component[] { ci.exec.createComponents(childdef.getMacroURI(), parent, props)}; } else { String rt = null; if (replaceableText != null) { rt = replaceableText.text; replaceableText.text = childInfo.getReplaceableText();; if (replaceableText.text != null) return new Component[0]; //Note: replaceableText is one-shot only //So, replaceable text might not be generated //and it is ok since it is onl blank string } Component child = execCreateChild0(ci, parent, childInfo, rt); return child != null ? new Component[] {child}: new Component[0]; } } private static Component execCreateChild0(CreateInfo ci, Component parent, ComponentInfo childInfo, String replaceableText) { Composer composer = childInfo.resolveComposer(ci.page, parent); ComposerExt composerExt = null; boolean bPopComposer = false; if (composer instanceof FullComposer) { ci.pushFullComposer(composer); bPopComposer = true; composer = null; //ci will handle it } else if (composer instanceof ComposerExt) { composerExt = (ComposerExt)composer; } Component child = null; final boolean bRoot = parent == null; try { if (composerExt != null) { childInfo = composerExt.doBeforeCompose(ci.page, parent, childInfo); if (childInfo == null) return null; } childInfo = ci.doBeforeCompose(ci.page, parent, childInfo, bRoot); if (childInfo == null) return null; child = ci.uf.newComponent(ci.page, parent, childInfo); if (replaceableText != null) { final Object xc = ((ComponentCtrl)child).getExtraCtrl(); if (xc instanceof PrologAllowed) ((PrologAllowed)xc).setPrologContent(replaceableText); } final boolean bNative = childInfo instanceof NativeInfo; if (bNative) setProlog(ci, child, (NativeInfo)childInfo); if (composerExt != null) composerExt.doBeforeComposeChildren(child); ci.doBeforeComposeChildren(child, bRoot); execCreate(ci, childInfo, child); //recursive if (bNative) setEpilog(ci, child, (NativeInfo)childInfo); if (child instanceof AfterCompose) ((AfterCompose)child).afterCompose(); if (composer != null) composer.doAfterCompose(child); ci.doAfterCompose(child, bRoot); ComponentsCtrl.applyForward(child, childInfo.getForward()); //applies the forward condition //1) we did it after all child created, so it may reference //to it child (thought rarely happens) //2) we did it after afterCompose, so what specified //here has higher priority than class defined by app dev if (Events.isListened(child, Events.ON_CREATE, false)) Events.postEvent( new CreateEvent(Events.ON_CREATE, child, ci.exec.getArg())); return child; } catch (Throwable ex) { boolean ignore = false; if (composerExt != null) { try { ignore = composerExt.doCatch(ex); } catch (Throwable t) { log.error("Failed to invoke doCatch for "+childInfo, t); } } if (!ignore) { ignore = ci.doCatch(ex, bRoot); if (!ignore) throw UiException.Aide.wrap(ex); } return child != null && child.getPage() != null ? child: null; //return child only if attached successfully } finally { try { if (composerExt != null) composerExt.doFinally(); ci.doFinally(bRoot); } catch (Throwable ex) { throw UiException.Aide.wrap(ex); } finally { if (bPopComposer) ci.popFullComposer(); } } } /** Handles <zk switch>. */ private static Component[] execSwitch(CreateInfo ci, ZkInfo switchInfo, Component parent) { final Page page = ci.page; final Object switchCond = switchInfo.resolveSwitch(page, parent); for (Iterator it = switchInfo.getChildren().iterator(); it.hasNext();) { final ZkInfo caseInfo = (ZkInfo)it.next(); final ForEach forEach = caseInfo.resolveForEach(page, parent); if (forEach == null) { if (isEffective(caseInfo, page, parent) && isCaseMatched(caseInfo, page, parent, switchCond)) { return execCreateChild(ci, parent, caseInfo, null); } } else { final List created = new LinkedList(); while (forEach.next()) { if (isEffective(caseInfo, page, parent) && isCaseMatched(caseInfo, page, parent, switchCond)) { final Component[] children = execCreateChild(ci, parent, caseInfo, null); for (int j = 0; j < children.length; ++j) created.add(children[j]); return (Component[])created.toArray(new Component[created.size()]); //only once (AND condition) } } } } return new Component[0]; } private static boolean isCaseMatched(ZkInfo caseInfo, Page page, Component parent, Object switchCond) { if (!caseInfo.withCase()) return true; //default clause final Object[] caseValues = caseInfo.resolveCase(page, parent); for (int j = 0; j < caseValues.length; ++j) { if (caseValues[j] instanceof String && switchCond instanceof String) { final String casev = (String)caseValues[j]; final int len = casev.length(); if (len >= 2 && casev.charAt(0) == '/' && casev.charAt(len - 1) == '/') { //regex if (Pattern.compile(casev.substring(1, len - 1)) .matcher((String)switchCond).matches()) return true; else continue; } } if (Objects.equals(switchCond, caseValues[j])) return true; //OR condition } return false; } /** Executes a non-component object, such as ZScript, AttributesInfo... */ private static final void execNonComponent( CreateInfo ci, Component comp, Object meta) { final Page page = ci.page; if (meta instanceof ZScript) { final ZScript zscript = (ZScript)meta; if (zscript.isDeferred()) { ((PageCtrl)page).addDeferredZScript(comp, zscript); //isEffective is handled later } else if (isEffective(zscript, page, comp)) { final Scope scope = Scopes.beforeInterpret(comp != null ? (Scope)comp: page); try { page.interpret(zscript.getLanguage(), zscript.getContent(page, comp), scope); } finally { Scopes.afterInterpret(); } } } else if (meta instanceof AttributesInfo) { final AttributesInfo attrs = (AttributesInfo)meta; if (comp != null) attrs.apply(comp); //it handles isEffective else attrs.apply(page); } else if (meta instanceof VariablesInfo) { final VariablesInfo vars = (VariablesInfo)meta; if (comp != null) vars.apply(comp); //it handles isEffective else vars.apply(page); } else { //Note: we don't handle ComponentInfo here, because //getNativeContent assumes no child component throw new IllegalStateException(meta+" not allowed in "+comp); } } private static final boolean isEffective(Condition cond, Page page, Component comp) { return comp != null ? cond.isEffective(comp): cond.isEffective(page); } public Component[] createComponents(Execution exec, PageDefinition pagedef, Page page, Component parent, Map arg) { if (pagedef == null) throw new IllegalArgumentException("pagedef"); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; boolean fakeIS = false; if (parent != null) { if (parent.getPage() != null) page = parent.getPage(); else fakeIS = true; if (page == null) { fakeIS = true; page = execCtrl.getCurrentPage(); } } if (!execCtrl.isActivated()) throw new IllegalStateException("Not activated yet"); final boolean fakepg = page == null; if (fakepg) { fakeIS = true; page = new VolatilePage(pagedef); //fake } final Desktop desktop = exec.getDesktop(); final WebApp wapp = desktop.getWebApp(); final Page prevpg = execCtrl.getCurrentPage(); if (page != null && page != prevpg) execCtrl.setCurrentPage(page); final PageDefinition olddef = execCtrl.getCurrentPageDefinition(); execCtrl.setCurrentPageDefinition(pagedef); exec.pushArg(arg != null ? arg: Collections.EMPTY_MAP); //Note: we add taglib, stylesheets and var-resolvers to the page //it might cause name pollution but we got no choice since they //are used as long as components created by this method are alive if (fakepg) ((PageCtrl)page).preInit(); pagedef.initXelContext(page); //Note: the forward directives are ignore in this case final Initiators inits = Initiators.doInit(pagedef, page, wapp.getConfiguration().getInitiators()); final IdSpace prevIS = fakeIS ? ExecutionsCtrl.setVirtualIdSpace( fakepg ? (IdSpace)page: new SimpleIdSpace()): null; try { if (fakepg) pagedef.init(page, false); final Component[] comps = execCreate( new CreateInfo(((WebAppCtrl)wapp).getUiFactory(), exec, page, null), //technically sys composer can be used but we don't (to make it simple) pagedef, parent); inits.doAfterCompose(page, comps); //Notice: if parent is not null, comps[j].page == parent.page if (fakepg && parent == null) for (int j = 0; j < comps.length; ++j) comps[j].detach(); afterCreate(comps); return comps; } catch (Throwable ex) { inits.doCatch(ex); throw UiException.Aide.wrap(ex); } finally { exec.popArg(); execCtrl.setCurrentPage(prevpg); //restore it execCtrl.setCurrentPageDefinition(olddef); //restore it if (fakeIS) ExecutionsCtrl.setVirtualIdSpace(prevIS); inits.doFinally(); if (fakepg) { try { ((DesktopCtrl)desktop).removePage(page); } catch (Throwable ex) { log.warningBriefly(ex); } ((PageCtrl)page).destroy(); } } } public void sendRedirect(String uri, String target) { if (uri != null && uri.length() == 0) uri = null; final UiVisualizer uv = getCurrentVisualizer(); uv.setAbortingReason( new AbortBySendRedirect( uri != null ? uv.getExecution().encodeURL(uri): "", target)); } public void setAbortingReason(AbortingReason aborting) { final UiVisualizer uv = getCurrentVisualizer(); uv.setAbortingReason(aborting); } //-- Recovering desktop --// public void execRecover(Execution exec, FailoverManager failover) { final Desktop desktop = exec.getDesktop(); final Session sess = desktop.getSession(); doActivate(exec, false, true, null, -1); //it must not return null try { failover.recover(sess, exec, desktop); } finally { doDeactivate(exec); } } //-- Asynchronous updates --// public void beginUpdate(Execution exec) { final UiVisualizer uv = doActivate(exec, true, false, null, -1); final Desktop desktop = exec.getDesktop(); desktop.getWebApp().getConfiguration().invokeExecutionInits(exec, null); ((DesktopCtrl)desktop).invokeExecutionInits(exec, null); } public void endUpdate(Execution exec) throws IOException { final Desktop desktop = exec.getDesktop(); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; final Configuration config = desktop.getWebApp().getConfiguration(); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; final UiVisualizer uv = (UiVisualizer)execCtrl.getVisualizer(); try { final List errs = new LinkedList(); Event event = nextEvent(uv); do { for (; event != null; event = nextEvent(uv)) { try { process(desktop, event); } catch (Throwable ex) { handleError(ex, uv, errs); } } resumeAll(desktop, uv, null); } while ((event = nextEvent(uv)) != null); desktopCtrl.piggyResponse(getResponses(exec, uv, errs), false); desktopCtrl.invokeExecutionCleanups(exec, null, errs); config.invokeExecutionCleanups(exec, null, errs); } catch (Throwable ex) { final List errs = new LinkedList(); errs.add(ex); desktopCtrl.invokeExecutionCleanups(exec, null, errs); config.invokeExecutionCleanups(exec, null, errs); if (!errs.isEmpty()) { ex = (Throwable)errs.get(0); if (ex instanceof IOException) throw (IOException)ex; throw UiException.Aide.wrap(ex); } } finally { doDeactivate(exec); } } public void execUpdate(Execution exec, List requests, AuWriter out) throws IOException { if (requests == null) throw new IllegalArgumentException(); assert D.OFF || ExecutionsCtrl.getCurrentCtrl() == null: "Impossible to re-activate for update: old="+ExecutionsCtrl.getCurrentCtrl()+", new="+exec; final Desktop desktop = exec.getDesktop(); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; final Configuration config = desktop.getWebApp().getConfiguration(); final PerformanceMeter pfmeter = config.getPerformanceMeter(); long startTime = 0; if (pfmeter != null) { startTime = System.currentTimeMillis(); //snapshot time since activate might take time meterAuClientComplete(pfmeter, exec); } final Object[] resultOfRepeat = new Object[1]; final UiVisualizer uv = doActivate(exec, true, false, resultOfRepeat, -1); if (resultOfRepeat[0] != null) { out.resend(resultOfRepeat[0]); doDeactivate(exec); return; } final Monitor monitor = config.getMonitor(); if (monitor != null) { try { monitor.beforeUpdate(desktop, requests); } catch (Throwable ex) { log.error(ex); } } final String pfReqId = pfmeter != null ? meterAuStart(pfmeter, exec, startTime): null; Collection doneReqIds = null; //request IDs that have been processed AbortingReason abrn = null; try { final RequestQueue rque = desktopCtrl.getRequestQueue(); rque.addRequests(requests); config.invokeExecutionInits(exec, null); desktopCtrl.invokeExecutionInits(exec, null); if (pfReqId != null) rque.addPerfRequestId(pfReqId); final List errs = new LinkedList(); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; //Process all; ignore getMaxProcessTime(); //we cannot handle them partially since UUID might be recycled for (AuRequest request; (request = rque.nextRequest()) != null;) { //Cycle 1: Process one request //Don't process more such that requests will be queued //and we have the chance to optimize them execCtrl.setCurrentPage(request.getPage()); try { ((DesktopCtrl)desktop).service(request, !errs.isEmpty()); } catch (Throwable ex) { handleError(ex, uv, errs); //we don't skip request to avoid mis-match between c/s } //Cycle 2: Process any pending events posted by components Event event = nextEvent(uv); do { for (; event != null; event = nextEvent(uv)) { try { process(desktop, event); } catch (Throwable ex) { handleError(ex, uv, errs); } } resumeAll(desktop, uv, errs); } while ((event = nextEvent(uv)) != null); } //Cycle 2a: Handle aborting reason abrn = uv.getAbortingReason(); if (abrn != null) abrn.execute(); //always execute even if !isAborting //Cycle 3: Generate output final List responses = getResponses(exec, uv, errs); doneReqIds = rque.clearPerfRequestIds(); final List prs = desktopCtrl.piggyResponse(null, true); if (prs != null) responses.addAll(0, prs); out.writeResponseId(desktopCtrl.getResponseId(true)); out.write(responses); // if (log.debugable()) // if (responses.size() < 5 || log.finerable()) log.finer("Responses: "+responses); // else log.debug("Responses: "+responses.subList(0, 5)+"..."); final String seqId = ((ExecutionCtrl)exec).getRequestId(); if (seqId != null) desktopCtrl.responseSent(seqId, out.complete()); desktopCtrl.invokeExecutionCleanups(exec, null, errs); config.invokeExecutionCleanups(exec, null, errs); } catch (Throwable ex) { final List errs = new LinkedList(); errs.add(ex); desktopCtrl.invokeExecutionCleanups(exec, null, errs); config.invokeExecutionCleanups(exec, null, errs); if (!errs.isEmpty()) { ex = (Throwable)errs.get(0); if (ex instanceof IOException) throw (IOException)ex; throw UiException.Aide.wrap(ex); } } finally { if (abrn != null) { try { abrn.finish(); } catch (Throwable t) { log.warning(t); } } if (monitor != null) { try { monitor.afterUpdate(desktop); } catch (Throwable ex) { log.error(ex); } } doDeactivate(exec); if (pfmeter != null && doneReqIds != null) meterAuServerComplete(pfmeter, doneReqIds, exec); } } public Object startUpdate(Execution exec) throws IOException { final Desktop desktop = exec.getDesktop(); UiVisualizer uv = doActivate(exec, true, false, null, -1); desktop.getWebApp().getConfiguration().invokeExecutionInits(exec, null); ((DesktopCtrl)desktop).invokeExecutionInits(exec, null); return new UpdateInfo(uv); } public JSONArray finishUpdate(Object ctx) throws IOException { final UpdateInfo ui = (UpdateInfo)ctx; final Execution exec = ui.uv.getExecution(); final Desktop desktop = exec.getDesktop(); final List errs = new LinkedList(); //1. process events Event event = nextEvent(ui.uv); do { for (; event != null; event = nextEvent(ui.uv)) { try { process(desktop, event); } catch (Throwable ex) { handleError(ex, ui.uv, errs); } } resumeAll(desktop, ui.uv, errs); } while ((event = nextEvent(ui.uv)) != null); //2. Handle aborting reason ui.abrn = ui.uv.getAbortingReason(); if (ui.abrn != null) ui.abrn.execute(); //always execute even if !isAborting //3. Retrieve responses final List responses = getResponses(exec, ui.uv, errs); final JSONArray rs = new JSONArray(); for (Iterator it = responses.iterator(); it.hasNext();) rs.add(AuWriters.toJSON((AuResponse)it.next())); return rs; } public void closeUpdate(Object ctx) throws IOException { final UpdateInfo ui = (UpdateInfo)ctx; final Execution exec = ui.uv.getExecution(); final Desktop desktop = exec.getDesktop(); ((DesktopCtrl)desktop).invokeExecutionCleanups(exec, null, null); desktop.getWebApp().getConfiguration().invokeExecutionCleanups(exec, null, null); if (ui.abrn != null) { try { ui.abrn.finish(); } catch (Throwable t) { log.warning(t); } } doDeactivate(exec); } private static class UpdateInfo { private final UiVisualizer uv; private AbortingReason abrn; private UpdateInfo(UiVisualizer uv) { this.uv = uv; } } /** Handles each error. The erros will be queued to the errs list * and processed later by {@link #visualizeErrors}. */ private static final void handleError(Throwable ex, UiVisualizer uv, List errs) { final Throwable t = Exceptions.findCause(ex, Expectable.class); if (t == null) { if (ex instanceof org.xml.sax.SAXException || ex instanceof org.zkoss.zk.ui.metainfo.PropertyNotFoundException) log.error(Exceptions.getMessage(ex)); else log.realCause(ex);//Briefly(ex); } else { ex = t; if (log.debugable()) log.debug(Exceptions.getRealCause(ex)); } if (ex instanceof WrongValueException) { WrongValueException wve = (WrongValueException)ex; final Component comp = wve.getComponent(); if (comp != null) { wve = ((ComponentCtrl)comp).onWrongValue(wve); if (wve != null) { Component c = wve.getComponent(); if (c == null) c = comp; uv.addResponse( new AuWrongValue(c, Exceptions.getMessage(wve))); } return; } } else if (ex instanceof WrongValuesException) { final WrongValueException[] wves = ((WrongValuesException)ex).getWrongValueExceptions(); final LinkedList infs = new LinkedList(); for (int i = 0; i < wves.length; i++) { final Component comp = wves[i].getComponent(); if (comp != null) { WrongValueException wve = ((ComponentCtrl)comp).onWrongValue(wves[i]); if (wve != null) { Component c = wve.getComponent(); if (c == null) c = comp; infs.add(c.getUuid()); infs.add(Exceptions.getMessage(wve)); } } } uv.addResponse( new AuWrongValue((String[])infs.toArray(new String[infs.size()]))); return; } errs.add(ex); } /** Returns the list of response of the given execution. */ private final List getResponses(Execution exec, UiVisualizer uv, List errs) { List responses; try { //Note: we have to call visualizeErrors before uv.getResponses, //since it might create/update components if (!errs.isEmpty()) visualizeErrors(exec, uv, errs); responses = uv.getResponses(); } catch (Throwable ex) { responses = new LinkedList(); responses.add(new AuAlert(Exceptions.getMessage(ex))); log.error(ex); } return responses; } /** Post-process the errors to represent them to the user. * Note: errs must be non-empty */ private final void visualizeErrors(Execution exec, UiVisualizer uv, List errs) { final StringBuffer sb = new StringBuffer(128); for (Iterator it = errs.iterator(); it.hasNext();) { final Throwable t = (Throwable)it.next(); if (sb.length() > 0) sb.append('\n'); sb.append(Exceptions.getMessage(t)); } final String msg = sb.toString(); final Throwable err = (Throwable)errs.get(0); final Desktop desktop = exec.getDesktop(); final Configuration config = desktop.getWebApp().getConfiguration(); final String location = config.getErrorPage(desktop.getDeviceType(), err); if (location != null) { try { exec.setAttribute("javax.servlet.error.message", msg); exec.setAttribute("javax.servlet.error.exception", err); exec.setAttribute("javax.servlet.error.exception_type", err.getClass()); exec.setAttribute("javax.servlet.error.status_code", new Integer(500)); exec.setAttribute("javax.servlet.error.error_page", location); //Future: consider to go thru UiFactory for the richlet //for the error page. //Challenge: how to call UiFactory.isRichlet final Richlet richlet = config.getRichletByPath(location); if (richlet != null) richlet.service(((ExecutionCtrl)exec).getCurrentPage()); else exec.createComponents(location, null, null); //process pending events //the execution is aborted if an exception is thrown Event event = nextEvent(uv); do { for (; event != null; event = nextEvent(uv)) { try { process(desktop, event); } catch (SuspendNotAllowedException ex) { //ignore it (possible and reasonable) } } resumeAll(desktop, uv, null); } while ((event = nextEvent(uv)) != null); return; //done } catch (Throwable ex) { log.realCause("Unable to generate custom error page, "+location, ex); } } uv.addResponse(new AuAlert(msg)); //default handling } /** Processing the event and stores result into UiVisualizer. */ private void process(Desktop desktop, Event event) { // if (log.finable()) log.finer("Processing event: "+event); final Component comp; if (event instanceof ProxyEvent) { final ProxyEvent pe = (ProxyEvent)event; comp = pe.getRealTarget(); event = pe.getProxiedEvent(); } else { comp = event.getTarget(); } if (comp != null) { processEvent(desktop, comp, event); } else { //since an event might change the page/desktop/component relation, //we copy roots first final List roots = new LinkedList(); for (Iterator it = desktop.getPages().iterator(); it.hasNext();) { roots.addAll(((Page)it.next()).getRoots()); } for (Iterator it = roots.iterator(); it.hasNext();) { final Component c = (Component)it.next(); if (c.getPage() != null) //might be removed, so check first processEvent(desktop, c, event); } } } public void wait(Object mutex) throws InterruptedException, SuspendNotAllowedException { if (mutex == null) throw new IllegalArgumentException("null mutex"); final Thread thd = Thread.currentThread(); if (!(thd instanceof EventProcessingThreadImpl)) throw new UiException("This method can be called only in an event listener, not in paging loading."); // if (log.finerable()) log.finer("Suspend "+thd+" on "+mutex); final EventProcessingThreadImpl evtthd = (EventProcessingThreadImpl)thd; evtthd.newEventThreadSuspends(mutex); //it may throw an exception, so process it before updating _suspended final Execution exec = Executions.getCurrent(); final Desktop desktop = exec.getDesktop(); incSuspended(); Map map; synchronized (_suspended) { map = (Map)_suspended.get(desktop); if (map == null) _suspended.put(desktop, map = new IdentityHashMap(3)); //note: we have to use IdentityHashMap because user might //use Integer or so as mutex } synchronized (map) { List list = (List)map.get(mutex); if (list == null) map.put(mutex, list = new LinkedList()); list.add(evtthd); } try { EventProcessingThreadImpl.doSuspend(mutex); } catch (Throwable ex) { //error recover synchronized (map) { final List list = (List)map.get(mutex); if (list != null) { list.remove(evtthd); if (list.isEmpty()) map.remove(mutex); } } if (ex instanceof InterruptedException) throw (InterruptedException)ex; throw UiException.Aide.wrap(ex, "Unable to suspend "+evtthd); } finally { decSuspended(); } } private void incSuspended() { final int v = _wapp.getConfiguration().getMaxSuspendedThreads(); synchronized (this) { if (v >= 0 && _suspCnt >= v) throw new SuspendNotAllowedException(MZk.TOO_MANY_SUSPENDED); ++_suspCnt; } } private void decSuspended() { synchronized (this) { --_suspCnt; } } public void notify(Object mutex) { notify(Executions.getCurrent().getDesktop(), mutex); } public void notify(Desktop desktop, Object mutex) { if (desktop == null || mutex == null) throw new IllegalArgumentException("desktop and mutex cannot be null"); final Map map; synchronized (_suspended) { map = (Map)_suspended.get(desktop); } if (map == null) return; //nothing to notify final EventProcessingThreadImpl evtthd; synchronized (map) { final List list = (List)map.get(mutex); if (list == null) return; //nothing to notify //Note: list is never empty evtthd = (EventProcessingThreadImpl)list.remove(0); if (list.isEmpty()) map.remove(mutex); //clean up } addResumed(desktop, evtthd); } public void notifyAll(Object mutex) { final Execution exec = Executions.getCurrent(); if (exec == null) throw new UiException("resume can be called only in processing a request"); notifyAll(exec.getDesktop(), mutex); } public void notifyAll(Desktop desktop, Object mutex) { if (desktop == null || mutex == null) throw new IllegalArgumentException("desktop and mutex cannot be null"); final Map map; synchronized (_suspended) { map = (Map)_suspended.get(desktop); } if (map == null) return; //nothing to notify final List list; synchronized (map) { list = (List)map.remove(mutex); if (list == null) return; //nothing to notify } for (Iterator it = list.iterator(); it.hasNext();) addResumed(desktop, (EventProcessingThreadImpl)it.next()); } /** Adds to _resumed */ private void addResumed(Desktop desktop, EventProcessingThreadImpl evtthd) { // if (log.finerable()) log.finer("Ready to resume "+evtthd); List list; synchronized (_resumed) { list = (List)_resumed.get(desktop); if (list == null) _resumed.put(desktop, list = new LinkedList()); } synchronized (list) { list.add(evtthd); } } /** Does the real resume. * <p>Note 1: the current thread will wait until the resumed threads, if any, complete * <p>Note 2: {@link #resume} only puts a thread into a resume queue in execution. */ private void resumeAll(Desktop desktop, UiVisualizer uv, List errs) { //We have to loop because a resumed thread might resume others while (!_resumed.isEmpty()) { //no need to sync (better performance) final List list; synchronized (_resumed) { list = (List)_resumed.remove(desktop); if (list == null) return; //nothing to resume; done } synchronized (list) { for (Iterator it = list.iterator(); it.hasNext();) { final EventProcessingThreadImpl evtthd = (EventProcessingThreadImpl)it.next(); if (uv.isAborting()) { evtthd.ceaseSilently("Resume aborted"); } else { // if (log.finerable()) log.finer("Resume "+evtthd); try { if (evtthd.doResume()) //wait it complete or suspend again recycleEventThread(evtthd); //completed } catch (Throwable ex) { recycleEventThread(evtthd); if (errs == null) { log.error("Unable to resume "+evtthd, ex); throw UiException.Aide.wrap(ex); } handleError(ex, uv, errs); } } } } } } /** Process an event. */ private void processEvent(Desktop desktop, Component comp, Event event) { final Configuration config = desktop.getWebApp().getConfiguration(); if (config.isEventThreadEnabled()) { EventProcessingThreadImpl evtthd = null; synchronized (_idles) { while (!_idles.isEmpty() && evtthd == null) { evtthd = (EventProcessingThreadImpl)_idles.remove(0); if (evtthd.isCeased()) //just in case evtthd = null; } } if (evtthd == null) evtthd = new EventProcessingThreadImpl(); try { if (evtthd.processEvent(desktop, comp, event)) recycleEventThread(evtthd); } catch (Throwable ex) { recycleEventThread(evtthd); throw UiException.Aide.wrap(ex); } } else { //event thread disabled //Note: we don't need to call proc.setup() and cleanup(), //since they are in the same thread EventProcessor proc = new EventProcessor(desktop, comp, event); //Note: it also checks the correctness List cleanups = null, errs = null; try { final List inits = config.newEventThreadInits(comp, event); EventProcessor.inEventListener(true); if (config.invokeEventThreadInits(inits, comp, event)) //false measn ignore proc.process(); } catch (Throwable ex) { errs = new LinkedList(); errs.add(ex); cleanups = config.newEventThreadCleanups(comp, event, errs, false); if (!errs.isEmpty()) throw UiException.Aide.wrap((Throwable)errs.get(0)); } finally { EventProcessor.inEventListener(false); if (errs == null) //not cleanup yet cleanups = config.newEventThreadCleanups(comp, event, null, false); config.invokeEventThreadCompletes(cleanups, comp, event, errs, false); } } } private void recycleEventThread(EventProcessingThreadImpl evtthd) { if (!evtthd.isCeased()) { if (evtthd.isIdle()) { final int max = _wapp.getConfiguration().getMaxSpareThreads(); synchronized (_idles) { if (max < 0 || _idles.size() < max) { _idles.add(evtthd); //return to pool return; //done } } } evtthd.ceaseSilently("Recycled"); } } public void activate(Execution exec) { activate(exec, -1); } public boolean activate(Execution exec, int timeout) { assert D.OFF || ExecutionsCtrl.getCurrentCtrl() == null: "Impossible to re-activate for update: old="+ExecutionsCtrl.getCurrentCtrl()+", new="+exec; return doActivate(exec, false, false, null, timeout) != null; } public void deactivate(Execution exec) { doDeactivate(exec); } //-- Common private utilities --// /** Activates the specified execution. * * @param asyncupd whether it is for asynchronous update. * Note: it doesn't support if both asyncupd and recovering are true. * @param recovering whether it is in recovering, i.e., * cause by {@link FailoverManager#recover}. * If true, the requests argument must be null. * @param resultOfRepeat a single element array to return a value, or null * if it is not called by execUpdate. * If a non-null value is assigned to the first element of the array, * it means it is a repeated request, and the caller shall return * the result directly without processing the request. * @param timeout how many milliseconds to wait before timeout. * If non-negative and it waits more than it before granted, null is turned * to indicate failure. * @return the visualizer once the execution is granted, or null * if timeout is specified and it takes longer than the given value. */ private static UiVisualizer doActivate(Execution exec, boolean asyncupd, boolean recovering, Object[] resultOfRepeat, int timeout) { if (Executions.getCurrent() != null) throw new IllegalStateException("Use doReactivate instead"); assert D.OFF || !recovering || !asyncupd; //Not support both asyncupd and recovering are true yet final Desktop desktop = exec.getDesktop(); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; final Session sess = desktop.getSession(); final String seqId = resultOfRepeat != null ? ((ExecutionCtrl)exec).getRequestId(): null; // if (log.finerable()) log.finer("Activating "+desktop); //lock desktop final UiVisualizer uv; final Object uvlock = desktopCtrl.getActivationLock(); final int tmout = timeout >= 0 ? timeout: getRetryTimeout(); synchronized (uvlock) { for (boolean tried = false;;) { final Visualizer old = desktopCtrl.getVisualizer(); if (old == null) break; //grantable if (tried && timeout >= 0) return null; //failed if (seqId != null) { final String oldSeqId = ((ExecutionCtrl)old.getExecution()).getRequestId(); if (oldSeqId != null && !oldSeqId.equals(seqId)) throw new RequestOutOfSequenceException(seqId, oldSeqId); } try { uvlock.wait(tmout); tried = true; } catch (InterruptedException ex) { throw UiException.Aide.wrap(ex); } } if (!desktop.isAlive()) throw new org.zkoss.zk.ui.DesktopUnavailableException("Unable to activate destroyed desktop, "+desktop); //grant desktopCtrl.setVisualizer(uv = new UiVisualizer(exec, asyncupd, recovering)); desktopCtrl.setExecution(exec); } // if (log.finerable()) log.finer("Activated "+desktop); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; ExecutionsCtrl.setCurrent(exec); try { execCtrl.onActivate(); } catch (Throwable ex) { //just in case ExecutionsCtrl.setCurrent(null); synchronized (uvlock) { desktopCtrl.setVisualizer(null); desktopCtrl.setExecution(null); uvlock.notify(); //wakeup pending threads } throw UiException.Aide.wrap(ex); } if (seqId != null) { if (log.debugable()) { final Object req = exec.getNativeRequest(); log.debug("replicate request, SID: " + seqId +(req instanceof ServletRequest ? "\n" + Servlets.getDetail((ServletRequest)req): "")); } resultOfRepeat[0] = desktopCtrl.getLastResponse(seqId); } return uv; } private static Integer _retryTimeout, _destroyTimeout; private static final int getRetryTimeout() { if (_retryTimeout == null) { int v = 0; final String s = Library.getProperty(Attributes.ACTIVATE_RETRY_DELAY); if (s != null) { try { v = Integer.parseInt(s); } catch (Throwable t) { } } _retryTimeout = new Integer(v > 0 ? v: 120*1000); } return _retryTimeout.intValue(); } private static final int getDestroyTimeout() { if (_destroyTimeout == null) { int v = 0; final String s = Library.getProperty("org.zkoss.zk.ui.activate.wait.destroy.timeout"); if (s != null) { try { v = Integer.parseInt(s); } catch (Throwable t) { } } _destroyTimeout = new Integer(v > 0 ? v: 20*1000); //20 sec } return _destroyTimeout.intValue(); } /** Returns whether the desktop is being recovered. */ private static final boolean isRecovering(Desktop desktop) { final Execution exec = desktop.getExecution(); return exec != null && ((ExecutionCtrl)exec).isRecovering(); } /** Deactivates the execution. */ private static final void doDeactivate(Execution exec) { // if (log.finerable()) log.finer("Deactivating "+desktop); final ExecutionCtrl execCtrl = (ExecutionCtrl)exec; final Desktop desktop = exec.getDesktop(); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; try { //Unlock desktop final Object uvlock = desktopCtrl.getActivationLock(); synchronized (uvlock) { desktopCtrl.setVisualizer(null); desktopCtrl.setExecution(null); uvlock.notify(); //wakeup doActivate's wait } } finally { try { execCtrl.onDeactivate(); } catch (Throwable ex) { log.warningBriefly("Failed to deactive", ex); } ExecutionsCtrl.setCurrent(null); execCtrl.setCurrentPage(null); } final SessionCtrl sessCtrl = (SessionCtrl)desktop.getSession(); if (sessCtrl.isInvalidated()) sessCtrl.invalidateNow(); } /** Re-activates for another execution. It is callable only for * creating new page (execNewPage). It is not allowed for async-update. * <p>Note: doActivate cannot handle reactivation. In other words, * the caller has to detect which method to use. */ private static UiVisualizer doReactivate(Execution curExec, UiVisualizer olduv) { final Desktop desktop = curExec.getDesktop(); final Session sess = desktop.getSession(); // if (log.finerable()) log.finer("Re-activating "+desktop); assert D.OFF || olduv.getExecution().getDesktop() == desktop: "old dt: "+olduv.getExecution().getDesktop()+", new:"+desktop; final UiVisualizer uv = new UiVisualizer(olduv, curExec); final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; desktopCtrl.setVisualizer(uv); desktopCtrl.setExecution(curExec); final ExecutionCtrl curCtrl = (ExecutionCtrl)curExec; ExecutionsCtrl.setCurrent(curExec); try { curCtrl.onActivate(); } catch (Throwable ex) { //just in case ExecutionsCtrl.setCurrent(olduv.getExecution()); desktopCtrl.setVisualizer(olduv); desktopCtrl.setExecution(olduv.getExecution()); throw UiException.Aide.wrap(ex); } return uv; } /** De-reactivated exec. Work with {@link #doReactivate}. */ private static void doDereactivate(Execution curExec, UiVisualizer olduv) { if (olduv == null) throw new IllegalArgumentException("null"); final ExecutionCtrl curCtrl = (ExecutionCtrl)curExec; final Execution oldexec = olduv.getExecution(); try { final Desktop desktop = curExec.getDesktop(); // if (log.finerable()) log.finer("Deactivating "+desktop); try { curCtrl.onDeactivate(); } catch (Throwable ex) { log.warningBriefly("Failed to deactive", ex); } final DesktopCtrl desktopCtrl = (DesktopCtrl)desktop; desktopCtrl.setVisualizer(olduv); desktopCtrl.setExecution(oldexec); } finally { ExecutionsCtrl.setCurrent(oldexec); curCtrl.setCurrentPage(null); } } //Handling Native Component// /** Sets the prolog of the specified native component. */ private static final void setProlog(CreateInfo ci, Component comp, NativeInfo compInfo) { final Native nc = (Native)comp; final Native.Helper helper = nc.getHelper(); StringBuffer sb = null; final List prokids = compInfo.getPrologChildren(); if (!prokids.isEmpty()) { sb = new StringBuffer(256); getNativeContent(ci, sb, comp, prokids, helper); } final NativeInfo splitInfo = compInfo.getSplitChild(); if (splitInfo != null && splitInfo.isEffective(comp)) { if (sb == null) sb = new StringBuffer(256); getNativeFirstHalf(ci, sb, comp, splitInfo, helper); } if (sb != null && sb.length() > 0) nc.setPrologContent( sb.insert(0, (String)nc.getPrologContent()).toString()); } /** Sets the epilog of the specified native component. * @param comp the native component */ private static final void setEpilog(CreateInfo ci, Component comp, NativeInfo compInfo) { final Native nc = (Native)comp; final Native.Helper helper = nc.getHelper(); StringBuffer sb = null; final NativeInfo splitInfo = compInfo.getSplitChild(); if (splitInfo != null && splitInfo.isEffective(comp)) { sb = new StringBuffer(256); getNativeSecondHalf(ci, sb, comp, splitInfo, helper); } final List epikids = compInfo.getEpilogChildren(); if (!epikids.isEmpty()) { if (sb == null) sb = new StringBuffer(256); getNativeContent(ci, sb, comp, epikids, helper); } if (sb != null && sb.length() > 0) nc.setEpilogContent( sb.append(nc.getEpilogContent()).toString()); } public String getNativeContent(Component comp, List children, Native.Helper helper) { final StringBuffer sb = new StringBuffer(256); getNativeContent( new CreateInfo(((WebAppCtrl)_wapp).getUiFactory(), Executions.getCurrent(), comp.getPage(), null), sb, comp, children, helper); return sb.toString(); } /** * @param comp the native component */ private static final void getNativeContent(CreateInfo ci, StringBuffer sb, Component comp, List children, Native.Helper helper) { for (Iterator it = children.iterator(); it.hasNext();) { final Object meta = it.next(); if (meta instanceof NativeInfo) { final NativeInfo childInfo = (NativeInfo)meta; final ForEach forEach = childInfo.resolveForEach(ci.page, comp); if (forEach == null) { if (childInfo.isEffective(comp)) { getNativeFirstHalf(ci, sb, comp, childInfo, helper); getNativeSecondHalf(ci, sb, comp, childInfo, helper); } } else { while (forEach.next()) { if (childInfo.isEffective(comp)) { getNativeFirstHalf(ci, sb, comp, childInfo, helper); getNativeSecondHalf(ci, sb, comp, childInfo, helper); } } } } else if (meta instanceof TextInfo) { final String s = ((TextInfo)meta).getValue(comp); if (s != null) helper.appendText(sb, s); } else if (meta instanceof ZkInfo) { ZkInfo zkInfo = (ZkInfo)meta; if (zkInfo.withSwitch()) throw new UnsupportedOperationException("<zk switch> in native not allowed yet"); final ForEach forEach = zkInfo.resolveForEach(ci.page, comp); if (forEach == null) { if (isEffective(zkInfo, ci.page, comp)) { getNativeContent(ci, sb, comp, zkInfo.getChildren(), helper); } } else { while (forEach.next()) if (isEffective(zkInfo, ci.page, comp)) getNativeContent(ci, sb, comp, zkInfo.getChildren(), helper); } } else { execNonComponent(ci, comp, meta); } } } /** Before calling this method, childInfo.isEffective must be examined */ private static final void getNativeFirstHalf(CreateInfo ci, StringBuffer sb, Component comp, NativeInfo childInfo, Native.Helper helper) { helper.getFirstHalf(sb, childInfo.getTag(), evalProperties(comp, childInfo.getProperties()), childInfo.getDeclaredNamespaces()); final List prokids = childInfo.getPrologChildren(); if (!prokids.isEmpty()) getNativeContent(ci, sb, comp, prokids, helper); final NativeInfo splitInfo = childInfo.getSplitChild(); if (splitInfo != null && splitInfo.isEffective(comp)) getNativeFirstHalf(ci, sb, comp, splitInfo, helper); //recursive } /** Before calling this method, childInfo.isEffective must be examined */ private static final void getNativeSecondHalf(CreateInfo ci, StringBuffer sb, Component comp, NativeInfo childInfo, Native.Helper helper) { final NativeInfo splitInfo = childInfo.getSplitChild(); if (splitInfo != null && splitInfo.isEffective(comp)) getNativeSecondHalf(ci, sb, comp, splitInfo, helper); //recursive final List epikids = childInfo.getEpilogChildren(); if (!epikids.isEmpty()) getNativeContent(ci, sb, comp, epikids, helper); helper.getSecondHalf(sb, childInfo.getTag()); } /** Returns a map of properties, (String name, String value). */ private static final Map evalProperties(Component comp, List props) { if (props == null || props.isEmpty()) return Collections.EMPTY_MAP; final Map map = new LinkedHashMap(props.size() * 2); for (Iterator it = props.iterator(); it.hasNext();) { final Property prop = (Property)it.next(); if (prop.isEffective(comp)) map.put(prop.getName(), Classes.coerce(String.class, prop.getValue(comp))); } return map; } //Supporting Classes// /** The listener to create children when the fulfill condition is * satisfied. */ private static class FulfillListener implements EventListener, Express, java.io.Serializable, Cloneable, ComponentCloneListener { private String[] _evtnms; private Component[] _targets; private Component _comp; private final ComponentInfo _compInfo; private final String _fulfill; private transient String _uri; private FulfillListener(String fulfill, ComponentInfo compInfo, Component comp) { _fulfill = fulfill; _compInfo = compInfo; _comp = comp; init(); for (int j = _targets.length; --j >= 0;) _targets[j].addEventListener(_evtnms[j], this); } private void init() { _uri = null; final List results = new LinkedList(); for (int j = 0, len = _fulfill.length();;) { int k = j; for (int elcnt = 0; k < len; ++k) { final char cc = _fulfill.charAt(k); if (elcnt == 0) { if (cc == ',') break; if (cc == '=') { _uri = _fulfill.substring(k + 1).trim(); break; } } else if (cc == '{') { ++elcnt; } else if (cc == '}') { if (elcnt > 0) --elcnt; } } String sub = (k >= 0 ? _fulfill.substring(j, k): _fulfill.substring(j)).trim(); if (sub.length() > 0) results.add(ComponentsCtrl .parseEventExpression(_comp, sub, _comp, false)); if (_uri != null || k < 0 || (j = k + 1) >= len) break; } int j = results.size(); _targets = new Component[j]; _evtnms = new String[j]; j = 0; for (Iterator it = results.iterator(); it.hasNext(); ++j) { final Object[] result = (Object[])it.next(); _targets[j] = (Component)result[0]; _evtnms[j] = (String)result[1]; } } public void onEvent(Event evt) throws Exception { for (int j = _targets.length; --j >= 0;) _targets[j].removeEventListener(_evtnms[j], this); //one shot only final Execution exec = Executions.getCurrent(); execCreate0( new CreateInfo( ((WebAppCtrl)exec.getDesktop().getWebApp()).getUiFactory(), exec, _comp.getPage(), null), //technically sys composer can be used but we don't (to simplify it) _compInfo, _comp); if (_uri != null) { final String uri = (String)Evaluators.evaluate( _compInfo.getEvaluator(), _comp, _uri, String.class); if (uri != null) exec.createComponents(uri, _comp, null); } Events.sendEvent(new FulfillEvent(Events.ON_FULFILL, _comp, evt)); //Use sendEvent so onFulfill will be processed before //the event triggers the fulfill (i.e., evt) } //ComponentCloneListener// public Object willClone(Component comp) { final FulfillListener clone; try { clone = (FulfillListener)clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } clone._comp = comp; clone.init(); return clone; } } private static class ReplaceableText { private String text; } //performance meter// /** Handles the client complete of AU request for performance measurement. */ private static void meterAuClientComplete(PerformanceMeter pfmeter, Execution exec) { //Format of ZK-Client-Complete and ZK-Client-Receive: // request-id1=time1,request-id2=time2 String hdr = exec.getHeader("ZK-Client-Receive"); if (hdr != null) meterAuClient(pfmeter, exec, hdr, false); hdr = exec.getHeader("ZK-Client-Complete"); if (hdr != null) meterAuClient(pfmeter, exec, hdr, true); } private static void meterAuClient(PerformanceMeter pfmeter, Execution exec, String hdr, boolean complete) { for (int j = 0;;) { int k = hdr.indexOf(',', j); String ids = k >= 0 ? hdr.substring(j, k): j == 0 ? hdr: hdr.substring(j); int x = ids.lastIndexOf('='); if (x > 0) { try { long time = Long.parseLong(ids.substring(x + 1)); ids = ids.substring(0, x); for (int y = 0;;) { int z = ids.indexOf(' ', y); String pfReqId = z >= 0 ? ids.substring(y, z): y == 0 ? ids: ids.substring(y); if (complete) pfmeter.requestCompleteAtClient(pfReqId, exec, time); else pfmeter.requestReceiveAtClient(pfReqId, exec, time); if (z < 0) break; //done y = z + 1; } } catch (NumberFormatException ex) { log.warning("Ingored: unable to parse "+ids); } catch (Throwable ex) { //backward compatibile: requestReceiveAtClient added since 3.0.8 if (complete || !(ex instanceof AbstractMethodError)) log.warning("Ingored: failed to invoke "+pfmeter, ex); } } if (k < 0) break; //done j = k + 1; } } /** Handles the client and server start of AU request * for the performance measurement. * * @return the request ID from the ZK-Client-Start header, * or null if not found. */ private static String meterAuStart(PerformanceMeter pfmeter, Execution exec, long startTime) { //Format of ZK-Client-Start: // request-id=time String hdr = exec.getHeader("ZK-Client-Start"); if (hdr != null) { final int j = hdr.lastIndexOf('='); if (j > 0) { final String pfReqId = hdr.substring(0, j); try { pfmeter.requestStartAtClient(pfReqId, exec, Long.parseLong(hdr.substring(j + 1))); pfmeter.requestStartAtServer(pfReqId, exec, startTime); } catch (NumberFormatException ex) { log.warning("Ingored: failed to parse ZK-Client-Start, "+hdr); } catch (Throwable ex) { log.warning("Ingored: failed to invoke "+pfmeter, ex); } return pfReqId; } } return null; } /** Handles the server complete of the AU request for the performance measurement. * It sets the ZK-Client-Complete header. * * @param pfReqIds a collection of request IDs that are processed * at the server */ private static void meterAuServerComplete(PerformanceMeter pfmeter, Collection pfReqIds, Execution exec) { final StringBuffer sb = new StringBuffer(256); long time = System.currentTimeMillis(); for (Iterator it = pfReqIds.iterator(); it.hasNext();) { final String pfReqId = (String)it.next(); if (sb.length() > 0) sb.append(' '); sb.append(pfReqId); try { pfmeter.requestCompleteAtServer(pfReqId, exec, time); } catch (Throwable ex) { log.warning("Ingored: failed to invoke "+pfmeter, ex); } } exec.setResponseHeader("ZK-Client-Complete", sb.toString()); //tell the client what are completed } /** Handles the (client and) server start of load request * for the performance measurement. * * @return the request ID */ private static String meterLoadStart(PerformanceMeter pfmeter, Execution exec, long startTime) { //Future: handle the zkClientStart paramter final String pfReqId = exec.getDesktop().getId(); try { pfmeter.requestStartAtServer(pfReqId, exec, startTime); } catch (Throwable ex) { log.warning("Ingored: failed to invoke "+pfmeter, ex); } return pfReqId; } /** Handles the server complete of the AU request for the performance measurement. * It sets the ZK-Client-Complete header. * * @param pfReqId the request ID that is processed at the server */ private static void meterLoadServerComplete(PerformanceMeter pfmeter, String pfReqId, Execution exec) { try { pfmeter.requestCompleteAtServer(pfReqId, exec, System.currentTimeMillis()); } catch (Throwable ex) { log.warning("Ingored: failed to invoke "+pfmeter, ex); } } /** An interface used to extend the UI engine. * The class name of the extension shall be specified in * the library properties called org.zkoss.zk.ui.impl.UiEngineImpl.extension. * <p>Notice that it is used only internally. * @since 5.0.8 */ public static interface Extension { /** Called after the whole component tree has been created by * this engine. * <p>The implementation might implement this method to process * the components, such as merging, if necessary. * @param comps the components being created. It is never null but * it might be a zero-length array. */ public void afterCreate(Component[] comps); /** Called after a new page has been redrawn ({@link PageCtrl#redraw} * has been called). * <p>Notice that it is called in the rendering phase (the last phase), * so it is not allowed to post events or to invoke invalidate or smartUpdate * in this method. * <p>Notice that it is not called if an old page is redrawn. * <p>The implementation shall process the components such as merging * if necessary. * @see #execNewPage */ public void afterRenderNewPage(Page page); } private static class DefaultExtension implements Extension { public void afterCreate(Component[] comps) { } public void afterRenderNewPage(Page page) { } } } /** Info used with execCreate */ /*package*/ class CreateInfo { /*package*/ final Execution exec; /*package*/ final Page page; /*package*/ final UiFactory uf; private List _composers, _composerExts; private Composer _syscomposer; /*package*/ CreateInfo(UiFactory uf, Execution exec, Page page, Composer composer) { this.exec = exec; this.page = page; this.uf = uf; if (composer instanceof FullComposer) pushFullComposer(composer); else _syscomposer = composer; } /*package*/ void pushFullComposer(Composer composer) { assert composer instanceof FullComposer; //illegal state if (_composers == null) _composers = new LinkedList(); _composers.add(0, composer); if (composer instanceof ComposerExt) { if (_composerExts == null) _composerExts = new LinkedList(); _composerExts.add(0, composer); } } /*package*/ void popFullComposer() { Object o = _composers.remove(0); if (_composers.isEmpty()) _composers = null; if (o instanceof ComposerExt) { _composerExts.remove(0); if (_composerExts.isEmpty()) _composerExts = null; } } /** Invoke setFullComposerOnly to ensure only composers that implement * FullComposer are called. */ private static boolean beforeInvoke(Composer composer, boolean bRoot) { //If bRoot (implies system-level composer), always invoke (no setFullxxx) return !bRoot && composer instanceof MultiComposer && ((MultiComposer)composer).setFullComposerOnly(true); } private static void afterInvoke(Composer composer, boolean bRoot, boolean old) { if (!bRoot && composer instanceof MultiComposer) ((MultiComposer)composer).setFullComposerOnly(old); } /*package*/ void doAfterCompose(Component comp, boolean bRoot) throws Exception { if (_composers != null) for (Iterator it = _composers.iterator(); it.hasNext();) { final Composer composer = (Composer)it.next(); final boolean old = beforeInvoke(composer, bRoot); composer.doAfterCompose(comp); afterInvoke(composer, bRoot, old); } if (bRoot && _syscomposer != null) _syscomposer.doAfterCompose(comp); } /*package*/ ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo, boolean bRoot) throws Exception { if (_composerExts != null) for (Iterator it = _composerExts.iterator(); it.hasNext();) { final Composer composer = (Composer)it.next(); final boolean old = beforeInvoke(composer, bRoot); compInfo = ((ComposerExt)composer) .doBeforeCompose(page, parent, compInfo); afterInvoke(composer, bRoot, old); if (compInfo == null) return null; } if (bRoot && _syscomposer instanceof ComposerExt) compInfo = ((ComposerExt)_syscomposer) .doBeforeCompose(page, parent, compInfo); return compInfo; } /*package*/ void doBeforeComposeChildren(Component comp, boolean bRoot) throws Exception { if (_composerExts != null) for (Iterator it = _composerExts.iterator(); it.hasNext();) { final Composer composer = (Composer)it.next(); final boolean old = beforeInvoke(composer, bRoot); ((ComposerExt)composer).doBeforeComposeChildren(comp); afterInvoke(composer, bRoot, old); } if (bRoot && _syscomposer instanceof ComposerExt) ((ComposerExt)_syscomposer).doBeforeComposeChildren(comp); } /*package*/ boolean doCatch(Throwable ex, boolean bRoot) { if (_composerExts != null) for (Iterator it = _composerExts.iterator(); it.hasNext();) { final Composer composer = (Composer)it.next(); final boolean old = beforeInvoke(composer, bRoot); try { final boolean ret = ((ComposerExt)composer).doCatch(ex); afterInvoke(composer, bRoot, old); if (ret) return true; //ignore } catch (Throwable t) { UiEngineImpl.log.error("Failed to invoke doCatch for "+composer, t); } } if (bRoot && _syscomposer instanceof ComposerExt) try { return ((ComposerExt)_syscomposer).doCatch(ex); } catch (Throwable t) { UiEngineImpl.log.error("Failed to invoke doCatch for "+_syscomposer, t); } return false; } /*package*/ void doFinally(boolean bRoot) throws Exception { if (_composerExts != null) for (Iterator it = _composerExts.iterator(); it.hasNext();) { final Composer composer = (Composer)it.next(); final boolean old = beforeInvoke(composer, bRoot); ((ComposerExt)composer).doFinally(); afterInvoke(composer, bRoot, old); } if (bRoot && _syscomposer instanceof ComposerExt) ((ComposerExt)_syscomposer).doFinally(); } }
package com.loganconnor44.todoreactiverestapi.services; import com.loganconnor44.todoreactiverestapi.events.TaskCreatedEvent; import com.loganconnor44.todoreactiverestapi.models.Task; import com.loganconnor44.todoreactiverestapi.repositories.TaskRepository; import lombok.extern.log4j.Log4j2; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Log4j2 @Service public class TaskService { private final TaskRepository taskRepository; private final ApplicationEventPublisher publisher; TaskService(ApplicationEventPublisher publisher, TaskRepository taskRepository) { this.publisher = publisher; this.taskRepository = taskRepository; } public Flux<Task> getAll() { return this.taskRepository.findAll(); } public Mono<Task> getById(String id) { return this.taskRepository.findById(id); } public Mono<Task> create(Task task) { return this.taskRepository .save(task) .doOnSuccess(newTask -> this.publisher.publishEvent(new TaskCreatedEvent(newTask))); } }
package com.example.seita.choome_mainproject; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.DatePicker; import android.widget.Toast; import com.beardedhen.androidbootstrap.BootstrapButton; import com.example.seita.choome_mainproject.R; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.GregorianCalendar; public class AnniversaryAddDelDeialogActivity extends AppCompatActivity{ public static final String LOCAL_FILE = "AnniversaryDate.txt"; DatePicker mDatePicker = null; TextInputEditText mAnniversaryEditText = null; BootstrapButton mAddButton = null; BootstrapButton mCancelButton = null; //キーボードを操作するためのオブジェクト InputMethodManager inputMethodManager; //記念日の登録年月日 GregorianCalendar date = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anniversary_add_del_deialog); mDatePicker = (DatePicker)findViewById(R.id.datePicker); mAnniversaryEditText = (TextInputEditText)findViewById(R.id.AnniversaryEditText); mAddButton = (BootstrapButton)findViewById(R.id.AddButton); mCancelButton = (BootstrapButton)findViewById(R.id.CancelButton); //キーボード表示を制御するためのオブジェクト inputMethodManager = (InputMethodManager)getSystemService(getApplicationContext().INPUT_METHOD_SERVICE); mAnniversaryEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { //イベントを取得するタイミングには、ボタンが押されてなおかつエンターキーだったときを指定 if((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)){ //キーボードを閉じる inputMethodManager.hideSoftInputFromWindow(mAnniversaryEditText.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN); //登録ボタンを押したときの処理を実行する writeFile("[" + mAnniversaryEditText.getText() + "]" + "[" + mDatePicker.getYear() + mDatePicker.getMonth()+1 + mDatePicker.getDayOfMonth() + "]"); return true; } return false; } }); mAddButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { writeFile("[" + mAnniversaryEditText.getText() + "]" + "[" + mDatePicker.getYear() + mDatePicker.getMonth()+1 + mDatePicker.getDayOfMonth() + "]"); } }); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void writeFile(String data){ //エラー判定 if(String.valueOf(mAnniversaryEditText.getText()).equals("")){ Toast.makeText(getApplicationContext(),"記念名を入力してください",Toast.LENGTH_SHORT).show(); return; }else if(String.valueOf(mAnniversaryEditText.getText()).startsWith("[") || String.valueOf(mAnniversaryEditText.getText()).startsWith("]")){ Toast.makeText(getApplicationContext(),"申し訳ございません「[」又は「]」は使用できません",Toast.LENGTH_SHORT).show(); return; } if(mDatePicker.getYear() == 0){ Toast.makeText(getApplicationContext(),"記念日を入力してください",Toast.LENGTH_SHORT).show(); return; } BufferedWriter writer; Log.d("AnniversaryAddDel...",data); try { writer = new BufferedWriter(new OutputStreamWriter(openFileOutput(LOCAL_FILE, MODE_PRIVATE|MODE_APPEND), "UTF-8")); //追記する if(data != null) { writer.append(data); writer.newLine(); writer.close(); }else{ Toast.makeText(getApplicationContext(),"記念日を入力してください",Toast.LENGTH_SHORT); } } catch (IOException e) { e.printStackTrace(); finish(); } finish(); } }
package com.model; public class slevel { private String jlid; private String zlmj; private String zlmc; private String dah; private String remark; private String endtime; public String getJlid() { return jlid; } public void setJlid(String jlid) { this.jlid = jlid; } public String getZlmj() { return zlmj; } public void setZlmj(String zlmj) { this.zlmj = zlmj; } public String getZlmc() { return zlmc; } public void setZlmc(String zlmc) { this.zlmc = zlmc; } public String getDah() { return dah; } public void setDah(String dah) { this.dah = dah; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } }
package com.sky.dataapplication.view.basic_view; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; /** * Created by Starr on 2017/8/8. */ public class BasicSkyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setBarBg(); } private void setBarBg(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // getWindow().setBackgroundDrawableResource(R.mipmap.window_bg); getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); getWindow().setStatusBarColor(Color.TRANSPARENT); } } }
package org.prk.service; import java.util.ArrayList; import java.util.List; import org.prk.domain.User; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { private static List<User> userList = new ArrayList<User>(); @Override public void addUser(User user) { userList.add(user); } @Override public boolean validateUser(User user) { return userList.contains(user); } }
package behavioral.chain_of_responsibility; public class HandlerB extends AHandler{ @Override public void handle(int request) { if (request>=10&&request<=20) { System.out.println("HandlerB:"+String.valueOf(request)); }else { System.out.println("Out:"+String.valueOf(request)); } } }
package com.herokuapp.desafioamedigital.service.impl; import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader; import com.herokuapp.desafioamedigital.feign.SwapiClient; import com.herokuapp.desafioamedigital.template.CommonTemplateLoader; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.util.ReflectionTestUtils; import javax.servlet.http.HttpServletRequest; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; public class SwapiServiceImplTest { @InjectMocks private SwapiServiceImpl service; @Mock private SwapiClient swapiClient; @Mock private HttpServletRequest request; @BeforeClass public static void loadTemplates() { FixtureFactoryLoader.loadTemplates(CommonTemplateLoader.FIXTURE_FACTORY_BASE_PACKAGE); } @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void putRequestURL_page() { String url = "http://localhost:8080/v1/planeta/"; doReturn(new StringBuffer(url)).when(this.request).getRequestURL(); String swapiUrl = "https://swapi.co/api/planets/?page=2"; String requestURL = ReflectionTestUtils.invokeMethod(service, "putRequestURL", swapiUrl); String expect = swapiUrl.replaceAll("https://swapi.co/api/planets/", url); assertThat(expect, equalTo(requestURL)); } @Test public void putRequestURL_page_search() { String url = "http://localhost:8080/v1/planeta/"; doReturn(new StringBuffer(url)).when(this.request).getRequestURL(); String swapiUrl = "https://swapi.co/api/planets/?page=2&search=a"; String requestURL = ReflectionTestUtils.invokeMethod(service, "putRequestURL", swapiUrl); String expect = swapiUrl.replaceAll("https://swapi.co/api/planets/", url); assertThat(expect, equalTo(requestURL)); } }
package com.allmsi.plugin.flow.dao; import com.allmsi.plugin.flow.model.FlowInstanceState; public interface FlowInstanceStateMapper { int insertSelective(FlowInstanceState record); FlowInstanceState selectByInstanceId(String instanceId); int updateByPrimaryKeySelective(FlowInstanceState record); }
package p1; import com.netflix.discovery.EurekaClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ArticleController { @Autowired private RestTemplate restTemplate; @GetMapping("/article /callHello") public String callHello() { return restTemplate.getForObject("http://sa:sa@localhost:8081/user/hello", String.class); } @GetMapping("/article/callHello2") public String callHello2() { return restTemplate.getForObject("http://sa:sa@eureka-client-user-service/user/hello", String.class); } //@Autowired //@Qualifier(value = "eurekaClient") private EurekaClient eurekaClient; //@GetMapping("/article/infos") public Object serviceUrl() { return eurekaClient.getInstancesByVipAddress("eureka-client-user-service", false); } }
package com.java.locks.base; import java.util.concurrent.CountDownLatch; /** * 伪代码共享的问题 */ public class Test08 { public static void main(String[] args) throws InterruptedException { // long start = System.currentTimeMillis(); long start = System.nanoTime(); ; testShare(); System.out.println(System.nanoTime() - start); } private static void testShare() throws InterruptedException { int len = 10; //一个含有特定大小的数组 Sub[] longs = new Sub[len]; // 状态减少标识 CountDownLatch count = new CountDownLatch(len); for (int i = 0; i < len; i++) { int index = i; new Thread(() -> { //new出对象 Sub sub = new Sub(); //这里是取出对象 进行操作 我这里只是简单的 做了一个赋值操作 sub.A = index; longs[index] = sub; count.countDown(); }).start(); } //等所有线程 执行完后 执行下面的操作 count.await(); } // @Contended//方法二 使用注解 用来填充缓冲行 private static class Sub { //803640538 //未填充 缓存行 可能存在多个数据 //404105045 //填充缓存行 private long A = 12; //方法一 字节计算 填充剩余缓冲行 // private long a, b, c, d, e; } }
package main; import java.io.*; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import xml.AnticedentStringCreator; import xml.ConsequentStringCreator; import xml.EventListCreator; import xml.FileData; import xml.InputXml; import data.InputDataType; import eventlist.Event; import fileparser.FileParser; public class BatchCreateXML4DRBARMS { public static void main(String[] args) throws IOException { String configfile = null; String outputDir = null; String csvfile = null; List<InputDataType> dataSet = null; File f = null; List<FileData> multi_params = null; InputXml inputXML = null; List<Event> events = null; csvfile = "../data/xml_gen/input/SHIPS_MiningRI1982_2013.csv"; String configcsvFile = "../data/ships_drbarmsl_configuration.csv"; outputDir = "../data/xml_gen/output/ships_DRBARMS/"; multi_params = FileParser.parseCSVFile(configcsvFile); for (FileData params : multi_params) { dataSet = new ArrayList<InputDataType>(); for (InputDataType idt : params.getConsequentList()) { dataSet.add(idt); } for (InputDataType idt : params.getAnticedentList()) { dataSet.add(idt); } inputXML = new InputXml(); inputXML.createUserInput(params.getMinFreq(), params.getMinRelativeDensity(),params.getMinConf(), params.getAntWidth(), params.getConsWidth(), params.getLagWidth(), params.getEpisodeType(), Boolean.valueOf(params.getAllowRepeats())); String anteString = AnticedentStringCreator.anticedentStringCreator(dataSet); //String conseString = ConsequentStringCreator.consequentStringCreator(dataSet); String conseString = "2"; events = EventListCreator.createEventList(csvfile, dataSet); inputXML.createAnticedent(anteString); inputXML.createConsequent(conseString); inputXML.createRuleTypeAndLagType(params.getRuleType(), params.getLagType()); inputXML.createEventList(events); String outfileName = params.getMinFreq()+ "(mindensity)_" + params.getMinRelativeDensity()+ "(minrelativedensity)_" + params.getMinConf()+ "(minconf)_" + params.getAntWidth()+ "(antwidth)_" + params.getConsWidth()+ "(conswidth)_" + params.getLagWidth()+ "(lagwidth)_" + params.getEpisodeType() + "(episodetype)_" + params.getAllowRepeats() + "(allowrepeat)_" + params.getLagType() + "(lagtype).xml"; f = new File(outputDir + outfileName); inputXML.createParams(f); System.out.println("file created"); } } }
package com.phoenix.utils; enum Color { RED, GREEN; }
package br.mpac.dados; import javax.ejb.Stateless; import br.mpac.entidade.Assunto; @Stateless public class AssuntoDao extends GenericDao<Assunto> { public AssuntoDao() { super(Assunto.class); } }
package com.example.demo.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * 日期工具类. */ public final class DateUtils { /** 所有地方可用 */ public final static String YYYY_MM_DD_HH_mm_ss = "yyyy-MM-dd HH:mm:ss"; public final static String YYYY_MM_DD_HH_mm_ss_SSS = "yyyy-MM-dd HH:mm:ss SSS"; /** Activiti流程中专用 */ public final static String YYYY_MM_DD_T_HH_mm_ss = "yyyy-MM-dd'T'HH:mm:ss"; /** 所有地方可用 */ public final static String YYYY_MM_DD = "yyyy-MM-dd"; public final static String CST = "EEE MMM dd HH:mm:ss 'CST' yyyy"; public final static String YYYY_MM_DD_ZN_CH = "yyyy年MM月dd日"; /** The Constant LOGGER. */ private final static Logger LOG = LoggerFactory.getLogger(DateUtils.class); /** * Gets the server time. * * @return the server time */ public static long getServerTime() { return System.currentTimeMillis(); } /** * 格式化日期,默认返回yyyy-MM-dd HH:mm:ss. * * @param date * the date * @return the string */ public static String format(Date date) { return format(date, DateUtils.YYYY_MM_DD_HH_mm_ss); } /** * 格式化显示当前日期. * * @param format * the format * @return the string */ public static String format(String format) { return format(new Date(), format); } /** * 日期格式化. * * @param date * the date * @param format * the format * @return the string */ public static String format(Date date, String format) { if (date == null) return null; try { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } catch (Exception e) { LOG.warn("日期格式化失败.{}", e.getMessage()); } return null; } /** * 时间格式化, 传入毫秒. * * @param time * the time * @return the string */ public static String dateFormat(long time) { return format(new Date(time), DateUtils.YYYY_MM_DD_HH_mm_ss); } /** * 日期字符串从旧格式转换为新格式. * * @param dateStr * the date str * @param oldFromat * the old fromat * @param newFormat * the new format * @return the string */ public static String format(String dateStr, String oldFromat, String newFormat) { try { if (dateStr == null || "".equals(dateStr)) { return null; } SimpleDateFormat sdf1 = new SimpleDateFormat(oldFromat); Date date = sdf1.parse(dateStr); return format(date, newFormat); } catch (Exception e) { LOG.warn("日期格式化转换失败.{}", e.getMessage()); } return null; } /** * 日期字符串转换为Calendar对象. * * @param dateStr * the date str * @param dateStrFormat * the date str format * @return the calendar */ public static Calendar format(String dateStr, String dateStrFormat) { try { if (dateStr == null || "".equals(dateStr)) { return null; } SimpleDateFormat sdf = new SimpleDateFormat(dateStrFormat); Date date = sdf.parse(dateStr); Calendar ca = GregorianCalendar.getInstance(); ca.setTime(date); return ca; } catch (Exception e) { LOG.warn("日期格式化转换失败.{}", e.getMessage()); } return null; } /** * 日期字符串转换为Calendar对象. * * @param dateStr * the date str * @param dateStrFormat * the date str format * @return the calendar */ public static Calendar formatCalendar(Date date) { try { if (date == null) { return null; } Calendar ca = GregorianCalendar.getInstance(); ca.setTime(date); return ca; } catch (Exception e) { LOG.warn("日期格式化转换失败.{}", e.getMessage()); } return null; } /** * 日期字符串转换为Date对象. * * @param dateStr * the date str * @param dateStrFormat * the date str format * @return the date */ public static Date dateStr2Date(String dateStr, String dateStrFormat) { try { if (dateStr == null || "".equals(dateStr)) { return null; } SimpleDateFormat sdf = new SimpleDateFormat(dateStrFormat); return sdf.parse(dateStr); } catch (Exception e) { LOG.warn("日期格式化转换失败.{}", e.getMessage()); } return null; } /** * 增加日期的天数. * * @param date * the date * @param amount * the amount * @return the date * @createTime 2014-5-22 下午11:49:56 */ public static Date addDays(Date date, int amount) { return add(date, Calendar.DAY_OF_MONTH, amount); } /** * Adds the hours. * * @param date * the date * @param amount * the amount * @return the date */ public static Date addHours(Date date, int amount) { return add(date, Calendar.HOUR_OF_DAY, amount); } /** * Adds the seconds. * * @param date * the date * @param amount * the amount * @return the date */ public static Date addSeconds(Date date, int amount) { return add(date, Calendar.SECOND, amount); } /** * Adds the. * * @param date * the date * @param field * the field * @param amount * the amount * @return the date */ private static Date add(Date date, int field, int amount) { if (null == date) { return null; } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(field, amount); return cal.getTime(); } /** * 格式化日期字符串为日期时间字符串,以0点0时0分开始。例如:2012-04-14 格式化为2012-04-14 00:00:00 * * @param dateStr * the date str * @return the string */ public static String formatDate2DateTimeStart(String dateStr) { Calendar calendar = DateUtils.format(dateStr, DateUtils.YYYY_MM_DD); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return format(calendar.getTime()); } /** * 格式化日期字符串为日期时间字符串,以23点59时59分结束。例如:2012-04-14 格式化为2012-04-14 23:59:59 * * @param dateStr * the date str * @return the string */ public static String formatDate2DateTimeEnd(String dateStr) { Calendar calendar = DateUtils.format(dateStr, DateUtils.YYYY_MM_DD); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); return format(calendar.getTime()); } /** * 格式化日期字符串为日期时间字符串,以0点0时0分开始。例如:2012-04-14 格式化为2012-04-14 00:00:00 * * @param date * the date str * @return the string */ public static Date formatDate2DateTimeStart(Date date) { if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(); } /** * 格式化日期字符串为日期时间字符串,以23点59时59分结束。例如:2012-04-14 格式化为2012-04-14 23:59:59 * @param date * param date str * @return the string */ public static Date formatDate2DateTimeEnd(Date date) { if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); return calendar.getTime(); } public static boolean isEarlyThan(Date d1, Date d2) { if (d1 != null && d2 != null) { Calendar c1 = Calendar.getInstance(); c1.setTime(d1); Calendar c2 = Calendar.getInstance(); c2.setTime(d2); return c1.before(c2); } return false; } /** * 日期格式化 返回格式 yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static Date formatDateStr2Date(String date) { return DateUtils.dateStr2Date(date, DateUtils.YYYY_MM_DD_HH_mm_ss); } public static Date getCurrentDate() { return new Date(); } public static String getTodayStr() { return format(new Date(), YYYY_MM_DD); } public static Date getTodayMinTime() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 1); return c.getTime(); } public static Date getTodayMaxTime() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); return c.getTime(); } public static String convertDateYMString2(Date date) { String s = null; if (date != null) { SimpleDateFormat sdf_YYYYMMDDHMS = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒"); s = sdf_YYYYMMDDHMS.format(date); } return s; } public static Date addMonths(Date date, int amount) { return add(date, Calendar.MONTH, amount); } private DateUtils() { } }
/* * 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 aesdes; /** * * @author tonis */ //librerias wiiiii que hagan todo por mi *w* import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; //para poder hacer el cifrado import javax.crypto.spec.SecretKeySpec; //para poder realizar las subllaves del algoritmo import java.util.*; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import sun.misc.BASE64Encoder; public class AES { //ahora el objeto de cifrado Cipher cifrado; public void AES(){ } public void Cifrar(String contra, String texto) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, FileNotFoundException, IOException{ String llavesimetrica = /*entrada.nextLine()*/contra; //ahora vamos a crear las subllaves a traves del uso de la clase //SecretKeySpec SecretKeySpec key = new SecretKeySpec(llavesimetrica.getBytes(), "AES"); //se debe de tener el tipo de instancia del cifrado que en este caso es AES cifrado = Cipher.getInstance("AES"); //comenzar por el metodo de cifrado cifrado.init(Cipher.ENCRYPT_MODE, key); System.out.println("Ingresa el mensaje a cifrar: "); String mensaje = /*entrada.nextLine()*/texto; //ahora necesitamos almacenar el mensaje en un bloque de bytes byte[] campoCifrado = cifrado.doFinal(mensaje.getBytes()); //vamos a visualizar el mensaje cifrado System.out.println("Mensaje cifrado: " + campoCifrado); //vamos a transformarlo en una cadena System.out.println("Mensaje en cadena: " + new String(campoCifrado)); //para poder entender el mensaje cifrado en caracteres es necesario codificarlo String base64 = new BASE64Encoder().encode(campoCifrado); System.out.println("Mensaje cifrado entendible: " + base64); byte[] buffer = new byte[1000]; byte[] bufferCifrado; //vamos a generar el archivo FileInputStream in = new FileInputStream("AES.txt"); FileOutputStream out = new FileOutputStream("AES.txt"+".cifrado"); //tenemos que empezar por la lectura del archivo y converlo en bytes int bytesleidos = in.read(buffer, 0, 1000); while (bytesleidos != -1) { bufferCifrado = cifrado.update(buffer, 0, bytesleidos); out.write(bufferCifrado); bytesleidos = in.read(buffer, 0, bytesleidos); } //cuando termine de leer el archivo bufferCifrado = cifrado.doFinal(); //escribir el archivo de salida out.write(bufferCifrado); in.close(); out.close(); } public void Descifrar(String contra)throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException{ String llavesimetrica = /*entrada.nextLine()*/ contra; //ahora vamos a crear las subllaves a traves del uso de la clase //SecretKeySpec SecretKeySpec key = new SecretKeySpec(llavesimetrica.getBytes(), "AES"); //String mensaje = /*entrada.nextLine()*/texto; /*byte[] campoCifrado = cifrado.doFinal(mensaje.getBytes()); //ahora vamos a decifrar */ cifrado = Cipher.getInstance("AES"); cifrado.init(Cipher.DECRYPT_MODE, key); /* //necesito un arreglo que se encargue de almacenar el mensaje cifrado //a descifrar byte[] mensajeDescifrado = cifrado.doFinal(campoCifrado); System.out.println("Mensaje descifrado: " + mensajeDescifrado); //dandole formato de cadena String mensaje_claro = new String(mensajeDescifrado); System.out.println("Mensaje descifrado en cadena: " + mensaje_claro);*/ byte[] buffer = new byte[1000]; byte[] bufferPlano; //vamos a generar el archivo FileInputStream in = new FileInputStream(/*args[0]*/"AES.txt" + ".cifrado"); FileOutputStream out = new FileOutputStream(/*args[0]*/"AES.txt" + ".descifrado"); //tenemos que empezar por la lectura del archivo y converlo en bytes int bytesleidos = in.read(buffer, 0, 1000); while (bytesleidos != -1) { bufferPlano = cifrado.update(buffer, 0, bytesleidos); out.write(bufferPlano); bytesleidos = in.read(buffer, 0, bytesleidos); } //cuando termine de leer el archivo bufferPlano = cifrado.doFinal(); //escribir el archivo de salida out.write(bufferPlano); in.close(); out.close(); } }
package cz.dix.alg.knapsack; import cz.dix.alg.genetics.GeneticsAlgorithm; import cz.dix.alg.genetics.Output; import cz.dix.alg.genetics.strategy.impl.*; import java.text.DecimalFormat; import java.util.List; /** * Tests the knapsack algorithms. * * @author Zdenek Obst, zdenek.obst-at-gmail.com */ public class KnapsackTest { private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#0.000"); public static void main(String[] args) { int runs = 10; int itemsCnt = 50; int instancesCnt = 1; int maxWeight = 50; int maxValue = 100; double weightsToCapacityRatio = 0.4; int granularityFactor = 0; InstancesGenerator instancesGenerator = new InstancesGenerator(itemsCnt, instancesCnt, maxWeight, maxValue, weightsToCapacityRatio, granularityFactor); List<KnapsackInput> inputs = instancesGenerator.generateInputs(); KnapsackInput input = inputs.get(0); int populationSize = 500; int tournamentSize = 3; int generationsCnt = 10; double pairingProbability = 0.7; double mutationProbability = 0.3; double relErrorsSum = 0; double lowestSecs = Double.MAX_VALUE; int finishedRuns = 0; for (int run = 0; run < runs; run++) { GeneticsAlgorithm algorithm = new GeneticsAlgorithm.Builder() .pairingProbability(pairingProbability) .mutationProbability(mutationProbability) .selectionStrategy(new TournamentSelectionStrategy(tournamentSize)) .partnerSelectionStrategy(new RandomPartnerSelectionStrategy()) .pairingStrategy(new OnePointPairingStrategy()) .replacementStrategy(new WorstReplacementStrategy()) .restrictionStrategy(new DeathRestrictionStrategy()) .mutationStrategy(new RandomPartMutationStrategy()) .endingStrategy(new GenerationsCountEndingStrategy(generationsCnt)) .population(new KnapsackPopulation(input, populationSize)) .build(); Output output = algorithm.solve(); if (output != null) { double secs = ((double) output.getElapsedTime()) / 1000; if (secs < lowestSecs) { lowestSecs = secs; } KnapsackDynaProgAlgorithm dpAlg = new KnapsackDynaProgAlgorithm(input); Output optimum = dpAlg.solve(); System.out.println("Gen: " + output); System.out.println("Opt: " + optimum); System.out.println("-----------------------------------"); double relError = ((double) (optimum.getFitness() - output.getFitness())) / optimum.getFitness(); relErrorsSum += relError; finishedRuns++; } } double relErrorAvg = relErrorsSum / finishedRuns; System.out.println("Runs: (finished/total): " + finishedRuns + "/" + runs); System.out.println("Average relative error of finished runs: " + DECIMAL_FORMAT.format(relErrorAvg * 100) + "%"); System.out.println("Lowest time of finished runs: " + DECIMAL_FORMAT.format(lowestSecs) + "s"); } }
package stepdef; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.java.After; import cucumber.api.java.Before; import runnerclass.ObjectRepo; public class Hooks extends ObjectRepo { @Before public void start() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Shruthi Keerthi\\eclipse-workspace\\MavenSample\\src\\test\\resources\\drivers\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @After public void close() { driver.close(); } }
package com.datagraph.common.exception; /** * Created by Denny Joseph on 6/1/16. */ public class JobException extends Exception { public JobException(String msg) { super(msg); } }
package com.ymhd.mifei.sign; import java.io.IOException; import java.text.ParseException; import com.example.mifen.R; import com.ymhd.mifen.http.APP_url; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import net.sf.json.JSONException; import net.sf.json.JSONObject; @SuppressLint("HandlerLeak") public class signin extends Fragment { private View view, view2, view3; private LinearLayout linformore,li2; private ImageView more, more2; private Button sign_login_btn; private EditText edt_signuser,edt_signpassword; private String user_name,password; private SharedPreferences sp; SharedPreferences.Editor editor; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub super.onViewCreated(view, savedInstanceState); view = inflater.inflate(R.layout.signin, container, false); linformore = (LinearLayout) view.findViewById(R.id.linformore); view3 = inflater.inflate(R.layout.signin3, container, false); view2 = inflater.inflate(R.layout.signin2, container, false); linformore.addView(view2); more = (ImageView) view2.findViewById(R.id.more); li2 = (LinearLayout) view2.findViewById(R.id.li2); more2 = (ImageView) view3.findViewById(R.id.more2); li2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub linformore.removeAllViews(); Log.e("1", "1"); linformore.addView(view3); Log.e("2", "2"); } }); more2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.e("2", "2"); linformore.removeAllViews(); linformore.addView(view2); } }); init(); return view; } public void init() { sign_login_btn = (Button) view.findViewById(R.id.sign_login_btn); edt_signuser = (EditText) view.findViewById(R.id.signin_user); edt_signpassword = (EditText) view.findViewById(R.id.signin_password); sp = getActivity().getSharedPreferences("token&refreshtoken", Context.MODE_PRIVATE); editor = sp.edit(); sign_login_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub user_name = edt_signuser.getText().toString(); password = edt_signpassword.getText().toString(); logintask lo = new logintask(); lo.execute(); } }); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); JSONObject res_j = (JSONObject) msg.obj; if(res_j.getString("token_type").equals("bearer")) { Log.e("111", "success"); editor.putBoolean("stype", false); editor.putString("logintoken", res_j.getString("access_token")); editor.commit(); getActivity().finish(); } } }; /** * ${TODO} <登录验证的线程> */ Runnable runnable = new Runnable(){ @Override public void run() { String st_bearertoken; JSONObject js = null; APP_url ap = new APP_url(); Message msg = handler.obtainMessage(); try { st_bearertoken = sp.getString("token",""); js = ap.Login(st_bearertoken, user_name, password); msg.obj = js; handler.sendMessage(msg); handler.removeCallbacks(runnable); } catch (JSONException | ParseException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; class logintask extends AsyncTask<Void, Void, String> { public logintask() { } @Override protected String doInBackground(Void... arg0) { // TODO Auto-generated method stub new Thread(runnable).start(); return ""; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); } } }
package com.kheirallah.inc.amazon; /* You are given an undirected connected graph. An articulation point (or cut vertex) is defined as a vertex which, when removed along with associated edges, makes the graph disconnected (or more precisely, increases the number of connected components in the graph). The task is to find all articulation points in the given graph. Input: The input to the function/method consists of three arguments: numNodes, an integer representing the number of nodes in the graph. numEdges, an integer representing the number of edges in the graph. edges, the list of pair of integers - A, B representing an edge between the nodes A and B. Output: Return a list of integers representing the critical nodes. Example: Input: numNodes = 7, numEdges = 7, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [2, 5], [5, 6], [3, 4]] Output: [2, 3, 5] */ import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class CriticalRouters { //Time Complexity O(vertices * edges) private static List<Integer> criticalNodes(int[][] edges, int numNodes, int numEdges) { List<Integer> criticalNodes = new ArrayList<>(); for (int i = 0; i < numNodes; i++) { HashSet<Integer> visitedNodes = new HashSet<>(); boolean firstAdd = false; for (int j = 0; j < numEdges; j++) { //ignore edges that have the starting node as a starting or ending point if (edges[j][0] == i || edges[j][1] == i) { continue; } //adding any edge as the starting point, both vertices will fail if the edges are self edges if (!firstAdd) { visitedNodes.add(edges[j][0]); visitedNodes.add(edges[j][1]); firstAdd = true; } //if the next edge has one of the edges already in the set of visitedNodes, I can visit it if (visitedNodes.contains(edges[j][0]) || visitedNodes.contains(edges[j][1])) { visitedNodes.add(edges[j][0]); visitedNodes.add(edges[j][1]); } } if (visitedNodes.size() != numNodes - 1) { criticalNodes.add(i); } } return criticalNodes; } public static void main(String[] args) { int[][] edges = new int[][]{{0, 1}, {0, 2}, {1, 3}, {2, 3}, {2, 5}, {5, 6}, {3, 4}}; for (int[] edge : edges) { for (Integer value : edge) { System.out.print(value + " "); } System.out.println(); } int numNodes = 7; //amount of vertices or routers in this case int numEdges = 7; System.out.println(criticalNodes(edges, numNodes, numEdges)); } }
package com.gagetalk.gagetalkcustomer.fragment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.gagetalk.gagetalkcustomer.R; import com.gagetalk.gagetalkcustomer.adapter.MenuAdapter; import com.gagetalk.gagetalkcommon.constant.ConstValue; import com.gagetalk.gagetalkcustomer.data.MenuData; import com.gagetalk.gagetalkcommon.util.CustomToast; import java.util.ArrayList; /** * Created by hyochan on 3/28/15. */ public class HelpFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener{ private static final String TAG = "HelpFragment"; private Activity activity; private Context context; private ImageView imgHamburger; private TextView txtTitle; private ListView listHelp; public interface HamburgerBtnClick { void onHamburgerBtnClick(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.help_fragment, container, false); activity = getActivity(); context = getActivity().getApplicationContext(); imgHamburger = (ImageView) view.findViewById(R.id.img_hamburger); txtTitle = (TextView) view.findViewById(R.id.txt_title); txtTitle.setText(context.getResources().getString(R.string.help)); listHelp = (ListView) view.findViewById(R.id.list_help); // 1. setup data String[] arrayHelp = getResources().getStringArray(R.array.array_help); String[] arrayHelpMore = getResources().getStringArray(R.array.array_help_more); ArrayList<MenuData> arrayCustom = new ArrayList<>(); for(int i=0; i<arrayHelp.length; i++){ arrayCustom.add(new MenuData( arrayHelp[i], arrayHelpMore[i] )); } // 2. setup adapter MenuAdapter menuAdapter = new MenuAdapter(context, R.layout.custom_adapter, arrayCustom); // 3. bind to listview listHelp.setAdapter(menuAdapter); listHelp.setOnItemClickListener(this); imgHamburger.setOnClickListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.img_hamburger: ((HamburgerBtnClick) activity).onHamburgerBtnClick(); break; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()){ case R.id.list_help: switch (position){ case ConstValue.HELP_GUIDE_POS: CustomToast.getInstance(context).createToast("이용 안내"); break; case ConstValue.HELP_MOST_QUESTION_POS: CustomToast.getInstance(context).createToast("자주 묻는 질문"); break; case ConstValue.HELP_CONTACT_POS: CustomToast.getInstance(context).createToast("연락하기"); break; case ConstValue.HELP_ABOUT_POS: CustomToast.getInstance(context).createToast("ABOUT"); break; } break; } } }
package com.fhsoft.model; import java.util.List; /** * @ClassName:com.fhsoft.model.PaperModel * @Description: * * @Author:liyi * @Date:2015年12月1日上午11:04:48 * */ public class PaperModel { private String paperTitle; private String paperNote; private String paperAuthor; private String parperAnswerTime; private int productId; private int subject; private List<QstTypeModel> typeList; public String getPaperTitle() { return paperTitle; } public void setPaperTitle(String paperTitle) { this.paperTitle = paperTitle; } public String getPaperNote() { return paperNote; } public void setPaperNote(String paperNote) { this.paperNote = paperNote; } public String getPaperAuthor() { return paperAuthor; } public void setPaperAuthor(String paperAuthor) { this.paperAuthor = paperAuthor; } public String getParperAnswerTime() { return parperAnswerTime; } public void setParperAnswerTime(String parperAnswerTime) { this.parperAnswerTime = parperAnswerTime; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public List<QstTypeModel> getTypeList() { return typeList; } public void setTypeList(List<QstTypeModel> typeList) { this.typeList = typeList; } public int getSubject() { return subject; } public void setSubject(int subject) { this.subject = subject; } }
package cn.kgc.service.impl; import cn.kgc.dao.TakeoutMapper; import cn.kgc.domain.Takeout; import cn.kgc.service.TakeOutService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TakeOutImpl implements TakeOutService { @Autowired private TakeoutMapper takeoutMapper; @Override public int insertIntoTakeOut(Takeout takeout) { return takeoutMapper.insertSelective(takeout); } }
package testmodel; import java.io.Serializable; public class Pupil implements Serializable { private static final long serialVersionUID = 1L; private String fullName; public Pupil(String fullName) { this.fullName = fullName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } }
package jianzhioffer; import java.util.ArrayList; import java.util.HashMap; /** * @ClassName : S50_FirstRepeatingChar * @Description : 第一个只出现1次的字符 * @Date : 2019/3/11 17:03 */ public class Solution50 { public static void main(String [] args){ // System.out.println(FirstNotRepeatingChar("ccaaabc")); System.out.print(FirstNotRepeatingChar2("ccaaabc")); } // 优秀大佬的做法,但是不正确 public static int FirstNotRepeatingChar(String str) { if (str==null||str.length()==0) return -1; //位置0有点奇怪 ArrayList<Character> list=new ArrayList<>(); for(int i=0;i<str.length();i++){ char ch = str.charAt(i); if(!list.contains(ch)){ list.add(Character.valueOf(ch)); }else{ list.remove(Character.valueOf(ch)); } } if(list.size() <=0) return -1; return str.indexOf(list.get(0)); } // 按书上的做法写的,通过牛客网测试,52ms // 第一次遍历,统计各个字符出现的次数 // 第二次遍历,获得第一个出现1次的字符所在位置 public static int FirstNotRepeatingChar2(String str) { if (str==null||str.length()==0) return -1; //位置0有点奇怪 HashMap<Character,Integer> map=new HashMap<>(); for (int i=0;i<str.length();++i){ if (map.containsKey(str.charAt(i))) { int val = map.get(str.charAt(i)); map.put(str.charAt(i),++val); }else{ map.put(str.charAt(i),1); } } for (int i=0;i<str.length();++i){ if (map.get(str.charAt(i))==1) return i; } return -1; } }
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.status; import java.io.Serializable; /** * @author douglas * @since 20/03/2017 */ public class StatusCreditDTO implements Serializable { private static final long serialVersionUID = -126613989931625508L; private Integer id; private String status; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.reacheng.rc.entity; import lombok.Data; import javax.persistence.*; import java.util.Date; @Data @Entity @Table(name = "t_project") public class Project { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "project_name") private String projectName; @Column(name = "create_time") private Date createTime; }
public interface AccountInter { public void create( int accNo, String name, double accBal );// – method to create an account public double delete( int accNo );// – method to delete an account passed as parameter public void print ( int accNo );// – method to print details of an account passed as parameter }
package codePlus.AGBasic2.BruteForce; import java.util.*; public class No_1476 { public static void main(String[] args) { //전체 경우의 수 = 15*28*19=7980 Scanner scn = new Scanner(System.in); int E = scn.nextInt(); int S = scn.nextInt(); int M = scn.nextInt(); int e=1, s=1, m=1; for(int i=1;; i++) { if(e==E && s==S && m==M) { System.out.println(i); break; } //e,s,m 모두 한꺼번에 1증가 e++; s++; m++; if(e==16) { e=1; } if(s==29) { s=1; } if(m==20) { m=1; } } } }
package oopDemot3; public class BSTest{ public static void main(String[] args) { BST<Integer> B = new BST<Integer>(); B.add(1,1); B.print(); B.add(5,5); B.print(); B.add(3,3); B.print(); B.find(3); B.add(42,42); B.add(2021,2021); B.add(364,364); B.add(34,34); B.add(769,769); B.add(6,6); B.print(); } }
package com.zpf.controller; import com.zpf.dto.girl; import com.zpf.dto.girlRepository; import com.zpf.service.GirlService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * Created by LoseMyself * on 2017/3/13 13:46 */ @RestController public class GirlController { @Autowired private girlRepository girlRepository; @Autowired private GirlService girlService; // 查询女生列表 @GetMapping(value= "/girls") public List<girl> girls(){ return girlRepository.findAll(); } // 新增女生列表 @PostMapping(value = "/girls") public girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Long age){ girl girl = new girl().setAge(age).setCupSize(cupSize); return girlRepository.save(girl); } // 查询指定id的女生 @GetMapping(value= "/girls/{id}") public girl girlFindOne(@PathVariable("id") Long id){ return girlRepository.findOne(id); } //更新 @PutMapping(value= "/girls/{id}") public girl update(@PathVariable("id") Long id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Long age ){ girl girl = new girl().setId(id).setCupSize(cupSize).setAge(age); return girlRepository.save(girl); } // 删除 @DeleteMapping(value= "/girls/{id}") public void delete(@PathVariable("id") Long id){ girlRepository.delete(id); } //通过年龄查询女生列表 @GetMapping(value = "/girls/age/{age}") public List<girl> girls(@PathVariable("age") Long age){ return girlRepository.findByAge(age); } @PostMapping(value = "girls/add") public void addTwo(){ girlService.insertTwo(); } }
package org.digdata.swustoj.util; import java.util.ArrayList; import java.util.List; /** * * @author wwhhf * @since 2016年6月13日 * @comment 数组工具 */ public class ArrayUtil { /** * * @author wwhhf * @since 2016年6月13日 * @comment 字符串转为整形list * @param ids * @param symbol * @return */ public static List<Integer> string2IntList(String ids, String symbol) { if (ids == null || "".equals(ids) == true) return null; String s[] = ids.split(symbol); List<Integer> list = new ArrayList<Integer>(); for (int i = 0, length = s.length; i < length; i++) { Integer x = Integer.valueOf(s[i]); if (list.contains(x) == false) list.add(x); } return list; } /** * * @author wwhhf * @since 2016年6月13日 * @comment 字符串转为字符串数组 * @param ids * @param symbol * @return */ public static List<String> string2StrList(String ids, String symbol) { if (ids == null || "".equals(ids) == true) return null; String s[] = ids.split(symbol); List<String> list = new ArrayList<String>(); for (int i = 0, length = s.length; i < length; i++) { if (list.contains(s[i]) == false) list.add(s[i]); } return list; } /** * * @author wwhhf * @since 2016年6月13日 * @comment 拼接字符串 * @param ids * @param symbol * @return */ public static String list2String(List<Integer> ids, String symbol) { StringBuffer sb = new StringBuffer(); for (int i = 0, len = ids.size(); i < len; i++) { if (i == 0) sb.append(ids.get(i)); else { sb.append(symbol).append(ids.get(i)); } } return sb.toString(); } }
package com.mou.mvvmmodule.util; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.text.TextUtils; import java.io.File; import java.util.List; import androidx.core.content.FileProvider; /** * @version V1.0 * @FileName: AppUtil.java * @author: villa_mou * @date: 02-13:48 * @desc: utils about app */ public final class AppUtils { private static final int M_BYTE = 1024 * 1024; /** * 获取app的名称 */ public static String getAppName(Application app) { if (app == null) return ""; return getAppName(app, app.getPackageName()); } /** * 通过包名获取app名称 */ private static String getAppName(Application app, final String packageName) { if (TextUtils.isEmpty(packageName) || app == null) { return ""; } try { PackageManager pm = app.getPackageManager(); PackageInfo pi = pm.getPackageInfo(packageName, 0); return pi == null ? "" : pi.applicationInfo.loadLabel(pm).toString(); } catch (PackageManager.NameNotFoundException e) { return ""; } } /** * 获取app的icon */ public static Drawable getAppIcon(Application app) { if (app == null) return null; PackageManager pm = app.getPackageManager(); String packageName = app.getPackageName(); if (pm == null || TextUtils.isEmpty(packageName)) return null; try { PackageInfo packageInfo = pm.getPackageInfo(packageName, 0); ApplicationInfo ai = packageInfo.applicationInfo; if (ai == null) return null; return ai.loadIcon(pm); } catch (PackageManager.NameNotFoundException e) { return null; } } /** * 获取app版本名称 */ public static String getAppVersionName(Application app) { if (app == null) return ""; String packageName = app.getPackageName(); if (TextUtils.isEmpty(packageName)) return ""; try { PackageManager pm = app.getPackageManager(); PackageInfo pi = pm.getPackageInfo(packageName, 0); return pi == null ? "" : pi.versionName; } catch (PackageManager.NameNotFoundException e) { return ""; } } /** * 获取app版本号 */ public static int getAppVersionCode(Application app) { if (app == null) return -1; String packageName = app.getPackageName(); if (TextUtils.isEmpty(packageName)) return -1; try { PackageManager pm = app.getPackageManager(); PackageInfo pi = pm.getPackageInfo(packageName, 0); return pi == null ? -1 : pi.versionCode; } catch (PackageManager.NameNotFoundException e) { return -1; } } /** * 获取app的包名 */ public static String getAppPackageName(Application app) { if (app == null) return ""; return app.getPackageName(); } /** * 获取app的最大内存 */ public static long getMaxMemory() { Runtime r = Runtime.getRuntime(); return r != null ? (r.maxMemory() / M_BYTE) : -1; } /** * 获取app的剩余未使用的内存值 */ public static long getUselessMemory() { Runtime r = Runtime.getRuntime(); return (r.maxMemory() - (r.totalMemory() - r.freeMemory())) / M_BYTE; } /** * 根据文件地址安装app */ public static void installApp(Application app, final String filePath) { installApp(app, getFileByPath(filePath)); } /** * 根据文件安装app */ public static void installApp(Application app, final File file) { Intent installAppIntent = getInstallAppIntent(app,file); if (installAppIntent == null || app == null) return; app.startActivity(installAppIntent); } /** * 根据文件uri安装api */ public static void installApp(Application app, final Uri uri) { Intent installAppIntent = getInstallAppIntent(uri); if (installAppIntent == null || app == null) return; app.startActivity(installAppIntent); } /** * 根据包名卸载app */ public static void uninstallApp(Application app, final String packageName) { if (isSpace(packageName) || app == null) return; app.startActivity(getUninstallAppIntent(packageName)); } /** * 根据包名判断app是否安装 */ public static boolean isAppInstalled(Application app, final String pkgName) { if (isSpace(pkgName) || app == null) return false; PackageManager pm = app.getPackageManager(); try { return pm.getApplicationInfo(pkgName, 0).enabled; } catch (PackageManager.NameNotFoundException e) { return false; } } /** * 判断app是否处于后台 */ public static boolean isAppBackground(Application context) { //TODO:有待验证,用lifecycler比较好 ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager .getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equals(context.getPackageName())) { return appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND; } } return false; } /** * 根据文件路径创建文件 */ private static File getFileByPath(final String filePath) { return isSpace(filePath) ? null : new File(filePath); } private static boolean isSpace(final String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } private static Intent getInstallAppIntent(Application app, final File file) { if (!isFileExists(file) || app == null) return null; Uri uri; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { uri = Uri.fromFile(file); } else { //TODO: 需要和清单文件fileprovider的authority保持一次 String authority = app.getPackageName() + ".fileprovider"; uri = FileProvider.getUriForFile(app, authority, file); } return getInstallAppIntent(uri); } public static Intent getInstallAppIntent(final Uri uri) { if (uri == null) return null; Intent intent = new Intent(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(uri, type); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } public static boolean isFileExists(final File file) { return file != null && file.exists(); } private static Intent getUninstallAppIntent(final String pkgName) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + pkgName)); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } }
package kr.ac.pknu.dormitory.controller; public class WeekViewController { }
package org.wuxinshui.boosters.designPatterns.simpleFacthory.moreMethods; /** * Created by FujiRen on 2016/10/30. */ public class Sms implements Sender { @Override public void send() { System.out.println("This is SMS from MORE METHODS"); } }
package com.main; import java.util.Random; import java.util.Scanner; public class PlusOuMoins { private int longNbAleaConf ; //Dans le fichier de conf private int nombreTourConf ; //Dans le fichier de conf private int devMode ; //Dans le fichier de conf /** * Constructeur du jeux Plus ou Moins * @param longNbAleaConf longeur du nombre à trouver, passer dans config.properties * @param nombreTourConf nombre de tour possible, passer dans config.properties * @param devMode Mode developpeur activé ou non, passer dans config.properties */ public PlusOuMoins(int longNbAleaConf, int nombreTourConf, int devMode) { this.longNbAleaConf = longNbAleaConf; this.nombreTourConf = nombreTourConf; this.devMode = devMode; } /** * Cette méthode permet de générer la réponse en fonction de la réponse de l'utilisateur * * @param longNbAleaConf passé dans le fichier conf, longueur du nombre à trouvé * @param choix c'est la réponse rentré par l'utilisateur * @param nbAlea ce nombre est généré aléatoirement (dans Tools méthode geneNbAlea) * @param reponse réponse généré par l'ordinateur (avec les signes =+-) * */ private void mainGameChal(int longNbAleaConf, String choix, StringBuilder nbAlea, StringBuilder reponse){ for (int i = 0; i < longNbAleaConf; i++) { int y = Character.getNumericValue(nbAlea.charAt(i)); int z = Character.getNumericValue(choix.charAt(i)); if (y == z) reponse.insert(i, "="); else if (y < z) reponse.insert(i, "-"); else reponse.insert(i, "+"); } //display un message pour la réponse System.out.println("Votre proposition est : " + choix + " -> Réponse : " + reponse); } /** * Méthode du jeux Plus ou Moins dans son mode Challenger, l'utilisateur doit trouver la solution de l'ordinateur */ public void plusOuMoinsChallenger() { boolean replay = true; while (replay == true) { //Boucle utilisé afin de pouvoir rejouer en fin de partie replay = false ; String choix; //Saisie de l'utlisateur StringBuilder reponse = new StringBuilder(); StringBuilder nbAlea = new StringBuilder(); int numeroTour = 0; boolean winLoose; nbAlea = Tools.geneNbAlea(longNbAleaConf, 1, 9); //Génération du nombre aléatoire if (devMode == 1) Tools.devMode(nbAlea); do { reponse.delete(0, reponse.length());//On réinitialise la réponse afin de ne pas mettre bout à bout les réponses //Demande de première saisie utillisateur et boucle pour avoir le bon nombre de chiffre saisi par l'utilisateur numeroTour++; Tools.affichageTour(numeroTour, nombreTourConf); System.out.println("Veuillez saisir un nombre(" + longNbAleaConf + " chiffres)"); choix = Tools.saisieNuméros(longNbAleaConf); mainGameChal(longNbAleaConf, choix, nbAlea, reponse); winLoose = Tools.combinaisonValide(reponse, longNbAleaConf); } while (!winLoose && numeroTour < nombreTourConf); if (!winLoose) System.out.println("Vous avez perdu !"); else System.out.println("Bravo ! Vous avez trouvé la combinaison secrète ! (" + choix + ")"); replay = Menu.finDePArtie(); } } /** *Cette méthode permet de généré un nouveau nombre aléatoire en fonction de la réponse en signe donné par l'utilisateur * * @param longNbAleaConf passé dans le fichier de conf, longueur du nombre à trouver * @param reponseEnSigne réponse avec les signes +,- ou = rentré par l'utilisateur * @param reponseOrdi la réponse précédement généré par l'ordinateur, le passer en paramètre permet de générer un nombre aléatoire compris dans les bonnes bornes * @param r Méthode Random */ private void mainGameDef(int longNbAleaConf, String reponseEnSigne, StringBuilder reponseOrdi, Random r){ for(int i = 0; i < longNbAleaConf; i++) { switch (reponseEnSigne.charAt(i)) { case ('='): break; case ('+'): int z = Character.getNumericValue(reponseOrdi.charAt(i)); int geneNbAleaz = z + r.nextInt((9+1) - z); reponseOrdi.deleteCharAt(i); reponseOrdi.insert(i, geneNbAleaz); break; case ('-'): int y = Character.getNumericValue(reponseOrdi.charAt(i)); if (y > 1) { int geneNbAleay = 1 + r.nextInt(y + - 1); reponseOrdi.deleteCharAt(i); reponseOrdi.insert(i, geneNbAleay); break; } else { int geneNbAleay = 1 + r.nextInt((y+1) - 1); reponseOrdi.deleteCharAt(i); reponseOrdi.insert(i, geneNbAleay); } } } } /** * Méthode du jeux Plus ou Moins dans son mode défenseur, l'ordinateur doit trouver la solution de l'utilisateur */ public void plusOuMoinsDefenseur() { boolean replay = true; while (replay == true) { Random r = new Random(); StringBuilder reponseOrdi = new StringBuilder(); //Nombre généré par l'ordinateur StringBuilder reponseEnSigne = new StringBuilder(); String saisieUtilisateur; //Saisie de l'utlisateur String codeSecretUtilisateur; int numeroTour = 0; boolean winLoose; //On récupère le nombre de l'utilisateur que l'ordinateur doit deviner System.out.println("L'ordinateur doit deviner votre combinaison !"); codeSecretUtilisateur = Tools.saisieNuméros(longNbAleaConf); reponseOrdi = Tools.geneNbAlea(longNbAleaConf, 1, 9); //Ici l'ordinateur doit générer une nouvelle réponse en fonction de la variable choix do { numeroTour++; reponseEnSigne.delete(0, reponseEnSigne.length()); Tools.affichageTour(numeroTour, nombreTourConf); //On récupère ici la réponse de l'utilisateur System.out.println("L'ordinateur vous donne comme réponse : " + reponseOrdi); System.out.println("Pour chaque nombre, indiquer + ou - ou = (pour rappel, votre code secret est " + codeSecretUtilisateur + ")"); saisieUtilisateur = Tools.saisieSignes(longNbAleaConf); System.out.println("Vous avez saisi: " + saisieUtilisateur); reponseEnSigne.append(saisieUtilisateur); //On passe en StringBuilder afin de pouvoir utiliser la méthode combinaisonValide dans Tools mainGameDef(longNbAleaConf, saisieUtilisateur, reponseOrdi, r); winLoose = Tools.combinaisonValide(reponseEnSigne, longNbAleaConf); } while (!winLoose && numeroTour < nombreTourConf ); Tools.winLoose(winLoose); replay = Menu.finDePArtie(); } } /** * Méthode du jeux Plus ou Moins dans son mode duel, utilisateur vs ordinateur, chacun doit trouver la solution de l'autre */ public void plusOuMoinsDuel() { boolean replay = true; while (replay == true) { replay = false ; Random r = new Random(); StringBuilder reponseOrdi = new StringBuilder(); //Nombre généré par l'ordinateur StringBuilder reponse = new StringBuilder(); StringBuilder nbAlea = new StringBuilder(); StringBuilder reponseEnSigne = new StringBuilder(); String saisieUtilisateur; //Saisie de l'utlisateur String codeSecretUtilisateur; String choix; //Saisie de l'utlisateur int gagnant; int numeroTour = 0; boolean winLoose; reponseOrdi = Tools.geneNbAlea(longNbAleaConf, 1, 9); //L'ordinateur génère sa première réponse nbAlea = Tools.geneNbAlea(longNbAleaConf, 1, 9); //Génération du nombre que l'utilisateur doit trouver if (devMode == 1) //Condition permettant l'affichage de la solution que l'utilisateur doit trouver en dev mode Tools.devMode(nbAlea); System.out.println("L'odinateur commence !"); //On récupère le nombre de l'utilisateur que l'ordinateur doit deviner System.out.println("Veuillez saisir le nombre que l'ordinateur doit deviner ! (" + longNbAleaConf + " chiffres)"); codeSecretUtilisateur = Tools.saisieNuméros(longNbAleaConf); do { //On incrémente le numéro du tour + display du tour en cours numeroTour++; Tools.affichageTour(numeroTour, nombreTourConf); //L'ordinateur affiche sa première tentative, pour chaque chiffre l'utilisateur indique +, = ou - System.out.println("L'ordinateur vous donne comme réponse : " + reponseOrdi); System.out.println("Pour chaque nombre, indiquer + ou - ou = (pour rappel, votre code secret est " + codeSecretUtilisateur + ")"); saisieUtilisateur = Tools.saisieSignes(longNbAleaConf); System.out.println("Vous avez saisi: " + saisieUtilisateur); mainGameDef(longNbAleaConf, saisieUtilisateur, reponseOrdi, r); //On génère une nouvelle réponse en fonction de la réponse de l'utilisateur reponseEnSigne.delete(0, reponseEnSigne.length()); //On supprime la réponse de l'utilisateur pour la prochaine tentative afin de ne pas mettre bout à bout ses réponses reponseEnSigne.append(saisieUtilisateur); //On passe en Stringbuilder afin de pouvoir utliser la méthode CombinaisonValide dans Tools winLoose = Tools.combinaisonValide(reponseEnSigne, longNbAleaConf); //On regarde si l'ordinateur à gagné if (winLoose) { gagnant = 1; break; } else { System.out.println("A votre tour, à vous de trouver le nombre de l'ordinateur"); reponse.delete(0, longNbAleaConf);//On réinitialise la réponse afin de ne pas mettre bout à bout les réponses //Demande de saisie utillisateur et boucle pour avoir le bon nombre de chiffre saisi par l'utilisateur do { System.out.println("Veuillez saisir un nombre(" + longNbAleaConf + " chiffres)"); choix = Tools.saisieNuméros(longNbAleaConf); } while (choix.length() != longNbAleaConf); mainGameChal(longNbAleaConf, choix, nbAlea, reponse); //On génère la réponse de l'ordinateur en signe. winLoose = Tools.combinaisonValide(reponse, longNbAleaConf);//On regarde si l'utilisateur à gagné gagnant = 2; } }while (!winLoose); Tools.gagnant(gagnant); replay = Menu.finDePArtie(); } } }
package co.sblock.machines; import java.util.HashMap; import java.util.Map; import java.util.UUID; import co.sblock.machines.type.Alchemiter; import co.sblock.machines.type.Machine; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryCloseEvent; import net.minecraft.server.v1_11_R1.BlockPosition; import net.minecraft.server.v1_11_R1.ChatComponentText; import net.minecraft.server.v1_11_R1.Container; import net.minecraft.server.v1_11_R1.ContainerMerchant; import net.minecraft.server.v1_11_R1.EntityHuman; import net.minecraft.server.v1_11_R1.EntityPlayer; import net.minecraft.server.v1_11_R1.EntityVillager; import net.minecraft.server.v1_11_R1.IChatBaseComponent; import net.minecraft.server.v1_11_R1.ItemStack; import net.minecraft.server.v1_11_R1.MerchantRecipe; import net.minecraft.server.v1_11_R1.MerchantRecipeList; import net.minecraft.server.v1_11_R1.PacketPlayOutOpenWindow; import net.minecraft.server.v1_11_R1.World; import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer; /** * brb going insane because of NMS * * @author Jikoo */ public class MachineInventoryTracker { private final Map<UUID, Pair<Machine, Location>> openMachines; private final Machines machines; public MachineInventoryTracker(Machines machines) { this.openMachines = new HashMap<>(); this.machines = machines; } public boolean hasMachineOpen(Player p) { return openMachines.containsKey(p.getUniqueId()); } public Pair<Machine, ConfigurationSection> getOpenMachine(Player p) { if (!openMachines.containsKey(p.getUniqueId())) { return null; } return machines.getMachineByLocation(openMachines.get(p.getUniqueId()).getRight()); } public void closeMachine(InventoryCloseEvent event) { Pair<Machine, Location> pair = openMachines.remove(event.getPlayer().getUniqueId()); if (pair == null) { return; } // Do not drop exp bottle placed in second slot if (pair.getLeft() instanceof Alchemiter) { event.getInventory().setItem(1, null); } } public void openVillagerInventory(Player player, Machine m, Location key) { EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); int containerCounter = nmsPlayer.nextContainerCounter(); Container container = new MerchantContainer(nmsPlayer, key); nmsPlayer.activeContainer = container; container.windowId = containerCounter; container.addSlotListener(nmsPlayer); nmsPlayer.playerConnection.sendPacket(new PacketPlayOutOpenWindow(containerCounter, "minecraft:villager", new ChatComponentText(m.getClass().getSimpleName()), 3)); this.openMachines.put(player.getUniqueId(), new ImmutablePair<Machine, Location>(m, key)); } public class MerchantContainer extends ContainerMerchant { public MerchantContainer(EntityPlayer player, Location location) { super(player.inventory, new FakeNMSVillager(player, player.world, location), player.world); this.checkReachable = false; } } public class FakeNMSVillager extends EntityVillager { public FakeNMSVillager(EntityPlayer player, World world, Location location) { super(world); setTradingPlayer(player); // Set location so that logging plugins know where the transaction is taking place a(new BlockPosition(location.getX(), location.getY(), location.getZ()), -1); } @Override public MerchantRecipeList getOffers(EntityHuman paramEntityHuman) { return new MerchantRecipeList(); } @Override public void a(MerchantRecipe paramMerchantRecipe) { // adds a trade } @Override public void a(ItemStack paramItemStack) { // reduces remaining trades and makes yes/no noises } @Override public IChatBaseComponent getScoreboardDisplayName() { return new ChatComponentText("Machine"); } } }
package com.haku.light.graphics.gl; public abstract class GLObject { public final int id; public GLObject(int id) { this.id = id; } public int getId() { return this.id; } public abstract void bind(); public abstract void unbind(); }
package singleton; public class main { public static void main(String[] args) { DbConnection dbConnection = DbConnection.getInstance(); DbConnection dbConnection1 = DbConnection.getInstance(); dbConnection1.setDatabaseName("Fajna nazwa"); System.out.println(dbConnection.getDatabaseName()); } }
package com.example.innovative; public class Question { public String[] questions ={ " 1. Man-made things that make our work easy are called____________.", " 2. A_____that keeps things cool and is a machine.", " 3. A machine is a _____ thing.", " 4. A computer is a ____ machine.", " 5. Some machines such as car and bus need______,diesel,_____or CNG to run.", " 6. " }; private String[][] choices={ {"Machines","Refrigerator","Home-made","TV"}, {"Refrigerator","House","Cooler","Fan"}, {"Home-made","Man-made","Machines","Gas"}, {"Smart","Electric","Time-pass","Software"}, {"Gas,water","Electricity,petrol","Water","Oil"}, }; public String correctAnswer[]={ "Machines","Refrigerator","Home-made","Smart","Electricity,petrol" }; public String getQuestion(int a){ String question=questions[a]; return question; } public String getchoice1(int a){ String choice=choices[a][3]; return choice; } public String getchoice2(int a){ String choice=choices[a][0]; return choice; } public String getchoice3(int a){ String choice=choices[a][2]; return choice; } public String getchoice4(int a){ String choice=choices[a][1]; return choice; } public String getCorrectAnswer(int a){ String answer=correctAnswer[a]; return answer; } }
package com.wangzhu.jvm; /** * Created by wang.zhu on 2021-03-31 23:25. **/ public class CmsTest { private static final int _1MB = 1024 * 1024; //-Xmx20m -Xms20m -Xmn10m // -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=60 //-XX:CMSMaxAbortablePrecleanTime=1000 -XX:CMSScheduleRemarkEdenPenetration=10 //-XX:+CMSScavengeBeforeRemark // -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:./gclogs public static void main(String[] args) throws Exception { byte[] allocation1 = new byte[2 * _1MB]; byte[] allocation2 = new byte[2 * _1MB]; byte[] allocation3 = new byte[2 * _1MB]; byte[] allocation4 = new byte[7 * _1MB]; System.in.read(); } }
package com.impact; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.impact.model.Task; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class GetTasksHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { private static final Logger LOG = LogManager.getLogger(GetTasksHandler.class); private Connection connection= null; private PreparedStatement preparedStatement=null; private ResultSet resultSet = null; @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) { LOG.info("received"); String userId = request.getPathParameters().get("userId"); List<Task> tasks = new ArrayList<Task>(); try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection( String.format("jdbc:mysql//%s/%s?user=%s&password=%s", "rds-instance-task.chiwvf0mvtlq.eu-west-2.rds.amazonaws.com", "taskdb", "root", "xxxxx") ); preparedStatement = connection.prepareStatement("select * from task where userId=?"); preparedStatement.setString(1,userId); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Task task = new Task(resultSet.getString("taskId"), resultSet.getString("description"), resultSet.getBoolean("completed")); tasks.add(task); } }catch (Exception e){ LOG.error(String.format("Unable to query database for tasks for user %s",userId),e); } finally{ closeConnection(); } APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); response.setStatusCode(200); ObjectMapper objectMapper = new ObjectMapper(); try{ String responsebody = objectMapper.writeValueAsString(tasks); response.setBody(responsebody); } catch (JsonProcessingException e){ LOG.error("Unable to marshall task array",e); } return response; } private void closeConnection(){ try{ if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e){ LOG.error("Unable to close connection to MYSQL - {}",e.getMessage()); } } }
/* Xây dựng class: HinhChuNhat +Thuộc tính (attributs): chiều dài, chiều rộng +Phương thức (methods): -Nhập chiều dài, chiều rộng -Tính chu vi, diện tích -In kết quả */ package oop_ex1; import java.util.Scanner; public class HinhChuNhat { // thuoc tinh (attributes) private float chieuDai; private float chieuRong; // constructor public HinhChuNhat(){ } public HinhChuNhat(float chieuDai, float chieuRong){ this.chieuDai = chieuDai; this.chieuRong = chieuRong; } //phuong thuc (methods) // phuong thuc set, get public void SetChieuDai(float chieuDai){ this.chieuDai = chieuDai; } public float GetChieuDai(){ return chieuDai; } public void SetChieuRong(float chieuRong){ this.chieuRong = chieuRong; } public float GetChieuRong(){ return chieuRong; } // nhap public void Nhap(){ Scanner inp = new Scanner(System.in); System.out.print("\n Nhap 2 canh cua hinh chu nhat: "); System.out.print("\n + Chieu dai: "); chieuDai = inp.nextFloat(); System.out.print("\n + Chieu rong: "); chieuRong = inp.nextFloat(); } // tinh chu vi private float TinhChuVi(){ return 2*(chieuDai+chieuRong); } // tinh dien tich private float TinhDienTich(){ return chieuDai*chieuRong; } // in ket qua public void InKetQua(){ System.out.println("\n In ket qua: \n" + " + Chu vi: "+TinhChuVi()+"\n" + " + Dien tich: "+TinhDienTich()); } // to string public String ToString(){ String str = "\n In ket qua: \n" + " + Chu vi: "+TinhChuVi()+"\n" + " + Dien tich: "+TinhDienTich(); return str; } }
package com.example.vlada.musicplayer; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class MusicAdapter extends ArrayAdapter<Song> { public MusicAdapter(Activity context, PlayList playList){ super (context,0, playList.getSongs()); } @Override public View getView(int position, View convertView, ViewGroup parent) { View listItemView = convertView; if(listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.list_item, parent, false); } Song currentMusic = getItem(position); TextView artistTextView = listItemView.findViewById(R.id.artist_name); artistTextView.setText(currentMusic.getArtist()); TextView titleTextView = listItemView.findViewById(R.id.song_name); titleTextView.setText(currentMusic.getTitle()); TextView genreTextView = listItemView.findViewById(R.id.song_genre); genreTextView.setText(currentMusic.getGenre()); TextView albumTextView = listItemView.findViewById(R.id.song_album); albumTextView.setText(currentMusic.getAlbum()); return listItemView; } public PlayList getCurrentPlayList(int currentSong) { PlayList playList = new PlayList(); for (int i=0; i<getCount(); i++) playList.add(getItem(i)); playList.currentSongIndex = currentSong; return playList; } }
package pp; import pp.model.Guild; import pp.model.IModel; import pp.model.Player; import pp.model.comparators.IdComparator; import pp.service.GlRuService; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; /** * @author alexander.sokolovsky.a@gmail.com */ public class GuildMonitorActivity extends Activity { List<Long> guildIds = Arrays.asList(10L, 15L); protected GuildMonitorActivity(final GlRuService service) { super(service); } @Override public void doSome() { try { /* service.visitGuilds(); Map<Long,IModel> guilds = service.getGuilds(); List<IModel> guildList = new ArrayList<IModel>(guilds.values()); Collections.sort(guildList, new IdComparator()); Utils.print(guildList); */ for (Long guildId : guildIds) { service.visitGuild(guildId); } Map<Long, Guild> guilds = service.getGuilds(); System.out.println("-----------------------------------------------------"); List<Player> senators = new ArrayList<Player>(); List<Player> imperators = new ArrayList<Player>(); List<Player> total = new ArrayList<Player>(); for (Long guildId : guildIds) { Guild guild = (Guild) guilds.get(guildId); for (IModel iModel : guild.getPlayers().values()) { Player p = (Player) iModel; if (p.getOnline() == null ? false : p.getOnline() && p.getVip() == null ? false : p.getVip() > 0) { senators.add(p); } if (p.getOnline() == null ? false : p.getOnline() && p.getLvl() == null ? false : p.getLvl() > 8) { imperators.add(p); } if (p.getOnline() == null ? false : p.getOnline()) { total.add(p); } } } DateFormat df = DateFormat.getInstance(); System.out.println(df.format(new Date()) + " " + senators.size() + "/" + imperators.size()); System.out.print("Senators:" + senators.size()); System.out.println(Arrays.deepToString(senators.toArray())); System.out.print("Imperators:" + imperators.size()); System.out.println(Arrays.deepToString(imperators.toArray())); System.out.print("Total:" + total.size()); System.out.println(Arrays.deepToString(total.toArray())); completed = true; } catch (IOException e) { e.printStackTrace(); } } public void setGuildIds(final List<Long> guildIds) { this.guildIds = guildIds; } public List<Long> getGuildIds() { return guildIds; } }
package slimeknights.tconstruct.shared.tileentity; import net.minecraft.block.Block; import net.minecraft.block.BlockPane; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import slimeknights.mantle.tileentity.TileInventory; import slimeknights.tconstruct.common.TinkerNetwork; import slimeknights.tconstruct.common.config.Config; import slimeknights.tconstruct.library.client.model.ModelHelper; import slimeknights.tconstruct.shared.block.BlockTable; import slimeknights.tconstruct.shared.block.PropertyTableItem; import slimeknights.tconstruct.tools.common.network.InventorySlotSyncPacket; public class TileTable extends TileInventory { public static final String FEET_TAG = "textureBlock"; public static final String FACE_TAG = "facing"; protected int displaySlot = 0; // default constructor for loading public TileTable() { super("", 0, 0); } public TileTable(String name, int inventorySize) { super(name, inventorySize); } public TileTable(String name, int inventorySize, int maxStackSize) { super(name, inventorySize, maxStackSize); } public IExtendedBlockState writeExtendedBlockState(IExtendedBlockState state) { String texture = getTileData().getString("texture"); // texture not loaded if(texture.isEmpty()) { // load it from saved block ItemStack stack = new ItemStack(getTileData().getCompoundTag(FEET_TAG)); if(!stack.isEmpty()) { Block block = Block.getBlockFromItem(stack.getItem()); texture = ModelHelper.getTextureFromBlock(block, stack.getItemDamage()).getIconName(); getTileData().setString("texture", texture); } } if(!texture.isEmpty()) { state = state.withProperty(BlockTable.TEXTURE, texture); } EnumFacing facing = getFacing(); state = state.withProperty((IUnlistedProperty<EnumFacing>) BlockTable.FACING, facing); state = setInventoryDisplay(state); return state; } protected IExtendedBlockState setInventoryDisplay(IExtendedBlockState state) { PropertyTableItem.TableItems toDisplay = new PropertyTableItem.TableItems(); if(!getStackInSlot(displaySlot).isEmpty()) { ItemStack stack = getStackInSlot(displaySlot); PropertyTableItem.TableItem item = getTableItem(stack, getWorld(), null); if(item != null) { toDisplay.items.add(item); } } // add inventory if needed return state.withProperty(BlockTable.INVENTORY, toDisplay); } public boolean isInventoryEmpty() { for (int i = 0; i < this.getSizeInventory(); ++i) { if (!getStackInSlot(i).isEmpty()) { return false; } } return true; } @SideOnly(Side.CLIENT) public static PropertyTableItem.TableItem getTableItem(ItemStack stack, World world, EntityLivingBase entity) { if(stack.isEmpty()) { return null; } if(!Config.renderTableItems) { return new PropertyTableItem.TableItem(stack, null); } IBakedModel model = ModelHelper.getBakedModelForItem(stack, world, entity); PropertyTableItem.TableItem item = new PropertyTableItem.TableItem(stack, model, 0, -0.46875f, 0, 0.8f, (float) (Math.PI / 2)); if(stack.getItem() instanceof ItemBlock) { if(!(Block.getBlockFromItem(stack.getItem()) instanceof BlockPane)) { item.y = -0.3125f; item.r = 0; } item.s = 0.375f; } return item; } @Override public SPacketUpdateTileEntity getUpdatePacket() { // note that this sends all of the tile data. you should change this if you use additional tile data NBTTagCompound tag = getTileData().copy(); writeToNBT(tag); return new SPacketUpdateTileEntity(this.getPos(), this.getBlockMetadata(), tag); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { NBTTagCompound tag = pkt.getNbtCompound(); NBTBase feet = tag.getTag(FEET_TAG); if(feet != null) { getTileData().setTag(FEET_TAG, feet); } NBTBase facing = tag.getTag(FACE_TAG); if(facing != null) { getTileData().setTag(FACE_TAG, facing); } readFromNBT(tag); } @Nonnull @Override public NBTTagCompound getUpdateTag() { // new tag instead of super since default implementation calls the super of writeToNBT return writeToNBT(new NBTTagCompound()); } @Override public void handleUpdateTag(@Nonnull NBTTagCompound tag) { readFromNBT(tag); } public void setFacing(EnumFacing face) { getTileData().setInteger(FACE_TAG, face.getIndex()); } public EnumFacing getFacing() { return EnumFacing.getFront(getTileData().getInteger(FACE_TAG)); } public void updateTextureBlock(NBTTagCompound tag) { getTileData().setTag(FEET_TAG, tag); } public NBTTagCompound getTextureBlock() { return getTileData().getCompoundTag(FEET_TAG); } @Override public void setInventorySlotContents(int slot, ItemStack itemstack) { // we sync slot changes to all clients around if(getWorld() != null && getWorld() instanceof WorldServer && !getWorld().isRemote && !ItemStack.areItemStacksEqual(itemstack, getStackInSlot(slot))) { TinkerNetwork.sendToClients((WorldServer) getWorld(), this.pos, new InventorySlotSyncPacket(itemstack, slot, pos)); } super.setInventorySlotContents(slot, itemstack); if(getWorld() != null && getWorld().isRemote && Config.renderTableItems) { Minecraft.getMinecraft().renderGlobal.notifyBlockUpdate(null, pos, null, null, 0); } } }
package org.apache.hadoop.hdfs; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.io.IOUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * * @author Hooman <hooman@sics.se> */ public class TestAddBlock { public static final Log LOG = LogFactory.getLog(TestAddBlock.class.getName()); private final short DATANODES = 5; short replicas = 5; private int seed = 139; private int blockSize = 8192; Configuration conf; MiniDFSCluster cluster; DistributedFileSystem dfs; @Before public void initialize() throws IOException { conf = new HdfsConfiguration(); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(DATANODES).build(); } @After public void close() { if (dfs != null) { IOUtils.closeStream(dfs); } cluster.shutdown(); System.out.println("closed"); } /** * Creates a file and writes a block using the returned output stream. It checks * if the block is written and checks if the number of located blocks and replicas * are as expected. * @throws IOException */ @Test public void testAddBlock() throws IOException { cluster.waitActive(); dfs = (DistributedFileSystem) cluster.getFileSystem(); //DFSClient client = dfs.dfs; DFSClient client = dfs.getDefaultDFSClient(); // create a new file. // Path file1 = new Path("/hooman.dat"); FSDataOutputStream strm = createFile(dfs, file1, replicas); LOG.info("testAddBlock: " + "Created file hooman.dat with " + replicas + " replicas."); LocatedBlocks locations = client.getNamenode().getBlockLocations( file1.toString(), 0, Long.MAX_VALUE); LOG.info("testAddBlock: " + "The file has " + locations.locatedBlockCount() + " blocks."); // add one block to the file writeFile(strm, blockSize); strm.hflush(); strm.close(); try{ // file is closed when min replication is reached. // wait until all data nodea have written the blocks Thread.sleep(5000); }catch(Exception e){ } locations = client.getNamenode().getBlockLocations( file1.toString(), 0, Long.MAX_VALUE); //Check the number of blocks assert locations != null; assert locations.getLocatedBlocks().size() == 1; LocatedBlock location = locations.getLocatedBlocks().get(0); //check the number of replicas assertTrue("Location is null", location != null); assertTrue("wrong nubmer of blocks. blocks are " +location.getLocations().length +" expected were "+replicas, location.getLocations().length == replicas); //Check the validity of the replicas.8 for (DatanodeInfo dn : location.getLocations()) { assert dn != null; } } // // writes specified bytes to file. // private void writeFile(FSDataOutputStream stm, int size) throws IOException { byte[] buffer = AppendTestUtil.randomBytes(seed, size); stm.write(buffer, 0, size); } // creates a file but does not close it private FSDataOutputStream createFile(FileSystem fileSys, Path name, int repl) throws IOException { LOG.info("createFile: Created " + name + " with " + repl + " replica."); FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize); return stm; } }
package com.kaka.blog.service; import com.kaka.blog.dao.TagRepository; import com.kaka.blog.po.Tag; import com.kaka.blog.web.ClassNotFoundException; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * @author Kaka */ @Service public class TagServiceImpl implements TagService { @Autowired private TagRepository tagRepository; @Transactional(rollbackFor = Throwable.class) @Override public Tag saveTag(Tag tag) { return tagRepository.save(tag); } @Transactional(rollbackFor = Throwable.class) @Override public Tag getTag(Long id) { return tagRepository.getOne(id); } @Override public Tag getTagByName(String tagName) { return tagRepository.findByTagName(tagName); } @Transactional(rollbackFor = Throwable.class) @Override public Page<Tag> listTag(Pageable pageable) { return tagRepository.findAll(pageable); } @Override public List<Tag> listTag() { return tagRepository.findAll(); } @Override public List<Tag> listTag(String ids) { //1,2,3 return tagRepository.findAllById(convertToList(ids)); } private List<Long> convertToList(String ids) { List<Long> list = new ArrayList<>(); if (!"".equals(ids) && ids != null) { String[] idarray = ids.split(","); for (String s : idarray) { list.add(new Long(s)); } } return list; } @Transactional(rollbackFor = Throwable.class) @Override public Tag updateTag(Long id, Tag tag) throws ClassNotFoundException { Tag tag1 = tagRepository.findById(id).orElse(null); if (tag1 == null) { throw new ClassCastException("找不到tag"); } BeanUtils.copyProperties(tag,tag1); return tagRepository.save(tag1); } @Transactional(rollbackFor = Throwable.class) @Override public void deleteTag(Long id) { tagRepository.deleteById(id); } }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.eao.germplasm.impl; import java.util.List; import org.inbio.ara.eao.germplasm.*; import javax.ejb.Stateless; import javax.persistence.Query; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.germplasm.Breed; /** * * @author dasolano */ @Stateless public class BreedEAOImpl extends BaseEAOImpl<Breed, Long> implements BreedEAOLocal { public List<Long> findByBreedName(String breedName) { Query q = em.createQuery( " Select b.breedId " + " from Breed b " + " where lower(b.name) like '%"+breedName.toLowerCase() +"%'" ); return q.getResultList(); } public List<Long> findByScientificName(String scientificName) { Query q = em.createQuery( " Select b.breedId " + " from Breed b, Taxon t " + " where b.taxonId = t.taxonId and " + " lower(t.defaultName) like '%"+ scientificName.toLowerCase() +"%'" ); return q.getResultList(); } }
package com.lambda.iith.dashboard; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.work.PeriodicWorkRequest; import androidx.work.WorkManager; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.gson.Gson; import com.lambda.iith.dashboard.AcadNotifs.icsParse; import com.lambda.iith.dashboard.BackgroundTasks.DPload; import com.lambda.iith.dashboard.Cabsharing.BookingFilter; import com.lambda.iith.dashboard.Cabsharing.CabSharing; import com.lambda.iith.dashboard.Cabsharing.CabSharingBackgroundWork; import com.lambda.iith.dashboard.MainFragments.FragmentBS; import com.lambda.iith.dashboard.MainFragments.HomeScreenFragment; import com.lambda.iith.dashboard.MainFragments.MessMenu; import com.lambda.iith.dashboard.MainFragments.acad_info; import com.lambda.iith.dashboard.Timetable.AddCourse; import com.lambda.iith.dashboard.Timetable.NotificationInitiator; import com.lambda.iith.dashboard.Timetable.Timetable; import com.lambda.iith.dashboard.Timetable.timetableComp; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import Model.Filter; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { public static BottomNavigationView bottomNavigationView; public static String idToken; public static ImageView imageView; public String name; public static String email; public Uri photoUrl; int a; private GoogleSignInClient mGoogleSignInClient; private GoogleSignInOptions gso; private ImageButton MasterRefresh; private SharedPreferences sharedPreferences; private TextView Nav_Bar_Header; //Navigation Bar Header i.e User Name private TextView Nav_Bar_Email; //Navigation Bar email private List<String> courseList; private List<String> courseSegmentList; private List<String> slotList; private ArrayList<String> CourseName; private RequestQueue queue , queue1; private SwipeRefreshLayout pullToRefresh; private FragmentManager fragmentManager; private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Toolbar toolbar = findViewById(R.id.toolbar); switch (menuItem.getItemId()) { case R.id.nav_home: { a = 1; MasterRefresh.setVisibility(View.VISIBLE); pullToRefresh.setEnabled(true); findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); findViewById(R.id.addcourse).setVisibility(View.GONE); toolbar.setTitle("IITH Dashboard"); fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new HomeScreenFragment()).commit(); return true; } case R.id.nav_acads: { a = 2; final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: fetchData(); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; findViewById(R.id.TimeTableRefresh).setVisibility(View.VISIBLE); pullToRefresh.setEnabled(false); pullToRefresh.setRefreshing(false); MasterRefresh.setVisibility(View.GONE); toolbar.setTitle("Timetable"); fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new Timetable()).commit(); findViewById(R.id.addcourse).setVisibility(View.VISIBLE); findViewById(R.id.addcourse).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, AddCourse.class)); } }); return true; } case R.id.nav_bus: { a = 3; MasterRefresh.setVisibility(View.VISIBLE); findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); findViewById(R.id.addcourse).setVisibility(View.GONE); pullToRefresh.setEnabled(true); toolbar.setTitle("Bus Schedule"); fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new FragmentBS()).commit(); return true; } case R.id.nav_mess: { findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); MasterRefresh.setVisibility(View.VISIBLE); findViewById(R.id.addcourse).setVisibility(View.GONE); pullToRefresh.setEnabled(true); toolbar.setTitle("Mess Menu"); fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new MessMenu()).commit(); a = 4; return true; } case R.id.nav_acad_info: { findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); MasterRefresh.setVisibility(View.VISIBLE); findViewById(R.id.addcourse).setVisibility(View.GONE); pullToRefresh.setEnabled(false); toolbar.setTitle("Academic Info"); fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new acad_info()).commit(); a = 4; return true; } // case R.id.nav_cab: { // findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); // MasterRefresh.setVisibility(View.VISIBLE); // findViewById(R.id.addcourse).setVisibility(View.GONE); // pullToRefresh.setEnabled(true); // toolbar.setTitle("Cab Sharing"); // //fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new CabSharing()).commit(); // Intent i = new Intent(MainActivity.this, CabSharing.class); // startActivity(i); // a = 4; // return true; // } } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { fragmentManager = getSupportFragmentManager(); queue = Volley.newRequestQueue(MainActivity.this); queue1 = Volley.newRequestQueue(MainActivity.this); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); refresh(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Generate Timetable from Storage timetableComp Timetablecomp = new timetableComp(); Timetablecomp.execute(getApplicationContext()); //Getting User Login details FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url name = user.getDisplayName(); email = user.getEmail(); photoUrl = user.getPhotoUrl(); user.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { idToken = task.getResult().getToken(); } } }); } sharedPreferences.edit().putString("UserEmail" , email).apply(); //Setting Refresh and Swipe to Refresh MasterRefresh = findViewById(R.id.MainRefresh); pullToRefresh = findViewById(R.id.pullToRefresh); pullToRefresh.setRefreshing(false); pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); MasterRefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pullToRefresh.setRefreshing(true); refresh(); } }); //Initiating Navigation Drawer DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); navigationView.setOnCreateContextMenuListener(this); //Setting Up BottomNav //GoogleSignInClient gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso); //Getting Settings menu for first run if (sharedPreferences.getBoolean("firstrun", true)) { fetchData(); sharedPreferences.edit().putBoolean("firstrun", false).commit(); } //Setting up Timetable Refresh ( Displayed only when timetable fragment is active findViewById(R.id.TimeTableRefresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle("Warning"); alert.setMessage("This will clear any changes you made and restore your timetable to the AIMS version. Press Sync to proceed or cancel to discontinue"); alert.setPositiveButton("Sync", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { fetchData(); } }); alert.setNegativeButton("Cancel", null); alert.show(); } }); if(sharedPreferences.getBoolean("Registered" , false)){ WorkManager.getInstance().cancelAllWorkByTag("CAB"); PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(CabSharingBackgroundWork.class , 1 , TimeUnit.HOURS).addTag("CAB").build(); WorkManager.getInstance().enqueue(periodicWorkRequest); } bottomNavigationView = findViewById(R.id.BottomNavigation); bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); bottomNavigationView.setSelectedItemId(R.id.nav_home); } @Override protected void onResume() { super.onResume(); if (sharedPreferences.getBoolean("PleaseUpdateCAB", false)) { pullToRefresh.setRefreshing(true); refresh(); sharedPreferences.edit().putBoolean("PleaseUpdateCAB", false).commit(); } } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); this.finishAffinity(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. Nav_Bar_Header = findViewById(R.id.Nav_Bar_name); // Setting Username recieved from google account in navigation bar Nav_Bar_Email = findViewById(R.id.nav_bar_email); if (sharedPreferences.getBoolean("DEVELOPER", false)) { NavigationView navigationView = findViewById(R.id.nav_view); navigationView.getMenu().findItem(R.id.nav_dev).setVisible(true); sharedPreferences.edit().putBoolean("DEVELOPER", false).commit(); } imageView = findViewById(R.id.nav_bar_dp); try { Nav_Bar_Email.setText(email); // Setting email recieved from google account in navigation bar Nav_Bar_Header.setText(name); new DPload().execute(photoUrl.toString()); } catch (Exception e) { e.printStackTrace(); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } private void signOut() { // Firebase sign out FirebaseAuth.getInstance().signOut(); // Google sign out mGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { startActivity(new Intent(MainActivity.this, NoLogin.class)); } }); } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. Toolbar toolbar = findViewById(R.id.toolbar); int id = item.getItemId(); FragmentManager fragmentManager = getSupportFragmentManager(); //SideNav Settings if (id == R.id.logout) { signOut(); } else if (id == R.id.nav_Settings) { startActivity(new Intent(MainActivity.this, Settings.class)); } else if (id == R.id.about) { startActivity(new Intent(MainActivity.this, About.class)); } else if (id == R.id.nav_dev) { startActivity(new Intent(MainActivity.this, Developer.class)); } else if (id == R.id.nav_acad_info) { // findViewById(R.id.TimeTableRefresh).setVisibility(View.GONE); // MasterRefresh.setVisibility(View.VISIBLE); // findViewById(R.id.addcourse).setVisibility(View.GONE); // pullToRefresh.setEnabled(true); // toolbar.setTitle("Cab Sharing"); //fragmentManager.beginTransaction().replace(R.id.fragmentlayout, new CabSharing()).commit(); Intent i = new Intent(MainActivity.this, CabSharing.class); startActivity(i); a = 4; return true; } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return false; } @Override protected void onStart() { DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); Launch.height = displayMetrics.heightPixels; Launch.width = displayMetrics.widthPixels; if (sharedPreferences.getInt("MESSDEF", -1) == -1 || sharedPreferences.getString("DefaultSegment", "0").equals('0')) { setValues(); } if (sharedPreferences.getBoolean("FirstAfterV1.22", true)) { final AlertDialog.Builder b1 = new AlertDialog.Builder(this); b1.setTitle("How many minutes before you need notification"); b1.setCancelable(false); String[] types1 = {"5 mins", "10 mins" ,"15 mins","30 mins","45 mins" , "60 mins"}; b1.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { checkBatteryStatus(); } }); b1.setItems(types1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which==0){ sharedPreferences.edit().putInt("NotificationTime" , 5).commit();} if(which==1) { sharedPreferences.edit().putInt("NotificationTime", 10).commit(); } if(which==2) { sharedPreferences.edit().putInt("NotificationTime", 15).commit(); }if(which==3){ sharedPreferences.edit().putInt("NotificationTime" , 30).commit(); }if(which==4){ sharedPreferences.edit().putInt("NotificationTime" , 45).commit(); }if(which==5){ sharedPreferences.edit().putInt("NotificationTime" , 60).commit(); } WorkManager.getInstance().cancelAllWorkByTag("LECTUREREMINDER"); WorkManager.getInstance().cancelAllWorkByTag("TIMETABLE"); PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(NotificationInitiator.class, 6, TimeUnit.HOURS).addTag("TIMETABLE").build(); WorkManager.getInstance().enqueue(periodicWorkRequest); dialog.dismiss(); } }); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Want to recieve notifications before lectures?"); String[] types = {"YES", "NO"}; b.setCancelable(false); b.setItems(types, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { sharedPreferences.edit().putBoolean("EnableLectureNotification", true).commit(); b1.show(); sharedPreferences.edit().putBoolean("RequestAutostart", true).commit(); } else { sharedPreferences.edit().putBoolean("EnableLectureNotification", false).commit(); } } }); b.show(); sharedPreferences.edit().putBoolean("FirstAfterV1.22", false).commit(); } if (sharedPreferences.getBoolean("FirstAfterV1.30", true)) { final AlertDialog.Builder acadDialog = new AlertDialog.Builder(this); acadDialog.setTitle("Do you want to receive notification about Academic Calendar events?"); String[] acadPrefs = {"YES", "NO"}; acadDialog.setCancelable(false); acadDialog.setItems(acadPrefs, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { sharedPreferences.edit().putBoolean("EnableAcadNotification", true).commit(); sharedPreferences.edit().putBoolean("RequestAutostart", true).commit(); } else { sharedPreferences.edit().putBoolean("EnableAcadNotification", false).commit(); } } }); acadDialog.show(); sharedPreferences.edit().putBoolean("FirstAfterV1.30", false).apply(); } super.onStart(); } private void checkBatteryStatus() { //System.out.println(getBaseContext().getPackageName()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Intent intent = new Intent(); String packageName = getPackageName(); PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); if (!pm.isIgnoringBatteryOptimizations(packageName)) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Please Disable Battery Optimization"); alert.setMessage("Please exempt IITH Dashboard to receive uninterrupted notifications"); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startActivityForResult(new Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS), 0); } }); alert.show(); } } } //First run values for default segment and mess private void setValues() { final AlertDialog.Builder b1 = new AlertDialog.Builder(this); b1.setTitle("What segment is currently running?"); b1.setCancelable(false); String[] types1 = {"Segment 1-2", "Segment 3-4", "Segment 5-6"}; b1.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { recreate(); } }); b1.setItems(types1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sharedPreferences.edit().putString("DefaultSegment", Integer.toString(22 * which + 12)).commit(); dialog.dismiss(); } }); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Select Your Mess"); String[] types = {"LDH", "UDH"}; b.setCancelable(false); b.setItems(types, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sharedPreferences.edit().putInt("MESSDEF", which).commit(); dialog.dismiss(); if (sharedPreferences.getString("DefaultSegment", "0").equals("0")) { b1.show(); } } }); b.show(); } //This method is used to set the default screen that will be shown. private void setDefaultFragment(Fragment defaultFragment) { this.replaceFragment(new HomeScreenFragment()); } //replaces the current fragment with the destination one. private void replaceFragment(Fragment destFragment) { FragmentManager fragmentManager = this.getSupportFragmentManager(); //beginning fragment transaction FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //Replacing layout holder with the required fragment object fragmentTransaction.replace(R.id.drawer_layout, destFragment); // Commit the Fragment replace action. fragmentTransaction.commit(); } private int Switch = 0; //Fetching Data for Cabs Buses and Mess private void refresh() { if (!sharedPreferences.getBoolean("Registered", false) && sharedPreferences.getBoolean("FIRSTCABLAUNCH" , true)) { RetrieveBooking(); } /** if(sharedPreferences.getBoolean("Registered", false) ) { checkForUpdates(); } queue1.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() { @Override public void onRequestFinished(Request<Object> request) { if(Switch==1){ updateShares();} } }); **/ BusData(); messData(); GetCalendarData(); //System.out.println("In main activity"); queue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() { @Override public void onRequestFinished(Request<Object> request) { Fragment fragment = fragmentManager.findFragmentById(R.id.fragmentlayout); FragmentTransaction ft = fragmentManager.beginTransaction(); pullToRefresh.setRefreshing(false); ft.detach(fragment); ft.attach(fragment); ft.commitAllowingStateLoss(); return; } }); } private void BusData(){ String url = "https://iith.dev/v2/bus"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject JO = null; // Display the first 500 characters of the response string. try { JO = new JSONObject(response); JSONObject JA = JO.getJSONObject("TOIITH"); Iterator iterator = JA.keys(); ArrayList<String> Buses = new ArrayList<>(); while (iterator.hasNext()) { String key = (String) iterator.next(); Buses.add(key); } System.out.println(Buses); SharedPreferences.Editor edit = sharedPreferences.edit(); Buses.remove("LINGAMPALLYW"); Buses.remove("ODFS"); edit.putString("BusTypes", Buses.toString()); edit.putString("ToIITH", JO.getJSONObject("TOIITH").toString()); edit.putString("FromIITH", JO.getJSONObject("FROMIITH").toString()); edit.commit(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Server Refresh Failed ...", Toast.LENGTH_SHORT).show(); } }); queue.add(stringRequest); } private void messData(){ String url2 = "https://iith.dev/dining"; StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONArray JA = null; // Display the first 500 characters of the response string. SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString("MESSJSON", response); edit.commit(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Server Refresh Failed ...", Toast.LENGTH_SHORT).show(); } }); queue.add(stringRequest2); } //Retrieve Cab shares public void updateShares(){ final String url4 = "https://iith.dev/query"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url4, new Response.Listener<String>() { @Override public void onResponse(String response) { Filter filter = new Filter(); try { filter.set(response , sharedPreferences); } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } new BookingFilter().execute(filter); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Server Refresh Failed ...", Toast.LENGTH_SHORT).show(); } }); queue.add(stringRequest); } //Check if shares available private void checkForUpdates(){ String URL9 = "https://iith.dev/update"; JSONObject jsonBody = new JSONObject(); final String start = sharedPreferences.getString("startTime", " NA NA "); final String end = sharedPreferences.getString("endTime", " NA NA "); final int route = sharedPreferences.getInt("Route", 100); try { jsonBody.put("QueryTimeStart", start); jsonBody.put("QueryTimeEnd", end); jsonBody.put("RouteID", route); } catch (JSONException e) { e.printStackTrace(); } final String requestBody = jsonBody.toString(); JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, URL9, jsonBody, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if(response.getBoolean("IsUpdateReqd")){ Switch = 1;} else{ Switch = 0;} } catch (JSONException e) { Switch = 1; e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { return; } }); queue1.add(stringRequest); } //Retrieve already existing booking of current user from server if exists private void RetrieveBooking(){ final String url4 = "https://iith.dev/query"; final String startTime = sharedPreferences.getString("startTime", " NA NA "); final String endTime = sharedPreferences.getString("endTime", " NA NA "); final int CabID = sharedPreferences.getInt("Route", 100); StringRequest stringRequest = new StringRequest(Request.Method.GET, url4, new Response.Listener<String>() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. sharedPreferences.edit().putBoolean("FIRSTCABLAUNCH", false); JSONArray JA = null; JSONArray JA2 = null; try { JA = new JSONArray(response); JA2 = new JSONArray(); for (int i = 0; i < JA.length(); i++) { JSONObject JO = (JSONObject) JA.get(i); if (JO.getString("Email").equals(email)) { SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString("startTime", JO.getString("StartTime")); edit.putString("endTime", JO.getString("EndTime")); edit.putBoolean("Registered", true); edit.putInt("Private", 0); edit.putInt("Route", JO.getInt("RouteID")); edit.commit(); } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Server Refresh Failed ...", Toast.LENGTH_SHORT).show(); } }); queue.add(stringRequest); } //UID private String getUID() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { return user.getUid(); } else { return null; } } //+ // Fetching timetable private void fetchData() { String UUID = getUID(); pullToRefresh.setRefreshing(true); DocumentReference users = FirebaseFirestore.getInstance().document("users/" + UUID); users.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { courseList = (List<String>) documentSnapshot.get("identifiedCourses"); courseSegmentList = (List<String>) documentSnapshot.get("identifiedSegments"); slotList = (List<String>) documentSnapshot.get("identifiedSlots"); } CourseName = new ArrayList<>(); try { for (int j = 0; j < courseList.size(); j++) { CourseName.add("Name"); } } catch (Exception e) { } sharedPreferences.edit().putInt("seg1_begin", -1).apply(); sharedPreferences.edit().putInt("seg2_begin", -1).apply(); sharedPreferences.edit().putInt("seg3_begin", -1).apply(); saveArrayList(courseList, "CourseList"); saveArrayList(courseSegmentList, "Segment"); sharedPreferences.edit().putBoolean("RequireReset", true).commit(); saveArrayList(slotList, "SlotList"); saveArrayList2(CourseName, "CourseName"); new timetableComp().execute(getBaseContext()); Fragment fragment = fragmentManager.findFragmentById(R.id.fragmentlayout); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.detach(fragment); ft.attach(fragment); ft.commitAllowingStateLoss(); Toast.makeText(getBaseContext(), "Data Synced", Toast.LENGTH_SHORT).show(); pullToRefresh.setRefreshing(false); } }); } private void GetCalendarData() { String url = "https://calendar.google.com/calendar/ical/c_ll73em8s81nhu8nbjvggqhmbgc%40group.calendar.google.com/public/basic.ics"; StringRequest icsRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { System.out.println("Response Recieved."); icsParse icsparse = new icsParse(response) ; sharedPreferences.edit().putString("AcadCalendar",icsparse.getArray().toString()).apply(); PeriodicWorkRequest acadPeriodicRequest = new PeriodicWorkRequest.Builder(com.lambda.iith.dashboard.AcadNotifs.NotificationInitiator.class, 6,TimeUnit.HOURS) .addTag("ACADEVENTS") .build(); //do not enqueue a request if a user does not want notifications. if(sharedPreferences.getBoolean("EnableAcadNotification",true)) WorkManager.getInstance().enqueue(acadPeriodicRequest); } } , new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("Some error occurred"); System.out.println(error); } } ); queue.add(icsRequest); System.out.println("finished execution"); } //Saving timetable private void saveArrayList(List<String> list, String key) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); Gson gson = new Gson(); String json = gson.toJson(list); editor.putString(key, json); editor.apply(); // This line is IMPORTANT !!! } private void saveArrayList2(ArrayList<String> list, String key) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); Gson gson = new Gson(); String json = gson.toJson(list); editor.putString(key, json); editor.apply(); // This line is IMPORTANT !!! } }
// https://www.youtube.com/watch?v=C6r1fDKAW_o class Solution { // public int kthSmallest(TreeNode root, int k) { // int[] nums = new int[2]; // inorder(root, nums, k); // return nums[1]; // } // public void inorder(TreeNode root, int[] nums, int k) { // if (root == null) return; // inorder(root.left, nums, k); // if (++nums[0] == k) { // nums[1] = root.val; // return; // } // inorder(root.right, nums, k); // } public int kthSmallest(TreeNode root, int k) { LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); while (true) { while (root != null) { stack.add(root); root = root.left; } root = stack.removeLast(); if (--k == 0) return root.val; root = root.right; } } }
package com.example.prog3.alkasaffollowup.Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.prog3.alkasaffollowup.Model.ProjInvoi.ProjectInvoice; import com.example.prog3.alkasaffollowup.ProjInvoicesFollowup; import com.example.prog3.alkasaffollowup.R; import com.example.prog3.alkasaffollowup.ViewHolders.InvoicesViewHolder; import java.util.List; import java.util.StringTokenizer; /** * Created by prog3 on 3/26/2018. */ public class InvoicesRecyclerAdapter extends RecyclerView.Adapter<InvoicesViewHolder> { Context context; List<ProjectInvoice> invoices;String ref; public InvoicesRecyclerAdapter(Context context, List<ProjectInvoice> invoices,String ref) { this.context=context; this.invoices=invoices; this.ref=ref; } @Override public InvoicesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.project_invoices_row, parent, false); return new InvoicesViewHolder(view); } @Override public void onBindViewHolder(InvoicesViewHolder holder, int position) { ProjectInvoice invoice = invoices.get(position); String s =invoice.getInvoiceDate(); StringTokenizer tokenizer = new StringTokenizer(s, "T"); String invoicedate = tokenizer.nextToken(); holder.txtprojref.setText(ref); holder.txtinvoice.setText(invoice.getInvoiceNumber()); holder.txtinvoiceamount.setText(invoice.getInvoiceAmount()); holder.txtinvoicedate.setText(invoicedate); } @Override public int getItemCount() { return invoices.size(); } }
package com.zxt.framework.dictionary.entity; import java.util.List; import com.zxt.framework.common.entity.BasicEntity; public class SqlObj extends BasicEntity{ private String sqldicid; private String sqldicname; private String sqldic_expression; private String sqldic_type; private String sqldic_remark; private List sqlParam; private String sqldic_dataSourceid; public String getSqldicid() { return sqldicid; } public void setSqldicid(String sqldicid) { this.sqldicid = sqldicid; } public String getSqldicname() { return sqldicname; } public void setSqldicname(String sqldicname) { this.sqldicname = sqldicname; } public String getSqldic_expression() { return sqldic_expression; } public void setSqldic_expression(String sqldic_expression) { this.sqldic_expression = sqldic_expression; } public String getSqldic_type() { return sqldic_type; } public void setSqldic_type(String sqldic_type) { this.sqldic_type = sqldic_type; } public String getSqldic_remark() { return sqldic_remark; } public void setSqldic_remark(String sqldic_remark) { this.sqldic_remark = sqldic_remark; } public String getSqldic_dataSourceid() { return sqldic_dataSourceid; } public void setSqldic_dataSourceid(String sqldic_dataSourceid) { this.sqldic_dataSourceid = sqldic_dataSourceid; } public List getSqlParam() { return sqlParam; } public void setSqlParam(List sqlParam) { this.sqlParam = sqlParam; } }
package com.neusoft.issure.api.common.req; import lombok.Data; @Data public class LoginReq { private String mobile;//用户列表 }
package com.zxt.compplatform.organization.service; import java.util.List; import com.zxt.compplatform.organization.entity.TOrgOrg; import com.zxt.compplatform.organization.entity.TOrganization; import com.zxt.compplatform.organization.entity.TUserTable; /** * @author bozch * 2011-03-15 * */ public interface OrganizationService { /* * 根据组织结构id 修改组织结构状态之前将组织机构状态全部归零 * */ public void updateAllOrgClssify(); /* * 根据组织结构id 修改组织结构状态 * */ public void updateOrgClssify(String oid); /* * 根据部门复制部门id选取部门间的关系 * */ public List getOrgOrg(String ooid[]); /** * 获取所有的组织机构列表 * @return */ public List get_allOrginationList(); /** * 跟据部门表和部门关系表 得出所需的json * @return */ public List get_jsonList(); /** * 跟据部门表和部门关系表和部门状态 得出所需的json * @return */ public List get_jsonListByClassify(); /** * 跟据部门表和部门关系表 得出所需的json * 带参数 * @return */ public List get_jsonListWithParam(String oid); /** * 根据父节点id查询子节点 * @param pid * @return */ public List load_childrenJsonList(String pid); /** * 根据部门id查询部门成员 * @param oid * @return */ public List getUserByGroupId(String oid); /** * 根据部门id查询其子部门的字符串 * @param oid * @return */ public String getOidsByOid(String oid); /** * 根据部门id查询特定部门信息 * @param oid * @return */ public TOrganization getOrganization(String oid); /** * 部门添加 */ public void addOrganization(TOrganization organization,String upOrgId); /** * 判断部门是否存在 */ public int isExistOrg(String oid,String oupid,String oname); /** * 得到部门中oid的最大值 */ public int maxvalue() ; /** * 得到部门上下级表中的最大值 */ public int maxValueFromOrgOrg(); /** * 向部门的上下级表中添加 */ public void addOrgOrg(TOrgOrg orgorg) ; /** * 部门修改 */ public void updateOrganization(TOrganization organization); /** * 部门删除 */ public String deleteOrganization(String oid); //************************************************************************ /** * 根据用户id查询用户名(pass) * @param uid * @return */ public String getUserName(String uid); /** * 分页查询(部门下) * @param page 当前页 * @param rows 每页显示条数 * @param oid 部门id * @return */ public List findAllByPageAndOid(int page,int rows,String oid); /** * 用户条数(部门下) */ public int findUserTotalUnderOid(String oid); /** * 添加用户(用户名可以重复) * @param usertable */ public String addUser(TUserTable usertable,String oid); /** * 修改用户 */ public void updateUser(TUserTable usertable); /** * 保存修改的用户的组织机构 */ public void updateUserOragination(String userId,String oid); //查询所有用户 public List getAllUser(); /** * 删除用户 */ public void deleteUserById(String id); /** * 删除用户 */ public String checkUserIsUse(String userId); /** * 根据userid查询本条用户的信息 * @param userId * @return */ public TUserTable findUserAllById(String userId); /** * 判断用户名不是不是存在 * @param userName * @param userId * @return */ public boolean isUserNameExist(String userName,String userId); //*********************************************** /** * 根据用户名得到其包含的角色(包含角色的子角色) * @param userid * @return */ public List findAllRoleByUserId(String userid); /** * 获取用户所对应的权限 * @return */ public List getAuthoritysIDByUserId(String userid); //********************************************************** /** * 获取带用户的树 * @param treeDataList * @param parentID * @return */ public List treeAlgorithm(List treeDataList,String parentID); //********************************************************** /** * 管理用户级别 */ public void updateUser_UserLevel(String userid,String id); /** * 管理用户角色(删除用户角色) */ public void deleteRoleUnderUser(String userid, String rids); /** * 管理用户角色(添加用户角色) */ public void addRolesToUser(String userid, String rids); //*********************************************************** /** * 获取部门主管(根据部门id) */ public List getOrgLead(String oid); /** * 给部门添加主管 */ public void addLeadToOrg(String oid,String userids); /** * 从部门移除主管 */ public void removeLeadFormOrg(String oid,String userids); //GUOWEIXIN 获取部门数据组合树结构 用于后台。此方法作用是 configSql.properties 不影响后面 表单管理操作 public List getAllJsonListByBack(); //********************************************************** }
package pl.edu.pw.mini.taio.omino.lib.generators; import org.junit.jupiter.api.Test; import pl.edu.pw.mini.taio.omino.core.Block; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class IncrementalBlockGeneratorTest { @Test public void throwsExceptionWhenBlockSizeIsNegative() { // given: // when: // then: assertThatThrownBy(() -> new IncrementalBlockGenerator(-1, 0)) .isInstanceOf(IllegalArgumentException.class); } @Test public void shouldBeOneBlockWithSizeZero() { // given: BlockGenerator generator = new IncrementalBlockGenerator(0, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(1); } @Test public void shouldBeOneBlockWithSizeOne() { // given: BlockGenerator generator = new IncrementalBlockGenerator(1, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(1); } @Test public void shouldBeOneBlockWithSizeTwo() { // given: BlockGenerator generator = new IncrementalBlockGenerator(2, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(1); } @Test public void shouldBeTwoBlocksWithSizeThree() { // given: BlockGenerator generator = new IncrementalBlockGenerator(3, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(2); } @Test public void shouldBeSevenBlocksWithSizeFour() { // given: BlockGenerator generator = new IncrementalBlockGenerator(4, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(7); } @Test public void shouldBeEighteenBlocksWithSizeFive() { // given: BlockGenerator generator = new IncrementalBlockGenerator(5, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(18); } @Test public void shouldBeSixtyBlocksWithSizeSix() { // given: BlockGenerator generator = new IncrementalBlockGenerator(6, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(blocks).size().isEqualTo(60); } @Test public void allBlocksShouldBeUnique() { // given: BlockGenerator generator = new IncrementalBlockGenerator(6, 0); // when: Collection<Block> blocks = generator.all().collect(Collectors.toList()); // then: assertThat(new HashSet<>(blocks)).size().isEqualTo(blocks.size()); } @Test public void allStreamCountShouldBeSameAsGeneratorCount() { // given: BlockGenerator generator = new IncrementalBlockGenerator(6, 0); // when: Stream<Block> all = generator.all(); // then: assertThat(all.count()).isEqualTo(generator.count()); } @Test public void allBlocksFromGeneratorShouldHaveDesiredSize() { // given: int size = 6; BlockGenerator generator = new IncrementalBlockGenerator(size, 0); // when: Collection<Integer> sizes = generator.all() .mapToInt(Block::getSize) .boxed() .collect(Collectors.toSet()); // then: assertThat(sizes).containsOnly(size); } }
package io.github.seregaslm.jsonapi.simple.response; import com.fasterxml.jackson.annotation.JsonInclude; import io.github.seregaslm.jsonapi.simple.annotation.JsonApiId; import io.github.seregaslm.jsonapi.simple.annotation.JsonApiType; import lombok.Data; import lombok.experimental.Accessors; import java.time.LocalDateTime; import java.util.UUID; @Data @Accessors(chain = true) @JsonApiType(TestDto.API_TYPE) @JsonInclude(JsonInclude.Include.NON_NULL) public class TestDto { public static final String API_TYPE = "test-object"; @JsonApiId private UUID id; private String name; private LocalDateTime createDate; }
package ru.itmo.ctlab.sgmwcs.solver; import ru.itmo.ctlab.sgmwcs.Pair; import ru.itmo.ctlab.sgmwcs.graph.Edge; import ru.itmo.ctlab.sgmwcs.graph.Graph; import ru.itmo.ctlab.sgmwcs.graph.Node; import ru.itmo.ctlab.sgmwcs.graph.flow.EdmondsKarp; import ru.itmo.ctlab.sgmwcs.graph.flow.MaxFlow; import java.util.*; public class CutGenerator { private MaxFlow maxFlow; private Map<Node, Integer> nodes; private Node root; private Map<Edge, Pair<Integer, Integer>> edges; private List<Node> backLink; private Map<Node, Double> weights; private Graph graph; public CutGenerator(Graph graph, Node root) { int i = 0; weights = new HashMap<>(); backLink = new ArrayList<>(); nodes = new HashMap<>(); edges = new HashMap<>(); for (Node node : graph.vertexSet()) { nodes.put(node, i++); backLink.add(node); } maxFlow = new EdmondsKarp(graph.vertexSet().size()); for (Edge e : graph.edgeSet()) { Node v = graph.getEdgeSource(e); Node u = graph.getEdgeTarget(e); maxFlow.addEdge(nodes.get(v), nodes.get(u)); edges.put(e, new Pair<>(nodes.get(v), nodes.get(u))); } this.root = root; this.graph = graph; } public void setCapacity(Edge e, double capacity) { Pair<Integer, Integer> edge = edges.get(e); maxFlow.setCapacity(edge.first, edge.second, capacity); maxFlow.setCapacity(edge.second, edge.first, capacity); } public void setVertexCapacity(Node v, double capacity) { weights.put(v, capacity); } public List<Edge> findCut(Node v) { List<Pair<Integer, Integer>> cut = maxFlow.computeMinCut(nodes.get(root), nodes.get(v), weights.get(v)); if (cut == null) { return null; } List<Edge> result = new ArrayList<>(); for (Pair<Integer, Integer> p : cut) { result.addAll(graph.getAllEdges(backLink.get(p.first), backLink.get(p.second))); } return result; } public Set<Node> getNodes() { return nodes.keySet(); } public Set<Edge> getEdges() { return edges.keySet(); } public Node getRoot() { return root; } }
package com.zzwc.cms.mongo.crud; import org.bson.Document; import java.util.Map; /** * 查询解析器,每种解析器都有自定义的规则,客户端按照规则组织查询条件,经过解析后生成mongodb可执行的查询语句 * * @author weirdor * */ public interface QueryParser { /** * 根据客户端条件,解析出mongodb查询语句 * * @param query * 按照解析器规则组织好的客户端查询条件 * @return * @author weirdor */ Document parse(Map<String, Object> query); }
package org.ordogene.file; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.stream.Stream; import org.ordogene.file.utils.Const; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.emory.mathcs.backport.java.util.Arrays; /** * Handle Users : check existency, add and remove. * @author darwinners team * */ public class UserManager { private final static Logger log = LoggerFactory.getLogger(UserManager.class); /** * check if the given user exist on the server * * @param username * : name of the user to check * @return true if the user exists, false else. */ public boolean checkUserExists(String username) { if (username == null || username.isEmpty()) { return false; } else { Path path = Paths.get(Const.getConst().get("ApplicationPath") + File.separatorChar + username); return (path.toFile().exists()); } } /** * add an user on the server * * @param username * : name of the user to add * @return true if the user has been added, false else. */ public boolean createUser(String username) { if (username == null || username.isEmpty()) { return false; } else { Path newUserPath = Paths.get(Const.getConst().get("ApplicationPath") + File.separatorChar + username); if(newUserPath.toFile().exists()) { return false; } try { log.info("Create new user {}", username); Files.createDirectories(newUserPath); } catch (IOException e) { log.error("... failed :"); log.debug(Arrays.toString(e.getStackTrace())); return false; } return (Paths.get(Const.getConst().get("ApplicationPath") + File.separatorChar + username).toFile().exists()); } } /** * remove an user on the server * * @param username * : name of the user to add * @return true if the user has been added, false else. */ public boolean removeUser(String username) { if (username == null || username.equals("")) { return false; } File todelete = new File(Const.getConst().get("ApplicationPath") + File.separatorChar + username); if(!todelete.exists()) { return false; } try(Stream<Path> paths = Files.walk(todelete.toPath())) { paths.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { e.printStackTrace(); return false; } return true; } }
package com.codecool.stampcollection.validator; import com.codecool.stampcollection.exception.CurrencyNotExistsException; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.constraints.NotNull; import java.util.Currency; import java.util.Set; public class CurrencyValidator implements ConstraintValidator<CurrencyConstraint, String> { @Override public boolean isValid(String currency, ConstraintValidatorContext constraintValidatorContext) { if (currency == null) { return false; } Set<Currency> currencies = Currency.getAvailableCurrencies(); try { return currencies.contains(Currency.getInstance(currency)); } catch (IllegalArgumentException iae) { throw new CurrencyNotExistsException(currency); } } }
package be.pxl.computerstore.hardware; public enum ComputerComponentTypes { COMPUTER_CASES("Computer Cases"), PROCESSORS("Processors"), HARD_DISK_DRIVES("Hard Disk Drives"), PERIPHERALS("Peripherals"); private String displayName; ComputerComponentTypes(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } @Override public String toString() { return getDisplayName(); } }
package ca.polymtl.rubikcube.CubeActivity; public class ErrorStatusException extends Exception { private static final long serialVersionUID = 1L; public ErrorStatusException() { super(); } public ErrorStatusException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public ErrorStatusException(String detailMessage) { super(detailMessage); } public ErrorStatusException(Throwable throwable) { super(throwable); } }