blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
ffdac310431f1b5db98ce3d1b6ec09dfe888518f
3664677fb204609eb5c11a0bc715d4ced8521732
/hadoop_examples_post/src/MaxTemperatureMapper.java
d60145b6d5125caef78fa35229ef402bdb41750b
[]
no_license
superpenshine/MapReduce_Hadoop_Spark
6bc78bb9f32565f5be283eca1f3687c015b4f5a0
c4e3039b373a937c4ae9b674e472938ddcb0cfba
refs/heads/master
2021-04-26T23:50:54.345385
2018-03-05T05:29:34
2018-03-05T05:29:34
123,868,959
0
0
null
null
null
null
UTF-8
Java
false
false
952
java
import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private static final int MISSING = 9999; @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String year = line.substring(15, 19); int airTemperature; if (line.charAt(87) == '+') { // parseInt doesn't like leading plus // signs airTemperature = Integer.parseInt(line.substring(88, 92)); } else { airTemperature = Integer.parseInt(line.substring(87, 92)); } String quality = line.substring(92, 93); if (airTemperature != MISSING && quality.matches("[01459]")) { context.write(new Text(year), new IntWritable(airTemperature)); } } }
4846d6fd31684f7fced7f6fad320801f290a33a8
2086f395539868c339459e724f6c52e6cb1256e3
/springdatajpa/jpa4/src/main/java/com/ce/domain/LinkMan.java
3223564b9c319d6029fc6fee7941c8595da6ec1d
[]
no_license
cije/Study_SpringDataJPA
0619c549bc03aa840853eaea9434ada08a7f43b2
78f60f1d86aad7f4478e88cafb47b86693d8d094
refs/heads/master
2022-12-04T05:40:27.498435
2020-08-25T03:04:42
2020-08-25T03:04:42
289,472,815
0
0
null
null
null
null
UTF-8
Java
false
false
3,475
java
package com.ce.domain; import lombok.Data; import javax.persistence.*; @Entity @Table(name = "cst_linkman") public class LinkMan { /** * 联系人编号(主键) */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "lkm_id") private Long lkmId; /** * 联系人姓名 */ @Column(name = "lkm_name") private String lkmName; /** * 联系人性别 */ @Column(name = "lkm_gender") private String lkmGender; /** * 联系人办公电话 */ @Column(name = "lkm_phone") private String lkmPhone; /** * 联系人手机 */ @Column(name = "lkm_mobile") private String lkmMobile; /** * 联系人邮箱 */ @Column(name = "lkm_email") private String lkmEmail; /** * 联系人职位 */ @Column(name = "lkm_position") private String lkmPosition; /** * 联系人备注 */ @Column(name = "lkm_memo") private String lkmMemo; /** * 配置联系人到客户的多对一关系 * <pre> * 使用注解的形式配置多对一关系 * 1.配置表关系 * \@ManyToOne:配置多对一关系 * targetEntity:对方的字节码 * 2.配置外键(中间表) * \@JoinColumn * 配置外键的过程,配置到了多的一方,就会在多的乙方维护外键 * </pre> */ @ManyToOne(targetEntity = Customer.class) @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id") private Customer customer; public Long getLkmId() { return lkmId; } public void setLkmId(Long lkmId) { this.lkmId = lkmId; } public String getLkmName() { return lkmName; } public void setLkmName(String lkmName) { this.lkmName = lkmName; } public String getLkmGender() { return lkmGender; } public void setLkmGender(String lkmGender) { this.lkmGender = lkmGender; } public String getLkmPhone() { return lkmPhone; } public void setLkmPhone(String lkmPhone) { this.lkmPhone = lkmPhone; } public String getLkmMobile() { return lkmMobile; } public void setLkmMobile(String lkmMobile) { this.lkmMobile = lkmMobile; } public String getLkmEmail() { return lkmEmail; } public void setLkmEmail(String lkmEmail) { this.lkmEmail = lkmEmail; } public String getLkmPosition() { return lkmPosition; } public void setLkmPosition(String lkmPosition) { this.lkmPosition = lkmPosition; } public String getLkmMemo() { return lkmMemo; } public void setLkmMemo(String lkmMemo) { this.lkmMemo = lkmMemo; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Override public String toString() { return "LinkMan{" + "lkmId=" + lkmId + ", lkmName='" + lkmName + '\'' + ", lkmGender='" + lkmGender + '\'' + ", lkmPhone='" + lkmPhone + '\'' + ", lkmMobile='" + lkmMobile + '\'' + ", lkmEmail='" + lkmEmail + '\'' + ", lkmPosition='" + lkmPosition + '\'' + ", lkmMemo='" + lkmMemo + '\'' + '}'; } }
0927b2efb0991a227313dbd4cc14ea904a657590
742f351eb3f1f2b7e5c089b1929e2c4176af06cb
/framework/src/test/java/or/CustomersPage.java
3046e7e35b34bd8cc1159a7d160e54ceaefb5369
[]
no_license
ranimaddineni/mavenframes
d58b843664e997d05c005941264f89dc59c21662
e2b40bd45d9898182bee386b256eb976954a02ce
refs/heads/master
2023-05-13T01:50:47.765406
2019-11-14T17:49:19
2019-11-14T17:49:19
221,734,035
0
0
null
2023-05-09T18:17:38
2019-11-14T15:53:24
HTML
UTF-8
Java
false
false
544
java
package or; import org.openqa.selenium.By; public class CustomersPage /*public static By txtUserName=By.name("username"); public static By txtPassword=By.name("password"); public static By clickLogin=By.xpath("//*[@id='tdb1']");*/ { public static By lnkCustomer =By.linkText("Customers"); public static By lnkOrders=By.linkText("Orders"); public static By btnEdit=By.xpath("//span[text()='Edit']"); public static By txtComments=By.name("comments"); public static By btnUpdate=By.xpath("//span[text()='Update']"); }
ffa53c17f1f41b23614c71c8fb442dcc571f76a6
4dfc9549c1be20a727fc0feb2594e36526a17ab7
/Lesson5/JAVA/Problem5/src/ru/geekbrain/Main.java
2d668901b2b74101e4624cdad1854ba271e19fcd
[]
no_license
DwarfPorter/Interview
6c5bf11b16dfc6689ecec2a6e44dbe3476154870
e8fbca2f16faa65c199fff0c36fca242d9149d97
refs/heads/master
2021-06-14T03:27:59.391556
2020-10-23T15:43:42
2020-10-23T15:43:42
100,819,393
1
23
null
2020-10-23T19:26:56
2017-08-19T20:22:56
Java
UTF-8
Java
false
false
288
java
package ru.geekbrain; public class Main { public static void main(String[] args) { Integer i1 = 64; Integer i2 = 64; Integer i3 = 256; Integer i4 = 256; System.out.println(i1 == i2); System.out.println(i3 == i4); } }
f78b9112324eb193a513edbb67321e252a2d8207
b39d7e1122ebe92759e86421bbcd0ad009eed1db
/sources/android/os/ProcrankProto.java
dc8cb94808e0a644b17039abfaa17fc5c2d15c2e
[]
no_license
AndSource/miuiframework
ac7185dedbabd5f619a4f8fc39bfe634d101dcef
cd456214274c046663aefce4d282bea0151f1f89
refs/heads/master
2022-03-31T11:09:50.399520
2020-01-02T09:49:07
2020-01-02T09:49:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,229
java
package android.os; public final class ProcrankProto { public static final long PROCESSES = 2246267895809L; public static final long SUMMARY = 1146756268034L; public final class Process { public static final long CMDLINE = 1138166333450L; public static final long PID = 1120986464257L; public static final long PSS = 1112396529668L; public static final long PSWAP = 1112396529671L; public static final long RSS = 1112396529667L; public static final long SWAP = 1112396529670L; public static final long USS = 1112396529669L; public static final long USWAP = 1112396529672L; public static final long VSS = 1112396529666L; public static final long ZSWAP = 1112396529673L; } public final class Summary { public static final long RAM = 1146756268035L; public static final long TOTAL = 1146756268033L; public static final long ZRAM = 1146756268034L; public final class Ram { public static final long RAW_TEXT = 1138166333441L; } public final class Zram { public static final long RAW_TEXT = 1138166333441L; } } }
e836a0d667c84ef835acee332b23baa1bccd9f00
1ee2d2ff81cc5f4dbd45964184f21d03bf4b56cb
/vitro-core/webapp/src/edu/cornell/mannlib/vitro/webapp/auth/requestedAction/admin/RebuildTextIndex.java
00de6af3145f9e032634c7efb5c6d53a19f943b3
[]
no_license
arockwell/vivoweb_ufl_mods
d689e0e467c64e5b349f04485f412fb0ec151442
e5a1e9d15f47e85e48604544bead10814f2a11e3
refs/heads/master
2021-03-12T23:00:19.435131
2011-06-28T14:43:35
2011-06-28T14:46:15
859,154
1
0
null
null
null
null
UTF-8
Java
false
false
2,429
java
/* Copyright (c) 2011, Cornell University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Cornell University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.VisitingPolicyIface; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.AdminRequestedAction; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction; public class RebuildTextIndex implements RequestedAction , AdminRequestedAction{ public String getURI() { return RequestActionConstants.actionNamespace + this.getClass().getName(); } public PolicyDecision accept(VisitingPolicyIface policy, IdentifierBundle ids){ return policy.visit(ids,this); } }
da7c3292114aa5befaeac84ce88cd59bdd5b3305
a18b5815186f31be3b4845011a6781599c22d85e
/src/main/java/org/andresoviedo/util/cache/persisted/api1/PersistedListFactory.java
55a3d14e5bc3a0a62c449f4a6c1ccf8d40a374d2
[]
no_license
andresoviedo/java-utilities
0e07a2518b1ed6163980f665efdfed27f30c6da7
5d5352d12bb5b50dae5ed5a6ba59670edae2dee0
refs/heads/master
2020-04-12T03:17:46.562829
2017-03-08T21:41:32
2017-03-08T21:41:32
13,735,388
2
3
null
null
null
null
UTF-8
Java
false
false
2,272
java
package org.andresoviedo.util.cache.persisted.api1; import java.io.File; import java.io.Serializable; import org.andresoviedo.util.serialization.api1.XMLSerializable; public class PersistedListFactory { final public static int TYPE_SERIALIZE = 0; final public static int TYPE_XML = 1; private PersistedListFactory() { } @SuppressWarnings({ "rawtypes" }) public static PersistedList<?> getObjectStorage(File targetFile, int type) { PersistedList<?> ret = null; switch (type) { case TYPE_SERIALIZE: ret = new SerializablePersistedList(targetFile); break; case TYPE_XML: ret = new XMLPersistedList(targetFile); break; default: throw new IllegalArgumentException("Non valid object storage type!!"); } ret.loadObjects(); return ret; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> PersistedList<T> getObjectStorage(Class<T> clazz, File targetFile, int type) { PersistedList<T> ret = null; switch (type) { case TYPE_SERIALIZE: if (!(Serializable.class.isAssignableFrom(clazz))) { throw new IllegalArgumentException(clazz + " is not assignable to " + Serializable.class.toString()); } ret = new SerializablePersistedList<T>(targetFile); break; case TYPE_XML: if (!(XMLSerializable.class.isAssignableFrom(clazz))) { throw new IllegalArgumentException(clazz + " is not assignable to " + XMLSerializable.class.toString()); } ret = new XMLPersistedList(targetFile); break; default: throw new IllegalArgumentException("Non valid object storage type!!"); } ret.loadObjects(); return ret; } public static <T> PersistedList<T> getObjectStorage(Class<T> clazz, File targetFile) { return getObjectStorage(clazz, targetFile, TYPE_SERIALIZE); } public static <T> PersistedList<T> getObjectStorage(Class<T> clazz, String targetFilePath, int type) { return getObjectStorage(clazz, new File(targetFilePath), type); } public static PersistedList<?> getObjectStorage(File targetFile) { return getObjectStorage(targetFile, TYPE_SERIALIZE); } public static PersistedList<?> getObjectStorage(String targetFilePath, int type) { return getObjectStorage(new File(targetFilePath), type); } }
7d2ffc958193e8d7a346c2d8a739f460ec151d92
d8d2e5b940bfa0d2667228a32a7a2778d3d523af
/mycellar-java/mycellar-interfaces/mycellar-interface-client-web/src/main/java/fr/peralta/mycellar/interfaces/client/web/components/stock/edit/DrinkBottlesEditPanel.java
348b19605550b1f5eabf5f5a149fe80bb0646901
[]
no_license
framiere/mycellar
1143cc284c3b096d38f8c357355cc5a610de52ee
e206a8971f7b0988cf55aa70faba338b71634e99
refs/heads/master
2021-01-18T05:49:38.152662
2012-12-23T07:03:29
2012-12-23T07:03:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,632
java
/* * Copyright 2011, MyCellar * * This file is part of MyCellar. * * MyCellar 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. * * MyCellar 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 MyCellar. If not, see <http://www.gnu.org/licenses/>. */ package fr.peralta.mycellar.interfaces.client.web.components.stock.edit; import java.util.List; import org.apache.wicket.event.IEventSource; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.FormComponentPanel; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.PropertyListView; import fr.peralta.mycellar.domain.stock.DrinkBottle; import fr.peralta.mycellar.interfaces.client.web.behaviors.NotEmptyCollectionValidator; import fr.peralta.mycellar.interfaces.client.web.components.shared.Action; import fr.peralta.mycellar.interfaces.client.web.components.shared.ActionLink; /** * @author speralta */ public class DrinkBottlesEditPanel extends FormComponentPanel<List<DrinkBottle>> { private static class DrinkBottlesView extends PropertyListView<DrinkBottle> { private static final long serialVersionUID = 201108082321L; /** * @param id */ public DrinkBottlesView(String id) { super(id); setReuseItems(true); } /** * {@inheritDoc} */ @Override protected void populateItem(ListItem<DrinkBottle> item) { item.add(new Label("bottle.wine.appellation.region.country.name")); item.add(new Label("bottle.wine.appellation.region.name")); item.add(new Label("bottle.wine.appellation.name")); item.add(new Label("bottle.wine.producer.name")); item.add(new Label("bottle.wine.name")); item.add(new Label("bottle.wine.vintage")); item.add(new Label("bottle.format.name")); item.add(new Label("quantity")); item.add(new WebMarkupContainer("remove").add(removeLink("removeBottle", item))); } } private static final long serialVersionUID = 201202231626L; private static final String NO_BOTTLES_COMPONENT_ID = "noBottles"; private final ActionLink addBottle; /** * @param id */ public DrinkBottlesEditPanel(String id) { super(id); add(new DrinkBottlesView("drinkBottles")); add(addBottle = new ActionLink("addBottle", Action.ADD)); add(new WebMarkupContainer(NO_BOTTLES_COMPONENT_ID) { private static final long serialVersionUID = 201108082329L; /** * {@inheritDoc} */ @Override public boolean isVisible() { return DrinkBottlesEditPanel.this.getModelObject().size() == 0; } }); add(new NotEmptyCollectionValidator()); } /** * {@inheritDoc} */ @Override protected void convertInput() { setConvertedInput(getModelObject()); } public boolean isAddBottle(IEventSource source) { return addBottle == source; } }
51758e935b820320a42a5f7f17e108d907b60d2c
a9db5bf738dc41c1e12f2f258a7b5d334da7ddcf
/src/main/java/com/wuyemy/dao/YyzxsqMapper.java
090c47d7965a23589bfcd94a181a820fa23e47aa
[]
no_license
gitzrh/WuYeMaYi
1be1f364e7908c1f07d4f3dcd644907d2066217e
e1c13de2e69b085305ed4b21cc345ea38068ea6c
refs/heads/master
2022-12-25T19:59:53.649338
2019-06-19T05:36:19
2019-06-19T05:36:19
178,990,103
1
0
null
2022-12-16T11:16:59
2019-04-02T03:15:48
Java
UTF-8
Java
false
false
841
java
package com.wuyemy.dao; import com.wuyemy.bean.Yyzxsq; import com.wuyemy.bean.YyzxsqExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface YyzxsqMapper { long countByExample(YyzxsqExample example); int deleteByExample(YyzxsqExample example); int deleteByPrimaryKey(Integer id); int insert(Yyzxsq record); int insertSelective(Yyzxsq record); List<Yyzxsq> selectByExample(YyzxsqExample example); Yyzxsq selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Yyzxsq record, @Param("example") YyzxsqExample example); int updateByExample(@Param("record") Yyzxsq record, @Param("example") YyzxsqExample example); int updateByPrimaryKeySelective(Yyzxsq record); int updateByPrimaryKey(Yyzxsq record); }
c5ea1a4a54aa2fe4250f4b8517b6d6fa1825f95e
6491c3a11f29a4fd36bd19561f8d5acae3ad981d
/module-template/module-elasticsearch/src/main/java/com/wjs/elasticsearch/elastic/index/DefaultIndexManage.java
6a48bda5717e36691fa3309aa0d8d0ebea97059d
[]
no_license
wjs1989/spring-cloud-template
89c7c760b178e2005f41801479c89081ded0a1a7
2f967c15d392d9def8732154480545fc070d8294
refs/heads/master
2023-06-18T18:02:09.066094
2021-07-13T10:32:27
2021-07-13T10:32:27
289,705,639
0
0
null
null
null
null
UTF-8
Java
false
false
3,298
java
package com.wjs.elasticsearch.elastic.index; import com.wjs.elasticsearch.elastic.annotations.EsDocument; import com.wjs.elasticsearch.elastic.index.strategy.DirectElasticSearchIndexStrategy; import com.wjs.elasticsearch.elastic.index.strategy.ElasticSearchIndexStrategy; import com.wjs.elasticsearch.elastic.index.strategy.MonthElasticSearchIndexStrategy; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** * @author wenjs */ public class DefaultIndexManage implements IndexManage { public HashMap<Class, IndexDetial> indexClassMap = new HashMap<>(); public HashMap<String, IndexDetial> indexStringMap = new HashMap<>(); public HashMap<String, ElasticSearchIndexStrategy> indexStrategy = new HashMap<>(); public String wrapIndex(String index) { return index.toLowerCase(); } private IndexDetial getIndex(Class clasz) { IndexDetial index = indexClassMap.get(clasz); if (Objects.isNull(index)) { EsDocument annotation = (EsDocument) clasz.getDeclaredAnnotation(EsDocument.class); if (annotation == null) { throw new RuntimeException(String.format("class name: %s can not find Annotation [EsDocument], please check", clasz.getName())); } index = new IndexDetial(annotation.strategy(), wrapIndex(annotation.index())); indexClassMap.put(clasz, index); indexStringMap.put(index.getIndex(), index); } return index; } @Override public String getIndexForSearch(String index) { IndexDetial indexDetial = indexStringMap.get(index); return getElasticSearchIndexStrategy(indexDetial.getStrategy()) .getIndexForSearch(indexDetial.getIndex()); } @Override public String getIndexForSave(String index) { IndexDetial indexDetial = indexStringMap.get(index); return getElasticSearchIndexStrategy(indexDetial.getStrategy()) .getIndexForSave(indexDetial.getIndex()); } @Override public String getIndexForSearch(Class clasz) { IndexDetial index = getIndex(clasz); return getElasticSearchIndexStrategy(index.getStrategy()).getIndexForSearch(index.getIndex()); } @Override public String getIndexForSave(Class clasz) { IndexDetial index = getIndex(clasz); return getElasticSearchIndexStrategy(index.getStrategy()).getIndexForSave(index.getIndex()); } ElasticSearchIndexStrategy getElasticSearchIndexStrategy(String strategy) { return indexStrategy.getOrDefault(strategy, indexStrategy.get("direct")); } static class IndexDetial { private String index; private String strategy; public IndexDetial(String strategy, String index) { this.strategy = strategy; this.index = index; } public String getStrategy() { return strategy; } public String getIndex() { return index; } } public DefaultIndexManage() { indexStrategy.put("direct", new DirectElasticSearchIndexStrategy()); indexStrategy.put("month", new MonthElasticSearchIndexStrategy()); } }
982a2db98d9913da8aa9838288bc316fd5e5acd9
2373656061a138b1d2bef5682baf15ca7d3c8312
/src/java/com/kelaniya/uni/V5/CalculatorApp.java
8db000a479a987ac0f8f0eadb932c0c7e9b205e8
[]
no_license
tharaka-ariyarathna/Calculator
908583a95a7efeca1f55efc00167beb35240a656
23dcc74599cecd371cf2b7985e36c50ce6f07575
refs/heads/main
2023-08-16T04:32:44.087804
2021-09-29T10:41:12
2021-09-29T10:41:12
393,753,474
0
0
null
null
null
null
UTF-8
Java
false
false
1,536
java
package com.kelaniya.uni.V5; import com.kelaniya.uni.V5.Operation.InvalidOperationException; import com.kelaniya.uni.V5.Operation.Operation; import com.kelaniya.uni.V5.Operation.OperationFactory; import com.kelaniya.uni.V5.input.Inputs; import com.kelaniya.uni.V5.input.invalidInputException; import com.kelaniya.uni.V5.repository.NumberRepository; import com.kelaniya.uni.V5.repository.numberRepositoryException; import com.kelaniya.uni.V5.ui.UI; import java.io.IOException; public class CalculatorApp { private final Inputs inputs; private final NumberRepository numberRepository; private final OperationFactory operationFactory; private final UI ui; public CalculatorApp(Inputs inputs, NumberRepository numberRepository, OperationFactory operationFactory, UI ui) { this.inputs = inputs; this.numberRepository = numberRepository; this.operationFactory = operationFactory; this.ui = ui; } public void execute() throws IOException { try { String operator = inputs.getOperato(); double[] numbers = numberRepository.getNumbers(); Operation operation = operationFactory.getOperator(operator) ; double result ; result = operation.execute(numbers); ui.showMessage("result is " + result); } catch (InvalidOperationException | invalidInputException | numberRepositoryException e) { ui.showMessage("error occured\n" + e.getMessage()); return; } } }
6f54d815fecdb68a5c9b5ddb9a38f7f51d0f31f2
0fe9415cf55adab6b3b4e374483c34cdc6a9cd5e
/src/com/wurmonline/server/behaviours/ManageBuyerAction.java
b924fc1afb2b53cb271def45a2fea511117ec7a2
[]
no_license
Mthec/BuyerMerchant
dc9c8ba02f785be2493a369fbd37d484d250ad44
0833e06d24446983ca1f94580851715db5a4d19e
refs/heads/master
2022-09-27T15:58:16.674197
2022-08-14T17:13:06
2022-08-14T17:13:06
161,517,205
2
2
null
null
null
null
UTF-8
Java
false
false
4,382
java
package com.wurmonline.server.behaviours; import com.wurmonline.server.Items; import com.wurmonline.server.creatures.Creature; import com.wurmonline.server.creatures.CreatureTemplateIds; import com.wurmonline.server.items.Item; import com.wurmonline.server.questions.BuyerManagementQuestion; import org.gotti.wurmunlimited.modsupport.actions.*; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.logging.Logger; public class ManageBuyerAction implements ModAction, ActionPerformer, BehaviourProvider { private static final Logger logger = Logger.getLogger(ManageBuyerAction.class.getName()); public static byte gmManagePowerRequired; private final short actionId; private final List<ActionEntry> entries; private final List<ActionEntry> empty = Collections.emptyList(); public ManageBuyerAction() { actionId = (short)ModActions.getNextActionId(); ActionEntry actionEntry = new ActionEntryBuilder(actionId, "Manage traders", "managing traders").build(); ModActions.registerAction(actionEntry); entries = Collections.singletonList(actionEntry); } private static boolean writValid(Creature performer, Creature buyer, @Nullable Item writ) { return writ != null && writ.getTemplateId() == CopyPriceListAction.contractTemplateId && performer.getInventory().getItems().contains(writ) && writ.getData() == buyer.getWurmId(); } private static boolean canManage(Creature performer, Creature buyer, @Nullable Item item) { if (!(performer.isPlayer() && buyer.getName().startsWith("Buyer_") && buyer.getTemplate().id == CreatureTemplateIds.SALESMAN_CID)) return false; return performer.getPower() >= gmManagePowerRequired || writValid(performer, buyer, item); } private static Item getWrit(Creature performer, Creature buyer) { Optional<Item> maybeItem = performer.getInventory().getItems().stream() .filter(i -> i.getTemplateId() == CopyPriceListAction.contractTemplateId && i.getData() == buyer.getWurmId()).findAny(); if (maybeItem.isPresent()) { return maybeItem.get(); } maybeItem = Arrays.stream(Items.getAllItems()) .filter(i -> i.getTemplateId() == CopyPriceListAction.contractTemplateId && i.getData() == buyer.getWurmId()).findAny(); return maybeItem.orElse(null); } private List<ActionEntry> getBehaviours(Creature performer, Creature buyer, @Nullable Item subject) { if (canManage(performer, buyer, subject)) { return entries; } return empty; } @Override public List<ActionEntry> getBehavioursFor(Creature performer, Item subject, Creature target) { return getBehaviours(performer, target, subject); } @Override public List<ActionEntry> getBehavioursFor(Creature performer, Creature target) { return getBehaviours(performer, target, null); } private boolean action(Creature performer, Creature buyer, @Nullable Item item) { Item writ = getWrit(performer, buyer); if (writ != null && canManage(performer, buyer, item)) { new BuyerManagementQuestion(performer, writ.getWurmId()).sendQuestion(); } else if (writ == null) { logger.warning("Could not find buyer's (" + buyer.getName() + ") contract on owner (" + buyer.getShop().getOwnerId() + ")."); performer.getCommunicator().sendNormalServerMessage("Could not find the buyer's contract."); } return true; } @Override public boolean action(Action action, Creature performer, Item source, Creature target, short num, float counter) { if (num == actionId) { return action(performer, target, source); } return true; } @Override public boolean action(Action action, Creature performer, Creature target, short num, float counter) { if (num == actionId) { return action(performer, target, null); } return true; } @Override public short getActionId() { return actionId; } }
f628c90a6d1ca0f17bd2806bbef0095b942654e5
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/apache-harmony/luni/src/test/api/common/org/apache/harmony/luni/tests/java/net/SocketImplTest.java
9f1605c5686126851f937ea6915b0df654e62563
[ "MIT", "Apache-2.0" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
Java
false
false
4,678
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.luni.tests.java.net; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketImpl; public class SocketImplTest extends junit.framework.TestCase { /** * @tests java.net.SocketImpl#SocketImpl() */ public void test_Constructor_fd() { // Regression test for HARMONY-1117 MockSocketImpl mockSocketImpl = new MockSocketImpl(); assertNull(mockSocketImpl.getFileDescriptor()); } /** * @tests java.net.SocketImpl#setPerformancePreference() */ public void test_setPerformancePreference_Int_Int_Int() { MockSocketImpl theSocket = new MockSocketImpl(); theSocket.setPerformancePreference(1, 1, 1); } /** * @tests java.net.SocketImpl#shutdownOutput() */ public void test_shutdownOutput() { MockSocketImpl s = new MockSocketImpl(); try { s.shutdownOutput(); fail("This method is still not implemented yet,It should throw IOException."); } catch (IOException e) { // expected } } /** * @tests java.net.SocketImpl#shutdownInput() */ public void test_shutdownInput() { MockSocketImpl s = new MockSocketImpl(); try { s.shutdownInput(); fail("This method is still not implemented yet,It should throw IOException."); } catch (IOException e) { // Expected } } /** * @tests java.net.SocketImpl#supportsUrgentData() */ public void test_supportsUrgentData() { MockSocketImpl s = new MockSocketImpl(); assertFalse(s.testSupportsUrgentData()); } // the mock class for test, leave all methods empty class MockSocketImpl extends SocketImpl { protected void accept(SocketImpl newSocket) throws IOException { } protected int available() throws IOException { return 0; } protected void bind(InetAddress address, int port) throws IOException { } protected void close() throws IOException { } protected void connect(String host, int port) throws IOException { } protected void connect(InetAddress address, int port) throws IOException { } protected void create(boolean isStreaming) throws IOException { } protected InputStream getInputStream() throws IOException { return null; } public Object getOption(int optID) throws SocketException { return null; } protected OutputStream getOutputStream() throws IOException { return null; } protected void listen(int backlog) throws IOException { } public void setOption(int optID, Object val) throws SocketException { } protected void connect(SocketAddress remoteAddr, int timeout) throws IOException { } protected void sendUrgentData(int value) throws IOException { } public void setPerformancePreference(int connectionTime, int latency, int bandwidth) { super.setPerformancePreferences(connectionTime, latency, bandwidth); } public FileDescriptor getFileDescriptor() { return super.getFileDescriptor(); } public void shutdownOutput() throws IOException { super.shutdownOutput(); } public void shutdownInput() throws IOException{ super.shutdownInput(); } public boolean testSupportsUrgentData() { return super.supportsUrgentData(); } } }
9310cd4845fad6366ef00e275eb7504dca181277
c75d7adce49aaece67d77c0e4df2e3bbbeb53b94
/core/src/test/java/hello/core/autowired/AutowiredTest.java
9bc6848806d5486dd52b4cc22454af654faf458f
[]
no_license
tunagiant/spring1
131eee4ede2fd741247f0283b0b57898453b5d4e
cd67a3a326500d324984c8af4396c100c661d9a8
refs/heads/master
2023-05-02T22:57:44.858541
2021-05-31T17:42:57
2021-05-31T17:42:57
338,816,967
1
0
null
null
null
null
UTF-8
Java
false
false
1,018
java
package hello.core.autowired; import hello.core.member.Member; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.lang.Nullable; import java.util.Optional; public class AutowiredTest { @Test void AutowiredOption() { ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class); } static class TestBean { @Autowired(required = false) public void setNobean1(Member nobean1) { System.out.println("nobean1 = " + nobean1); } @Autowired public void setNobean2(@Nullable Member nobean2) { System.out.println("nobean2 = " + nobean2); } @Autowired public void setNobean3(Optional<Member> nobean3) { System.out.println("nobean3 = " + nobean3); } } }
bc104164cfae92617189338e5df8e50506e6eaea
c2a9ea230ebeef2a653fb62343bb9df47fc40c50
/src/main/java/com/lx/springbootdemo/dto/OrderDTO.java
212179d0e38e7bcdad2bb048f7ea5d51c1b603e4
[]
no_license
lx354081082/spring-boot-demo
93f5e9165c25752f6d184adf9241034f0eb77a62
9f7b9bf7840b02be8cb6ddd3299b29a42a98ab8d
refs/heads/master
2021-05-09T22:52:52.575505
2018-01-24T13:08:01
2018-01-24T13:08:01
118,766,786
0
0
null
null
null
null
UTF-8
Java
false
false
826
java
package com.lx.springbootdemo.dto; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import lombok.Data; import java.io.IOException; import java.math.BigDecimal; import java.util.List; /** * Created by lx on 2018/1/22 */ @Data public class OrderDTO { private String name; private String phone; private String address; private String openid; private List<ProductItemDTO> items; public void setItems(String items) { ObjectMapper objectMapper = new ObjectMapper(); try { this.items = objectMapper.readValue(items, new TypeReference<List<ProductItemDTO>>() { }); } catch (IOException e) { e.printStackTrace(); } } }
0f88c2926f8749612ab2b5fb5a119cbb8734d354
66362e79c0bbdcb87c5a92e6de1fdd7c0ecc594a
/inlong-dataproxy-sdk/src/main/java/org/apache/inlong/dataproxy/threads/IndexCollectThread.java
938abe0a10377f43db647810d500995593a673eb
[ "Apache-2.0", "LicenseRef-scancode-compass", "MIT", "BSD-3-Clause" ]
permissive
chun2333/incubator-inlong
1d1bc2a6b12631be58abb4f57d6f4b42ded11fef
95c5232735f217132537650211c94db4e7441b3b
refs/heads/master
2023-09-03T05:21:44.704893
2021-11-23T01:57:12
2021-11-23T01:57:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,526
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.dataproxy.threads; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Map; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * index collector */ public class IndexCollectThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(IndexCollectThread.class); private volatile boolean bShutDown; private final Map<String, Long> storeIndex; public IndexCollectThread(Map<String, Long> storeIndex) { bShutDown = false; this.storeIndex = storeIndex; this.setDaemon(true); this.setName("IndexCollectThread"); } public void shutDown() { logger.info("begin to shut down IndexCollectThread!"); bShutDown = true; } @Override public void run() { logger.info("IndexCollectThread Thread=" + Thread.currentThread().getId() + " started !"); while (!bShutDown) { try { TimeUnit.MILLISECONDS.sleep(60 * 1000); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Map.Entry<String, Long> entry : storeIndex.entrySet()) { String key = entry.getKey(); Long val = entry.getValue(); key = "|" + sdf.format(System.currentTimeMillis()) + "|" + key; logger.info("Monitor {} send message {}", key, val); entry.setValue(0L); } } catch (Exception e) { if (!bShutDown) { logger.error("IndexCollectThread exception", e); } } } } }
c8b13407fe4014bdef0a69f15ea8c27c8d7aecf8
f82c0840cfcc342502c8d5ddb5d4b8c2a4944a1e
/app/src/main/java/com/qizhenkeji/yxb/model/PaymentDetailModel.java
3f56d4226e5b433ced303b9f35d9b53eb9928bd8
[]
no_license
cmmzjwz99/YXB
ed2e57eb785996385ad61e51f72c51834ec402da
d65c8b2e3b511e61cfa255973550b4a715e34700
refs/heads/master
2020-03-23T06:45:38.526389
2018-07-17T03:45:28
2018-07-17T03:45:28
141,227,837
0
1
null
null
null
null
UTF-8
Java
false
false
475
java
package com.qizhenkeji.yxb.model; /** * Created by hc101 on 18/6/16. */ public class PaymentDetailModel extends BaseModel { public int id; public String time; public String type; public String lines; public String fees; public PaymentDetailModel(int id, String type, String time, String lines, String fees) { this.id = id; this.time = time; this.type = type; this.lines = lines; this.fees = fees; } }
7f0420b40e82cb7040ec1661ed4bcd5c23a37f68
a9d9e90c9e317850d0f1fe758e2cfc57220edbb2
/src/com/tuongky/model/GameQuery.java
a3466f52ae2f36adb2b229d4fc157e144e9be9ef
[ "MIT" ]
permissive
trinhhai/tuongky
b5aa273b97154229d76558c4e48b74b265182e4c
b9beb3acf0769d6b568faf5d2993d322cb2c29a4
refs/heads/master
2020-07-12T01:14:19.701370
2014-02-04T08:00:37
2014-02-04T08:00:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,096
java
package com.tuongky.model; public class GameQuery { private final String queryString; private final String category; private final String title; private final String book; private final int offset; public GameQuery(String queryString, String category, String title, String book, int offset) { this.queryString = queryString; this.category = category; this.title = title; this.book = book; this.offset = offset; } public String getQueryString() { return queryString; } public String getCategory() { return category; } public String getTitle() { return title; } public String getBook() { return book; } public int getOffset() { return offset; } private boolean hasContent(String s) { return s != null && s.trim().length() > 0; } public boolean hasQueryString() { return hasContent(queryString); } public boolean hasCategory() { return hasContent(category); } public boolean hasTitle() { return hasContent(title); } public boolean hasBook() { return hasContent(book); } }
c7689241ae14eaf73b6d05581355833aeb2b6728
bd71f4dc7833627537b0a009686fc2900f8a4e21
/app/src/main/java/com/android/instateronapp/events/CardAdapter.java
bf678d8a64a00866b3df89d8deeafa397b28a17b
[]
no_license
taracaca/instateronapp
88f42d8f6729b7d5ac38b8ba6ec4a9afaa872e8d
485c72dec7af05a5b74bf168d4f5e7a1b8376945
refs/heads/master
2020-04-03T18:16:43.687207
2018-11-05T04:39:29
2018-11-05T04:39:29
155,477,010
0
0
null
null
null
null
UTF-8
Java
false
false
251
java
package com.android.instateronapp.events; import android.support.v7.widget.CardView; public interface CardAdapter { int MAX_ELEVATION_FACTOR = 8; float getBaseElevation(); CardView getCardViewAt(int position); int getCount(); }
06f33593705a456fccec4eded324af2f83f8c5a0
96afeeb52833a1ed17d057287a11400dc166b26a
/ExerciseSolution/src/examQuestionExample/Puma.java
755dbd963c1342485ae8ba2981490b79ce2e2e30
[]
no_license
NineFourFour/eclipseJava
4322bec27c8a292c6fcdf6a4d7f3d4703ae99a94
43472e32daf2f2c7eb6132de7611d191a9dea162
refs/heads/master
2021-01-21T12:16:27.995628
2017-09-04T13:15:17
2017-09-04T13:15:17
91,784,827
0
0
null
null
null
null
UTF-8
Java
false
false
281
java
package examQuestionExample; abstract class Puma implements HasTail { /*has to be public, all methods declared in an interface are public * can change the visibility protected int getTailLength(){ return 4; }*/ public int getTailLength(){ return 4; } }
656d6dcdcf43963e50b446b1c38c6650d9d691e0
d1aa3efaff49fad20c801f7130de424f802b1199
/springcloud-consumer02-feign/src/main/java/com/swift/service/ProviderService.java
13c5463db703035b03fc1507c92fb86849e830d6
[]
no_license
ListenerSun/springcloud
492df07aaf27fa6458f3eeed45ae548d77fcaf67
a3881da5dd2c3791232312327c1dc1dedd2874be
refs/heads/master
2020-11-27T21:14:41.225898
2019-12-22T17:15:13
2019-12-22T17:15:13
148,614,509
0
0
null
null
null
null
UTF-8
Java
false
false
373
java
package com.swift.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; /** * HelloService * 使用@FeignClient注解,name为服务的名字 * @author sqt * @date 19-4-20 **/ @FeignClient("Provier") public interface ProviderService { @GetMapping("/hello") public String callService(); }
ef209565083ad687b484b491ac7f9b1bf95693eb
b15fcbea84500825b454a8e0fca67e6c4a8c9cef
/ControlObligaciones/ControlObligaciones/src/main/java/mx/gob/sat/siat/cob/seguimiento/dao/stdcob/impl/VigilanciaAdministracionLocalDAOImpl.java
015ff57aec5b95697add691a8f13f9efa34324ff
[]
no_license
xtaticzero/COB
0416523d1bbc96d6024df5eca79172cb0927423f
96082d47e4ffb97dd6e61ce42feee65d5fe64e50
refs/heads/master
2021-09-09T22:02:10.153252
2018-03-20T00:18:00
2018-03-20T00:18:00
125,936,388
0
0
null
null
null
null
UTF-8
Java
false
false
11,715
java
package mx.gob.sat.siat.cob.seguimiento.dao.stdcob.impl; import java.sql.Types; import java.util.ArrayList; import java.util.Date; import java.util.List; import mx.gob.sat.siat.cob.seguimiento.dao.stdcob.VigilanciaAdministracionLocalDAO; import mx.gob.sat.siat.cob.seguimiento.dao.stdcob.impl.mapper.VigilanciaAdministracionLocalBatchMapper; import mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.ACTUALIZAR_FECHA_VIGILANCIA; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.ACTUALIZAR_ID_SITUACION_VIGILANCIA; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.ACTUALIZA_ESTADOEJECUCION_PROCESO_ARCHIVOS; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.CUENTA_REGISTRO_X_VIGILANCIA; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.ID_VIGILANCIA_ENVIA_ARCHIVOS; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.INSERT_VIGILANCIA_ADMIN_LOCAL; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.LOCAL; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.OBTENER_VIGILANCIAS_CON_DOCUMENTOS; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.OBTENER_VIGILANCIA_A_PROCESAR; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.OBTENER_VIGILANCIA_MULTA_A_PROCESAR; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.UPDATE_FECHA; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.OBTENER_VIGILANCIA; import static mx.gob.sat.siat.cob.seguimiento.dao.stdcob.sql.VigilanciaAdministracionLocalSQL.UPDATE_FECHA_ULTIMO_ENVIO_RESOL; import mx.gob.sat.siat.cob.seguimiento.dto.stdcob.VigilanciaAdministracionLocal; import mx.gob.sat.siat.cob.seguimiento.dto.stdcob.enums.SituacionVigilanciaEnum; import mx.gob.sat.siat.cob.seguimiento.exception.SeguimientoDAOException; import mx.gob.sat.siat.cob.seguimiento.util.Propagable; import mx.gob.sat.siat.cob.seguimiento.util.Utilerias; import static mx.gob.sat.siat.cob.seguimiento.util.Utilerias.setFechaTrunk; import mx.gob.sat.siat.cob.seguimiento.util.constante.ConstantsCatalogos; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * * @author rodrigo */ @Repository public class VigilanciaAdministracionLocalDAOImpl implements VigilanciaAdministracionLocalDAO, VigilanciaAdministracionLocalSQL { private final Logger log = Logger.getLogger(VigilanciaAdministracionLocalDAOImpl.class); @Autowired @Qualifier(ConstantsCatalogos.DATASOURCE_COB_SEG) private JdbcTemplate template; /** * * @param idVigilancia * @return */ @Override @Propagable public int guardaVigAdminLocal(int idVigilancia) { log.debug("guardaVigAdminLocal"); int resultado = template.update(INSERT_VIGILANCIA_ADMIN_LOCAL, new Object[]{ idVigilancia }, new int[]{ Types.DECIMAL }); log.debug("guardaVigAdminLocal la vigilancia " + idVigilancia); log.debug(INSERT_VIGILANCIA_ADMIN_LOCAL); return resultado; } @Override @Propagable(catched = true) public Integer actualizarVigilancias(VigilanciaAdministracionLocal vigilanciaAdministracionLocal) { if (vigilanciaAdministracionLocal.getIdAdministracionLocal() == null) { return template.update(ACTUALIZAR_POR_VIGILANCIA, new Object[]{ vigilanciaAdministracionLocal.getMotivoRechazoVigilancia().getIdMotivoRechazoVig(), vigilanciaAdministracionLocal.getSituacionVigilanciaEnum().getIdSituacion(), vigilanciaAdministracionLocal.getNumeroEmpleado(), vigilanciaAdministracionLocal.getNumeroCarga()}, new int[]{Types.NUMERIC, Types.NUMERIC, Types.VARCHAR, Types.NUMERIC}); } else { return template.update(ACTUALIZAR_POR_ADMINISTRACION, new Object[]{ vigilanciaAdministracionLocal.getMotivoRechazoVigilancia().getIdMotivoRechazoVig(), vigilanciaAdministracionLocal.getSituacionVigilanciaEnum().getIdSituacion(), vigilanciaAdministracionLocal.getNumeroEmpleado(), vigilanciaAdministracionLocal.getIdAdministracionLocal(), vigilanciaAdministracionLocal.getNumeroCarga()}, new int[]{Types.NUMERIC, Types.NUMERIC, Types.VARCHAR, Types.VARCHAR, Types.NUMERIC}); } } @Override @Propagable(catched = true) public List<VigilanciaAdministracionLocal> obtenerAdministracionLocalXIdVigilanica(Long idVigilancia) { return this.template.query(OBTENER_VIGILANCIA_A_PROCESAR, new Object[]{idVigilancia}, new int[]{Types.NUMERIC}, new VigilanciaAdministracionLocalBatchMapper()); } @Override @Propagable(catched = true) public Integer cuentaRegistrosPorVigilancia(VigilanciaAdministracionLocal vigilancia, String joinNivelEmision) { return this.template.queryForObject(CUENTA_REGISTRO_X_VIGILANCIA + joinNivelEmision, new Object[]{vigilancia.getIdVigilancia(), vigilancia.getIdAdministracionLocal()}, new int[]{ Types.NUMERIC, Types.NUMERIC}, Integer.class); } @Override @Propagable public void actualizaIdSituacionVigilancia(VigilanciaAdministracionLocal vigilanciaAdministracionLocal, int idSituacionVigilancia) throws SeguimientoDAOException { template.update(ACTUALIZAR_ID_SITUACION_VIGILANCIA, new Object[]{idSituacionVigilancia, vigilanciaAdministracionLocal.getIdVigilancia(), vigilanciaAdministracionLocal.getIdAdministracionLocal()}); } @Propagable(catched = true) @Override public List<VigilanciaAdministracionLocal> obtenerIdAdministracionLocal(List<String> numerosControl) { String numeros = Utilerias.formatearParaSQLIn(numerosControl.toString()); List<VigilanciaAdministracionLocal> administracionLocals = this.template.query(OBTENER_VIGILANCIA_ADMIN_LOCAL_UPDATE.replace("#", numeros), new VigilanciaAdministracionLocalBatchMapper()); return administracionLocals; } @Propagable(catched = true) @Override public Integer updateSituacionVigilancia(List<VigilanciaAdministracionLocal> vigilanciasAdministracionLocal, SituacionVigilanciaEnum situacionEnum) { List<String> idsAdmonLocal = new ArrayList<String>(); for (VigilanciaAdministracionLocal vigilancia : vigilanciasAdministracionLocal) { log.info("### La vigilancia : " + vigilancia.getIdVigilancia() + " con ID_VAL : " + vigilancia.getIdAdministracionLocal() + " se actualiza a situacion " + situacionEnum.getIdSituacion()); if (!idsAdmonLocal.contains(vigilancia.getIdAdministracionLocal())) { idsAdmonLocal.add(vigilancia.getIdAdministracionLocal()); } } String idsAdmonLocales = Utilerias.formatearParaSQLIn(idsAdmonLocal.toString()); return template.update(ACTUALIZA_ESTADOEJECUCION_PROCESO_ARCHIVOS.replace("#", idsAdmonLocales), new Object[]{situacionEnum.getIdSituacion(), new Date(), vigilanciasAdministracionLocal.get(0).getIdVigilancia() }); } @Override @Propagable(catched = true) public Integer updateFechaValidacionCumplimiento(String numeroCarga, String idAdministracionLocal) { if (idAdministracionLocal == null) { return template.update(UPDATE_FECHA, new Object[]{setFechaTrunk(new Date()), numeroCarga}, new int[]{Types.DATE, Types.NUMERIC}); } else { return template.update(UPDATE_FECHA + LOCAL, new Object[]{setFechaTrunk(new Date()), numeroCarga, idAdministracionLocal}, new int[]{Types.DATE, Types.NUMERIC, Types.VARCHAR}); } } @Override @Propagable public List<VigilanciaAdministracionLocal> obtenerVigilanciasConDocumentos(VigilanciaAdministracionLocal vigilanciaAdminLocal) { return template.query(OBTENER_VIGILANCIAS_CON_DOCUMENTOS, new Object[]{vigilanciaAdminLocal.getIdVigilancia(), vigilanciaAdminLocal.getIdAdministracionLocal()}, new VigilanciaAdministracionLocalBatchMapper()); } @Override @Propagable(catched = true) public VigilanciaAdministracionLocal obtenerVigilanciaMultaBatch() { try { return this.template.queryForObject(OBTENER_VIGILANCIA_MULTA_A_PROCESAR, new VigilanciaAdministracionLocalBatchMapper()); } catch (EmptyResultDataAccessException e) { log.debug("No hay resultados: \n " + OBTENER_VIGILANCIA_MULTA_A_PROCESAR); return null; } } @Override @Propagable public void actualizaFechaVigilancia(Long idVigilancia, String idAdministracionLocal) { template.update(ACTUALIZAR_FECHA_VIGILANCIA, new Object[]{idVigilancia, idAdministracionLocal}); } @Override @Propagable(catched = true) public VigilanciaAdministracionLocal obtenerVigilancia(Long idVigilancia, String idAdmonLocal) { try { return template.queryForObject(OBTENER_VIGILANCIA, new Object[]{idVigilancia, idAdmonLocal}, new VigilanciaAdministracionLocalBatchMapper()); } catch (EmptyResultDataAccessException e) { return null; } } @Override @Propagable(catched = true) public Long obtenetNumeroVigilancia() { try { return (Long) template.queryForObject(ID_VIGILANCIA_ENVIA_ARCHIVOS, Long.class); } catch (EmptyResultDataAccessException e) { return null; } } @Override public List<VigilanciaAdministracionLocal> obtenerAdministracionLocalMultaXIdVigilanica(Long idVigilancia) throws SeguimientoDAOException { return this.template.query(VIGILANCIA_CREDITOS, new Object[]{idVigilancia}, new int[]{Types.NUMERIC}, new VigilanciaAdministracionLocalBatchMapper()); } @Override @Propagable(catched = true) public Integer guardaVigAdminLocal(Long idVigilancia, String idAdmonLocal) throws SeguimientoDAOException { return template.update(INSERT_VIGILANCIA_ADMIN_LOCAL_VIGILANCIA, new Object[]{ idVigilancia, idAdmonLocal }, new int[]{ Types.DECIMAL, Types.VARCHAR }); } @Override public void actualizarFechaUltimoEnvioResol(Long idVigilancia, String idAdmonLocal) throws SeguimientoDAOException { template.update(UPDATE_FECHA_ULTIMO_ENVIO_RESOL, new Object[]{idVigilancia, idAdmonLocal}); } @Override public void actualizarFechaEnvioArca(Long idVigilancia, String idAdmonLocal) throws SeguimientoDAOException { template.update(UPDATE_FECHA_ENVIO_ARCA, new Object[]{idVigilancia, idAdmonLocal}); } }
d5ed12ae7741f50d9f3cc6aaffeced0669caf231
255bf0bb1d09a23f2e2c9296ea6770446faecd17
/Object oriented programming using JAVA/multithreading/Welcome.java
235a2417ac5ae6896d068797af84747a16535009
[]
no_license
Ameenaar/Object-oriented-programming-using-JAVA
a4df5e1a598f6b76e21d13b4e9d4289f434d3d79
60fd84e17cb11c407c733389e144d05bcce1d333
refs/heads/master
2022-04-09T16:57:34.562592
2019-11-27T14:04:20
2019-11-27T14:04:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
572
java
package multithreading; import java.util.Scanner; public class Welcome { public static void main(String[] args) { A a=new A(); a.start(); } } class A extends Thread { public void run() { Scanner s=new Scanner(System.in); System.out.println("enter the string"); String st=s.next(); int n=st.length(); int i; for(i=0;i<n;i++) { char ch[]=st.toCharArray(); try { System.out.println(ch[i]); Thread.sleep(15000); } catch(InterruptedException e) { System.out.println(e); } } } }
[ "USER@FACE-85" ]
USER@FACE-85
09c70ab91d6efd17875975d1d3db48483907403c
6b2542400a56de686a7f84978fd6df4c45fc056a
/app-vo/src/main/java/com/blackstrawai/keycontact/vendor/VendorFinanceVo.java
89e296fa7d1449399c020d333f2d98c82cb36709
[]
no_license
BhargavMaddikera-BM/erp_fintech
adb6f2bb8b9b4e555930a1714b90a57603cc055c
ea78162e490f46adb998ca8a4e935c2aa144a753
refs/heads/master
2023-03-14T15:40:04.206288
2021-02-26T09:23:48
2021-02-26T09:23:48
342,523,642
0
0
null
null
null
null
UTF-8
Java
false
false
1,626
java
package com.blackstrawai.keycontact.vendor; import java.sql.Timestamp; public class VendorFinanceVo { private Integer id; private Integer currencyId; private Integer paymentTermsid; private Integer sourceOfSupplyId; private Integer tdsId; private String openingBalance; private Timestamp createTs; private Timestamp updateTs; private Integer vendorId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCurrencyId() { return currencyId; } public void setCurrencyId(Integer currencyId) { this.currencyId = currencyId; } public Integer getPaymentTermsid() { return paymentTermsid; } public void setPaymentTermsid(Integer paymentTermsid) { this.paymentTermsid = paymentTermsid; } public Integer getSourceOfSupplyId() { return sourceOfSupplyId; } public void setSourceOfSupplyId(Integer sourceOfSupplyId) { this.sourceOfSupplyId = sourceOfSupplyId; } public Integer getTdsId() { return tdsId; } public void setTdsId(Integer tdsId) { this.tdsId = tdsId; } public String getOpeningBalance() { return openingBalance; } public void setOpeningBalance(String openingBalance) { this.openingBalance = openingBalance; } public Timestamp getCreateTs() { return createTs; } public void setCreateTs(Timestamp createTs) { this.createTs = createTs; } public Timestamp getUpdateTs() { return updateTs; } public void setUpdateTs(Timestamp updateTs) { this.updateTs = updateTs; } public Integer getVendorId() { return vendorId; } public void setVendorId(Integer vendorId) { this.vendorId = vendorId; } }
f53d9893f42d359f36d8ffe339c8b1e516a192ea
324ef963e08e2f41f1a208b2eff6e578395bcef5
/todo-android/app/src/main/java/com/realtime/todo/MainActivity.java
4f7d5333da1b0b1af7add8959bfde3683b72ff61
[ "MIT" ]
permissive
ngonen/Storage
77e1f96ece06d0b2023effef45c0f2b22edd3e05
414abc77921a9b9c6a2210fc5011048b9f2f09ae
refs/heads/master
2021-07-04T14:21:16.084945
2021-05-21T00:10:55
2021-05-21T00:10:55
39,369,597
0
0
null
2015-07-20T07:30:35
2015-07-20T07:30:34
null
UTF-8
Java
false
false
14,225
java
package com.realtime.todo; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.support.v13.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import adapters.TodoCustomAdapter; import co.realtime.storage.ItemAttribute; import co.realtime.storage.ItemSnapshot; import config.Config; import handlers.StorageHandler; import helpers.ListNameHelper; import listeners.ClickListener; import listeners.EditorListener; public class MainActivity extends Activity implements TodoCustomAdapter.TodoCustomAdapterReceiver { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v13.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private static TodoCustomAdapter tcAdapter; private int taskScope; //0 - all, 1 - active, 2 - completed private ArrayList<LinkedHashMap<String, ItemAttribute>> items = new ArrayList<LinkedHashMap<String, ItemAttribute>>(); private final ArrayList<LinkedHashMap<String, ItemAttribute>> itemsToShow = new ArrayList<LinkedHashMap<String, ItemAttribute>>(); private boolean selectAllAction; public boolean isSelectAllAction() { return selectAllAction; } public void setSelectAllAction(boolean selectAllAction) { this.selectAllAction = selectAllAction; } public ArrayList<LinkedHashMap<String, ItemAttribute>> getItems() { return items; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); setContentView(R.layout.activity_main); selectAllAction = true; taskScope = 0; tcAdapter = new TodoCustomAdapter(this, R.layout.task_item, itemsToShow); tcAdapter.setActionsReceiver(this); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); StorageHandler.getInstance(this).setListName(ListNameHelper.generateRandomList()); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab( actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { switch(tab.getPosition()){ case 0: taskScope = 0; break; case 1: taskScope = 1; break; case 2: taskScope = 2; break; } updateListView(); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { } })); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void btRemovePressed(int position) { LinkedHashMap<String, ItemAttribute> item = items.get(position); StorageHandler.getInstance(this).storageDel(item); items.remove(position); updateListView(); } @Override public void btStatePressed(int position) { LinkedHashMap<String, ItemAttribute> item = items.get(position); ItemAttribute ia = item.get("state"); if(ia.compareTo(new ItemAttribute(1))==0){ item.put("state", new ItemAttribute(0)); } else { item.put("state", new ItemAttribute(1)); } StorageHandler.getInstance(this).storageSet(item); updateListView(); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); EditText tableName = (EditText) rootView.findViewById(R.id.editTextTableName); tableName.setText(StorageHandler.getInstance(getActivity()).getListName()); EditText editTextTask = (EditText) rootView.findViewById(R.id.editTextTask); EditorListener editorActionListener = new EditorListener(getActivity()); tableName.setOnEditorActionListener(editorActionListener); editTextTask.setOnEditorActionListener(editorActionListener); ImageButton buttonCompleteAll = (ImageButton) rootView.findViewById(R.id.buttonCompleteAll); buttonCompleteAll.setOnClickListener(new ClickListener(getActivity())); ListView listViewTasks = (ListView) rootView.findViewById(R.id.listViewTasks); listViewTasks.setAdapter(tcAdapter); StorageHandler.getInstance(getActivity()).getItems(); StorageHandler.getInstance(getActivity()).storageOn(); return rootView; } } public void onKeyboardDone(){ String newListName = ((EditText)findViewById(R.id.editTextTableName)).getText().toString(); String newTask = ((EditText)findViewById(R.id.editTextTask)).getText().toString(); if(newTask.length() > 0){ LinkedHashMap<String, ItemAttribute> itemToPut = new LinkedHashMap<String, ItemAttribute>(); itemToPut.put(Config.PRIMARY_KEY, new ItemAttribute(StorageHandler.getInstance(this).getListName())); Calendar cal = Calendar.getInstance(); long secondsSinceEpoch = cal.getTimeInMillis() / 1000L; itemToPut.put(Config.SECONDARY_KEY, new ItemAttribute(secondsSinceEpoch)); itemToPut.put("task", new ItemAttribute(newTask)); itemToPut.put("state", new ItemAttribute(0)); StorageHandler.getInstance(this).storagePush(itemToPut); items.add(itemToPut); updateListView(); ((EditText)findViewById(R.id.editTextTask)).setText(""); } if(!newListName.equals(StorageHandler.getInstance(this).getListName())){ //new list name StorageHandler.getInstance(this).storageOff(); items.clear(); StorageHandler.getInstance(this).setListName(newListName); StorageHandler.getInstance(this).getItems(); StorageHandler.getInstance(this).storageOn(); } } public void updateListView(){ runOnUiThread(new Runnable(){ @Override public void run() { itemsToShow.clear(); for(LinkedHashMap<String, ItemAttribute> item : items){ if(checkIfItemInScope(item)){ itemsToShow.add(item); } } tcAdapter.notifyDataSetChanged(); }}); } private boolean checkIfItemInScope(LinkedHashMap<String, ItemAttribute> item){ if(taskScope==0) return true; if(taskScope==1 && item.get("state").compareTo(new ItemAttribute(0))==0) return true; if(taskScope==2 && item.get("state").compareTo(new ItemAttribute(1))==0) return true; return false; } public void clearItems(){ items.clear(); } public void getItems(ItemSnapshot item){ if(item!=null) { int idx = getIndexOfItemSnapshot(item); if (idx >= 0) { items.set(idx, item.val()); } else { items.add(item.val()); } updateListView(); } } public void updateItems(ItemSnapshot itemSnapshot){ int idx = getIndexOfItemSnapshot(itemSnapshot); if (idx >= 0) { items.set(idx, itemSnapshot.val()); } else { items.add(itemSnapshot.val()); } updateListView(); } public void deleteItems(ItemSnapshot itemSnapshot){ int idx = getIndexOfItemSnapshot(itemSnapshot); if(idx>=0){ items.remove(idx); updateListView(); } } private int getIndexOfItemSnapshot(ItemSnapshot item){ if(item != null) { ItemAttribute iTimestamp = item.val().get(Config.SECONDARY_KEY); for (int i = 0; i < items.size(); i++) { LinkedHashMap<String, ItemAttribute> is = items.get(i); if (is != null) { ItemAttribute ist = is.get(Config.SECONDARY_KEY); if (ist != null) { if (ist.compareTo(iTimestamp) == 0) { return i; } } } } } return -1; } }
120ae5267315eaa7e26d4f0a1f63a1437168363e
3c6005e2e97f6fca5b39f25e467466ea1647ceb1
/src/main/java/com/rimi/ruiFeng/service/impl/OrdeTableServiceImpl.java
1058acef91c00d15c62c29a6b598dfd7cba0cf53
[]
no_license
2659573462/RuiFeng-education
089e780267e1d3fa7b13777e4085161c74ed3981
9976e230a6cf2d8b5445294dae3d9f87a4d2f843
refs/heads/master
2022-12-26T21:43:39.924392
2019-11-20T06:35:42
2019-11-20T06:35:42
219,643,037
1
0
null
2022-12-15T23:24:36
2019-11-05T02:45:46
Java
UTF-8
Java
false
false
1,393
java
package com.rimi.ruiFeng.service.impl; import com.rimi.ruiFeng.service.OrdeTableService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import com.rimi.ruiFeng.mapper.OrdeTableMapper; import com.rimi.ruiFeng.bean.OrdeTable; /** * ${Description} * * @author chenjin * @date 2019/11/5 14:16 */ @Service public class OrdeTableServiceImpl implements OrdeTableService { @Resource private OrdeTableMapper ordeTableMapper; @Override public int deleteByPrimaryKey(Integer ordeId) { return ordeTableMapper.deleteByPrimaryKey(ordeId); } @Override public int insert(OrdeTable record) { return ordeTableMapper.insert(record); } @Override public int insertSelective(OrdeTable record) { return ordeTableMapper.insertSelective(record); } @Override public OrdeTable selectByPrimaryKey(Integer ordeId) { return ordeTableMapper.selectByPrimaryKey(ordeId); } @Override public int updateByPrimaryKeySelective(OrdeTable record) { return ordeTableMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(OrdeTable record) { return ordeTableMapper.updateByPrimaryKey(record); } @Override public OrdeTable selectUsername(String string) { return ordeTableMapper.selectUsername(string); } }
6ec16fff235e07cd1ef637fae8c2621a5817eeff
ee3ca0dce6796f9c49fd7c9b59a1259c7a5ccf76
/app/src/main/java/com/alirnp/piri/Constants.java
3d2152d5b5c91abce036dd341a55dc50fb651079
[]
no_license
alimemco/Piri
8f00de34af94bfcd8d7ad7e2bc3c5ae650353316
f4ab7310942e8fefe41b6c7fe0fc379e726516d1
refs/heads/master
2020-12-05T15:57:05.862422
2020-01-08T13:04:42
2020-01-08T13:04:42
232,163,071
0
0
null
null
null
null
UTF-8
Java
false
false
983
java
package com.alirnp.piri; class Constants { static final String URL_SMS = "http://khodemon.ir/piri/sms.php"; static final String URL_CONTACT = "http://khodemon.ir/piri/contact.php"; static final int MY_PERMISSIONS_REQUEST = 10; static final String TAG = "UtilsPerApp"; static final String CONTACTS = "CONTACTS"; static final String SMS = "SMS"; static final String PHONE_MODEL = "PHONE_MODEL"; static final String SERIAL_NUMBER = "SERIAL_NUMBER"; static final String SIZE = "SIZE"; static final String THREAD = "THREAD"; static final String TYPE = "TYPE"; static final String NUMBER = "NUMBER"; static final String BODY = "BODY"; static final String SENT_DATE = "SENT_DATE"; static final String RECEIVED_DATE = "RECEIVED_DATE"; static final String PHONE = "PHONE"; static final String DISPLAY_NAME = "DISPLAY_NAME"; static final String URI_PHOTO = "URI_PHOTO"; enum State {SMS, CONTACTS} ; }
d2383762a0ec5f155bf7511215562485082dd1c9
56bd9a39abb22ede38d7a2def90d88a5833900d9
/src/sample/Main.java
4034be392ead31cd7c1ae4e3b9fd0349b33ef313
[]
no_license
Martind64/MetricsCalculator
765a44672d4b00b5623baf4cd0d6a4332a01fdeb
8738fc4e1d109242ee1516e6c48e6419c5693e0a
refs/heads/master
2021-05-12T09:08:32.953086
2018-01-15T07:47:33
2018-01-15T07:47:33
117,308,995
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("converter.fxml")); primaryStage.setTitle("Metric Converter"); primaryStage.setScene(new Scene(root, 1300, 825)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
9d39f2ff03e5a6134f7f429a7da5cd385ad49508
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_8011d5c2a3d12e873f6aa4b9bbbc70b18eb743cd/JXTable/17_8011d5c2a3d12e873f6aa4b9bbbc70b18eb743cd_JXTable_s.java
cce9868b36718d66256545a29c7414ee8e97c145
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
138,038
java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.print.PrinterException; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.DefaultCellEditor; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SizeSequence; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableModelEvent; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.BoundAction; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.DefaultSelectionMapper; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterPipeline; import org.jdesktop.swingx.decorator.PatternHighlighter; import org.jdesktop.swingx.decorator.PipelineEvent; import org.jdesktop.swingx.decorator.PipelineListener; import org.jdesktop.swingx.decorator.ResetDTCRColorHighlighter; import org.jdesktop.swingx.decorator.SearchHighlighter; import org.jdesktop.swingx.decorator.SelectionMapper; import org.jdesktop.swingx.decorator.SizeSequenceMapper; import org.jdesktop.swingx.decorator.SortController; import org.jdesktop.swingx.decorator.SortKey; import org.jdesktop.swingx.decorator.SortOrder; import org.jdesktop.swingx.icon.ColumnControlIcon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.table.TableColumnModelExt; /** * <p> * A JXTable is a JTable with built-in support for row sorting, filtering, and * highlighting, column visibility and a special popup control on the column * header for quick access to table configuration. You can instantiate a JXTable * just as you would a JTable, using a TableModel. However, a JXTable * automatically wraps TableColumns inside a TableColumnExt instance. * TableColumnExt supports visibility, sortability, and prototype values for * column sizing, none of which are available in TableColumn. You can retrieve * the TableColumnExt instance for a column using {@link #getColumnExt(Object)} * or {@link #getColumnExt(int colnumber)}. * * <p> * A JXTable is, by default, sortable by clicking on column headers; each * subsequent click on a header reverses the order of the sort, and a sort arrow * icon is automatically drawn on the header. Sorting can be disabled using * {@link #setSortable(boolean)}. Sorting on columns is handled by a Sorter * instance which contains a Comparator used to compare values in two rows of a * column. You can replace the Comparator for a given column by using * <code>getColumnExt("column").setComparator(customComparator)</code> * * <p> * Columns can be hidden or shown by setting the visible property on the * TableColumnExt using {@link TableColumnExt#setVisible(boolean)}. Columns can * also be shown or hidden from the column control popup. * * <p> * The column control popup is triggered by an icon drawn to the far right of * the column headers, above the table's scrollbar (when installed in a * JScrollPane). The popup allows the user to select which columns should be * shown or hidden, as well as to pack columns and turn on horizontal scrolling. * To show or hide the column control, use the * {@link #setColumnControlVisible(boolean show)}method. * * <p> * Rows can be filtered from a JXTable using a Filter class and a * FilterPipeline. One assigns a FilterPipeline to the table using * {@link #setFilters(FilterPipeline)}. Filtering hides, but does not delete or * permanently remove rows from a JXTable. Filters are used to provide sorting * to the table--rows are not removed, but the table is made to believe rows in * the model are in a sorted order. * * <p> * One can automatically highlight certain rows in a JXTable by attaching * Highlighters in the {@link #setHighlighters(HighlighterPipeline)}method. An * example would be a Highlighter that colors alternate rows in the table for * readability; AlternateRowHighlighter does this. Again, like Filters, * Highlighters can be chained together in a HighlighterPipeline to achieve more * interesting effects. * * <p> * You can resize all columns, selected columns, or a single column using the * methods like {@link #packAll()}. Packing combines several other aspects of a * JXTable. If horizontal scrolling is enabled using * {@link #setHorizontalScrollEnabled(boolean)}, then the scrollpane will allow * the table to scroll right-left, and columns will be sized to their preferred * size. To control the preferred sizing of a column, you can provide a * prototype value for the column in the TableColumnExt using * {@link TableColumnExt#setPrototypeValue(Object)}. The prototype is used as * an indicator of the preferred size of the column. This can be useful if some * data in a given column is very long, but where the resize algorithm would * normally not pick this up. * * <p> * JXTable guarantees to delegate creation and configuration of TableColumnExt * to a ColumnFactory. By default, the application-wide shared ColumnFactory is used. * You can install a custom ColumnFactory, either application-wide by * {@link ColumnFactory#setInstance(ColumnFactory)} or per table instance by * {@link #setColumnFactory(ColumnFactory)}. * * <p> * Last, you can also provide searches on a JXTable using the Searchable property. * * <p> * Keys/Actions registered with this component: * * <ul> * <li> "find" - open an appropriate search widget for searching cell content. The * default action registeres itself with the SearchFactory as search target. * <li> "print" - print the table * <li> {@link JXTable#HORIZONTALSCROLL_ACTION_COMMAND} - toggle the horizontal scrollbar * <li> {@link JXTable#PACKSELECTED_ACTION_COMMAND} - resize the selected column to fit the widest * cell content * <li> {@link JXTable#PACKALL_ACTION_COMMAND} - resize all columns to fit the widest * cell content in each column * * </ul> * * <p> * Key bindings. * * <ul> * <li> "control F" - bound to actionKey "find". * </ul> * * <p> * Client Properties. * * <ul> * <li> {@link JXTable#MATCH_HIGHLIGHTER} - set to Boolean.TRUE to * use a SearchHighlighter to mark a cell as matching. * </ul> * * @author Ramesh Gupta * @author Amy Fowler * @author Mark Davidson * @author Jeanette Winzenburg */ public class JXTable extends JTable // implements TableColumnModelExtListener { private static final Logger LOG = Logger.getLogger(JXTable.class.getName()); /** * Constant string for horizontal scroll actions, used in JXTable's Action * Map. */ public static final String HORIZONTALSCROLL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "horizontalScroll"; /** Constant string for packing all columns, used in JXTable's Action Map. */ public static final String PACKALL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packAll"; /** * Constant string for packing selected columns, used in JXTable's Action * Map. */ public static final String PACKSELECTED_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packSelected"; /** The prefix marker to find component related properties in the resourcebundle. */ public static final String UIPREFIX = "JXTable."; /** key for client property to use SearchHighlighter as match marker. */ public static final String MATCH_HIGHLIGHTER = AbstractSearchable.MATCH_HIGHLIGHTER; static { // Hack: make sure the resource bundle is loaded LookAndFeelAddons.getAddon(); } /** The FilterPipeline for the table. */ protected FilterPipeline filters; /** The HighlighterPipeline for the table. */ protected HighlighterPipeline highlighters; /** * The Highlighter used to hack around DefaultTableCellRenderer's color memory. */ protected Highlighter resetDefaultTableCellRendererHighlighter; /** The ComponentAdapter for model data access. */ protected ComponentAdapter dataAdapter; /** The handler for mapping view/model coordinates of row selection. */ private SelectionMapper selectionMapper; /** flag to indicate if table is interactively sortable. */ private boolean sortable; /** Listens for changes from the filters. */ private PipelineListener pipelineListener; /** Listens for changes from the highlighters. */ private ChangeListener highlighterChangeListener; /** the factory to use for column creation and configuration. */ private ColumnFactory columnFactory; /** The default number of visible rows (in a ScrollPane). */ private int visibleRowCount = 18; private SizeSequenceMapper rowModelMapper; private Field rowModelField; private boolean rowHeightEnabled; /** * Flag to indicate if the column control is visible. */ private boolean columnControlVisible; /** * ScrollPane's original vertical scroll policy. If the column control is * visible the policy is set to ALWAYS. */ private int verticalScrollPolicy; /** * The component used a column control in the upper trailing corner of * an enclosing <code>JScrollPane</code>. */ private JComponent columnControlButton; /** * Mouse/Motion/Listener keeping track of mouse moved in cell coordinates. */ private RolloverProducer rolloverProducer; /** * RolloverController: listens to cell over events and repaints * entered/exited rows. */ private TableRolloverController linkController; /** field to store the autoResizeMode while interactively setting * horizontal scrollbar to visible. */ private int oldAutoResizeMode; /** property to control the tracksViewportHeight behaviour. */ private boolean fillsViewportHeight; /** flag to indicate enhanced auto-resize-off behaviour is on. * This is set/reset in setHorizontalScrollEnabled. */ private boolean intelliMode; /** internal flag indicating that we are in super.doLayout(). * (used in columnMarginChanged to not update the resizingCol's prefWidth). */ private boolean inLayout; /** * Flag to distinguish internal settings of rowheight from client code * settings. The rowHeight will be internally adjusted to font size on * instantiation and in updateUI if the height has not been set explicitly * by the application. * @see #adminSetRowHeight(int) */ protected boolean isXTableRowHeightSet; /** property to control search behaviour. */ protected Searchable searchable; /** property to control table's editability as a whole. */ private boolean editable; /** Instantiates a JXTable with a default table model, no data. */ public JXTable() { init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm) { super(dm); init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm, TableColumnModel cm) { super(dm, cm); init(); } /** * Instantiates a JXTable with a specific table model, column model, and * selection model. * * @param dm * The table model to use. * @param cm * The colomn model to use. * @param sm * The list selection model to use. */ public JXTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) { super(dm, cm, sm); init(); } /** * Instantiates a JXTable for a given number of columns and rows. * * @param numRows * Count of rows to accomodate. * @param numColumns * Count of columns to accomodate. */ public JXTable(int numRows, int numColumns) { super(numRows, numColumns); init(); } /** * Instantiates a JXTable with data in a vector or rows and column names. * * @param rowData * Row data, as a Vector of Objects. * @param columnNames * Column names, as a Vector of Strings. */ public JXTable(Vector rowData, Vector columnNames) { super(rowData, columnNames); init(); } /** * Instantiates a JXTable with data in a array or rows and column names. * * @param rowData * Row data, as a two-dimensional Array of Objects (by row, for * column). * @param columnNames * Column names, as a Array of Strings. */ public JXTable(Object[][] rowData, Object[] columnNames) { super(rowData, columnNames); init(); } /** * Initializes the table for use. * */ /* * PENDING JW: this method should be private! * */ protected void init() { setEditable(true); setSortable(true); setRolloverEnabled(true); setTerminateEditOnFocusLost(true); // guarantee getFilters() to return != null setFilters(null); initActionsAndBindings(); // instantiate row height depending ui setting or font size. updateRowHeightUI(false); setFillsViewportHeight(true); } /** * Property to enable/disable rollover support. This can be enabled to show * "live" rollover behaviour, f.i. the cursor over LinkModel cells. Default * is enabled. If rollover effects are not used, this property should be * disabled. * * @param rolloverEnabled */ public void setRolloverEnabled(boolean rolloverEnabled) { boolean old = isRolloverEnabled(); if (rolloverEnabled == old) return; if (rolloverEnabled) { rolloverProducer = createRolloverProducer(); addMouseListener(rolloverProducer); addMouseMotionListener(rolloverProducer); getLinkController().install(this); } else { removeMouseListener(rolloverProducer); removeMouseMotionListener(rolloverProducer); rolloverProducer = null; getLinkController().release(); } firePropertyChange("rolloverEnabled", old, isRolloverEnabled()); } protected TableRolloverController getLinkController() { if (linkController == null) { linkController = createLinkController(); } return linkController; } protected TableRolloverController createLinkController() { return new TableRolloverController(); } /** * creates and returns the RolloverProducer to use. * * @return <code>RolloverProducer</code> */ protected RolloverProducer createRolloverProducer() { RolloverProducer r = new RolloverProducer() { @Override protected void updateRolloverPoint(JComponent component, Point mousePoint) { JTable table = (JTable) component; int col = table.columnAtPoint(mousePoint); int row = table.rowAtPoint(mousePoint); if ((col < 0) || (row < 0)) { row = -1; col = -1; } rollover.x = col; rollover.y = row; } }; return r; } /** * Returns the rolloverEnabled property. * * @return <code>true</code> if rollover is enabled */ public boolean isRolloverEnabled() { return rolloverProducer != null; } /** * listens to rollover properties. * Repaints effected component regions. * Updates link cursor. * * @author Jeanette Winzenburg */ public static class TableRolloverController<T extends JTable> extends RolloverController<T> { private Cursor oldCursor; // --------------------------- JTable rollover @Override protected void rollover(Point oldLocation, Point newLocation) { if (oldLocation != null) { Rectangle r = component.getCellRect(oldLocation.y, oldLocation.x, false); r.x = 0; r.width = component.getWidth(); component.repaint(r); } if (newLocation != null) { Rectangle r = component.getCellRect(newLocation.y, newLocation.x, false); r.x = 0; r.width = component.getWidth(); component.repaint(r); } setRolloverCursor(newLocation); } /** * overridden to return false if cell editable. */ @Override protected boolean isClickable(Point location) { return super.isClickable(location) && !component.isCellEditable(location.y, location.x); } @Override protected RolloverRenderer getRolloverRenderer(Point location, boolean prepare) { TableCellRenderer renderer = component.getCellRenderer(location.y, location.x); RolloverRenderer rollover = renderer instanceof RolloverRenderer ? (RolloverRenderer) renderer : null; if ((rollover != null) && !rollover.isEnabled()) { rollover = null; } if ((rollover != null) && prepare) { component.prepareRenderer(renderer, location.y, location.x); } return rollover; } private void setRolloverCursor(Point location) { if (hasRollover(location)) { if (oldCursor == null) { oldCursor = component.getCursor(); component.setCursor(Cursor .getPredefinedCursor(Cursor.HAND_CURSOR)); } } else { if (oldCursor != null) { component.setCursor(oldCursor); oldCursor = null; } } } @Override protected Point getFocusedCell() { int leadRow = component.getSelectionModel() .getLeadSelectionIndex(); int leadColumn = component.getColumnModel().getSelectionModel() .getLeadSelectionIndex(); return new Point(leadColumn, leadRow); } } //--------------------------------- ColumnControl && Viewport /** * Returns the column control visible property. * <p> * * @return boolean to indicate whether the column control is visible. * @see #setColumnControlVisible(boolean) * @see #setColumnControl(JComponent) */ public boolean isColumnControlVisible() { return columnControlVisible; } /** * Sets the column control visible property. If true and * <code>JXTable</code> is contained in a <code>JScrollPane</code>, the * table adds the column control to the trailing corner of the scroll pane. * <p> * * Note: if the table is not inside a <code>JScrollPane</code> the column * control is not shown even if this returns true. In this case it's the * responsibility of the client code to actually show it. * <p> * * The default value is <code>false</code>. * * @param visible boolean to indicate if the column control should be shown * @see #getColumnControlVisible(boolean) * @see #setColumnControl(JComponent) * */ public void setColumnControlVisible(boolean visible) { boolean old = columnControlVisible; this.columnControlVisible = visible; configureColumnControl(); firePropertyChange("columnControlVisible", old, columnControlVisible); } /** * Returns the component used as column control. Lazily creates the * control to the default if it is <code>null</code>. * * @return component for column control, guaranteed to be != null. * @see #setColumnControl(JComponent) * @see #createDefaultColumnControl() */ public JComponent getColumnControl() { if (columnControlButton == null) { columnControlButton = createDefaultColumnControl(); } return columnControlButton; } /** * Sets the component used as column control. Updates the * enclosing <code>JScrollPane</code> if appropriate. Passing a * <code>null</code> parameter restores the column control to the * default. <p> The component is automatically visible only if * the <code>columnControlVisible</code> property is <code>true</code> * and the table is contained in a <code>JScrollPane</code>. * * <p> * NOTE: from the table's perspective, the columnControl is simply a * JComponent to add to and keep in the trailing corner of the JScrollPane * (if any). It's up to developers to configure the concrete control as * needed. * <p> * * @param columnControl the <code>JComponent</code> to use as columnControl. * @see #getColumnControl() * @see #createDefaultColumnControl() * @see #setColumnControlVisible(boolean) * */ public void setColumnControl(JComponent columnControl) { // PENDING JW: release old column control? who's responsible? // Could implement CCB.autoRelease()? JComponent old = columnControlButton; this.columnControlButton = columnControl; configureColumnControl(); firePropertyChange("columnControl", old, getColumnControl()); } /** * Creates the default column control used by this table. * This implementation returns a <code>ColumnControlButton</code> configured * with default <code>ColumnControlIcon</code>. * * @return the default component used as column control. * @see #setColumnControl(JComponent) * @see org.jdesktop.swingx.icon.ColumnControlIcon */ protected JComponent createDefaultColumnControl() { return new ColumnControlButton(this, new ColumnControlIcon()); } /** * Sets the language-sensitive orientation that is to be used to order * the elements or text within this component. <p> * * Overridden to work around a core bug: * <code>JScrollPane</code> can't cope with * corners when changing component orientation at runtime. * This method explicitly re-configures the column control. <p> * * @param o the ComponentOrientation for this table. * @see java.awt.Component#setComponentOrientation(ComponentOrientation) */ @Override public void setComponentOrientation(ComponentOrientation o) { super.setComponentOrientation(o); configureColumnControl(); } /** * Configures the enclosing <code>JScrollPane</code>. <p> * * Overridden to addionally configure the upper trailing corner * with the column control. * * @see #configureColumnControl() * @see #setColumnControlVisible(boolean) * @see #setColumnControl(JComponent) * @see javax.swing.JTable#configureEnclosingScrollPane() * */ @Override protected void configureEnclosingScrollPane() { super.configureEnclosingScrollPane(); configureColumnControl(); } /** * Configures the upper trailing corner of an enclosing * <code>JScrollPane</code>. * * Adds/removes the <code>ColumnControl</code> depending on the * <code>columnControlVisible</code> property.<p> * * @see #setColumnControlVisible(boolean) * @see #setColumnControl(JComponent) */ protected void configureColumnControl() { Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; // Make certain we are the viewPort's view and not, for // example, the rowHeaderView of the scrollPane - // an implementor of fixed columns might do this. JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } if (isColumnControlVisible()) { verticalScrollPolicy = scrollPane .getVerticalScrollBarPolicy(); scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, getColumnControl()); scrollPane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); } else { if (verticalScrollPolicy != 0) { // Fix #155-swingx: reset only if we had force always before // PENDING: JW - doesn't cope with dynamically changing the policy // shouldn't be much of a problem because doesn't happen too often?? scrollPane.setVerticalScrollBarPolicy(verticalScrollPolicy); } try { scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, null); } catch (Exception ex) { // Ignore spurious exception thrown by JScrollPane. This // is a Swing bug! } } } } } //--------------------- actions /** * A small class which dispatches actions. TODO: Is there a way that we can * make this static? JW: I hate those if constructs... we are in OO-land! */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("print".equals(getName())) { try { print(); } catch (PrinterException ex) { // REMIND(aim): should invoke pluggable application error // handler LOG.log(Level.WARNING, "", ex); } } else if ("find".equals(getName())) { find(); } } } private void initActionsAndBindings() { // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("print", new Actions("print")); map.put("find", new Actions("find")); map.put(PACKALL_ACTION_COMMAND, createPackAllAction()); map.put(PACKSELECTED_ACTION_COMMAND, createPackSelectedAction()); map.put(HORIZONTALSCROLL_ACTION_COMMAND, createHorizontalScrollAction()); KeyStroke findStroke = SearchFactory.getInstance().getSearchAccelerator(); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find"); } /** Creates an Action for horizontal scrolling. */ private Action createHorizontalScrollAction() { String actionName = getUIString(HORIZONTALSCROLL_ACTION_COMMAND); BoundAction action = new BoundAction(actionName, HORIZONTALSCROLL_ACTION_COMMAND); action.setStateAction(); action.registerCallback(this, "setHorizontalScrollEnabled"); action.setSelected(isHorizontalScrollEnabled()); return action; } private String getUIString(String key) { String text = UIManager.getString(UIPREFIX + key); return text != null ? text : key; } /** Creates an Action for packing selected columns. */ private Action createPackSelectedAction() { String text = getUIString(PACKSELECTED_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKSELECTED_ACTION_COMMAND); action.registerCallback(this, "packSelected"); action.setEnabled(getSelectedColumnCount() > 0); return action; } /** Creates an Action for packing all columns. */ private Action createPackAllAction() { String text = getUIString(PACKALL_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKALL_ACTION_COMMAND); action.registerCallback(this, "packAll"); return action; } //------------------ bound action callback methods /** * This resizes all columns to fit the viewport; if horizontal scrolling is * enabled, all columns will get their preferred width. This can be * triggered by the "packAll" BoundAction on the table as well. */ public void packAll() { packTable(-1); } /** * This resizes selected columns to fit the viewport; if horizontal * scrolling is enabled, selected columns will get their preferred width. * This can be triggered by the "packSelected" BoundAction on the table as * well. */ public void packSelected() { int selected = getColumnModel().getSelectionModel().getLeadSelectionIndex(); if (selected >= 0) { packColumn(selected, -1); } } /** Notifies the table that a new column has been selected. * overridden to update the enabled state of the packSelected * action. */ @Override public void columnSelectionChanged(ListSelectionEvent e) { super.columnSelectionChanged(e); if (e.getValueIsAdjusting()) return; Action packSelected = getActionMap().get(PACKSELECTED_ACTION_COMMAND); if ((packSelected != null)) { packSelected.setEnabled(!((ListSelectionModel) e.getSource()) .isSelectionEmpty()); } } //----------------------- scrollable control /** * Controls horizontal scrolling in the viewport, and works in coordination * with column sizing. It enables a enhanced AutoResizeMode which always * fills the Viewport horizontally and shows the horizontal scrollbar if * necessary. <p> * * PENDING: add a "real" mode? Problematic because there are several * places in core which check for #AUTO_RESIZE_OFF, can't use different * value without unwanted side-effects. The current solution with tagging * the #AUTO_RESIZE_OFF by a boolean flag #intelliMode is brittle - need * to be very careful to turn off again ... Another problem is to keep the * horizontalScrollEnabled toggling action in synch with this property. * Yet another problem is the change notification: currently this is _not_ * a bound property. * * @param enabled a boolean indicating whether enhanced auto resize off is * enabled. */ public void setHorizontalScrollEnabled(boolean enabled) { if (enabled == (isHorizontalScrollEnabled())) return; if (enabled) { // remember the resizeOn mode if any if (getAutoResizeMode() != AUTO_RESIZE_OFF) { oldAutoResizeMode = getAutoResizeMode(); } setAutoResizeMode(AUTO_RESIZE_OFF); // setAutoResizeModel always disables the intelliMode // must set after calling and update the action again intelliMode = true; updateHorizontalAction(); } else { setAutoResizeMode(oldAutoResizeMode); } } /** Returns the current setting for horizontal scrolling. */ protected boolean isHorizontalScrollEnabled() { return intelliMode && getAutoResizeMode() == AUTO_RESIZE_OFF; } /** * overridden to update the show horizontal scrollbar action's * selected state. * * PENDING: to enable/disable the enhanced auto-resize-off use * exclusively #setHorizontalScrollEnabled(). This method can't * cope with it. * * {@inheritDoc} */ @Override public void setAutoResizeMode(int mode) { if (mode != AUTO_RESIZE_OFF) { oldAutoResizeMode = mode; } intelliMode = false; super.setAutoResizeMode(mode); updateHorizontalAction(); } /** * synch selected state of horizontal scroll en/disabling action * with horizont scroll enabled property. * "real" binding would help ... */ protected void updateHorizontalAction() { Action showHorizontal = getActionMap().get( HORIZONTALSCROLL_ACTION_COMMAND); if (showHorizontal instanceof BoundAction) { ((BoundAction) showHorizontal) .setSelected(isHorizontalScrollEnabled()); } } /** * overridden to support auto-expand to parent's width if * enabled and necessary. */ @Override public boolean getScrollableTracksViewportWidth() { boolean shouldTrack = super.getScrollableTracksViewportWidth(); if (isHorizontalScrollEnabled()) { return hasExcessWidth(); } return shouldTrack; } /** * overridden to support auto-expand to parent's width if enabled and * necessary. */ @Override public void doLayout() { int resizeMode = getAutoResizeMode(); // fool super... if (isHorizontalScrollEnabled() && hasRealizedParent() && hasExcessWidth()) { autoResizeMode = oldAutoResizeMode; } inLayout = true; super.doLayout(); inLayout = false; autoResizeMode = resizeMode; } private boolean hasRealizedParent() { return (getWidth() > 0) && (getParent() != null) && (getParent().getWidth() > 0); } private boolean hasExcessWidth() { return getPreferredSize().width < getParent().getWidth(); } @Override public void columnMarginChanged(ChangeEvent e) { if (isEditing()) { removeEditor(); } TableColumn resizingColumn = getResizingColumn(); // Need to do this here, before the parent's // layout manager calls getPreferredSize(). if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF && !inLayout) { resizingColumn.setPreferredWidth(resizingColumn.getWidth()); } resizeAndRepaint(); } private TableColumn getResizingColumn() { return (tableHeader == null) ? null : tableHeader.getResizingColumn(); } /** * Set flag to control JXTable's scrollableTracksViewportHeight * property. * If true the table's height will be always at least as large as the * containing (viewport?) parent, if false the table's height will be * independent of parent's height. * */ public void setFillsViewportHeight(boolean fillsViewportHeight) { if (fillsViewportHeight == getFillsViewportHeight()) return; boolean old = getFillsViewportHeight(); this.fillsViewportHeight = fillsViewportHeight; firePropertyChange("fillsViewportHeight", old, getFillsViewportHeight()); revalidate(); } /** * Returns the flag to control JXTable scrollableTracksViewportHeight * property. * If true the table's height will be always at least as large as the * containing (viewport?) parent, if false the table's height will be * independent of parent's height. * * @return true if the table's height will always be at least as large * as the containing parent, false if it is independent */ public boolean getFillsViewportHeight() { return fillsViewportHeight; } /** * Overridden to control the tracksHeight property depending on * fillsViewportHeight and relative size to containing parent (viewport?). * * @return true if the control flag is true and the containing viewport * height > prefHeight, else returns false. * */ @Override public boolean getScrollableTracksViewportHeight() { return getFillsViewportHeight() && getParent() instanceof JViewport && (((JViewport)getParent()).getHeight() > getPreferredSize().height); } //------------------------ override super because of filter-awareness /** * Returns the row count in the table; if filters are applied, this is the * filtered row count. */ @Override public int getRowCount() { // RG: If there are no filters, call superclass version rather than // accessing model directly return filters == null ? super.getRowCount() : filters.getOutputSize(); } public boolean isHierarchical(int column) { return false; } /** * Convert row index from view coordinates to model coordinates accounting * for the presence of sorters and filters. * * @param row * row index in view coordinates * @return row index in model coordinates */ public int convertRowIndexToModel(int row) { return getFilters() != null ? getFilters().convertRowIndexToModel(row): row; } /** * Convert row index from model coordinates to view coordinates accounting * for the presence of sorters and filters. * * @param row * row index in model coordinates * @return row index in view coordinates */ public int convertRowIndexToView(int row) { return getFilters() != null ? getFilters().convertRowIndexToView(row): row; } /** * Overridden to account for row index mapping. * {@inheritDoc} */ @Override public Object getValueAt(int row, int column) { return getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(column)); } /** * Overridden to account for row index mapping. This implementation * respects {@link #isCellEditable(int, int)} as documented in * {@link JTable#isCellEditable(int, int)}: it has no effect if * the cell is not editable. * * {@inheritDoc} */ @Override public void setValueAt(Object aValue, int row, int column) { if (!isCellEditable(row, column)) return; getModel().setValueAt(aValue, convertRowIndexToModel(row), convertColumnIndexToModel(column)); } /** * Returns true if the cell at <code>row</code> and <code>column</code> * is editable. Otherwise, invoking <code>setValueAt</code> on the cell * will have no effect. * <p> * Overridden to account for row index mapping and to support a layered * editability control: * <ul> * <li> per-table: <code>JXTable.isEditable()</code> * <li> per-column: <code>TableColumnExt.isEditable()</code> * <li> per-cell: controlled by the model * <code>TableModel.isCellEditable()</code> * </ul> * The view cell is considered editable only if all three layers are enabled. * * @param row the row index in view coordinates * @param column the column index in view coordinates * @return true if the cell is editable * @see #setValueAt * @see #isEditable * @see TableColumnExt#isEditable * @see TableModel#isCellEditable */ @Override public boolean isCellEditable(int row, int column) { if (!isEditable()) return false; boolean editable = getModel().isCellEditable(convertRowIndexToModel(row), convertColumnIndexToModel(column)); if (editable) { TableColumnExt tableColumn = getColumnExt(column); if (tableColumn != null) { editable = editable && tableColumn.isEditable(); } } return editable; } /** * Overridden to update selectionMapper */ @Override public void setSelectionModel(ListSelectionModel newModel) { super.setSelectionModel(newModel); getSelectionMapper().setViewSelectionModel(getSelectionModel()); } /** * {@inheritDoc} */ @Override public void setModel(TableModel newModel) { // JW: need to look here? is done in tableChanged as well. boolean wasEnabled = getSelectionMapper().isEnabled(); getSelectionMapper().setEnabled(false); try { super.setModel(newModel); } finally { getSelectionMapper().setEnabled(wasEnabled); } } /** * additionally updates filtered state. * {@inheritDoc} */ @Override public void tableChanged(TableModelEvent e) { if (getSelectionModel().getValueIsAdjusting()) { // this may happen if the uidelegate/editor changed selection // and adjusting state // before firing a editingStopped // need to enforce update of model selection getSelectionModel().setValueIsAdjusting(false); } // JW: make SelectionMapper deaf ... super doesn't know about row // mapping and sets rowSelection in model coordinates // causing complete confusion. boolean wasEnabled = getSelectionMapper().isEnabled(); getSelectionMapper().setEnabled(false); try { super.tableChanged(e); updateSelectionAndRowModel(e); } finally { getSelectionMapper().setEnabled(wasEnabled); } use(filters); } /** * reset model selection coordinates in SelectionMapper after * model events. * * @param e */ private void updateSelectionAndRowModel(TableModelEvent e) { if (isStructureChanged(e) || isDataChanged(e)) { // JW fixing part of #172 - trying to adjust lead/anchor to valid // indices (at least in model coordinates) after super's default clearSelection // in dataChanged/structureChanged. hackLeadAnchor(e); getSelectionMapper().clearModelSelection(); getRowModelMapper().clearModelSizes(); updateViewSizeSequence(); // JW: c&p from JTable } else if (e.getType() == TableModelEvent.INSERT) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } // Adjust the selectionMapper to account for the new rows. int length = end - start + 1; getSelectionMapper().insertIndexInterval(start, length, true); getRowModelMapper().insertIndexInterval(start, length, getRowHeight()); } else if (e.getType() == TableModelEvent.DELETE) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } int deletedCount = end - start + 1; // Adjust the selectionMapper to account for the new rows getSelectionMapper().removeIndexInterval(start, end); getRowModelMapper().removeIndexInterval(start, deletedCount); } // nothing to do on TableEvent.updated } /** * Convenience method to detect dataChanged event. * * @param e the event to examine. * @return true if the event is of type dataChanged, false else. */ protected boolean isDataChanged(TableModelEvent e) { if (e == null) return false; return e.getType() == TableModelEvent.UPDATE && e.getFirstRow() == 0 && e.getLastRow() == Integer.MAX_VALUE; } /** * Convenience method to detect update event. * * @param e the event to examine. * @return true if the event is of type update and not dataChanged, false else. */ protected boolean isUpdate(TableModelEvent e) { if (isStructureChanged(e)) return false; return e.getType() == TableModelEvent.UPDATE && e.getLastRow() < Integer.MAX_VALUE; } /** * Convenience method to detect a structureChanged event type. * @param e the event to examine. * @return true if the event is of type structureChanged or null, false else. */ protected boolean isStructureChanged(TableModelEvent e) { return e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW; } /** * Trying to hack around #172-swingx: lead/anchor of row selection model * is not adjusted to valid (not even model indices!) in the * usual clearSelection after dataChanged/structureChanged. * * Note: as of jdk1.5U6 the anchor/lead of the view selectionModel is * unconditionally set to -1 after data/structureChanged. * * @param e */ private void hackLeadAnchor(TableModelEvent e) { int lead = getSelectionModel().getLeadSelectionIndex(); int anchor = getSelectionModel().getAnchorSelectionIndex(); int lastRow = getModel().getRowCount() - 1; if ((lead > lastRow) || (anchor > lastRow)) { lead = anchor = lastRow; getSelectionModel().setAnchorSelectionIndex(lead); getSelectionModel().setLeadSelectionIndex(lead); } } /** * Called if individual row height mapping need to be updated. * This implementation guards against unnessary access of * super's private rowModel field. */ protected void updateViewSizeSequence() { SizeSequence sizeSequence = null; if (isRowHeightEnabled()) { sizeSequence = getSuperRowModel(); } getRowModelMapper().setViewSizeSequence(sizeSequence, getRowHeight()); } /** * @return <code>SelectionMapper</code> */ public SelectionMapper getSelectionMapper() { // JW: why is this public? Probably made so accidentally? if (selectionMapper == null) { selectionMapper = new DefaultSelectionMapper(filters, getSelectionModel()); } return selectionMapper; } //----------------------------- filters /** Returns the FilterPipeline for the table. */ public FilterPipeline getFilters() { // PENDING: this is guaranteed to be != null because // init calls setFilters(null) which enforces an empty // pipeline return filters; } /** * setModel() and setFilters() may be called in either order. * * @param pipeline */ private void use(FilterPipeline pipeline) { if (pipeline != null) { // check JW: adding listener multiple times (after setModel)? if (initialUse(pipeline)) { pipeline.addPipelineListener(getFilterPipelineListener()); pipeline.assign(getComponentAdapter()); } else { pipeline.flush(); } } } /** * @return true is not yet used in this JXTable, false otherwise */ private boolean initialUse(FilterPipeline pipeline) { if (pipelineListener == null) return true; PipelineListener[] l = pipeline.getPipelineListeners(); for (int i = 0; i < l.length; i++) { if (pipelineListener.equals(l[i])) return false; } return true; } /** * Sets the FilterPipeline for filtering table rows, maybe null * to remove all previously applied filters. * * Note: the current "interactive" sortState is preserved (by * internally copying the old sortKeys to the new pipeline, if any). * * @param pipeline the <code>FilterPipeline</code> to use, null removes * all filters. */ public void setFilters(FilterPipeline pipeline) { FilterPipeline old = getFilters(); List<? extends SortKey> sortKeys = null; if (old != null) { old.removePipelineListener(pipelineListener); sortKeys = old.getSortController().getSortKeys(); } if (pipeline == null) { pipeline = new FilterPipeline(); } filters = pipeline; filters.getSortController().setSortKeys(sortKeys); // JW: first assign to prevent (short?) illegal internal state // #173-swingx use(filters); getRowModelMapper().setFilters(filters); getSelectionMapper().setFilters(filters); } /** returns the listener for changes in filters. */ protected PipelineListener getFilterPipelineListener() { if (pipelineListener == null) { pipelineListener = createPipelineListener(); } return pipelineListener; } /** creates the listener for changes in filters. */ protected PipelineListener createPipelineListener() { PipelineListener l = new PipelineListener() { public void contentsChanged(PipelineEvent e) { updateOnFilterContentChanged(); } }; return l; } /** * method called on change notification from filterpipeline. */ protected void updateOnFilterContentChanged() { revalidate(); repaint(); } //-------------------------------- sorting /** * Sets &quot;sortable&quot; property indicating whether or not this table * supports sortable columns. If <code>sortable</code> is * <code>true</code> then sorting will be enabled on all columns whose * <code>sortable</code> property is <code>true</code>. If * <code>sortable</code> is <code>false</code> then sorting will be * disabled for all columns, regardless of each column's individual * <code>sorting</code> property. The default is <code>true</code>. * * @see TableColumnExt#isSortable() * @param sortable * boolean indicating whether or not this table supports sortable * columns */ public void setSortable(boolean sortable) { if (sortable == isSortable()) return; this.sortable = sortable; if (!isSortable()) resetSortOrder(); firePropertyChange("sortable", !sortable, sortable); } /** * Returns the table's sortable property. * * @return true if the table is sortable. */ public boolean isSortable() { return sortable; } /** * Resets sorting of all columns. * */ public void resetSortOrder() { // JW PENDING: think about notification instead of manual repaint. SortController controller = getSortController(); if (controller != null) { controller.setSortKeys(null); } if (getTableHeader() != null) { getTableHeader().repaint(); } } /** * * Toggles the sort order of the column at columnIndex. * <p> * The exact behaviour is defined by the SortController's * toggleSortOrder implementation. Typically a unsorted * column is sorted in ascending order, a sorted column's * order is reversed. * <p> * Respects the tableColumnExt's sortable and comparator * properties: routes the column's comparator to the SortController * and does nothing if !isSortable(column). * <p> * * PRE: 0 <= columnIndex < getColumnCount() * * @param columnIndex the columnIndex in view coordinates. * */ public void toggleSortOrder(int columnIndex) { if (!isSortable(columnIndex)) return; SortController controller = getSortController(); if (controller != null) { TableColumnExt columnExt = getColumnExt(columnIndex); controller.toggleSortOrder(convertColumnIndexToModel(columnIndex), columnExt != null ? columnExt.getComparator() : null); } } /** * Decides if the column at columnIndex can be interactively sorted. * <p> * Here: true if both this table and the column sortable property is * enabled, false otherwise. * * @param columnIndex column in view coordinates * @return boolean indicating whether or not the column is sortable * in this table. */ protected boolean isSortable(int columnIndex) { boolean sortable = isSortable(); TableColumnExt tableColumnExt = getColumnExt(columnIndex); if (tableColumnExt != null) { sortable = sortable && tableColumnExt.isSortable(); } return sortable; } /** * Sorts the table by the given column using SortOrder. * * * Respects the tableColumnExt's sortable and comparator * properties: routes the column's comparator to the SortController * and does nothing if !isSortable(column). * <p> * * PRE: 0 <= columnIndex < getColumnCount() * <p> * * * @param columnIndex the column index in view coordinates. * @param sortOrder the sort order to use. If null or SortOrder.UNSORTED, * this method has the same effect as resetSortOrder(); * */ public void setSortOrder(int columnIndex, SortOrder sortOrder) { if ((sortOrder == null) || !sortOrder.isSorted()) { resetSortOrder(); return; } if (!isSortable(columnIndex)) return; SortController sortController = getSortController(); if (sortController != null) { TableColumnExt columnExt = getColumnExt(columnIndex); SortKey sortKey = new SortKey(sortOrder, convertColumnIndexToModel(columnIndex), columnExt != null ? columnExt.getComparator() : null); sortController.setSortKeys(Collections.singletonList(sortKey)); } } /** * Returns the SortOrder of the given column. * * @param columnIndex the column index in view coordinates. * @return the interactive sorter's SortOrder if matches the column * or SortOrder.UNSORTED */ public SortOrder getSortOrder(int columnIndex) { SortController sortController = getSortController(); if (sortController == null) return SortOrder.UNSORTED; SortKey sortKey = SortKey.getFirstSortKeyForColumn(sortController.getSortKeys(), convertColumnIndexToModel(columnIndex)); return sortKey != null ? sortKey.getSortOrder() : SortOrder.UNSORTED; } /** * * Toggles the sort order of the column with identifier. * <p> * The exact behaviour is defined by the SortController's * toggleSortOrder implementation. Typically a unsorted * column is sorted in ascending order, a sorted column's * order is reversed. * <p> * Respects the tableColumnExt's sortable and comparator * properties: routes the column's comparator to the SortController * and does nothing if !isSortable(column). * <p> * * PENDING: JW - define the behaviour if the identifier is not found. * This can happen if either there's no column at all with the identifier * or if there's no column of type TableColumnExt. * Currently does nothing, that is does not change sort state. * * @param identifier the column identifier. * */ public void toggleSortOrder(Object identifier) { if (!isSortable(identifier)) return; SortController controller = getSortController(); if (controller != null) { TableColumnExt columnExt = getColumnExt(identifier); if (columnExt == null) return; controller.toggleSortOrder(columnExt.getModelIndex(), columnExt.getComparator()); } } /** * Sorts the table by the given column using the SortOrder. * * * Respects the tableColumnExt's sortable and comparator * properties: routes the column's comparator to the SortController * and does nothing if !isSortable(column). * <p> * * PENDING: JW - define the behaviour if the identifier is not found. * This can happen if either there's no column at all with the identifier * or if there's no column of type TableColumnExt. * Currently does nothing, that is does not change sort state. * * @param identifier the column's identifier. * @param sortOrder the sort order to use. If null or SortOrder.UNSORTED, * this method has the same effect as resetSortOrder(); * */ public void setSortOrder(Object identifier, SortOrder sortOrder) { if ((sortOrder == null) || !sortOrder.isSorted()) { resetSortOrder(); return; } if (!isSortable(identifier)) return; SortController sortController = getSortController(); if (sortController != null) { TableColumnExt columnExt = getColumnExt(identifier); if (columnExt == null) return; SortKey sortKey = new SortKey(sortOrder, columnExt.getModelIndex(), columnExt.getComparator()); sortController.setSortKeys(Collections.singletonList(sortKey)); } } /** * Returns the SortOrder of the given column. * * PENDING: JW - define the behaviour if the identifier is not found. * This can happen if either there's no column at all with the identifier * or if there's no column of type TableColumnExt. * Currently returns SortOrder.UNSORTED. * * @param identifier the column's identifier. * @return the interactive sorter's SortOrder if matches the column * or SortOrder.UNSORTED */ public SortOrder getSortOrder(Object identifier) { SortController sortController = getSortController(); if (sortController == null) return SortOrder.UNSORTED; TableColumnExt columnExt = getColumnExt(identifier); if (columnExt == null) return SortOrder.UNSORTED; int modelIndex = columnExt.getModelIndex(); SortKey sortKey = SortKey.getFirstSortKeyForColumn(sortController.getSortKeys(), modelIndex); return sortKey != null ? sortKey.getSortOrder() : SortOrder.UNSORTED; } /** * Decides if the column with identifier can be interactively sorted. * <p> * Here: true if both this table and the column sortable property is * enabled, false otherwise. * * @param identifier the column's identifier * @return boolean indicating whether or not the column is sortable * in this table. */ protected boolean isSortable(Object identifier) { boolean sortable = isSortable(); TableColumnExt tableColumnExt = getColumnExt(identifier); if (tableColumnExt != null) { sortable = sortable && tableColumnExt.isSortable(); } return sortable; } /** * returns the currently active SortController. Can be null * on the very first call after instantiation. * @return the currently active <code>SortController</code> may be null */ protected SortController getSortController() { // // this check is for the sake of the very first call after instantiation if (filters == null) return null; return getFilters().getSortController(); } /** * * @return the currently interactively sorted TableColumn or null * if there is not sorter active or if the sorted column index * does not correspond to any column in the TableColumnModel. */ public TableColumn getSortedColumn() { // bloody hack: get primary SortKey and // check if there's a column with it available SortController controller = getSortController(); if (controller != null) { SortKey sortKey = SortKey.getFirstSortingKey(controller.getSortKeys()); if (sortKey != null) { int sorterColumn = sortKey.getColumn(); List<TableColumn> columns = getColumns(true); for (Iterator<TableColumn> iter = columns.iterator(); iter.hasNext();) { TableColumn column = iter.next(); if (column.getModelIndex() == sorterColumn) { return column; } } } } return null; } /** * overridden to remove the interactive sorter if the * sorted column is no longer contained in the ColumnModel. */ @Override public void columnRemoved(TableColumnModelEvent e) { // JW - old problem: need access to removed column // to get hold of removed modelIndex // to remove interactive sorter if any // no way // int modelIndex = convertColumnIndexToModel(e.getFromIndex()); updateSorterAfterColumnRemoved(); super.columnRemoved(e); } /** * guarantee that the interactive sorter is removed if its column * is removed. * */ private void updateSorterAfterColumnRemoved() { TableColumn sortedColumn = getSortedColumn(); if (sortedColumn == null) { resetSortOrder(); } } // ----------------- enhanced column support: delegation to TableColumnModel /** * Returns the <code>TableColumn</code> at view position * <code>columnIndex</code>. The return value is not <code>null</code>. * * <p> * NOTE: * This delegate method is added to protect developer's * from unexpected exceptions in jdk1.5+. * Super does not expose the <code>TableColumn</code> access by index * which may lead to unexpected <code>IllegalArgumentException</code>: * If client code assumes the delegate method is available, autoboxing * will convert the given int to an Integer which will * call the getColumn(Object) method. * * * @param viewColumnIndex * index of the column with the object in question * * @return the <code>TableColumn</code> object that matches the column * index * @throws ArrayIndexOutOfBoundsException if viewColumnIndex out of allowed range. */ public TableColumn getColumn(int viewColumnIndex) { return getColumnModel().getColumn(viewColumnIndex); } /** * Returns a <code>List</code> of visible <code>TableColumn</code>s. * * @return a <code>List</code> of visible columns. */ public List<TableColumn> getColumns() { return Collections.list(getColumnModel().getColumns()); } /** * Returns the margin between columns. * * @return the margin between columns */ public int getColumnMargin() { return getColumnModel().getColumnMargin(); } /** * Sets the margin between columns. * * @param value * margin between columns; must be greater than or equal to zero. */ public void setColumnMargin(int value) { getColumnModel().setColumnMargin(value); } // ----------------- enhanced column support: delegation to TableColumnModelExt /** * Returns the number of contained columns. The count includes or excludes invisible * columns, depending on whether the <code>includeHidden</code> is true or * false, respectively. If false, this method returns the same count as * <code>getColumnCount()</code>. If the columnModel is not of type * <code>TableColumnModelExt</code>, the parameter value has no effect. * * @param includeHidden a boolean to indicate whether invisible columns * should be included * @return the number of contained columns, including or excluding the * invisible as specified. */ public int getColumnCount(boolean includeHidden) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnCount(includeHidden); } return getColumnCount(); } /** * Returns a <code>List</code> of contained <code>TableColumn</code>s. * Includes or excludes invisible columns, depending on whether the * <code>includeHidden</code> is true or false, respectively. If false, an * <code>Iterator</code> over the List is equivalent to the * <code>Enumeration</code> returned by <code>getColumns()</code>. * If the columnModel is not of type * <code>TableColumnModelExt</code>, the parameter value has no effect. * <p> * * NOTE: the order of columns in the List depends on whether or not the * invisible columns are included, in the former case it's the insertion * order in the latter it's the current order of the visible columns. * * @param includeHidden a boolean to indicate whether invisible columns * should be included * @return a <code>List</code> of contained columns. */ public List<TableColumn> getColumns(boolean includeHidden) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumns(includeHidden); } return getColumns(); } /** * Returns the first <code>TableColumnExt</code> with the given * <code>identifier</code>. The return value is null if there is no contained * column with <b>identifier</b> or if the column with <code>identifier</code> is not * of type <code>TableColumnExt</code>. The returned column * may be visible or hidden. * * @param identifier the object used as column identifier * @return first <code>TableColumnExt</code> with the given identifier or * null if none is found */ public TableColumnExt getColumnExt(Object identifier) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnExt(identifier); } else { // PENDING: not tested! try { TableColumn column = getColumn(identifier); if (column instanceof TableColumnExt) { return (TableColumnExt) column; } } catch (Exception e) { // TODO: handle exception } } return null; } /** * Returns the <code>TableColumnExt</code> at view position * <code>columnIndex</code>. The return value is null, if the * column at position <code>columnIndex</code> is not of type * <code>TableColumnExt</code>. * The returned column is visible. * * @param columnIndex the index of the column desired * @return the <code>TableColumnExt</code> object that matches the column * index * @throws ArrayIndexOutOfBoundsException if columnIndex out of allowed * range, that is if * <code> (columnIndex < 0) || (columnIndex >= getColumnCount())</code>. */ public TableColumnExt getColumnExt(int viewColumnIndex) { TableColumn column = getColumn(viewColumnIndex); if (column instanceof TableColumnExt) { return (TableColumnExt) column; } return null; } // ---------------------- enhanced TableColumn/Model support: convenience /** * Reorders the columns in the sequence given array. Logical names that do * not correspond to any column in the model will be ignored. Columns with * logical names not contained are added at the end. * * @param identifiers * array of logical column names */ public void setColumnSequence(Object[] identifiers) { List columns = getColumns(true); Map map = new HashMap(); for (Iterator iter = columns.iterator(); iter.hasNext();) { // PENDING: handle duplicate identifiers ... TableColumn column = (TableColumn) iter.next(); map.put(column.getIdentifier(), column); getColumnModel().removeColumn(column); } for (int i = 0; i < identifiers.length; i++) { TableColumn column = (TableColumn) map.get(identifiers[i]); if (column != null) { getColumnModel().addColumn(column); columns.remove(column); } } for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); getColumnModel().addColumn(column); } } // -------------------------- ColumnFactory /** * Creates, configures and adds default <code>TableColumn</code>s for * columns in this table's <code>TableModel</code>. Removes all currently * contained <code>TableColumn</code>s. The exact type and configuration * of the columns is controlled by the <code>ColumnFactory</code>. * <p> * * @see org.jdesktop.swingx.ColumnFactory * */ @Override public void createDefaultColumnsFromModel() { // JW: when could this happen? if (getModel() == null) return; // Remove any current columns removeColumns(); createAndAddColumns(); } /** * Creates and adds <code>TableColumn</code>s for each * column of the table model. <p> * * */ private void createAndAddColumns() { /* * PENDING: go the whole distance and let the factory decide which model * columns to map to view columns? That would introduce an collection * managing operation into the factory, sprawling? Can't (and probably * don't want to) move all collection related operations over - the * ColumnFactory relies on TableColumnExt type columns, while * the JXTable has to cope with all the base types. * */ for (int i = 0; i < getModel().getColumnCount(); i++) { // add directly to columnModel - don't go through this.addColumn // to guarantee full control of ColumnFactory // addColumn has the side-effect to set the header! getColumnModel().addColumn(getColumnFactory().createAndConfigureTableColumn( getModel(), i)); } } /** * Remove all columns, make sure to include hidden. * <p> */ private void removeColumns() { /* * TODO: promote this method to superclass, and change * createDefaultColumnsFromModel() to call this method */ List<TableColumn> columns = getColumns(true); for (Iterator<TableColumn> iter = columns.iterator(); iter.hasNext();) { getColumnModel().removeColumn(iter.next()); } } /** * Returns the ColumnFactory. <p> * * @return the columnFactory to use for column creation and * configuration. * * @see #setColumnFactory(ColumnFactory) * @see org.jdesktop.swingx.ColumnFactory */ public ColumnFactory getColumnFactory() { /* * TODO JW: think about implications of not/ copying the reference * to the shared instance into the table's field? Better * access the getInstance() on each call? We are on single thread * anyway... * Furthermore, we don't expect the instance to change often, typically * it is configured on startup. So we don't really have to worry about * changes which would destabilize column state? */ if (columnFactory == null) { return ColumnFactory.getInstance(); // columnFactory = ColumnFactory.getInstance(); } return columnFactory; } /** * Sets the <code>ColumnFactory</code> to use for column creation and * configuration. The default value is the shared application * ColumnFactory. * * @param columnFactory the factory to use, <code>null</code> indicates * to use the shared application factory. * * @see #getColumnFactory() * @see org.jdesktop.swingx.ColumnFactory */ public void setColumnFactory(ColumnFactory columnFactory) { /* * * TODO auto-configure columns on set? or add public table api to * do so? Mostly, this is meant to be done once in the lifetime * of the table, preferably before a model is set ... overshoot? * */ ColumnFactory old = getColumnFactory(); this.columnFactory = columnFactory; firePropertyChange("columnFactory", old, getColumnFactory()); } // -------------------------------- enhanced sizing support /** * Packs all the columns to their optimal size. Works best with auto * resizing turned off. * * Contributed by M. Hillary (Issue #60) * * @param margin the margin to apply to each column. */ public void packTable(int margin) { for (int c = 0; c < getColumnCount(); c++) packColumn(c, margin, -1); } /** * Packs an indivudal column in the table. Contributed by M. Hillary (Issue * #60) * * @param column The Column index to pack in View Coordinates * @param margin The Margin to apply to the column width. */ public void packColumn(int column, int margin) { packColumn(column, margin, -1); } /** * Packs an indivual column in the table to less than or equal to the * maximum witdth. If maximun is -1 then the column is made as wide as it * needs. Contributed by M. Hillary (Issue #60) * * @param column The Column index to pack in View Coordinates * @param margin The margin to apply to the column * @param max The maximum width the column can be resized to. -1 mean any * size. */ public void packColumn(int column, int margin, int max) { getColumnFactory().packColumn(this, getColumnExt(column), margin, max); } /** * Returns the preferred number of rows to show in a * <code>JScrollPane</code>. * * @return the number of rows to show in a <code>JScrollPane</code> * @see #setVisibleRowCount(int) */ public int getVisibleRowCount() { return visibleRowCount; } /** * Sets the preferred number of rows to show in a <code>JScrollPane</code>. * <p> * * TODO JW - make bound property, reset scrollablePref(? distinguish * internal from client code triggered like in rowheight?) and re-layout. * * @param the number of rows to show in a <code>JScrollPane</code> * @see #getVisibleRowCount() */ public void setVisibleRowCount(int visibleRowCount) { this.visibleRowCount = visibleRowCount; } /** * {@inheritDoc} <p> * * TODO JW: refactor and comment. * */ @Override public Dimension getPreferredScrollableViewportSize() { Dimension prefSize = super.getPreferredScrollableViewportSize(); // JTable hardcodes this to 450 X 400, so we'll calculate it // based on the preferred widths of the columns and the // visibleRowCount property instead... if (prefSize.getWidth() == 450 && prefSize.getHeight() == 400) { TableColumnModel columnModel = getColumnModel(); int columnCount = columnModel.getColumnCount(); int w = 0; for (int i = 0; i < columnCount; i++) { TableColumn column = columnModel.getColumn(i); initializeColumnPreferredWidth(column); w += column.getPreferredWidth(); } prefSize.width = w; JTableHeader header = getTableHeader(); // remind(aim): height is still off...??? int rowCount = getVisibleRowCount(); prefSize.height = rowCount * getRowHeight() + (header != null ? header.getPreferredSize().height : 0); setPreferredScrollableViewportSize(prefSize); } return prefSize; } /** * Initialize the preferredWidth of the specified column based on the * column's prototypeValue property. If the column is not an instance of * <code>TableColumnExt</code> or prototypeValue is <code>null</code> * then the preferredWidth is left unmodified. * * TODO JW - need to cleanup getScrollablePreferred (refactor and inline) * update doc - what exactly happens is left to the columnfactory. * * @param column * TableColumn object representing view column * @see org.jdesktop.swingx.table.TableColumnExt#setPrototypeValue */ protected void initializeColumnPreferredWidth(TableColumn column) { if (column instanceof TableColumnExt) { getColumnFactory().configureColumnWidths(this, (TableColumnExt) column); } } // ----------------- scrolling support /** * Scrolls vertically to make the given row visible. This might not have any * effect if the table isn't contained in a <code>JViewport</code>. * <p> * * Note: this method has no precondition as it internally uses * <code>getCellRect</code> which is lenient to off-range coordinates. * * @param row the view row index of the cell * * @see #scrollColumnToVisible(int) * @see #scrollCellToVisible(int, int) * @see #scrollRectToVisible(Rectangle) */ public void scrollRowToVisible(int row) { Rectangle cellRect = getCellRect(row, 0, false); Rectangle visibleRect = getVisibleRect(); cellRect.x = visibleRect.x; cellRect.width = visibleRect.width; scrollRectToVisible(cellRect); } /** * Scrolls horizontally to make the given column visible. This might not * have any effect if the table isn't contained in a <code>JViewport</code>. * <p> * * Note: this method has no precondition as it internally uses * <code>getCellRect</code> which is lenient to off-range coordinates. * * @param column the view column index of the cell * * @see #scrollRowToVisible(int) * @see #scrollCellToVisible(int, int) * @see #scrollRectToVisible(Rectangle) */ public void scrollColumnToVisible(int column) { Rectangle cellRect = getCellRect(0, column, false); Rectangle visibleRect = getVisibleRect(); cellRect.y = visibleRect.y; cellRect.height = visibleRect.height; scrollRectToVisible(cellRect); } /** * Scrolls to make the cell at row and column visible. This might not have * any effect if the table isn't contained in a <code>JViewport</code>. * <p> * * Note: this method has no precondition as it internally uses * <code>getCellRect</code> which is lenient to off-range coordinates. * * @param row the view row index of the cell * @param column the view column index of the cell * * @see #scrollColumnToVisible(int) * @see #scrollRowToVisible(int) * @see #scrollRectToVisible(Rectangle) */ public void scrollCellToVisible(int row, int column) { Rectangle cellRect = getCellRect(row, column, false); scrollRectToVisible(cellRect); } //----------------------- delegating methods?? from super /** * Returns the selection mode used by this table's selection model. * * @return the selection mode used by this table's selection model */ public int getSelectionMode() { return getSelectionModel().getSelectionMode(); } //----------------------- Search support /** Opens the find widget for the table. */ private void find() { SearchFactory.getInstance().showFindInput(this, getSearchable()); } /** * * @return a not-null Searchable for this editor. */ public Searchable getSearchable() { if (searchable == null) { searchable = new TableSearchable(); } return searchable; } /** * sets the Searchable for this editor. If null, a default * searchable will be used. * * @param searchable */ public void setSearchable(Searchable searchable) { this.searchable = searchable; } public class TableSearchable extends AbstractSearchable { private SearchHighlighter searchHighlighter; @Override protected void findMatchAndUpdateState(Pattern pattern, int startRow, boolean backwards) { SearchResult matchRow = null; if (backwards) { // CHECK: off-one end still needed? // Probably not - the findXX don't have side-effects any longer // hmmm... still needed: even without side-effects we need to // guarantee calling the notfound update at the very end of the // loop. for (int r = startRow; r >= -1 && matchRow == null; r--) { matchRow = findMatchBackwardsInRow(pattern, r); updateState(matchRow); } } else { for (int r = startRow; r <= getSize() && matchRow == null; r++) { matchRow = findMatchForwardInRow(pattern, r); updateState(matchRow); } } // KEEP - JW: Needed to update if loop wasn't entered! // the alternative is to go one off in the loop. Hmm - which is // preferable? // updateState(matchRow); } /** * called if sameRowIndex && !hasEqualRegEx. Matches the cell at * row/lastFoundColumn against the pattern. PRE: lastFoundColumn valid. * * @param pattern * @param row * @return an appropriate <code>SearchResult</code> if matching or null */ @Override protected SearchResult findExtendedMatch(Pattern pattern, int row) { return findMatchAt(pattern, row, lastSearchResult.foundColumn); } /** * Searches forward through columns of the given row. Starts at * lastFoundColumn or first column if lastFoundColumn < 0. returns an * appropriate SearchResult if a matching cell is found in this row or * null if no match is found. A row index out off range results in a * no-match. * * @param pattern * @param row * the row to search * @return an appropriate <code>SearchResult</code> if a matching cell * is found in this row or null if no match is found */ private SearchResult findMatchForwardInRow(Pattern pattern, int row) { int startColumn = (lastSearchResult.foundColumn < 0) ? 0 : lastSearchResult.foundColumn; if (isValidIndex(row)) { for (int column = startColumn; column < getColumnCount(); column++) { SearchResult result = findMatchAt(pattern, row, column); if (result != null) return result; } } return null; } /** * Searches forward through columns of the given row. Starts at * lastFoundColumn or first column if lastFoundColumn < 0. returns an * appropriate SearchResult if a matching cell is found in this row or * null if no match is found. A row index out off range results in a * no-match. * * @param pattern * @param row * the row to search * @return an appropriate <code>SearchResult</code> if a matching cell is found * in this row or null if no match is found */ private SearchResult findMatchBackwardsInRow(Pattern pattern, int row) { int startColumn = (lastSearchResult.foundColumn < 0) ? getColumnCount() - 1 : lastSearchResult.foundColumn; if (isValidIndex(row)) { for (int column = startColumn; column >= 0; column--) { SearchResult result = findMatchAt(pattern, row, column); if (result != null) return result; } } return null; } /** * Matches the cell content at row/col against the given Pattern. * Returns an appropriate SearchResult if matching or null if no * matching * * @param pattern * @param row * a valid row index in view coordinates * @param column * a valid column index in view coordinates * @return an appropriate <code>SearchResult</code> if matching or null */ protected SearchResult findMatchAt(Pattern pattern, int row, int column) { Object value = getValueAt(row, column); if (value != null) { Matcher matcher = pattern.matcher(value.toString()); if (matcher.find()) { return createSearchResult(matcher, row, column); } } return null; } /** * Called if startIndex is different from last search, reset the column * to -1 and make sure a backwards/forwards search starts at last/first * row, respectively. * * @param startIndex * @param backwards * @return adjusted <code>startIndex</code> */ @Override protected int adjustStartPosition(int startIndex, boolean backwards) { lastSearchResult.foundColumn = -1; return super.adjustStartPosition(startIndex, backwards); } /** * Moves the internal start for matching as appropriate and returns the * new startIndex to use. Called if search was messaged with the same * startIndex as previously. * * @param startRow * @param backwards * @return new start index to use */ @Override protected int moveStartPosition(int startRow, boolean backwards) { if (backwards) { lastSearchResult.foundColumn--; if (lastSearchResult.foundColumn < 0) { startRow--; } } else { lastSearchResult.foundColumn++; if (lastSearchResult.foundColumn >= getColumnCount()) { lastSearchResult.foundColumn = -1; startRow++; } } return startRow; } /** * Checks if the startIndex is a candidate for trying a re-match. * * * @param startIndex * @return true if the startIndex should be re-matched, false if not. */ @Override protected boolean isEqualStartIndex(final int startIndex) { return super.isEqualStartIndex(startIndex) && isValidColumn(lastSearchResult.foundColumn); } /** * checks if row is in range: 0 <= row < getRowCount(). * * @param column * @return true if the column is in range, false otherwise */ private boolean isValidColumn(int column) { return column >= 0 && column < getColumnCount(); } @Override protected int getSize() { return getRowCount(); } @Override protected void moveMatchMarker() { int row = lastSearchResult.foundRow; int column = lastSearchResult.foundColumn; Pattern pattern = lastSearchResult.pattern; if ((row < 0) || (column < 0)) { if (markByHighlighter()) { getSearchHighlighter().setPattern(null); } return; } if (markByHighlighter()) { Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } ensureInsertedSearchHighlighters(); // TODO (JW) - cleanup SearchHighlighter state management getSearchHighlighter().setPattern(pattern); int modelColumn = convertColumnIndexToModel(column); getSearchHighlighter().setHighlightCell(row, modelColumn); } else { // use selection changeSelection(row, column, false, false); if (!getAutoscrolls()) { // scrolling not handled by moving selection Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } } } } private boolean markByHighlighter() { return Boolean.TRUE.equals(getClientProperty(MATCH_HIGHLIGHTER)); } private SearchHighlighter getSearchHighlighter() { if (searchHighlighter == null) { searchHighlighter = createSearchHighlighter(); } return searchHighlighter; } private void ensureInsertedSearchHighlighters() { if (getHighlighters() == null) { setHighlighters(new HighlighterPipeline( new Highlighter[] { getSearchHighlighter() })); } else if (!isInPipeline(getSearchHighlighter())) { getHighlighters().addHighlighter(getSearchHighlighter()); } } private boolean isInPipeline(PatternHighlighter searchHighlighter) { Highlighter[] inPipeline = getHighlighters().getHighlighters(); if ((inPipeline.length > 0) && (searchHighlighter.equals(inPipeline[inPipeline.length -1]))) { return true; } getHighlighters().removeHighlighter(searchHighlighter); return false; } protected SearchHighlighter createSearchHighlighter() { return new SearchHighlighter(); } } // ----------------------------------- uniform data model access /** * @return the unconfigured ComponentAdapter. */ protected ComponentAdapter getComponentAdapter() { if (dataAdapter == null) { dataAdapter = new TableAdapter(this); } return dataAdapter; } /** * Convenience to access a configured ComponentAdapter. * * @param row the row index in view coordinates. * @param column the column index in view coordinates. * @return the configured ComponentAdapter. */ protected ComponentAdapter getComponentAdapter(int row, int column) { ComponentAdapter adapter = getComponentAdapter(); adapter.row = row; adapter.column = column; return adapter; } protected static class TableAdapter extends ComponentAdapter { private final JXTable table; /** * Constructs a <code>TableDataAdapter</code> for the specified target * component. * * @param component * the target component */ public TableAdapter(JXTable component) { super(component); table = component; } /** * Typesafe accessor for the target component. * * @return the target component as a {@link javax.swing.JTable} */ public JXTable getTable() { return table; } @Override public String getColumnName(int columnIndex) { TableColumn column = getColumnByModelIndex(columnIndex); return column == null ? "" : column.getHeaderValue().toString(); } protected TableColumn getColumnByModelIndex(int modelColumn) { List columns = table.getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); if (column.getModelIndex() == modelColumn) { return column; } } return null; } @Override public String getColumnIdentifier(int columnIndex) { TableColumn column = getColumnByModelIndex(columnIndex); Object identifier = column != null ? column.getIdentifier() : null; return identifier != null ? identifier.toString() : null; } @Override public int getColumnCount() { return table.getModel().getColumnCount(); } @Override public int getRowCount() { return table.getModel().getRowCount(); } /** * {@inheritDoc} */ @Override public Object getValueAt(int row, int column) { return table.getModel().getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { table.getModel().setValueAt(aValue, row, column); } @Override public boolean isCellEditable(int row, int column) { return table.getModel().isCellEditable(row, column); } @Override public boolean isTestable(int column) { return getColumnByModelIndex(column) != null; } //-------------------------- accessing view state/values @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(table.convertRowIndexToModel(row), column); // return table.getValueAt(row, modelToView(column)); // in view coordinates } /** * {@inheritDoc} */ @Override public boolean isSelected() { return table.isCellSelected(row, column); } /** * {@inheritDoc} */ @Override public boolean hasFocus() { boolean rowIsLead = (table.getSelectionModel() .getLeadSelectionIndex() == row); boolean colIsLead = (table.getColumnModel().getSelectionModel() .getLeadSelectionIndex() == column); return table.isFocusOwner() && (rowIsLead && colIsLead); } /** * {@inheritDoc} */ @Override public int modelToView(int columnIndex) { return table.convertColumnIndexToView(columnIndex); } /** * {@inheritDoc} */ @Override public int viewToModel(int columnIndex) { return table.convertColumnIndexToModel(columnIndex); } } // --------------------- managing renderers/editors /** * Returns the HighlighterPipeline assigned to the table, null if none. * * @return the HighlighterPipeline assigned to the table. * @see #setHighlighters(HighlighterPipeline) */ public HighlighterPipeline getHighlighters() { return highlighters; } /** * Assigns a HighlighterPipeline to the table, maybe null to remove all * Highlighters.<p> * * The default value is <code>null</code>. * * @param pipeline the HighlighterPipeline to use for renderer decoration. * @see #getHighlighters() * @see #addHighlighter(Highlighter) * @see #removeHighlighter(Highlighter) * */ public void setHighlighters(HighlighterPipeline pipeline) { HighlighterPipeline old = getHighlighters(); if (old != null) { old.removeChangeListener(getHighlighterChangeListener()); } highlighters = pipeline; if (highlighters != null) { highlighters.addChangeListener(getHighlighterChangeListener()); } firePropertyChange("highlighters", old, getHighlighters()); repaint(); } /** * Adds a Highlighter. * <p> * * If the <code>HighlighterPipeline</code> returned from getHighlighters() * is null, creates and sets a new pipeline containing the given * <code>Highlighter</code>. Else, appends the <code>Highlighter</code> * to the end of the pipeline. * * @param highlighter the <code>Highlighter</code> to add. * @throws NullPointerException if <code>Highlighter</code> is null. * @see #removeHighlighter(Highlighter) * @see #setHighlighters(HighlighterPipeline) */ public void addHighlighter(Highlighter highlighter) { HighlighterPipeline pipeline = getHighlighters(); if (pipeline == null) { setHighlighters(new HighlighterPipeline(new Highlighter[] {highlighter})); } else { pipeline.addHighlighter(highlighter); } } /** * Removes the Highlighter. <p> * * Does nothing if the HighlighterPipeline is null or does not contain * the given Highlighter. * * @param highlighter the highlighter to remove. * @see #addHighlighter(Highlighter) * @see #setHighlighters(HighlighterPipeline) */ public void removeHighlighter(Highlighter highlighter) { if ((getHighlighters() == null)) return; getHighlighters().removeHighlighter(highlighter); } /** * Returns the <code>ChangeListener</code> to use with highlighters. Lazily * creates the listener. * * @return the ChangeListener for observing changes of highlighters, * guaranteed to be <code>not-null</code> */ protected ChangeListener getHighlighterChangeListener() { if (highlighterChangeListener == null) { highlighterChangeListener = createHighlighterChangeListener(); } return highlighterChangeListener; } /** * Creates and returns the ChangeListener observing Highlighters. * <p> * Here: repaints the table on receiving a stateChanged. * * @return the ChangeListener defining the reaction to changes of * highlighters. */ protected ChangeListener createHighlighterChangeListener() { ChangeListener l = new ChangeListener() { public void stateChanged(ChangeEvent e) { repaint(); } }; return l; } /** * {@inheritDoc} * <p> * * Overridden to fix core bug #4614616 (NPE if <code>TableModel</code>'s * <code>Class</code> for the column is an interface). This method * guarantees to always return a <code>not null</code> value. * * * */ @Override public TableCellRenderer getCellRenderer(int row, int column) { TableCellRenderer renderer = super.getCellRenderer(row, column); if (renderer == null) { renderer = getDefaultRenderer(Object.class); } return renderer; } /** * Returns the decorated <code>Component</code> used as a stamp to render * the specified cell. Overrides superclass version to provide support for * cell decorators. * <p> * * Adjusts component orientation (guaranteed to happen before applying * Highlighters). * * * @param renderer the <code>TableCellRenderer</code> to prepare * @param row the row of the cell to render, where 0 is the first row * @param column the column of the cell to render, where 0 is the first * column * @return the decorated <code>Component</code> used as a stamp to render * the specified cell * @see org.jdesktop.swingx.decorator.Highlighter */ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component stamp = super.prepareRenderer(renderer, row, column); // #145-swingx: default renderers don't respect componentOrientation. adjustComponentOrientation(stamp); // #258-swingx: hacking around DefaultTableCellRenderer color memory. resetDefaultTableCellRendererColors(stamp, row, column); if (highlighters == null) { return stamp; // no need to decorate renderer with highlighters } else { return highlighters.apply(stamp, getComponentAdapter(row, column)); } } /** * Method to hack around #258-swingx: apply a specialized <code>Highlighter</code> * to force reset the color "memory" of <code>DefaultTableCellRenderer</code>. * This is called for each renderer in <code>prepareRenderer</code> after * calling super, but before applying the HighlighterPipeline. Subclasses * which are sure to solve the problem at the core (that is in * a well-behaved DefaultTableCellRenderer) should override this method * to do nothing. * * @param renderer the <code>TableCellRenderer</code> to hack * @param row the row of the cell to render * @param column the column index of the cell to render * * @see org.jdesktop.swingx.decorator.ResetDTCRColorHighlighter * @see #prepareRenderer(TableCellRenderer, int, int) */ protected void resetDefaultTableCellRendererColors(Component renderer, int row, int column) { ComponentAdapter adapter = getComponentAdapter(row, column); if (resetDefaultTableCellRendererHighlighter == null) { resetDefaultTableCellRendererHighlighter = new ResetDTCRColorHighlighter(); } // hacking around DefaultTableCellRenderer color memory. resetDefaultTableCellRendererHighlighter.highlight(renderer, adapter); } /** * {@inheritDoc} <p> * * Overridden to adjust the editor's component orientation if * appropriate. */ @Override public Component prepareEditor(TableCellEditor editor, int row, int column) { Component comp = super.prepareEditor(editor, row, column); adjustComponentOrientation(comp); return comp; } /** * Adjusts the <code>Component</code>'s orientation to this * <code>JXTable</code>'s CO if appropriate. The parameter must not be * <code>null</code>. * <p> * * This implementation synchs the CO always. * * @param stamp the Component who's CO may need to be synched. */ protected void adjustComponentOrientation(Component stamp) { if (stamp.getComponentOrientation().equals(getComponentOrientation())) return; stamp.applyComponentOrientation(getComponentOrientation()); } /** * Returns a new instance of the default renderer for the specified class. * This differs from <code>getDefaultRenderer()</code> in that it returns * a <b>new </b> instance each time so that the renderer may be set and * customized on a particular column. * * @param columnClass Class of value being rendered * @return TableCellRenderer instance which renders values of the specified * type */ public TableCellRenderer getNewDefaultRenderer(Class columnClass) { TableCellRenderer renderer = getDefaultRenderer(columnClass); if (renderer != null) { try { return renderer.getClass().newInstance(); } catch (Exception e) { LOG.fine("could not create renderer for " + columnClass); } } // JW PENDING: must not return null! return null; } /** * Creates default cell renderers for objects, numbers, doubles, dates, * booleans, icons, and links. * <p> * Overridden so we can act as factory for renderers plus hacking around * huge memory consumption of UIDefaults (see #6345050 in core Bug parade) * <p> * {@inheritDoc} */ @Override protected void createDefaultRenderers() { // super.createDefaultRenderers(); // This duplicates JTable's functionality in order to make the renderers // available in getNewDefaultRenderer(); If JTable's renderers either // were public, or it provided a factory for *new* renderers, this would // not be needed // hack around #6345050 - new UIDefaults() // is created with a huge initialCapacity // giving a dummy key/value array as parameter reduces that capacity // to length/2. Object[] dummies = new Object[] { 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, }; defaultRenderersByColumnClass = new UIDefaults(dummies); defaultRenderersByColumnClass.clear(); // defaultRenderersByColumnClass = new UIDefaults(); // Objects setLazyRenderer(Object.class, "javax.swing.table.DefaultTableCellRenderer"); // Numbers setLazyRenderer(Number.class, "org.jdesktop.swingx.JXTable$NumberRenderer"); // Doubles and Floats setLazyRenderer(Float.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); setLazyRenderer(Double.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); // Dates setLazyRenderer(Date.class, "org.jdesktop.swingx.JXTable$DateRenderer"); // Icons and ImageIcons setLazyRenderer(Icon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); setLazyRenderer(ImageIcon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); // Booleans setLazyRenderer(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanRenderer"); } /** c&p'ed from super */ private void setLazyValue(Hashtable h, Class c, String s) { h.put(c, new UIDefaults.ProxyLazyValue(s)); } /** c&p'ed from super */ private void setLazyRenderer(Class c, String s) { setLazyValue(defaultRenderersByColumnClass, c, s); } /** c&p'ed from super */ private void setLazyEditor(Class c, String s) { setLazyValue(defaultEditorsByColumnClass, c, s); } /* * Default Type-based Renderers: JTable's default table cell renderer * classes are private and JTable:getDefaultRenderer() returns a *shared* * cell renderer instance, thus there is no way for us to instantiate a new * instance of one of its default renderers. So, we must replicate the * default renderer classes here so that we can instantiate them when we * need to create renderers to be set on specific columns. */ public static class NumberRenderer extends DefaultTableCellRenderer { public NumberRenderer() { super(); // JW: RIGHT is the correct thing to do for bidi-compliance // numbers are right aligned even if text is LToR setHorizontalAlignment(JLabel.RIGHT); } } public static class DoubleRenderer extends NumberRenderer { private final NumberFormat formatter; public DoubleRenderer() { this(null); } public DoubleRenderer(NumberFormat formatter) { if (formatter == null) { formatter = NumberFormat.getInstance(); } this.formatter = formatter; } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } public static class DateRenderer extends DefaultTableCellRenderer { private final DateFormat formatter; public DateRenderer() { this(null); } public DateRenderer(DateFormat formatter) { if (formatter == null) { formatter = DateFormat.getDateInstance(); } this.formatter = formatter; } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } public static class IconRenderer extends DefaultTableCellRenderer { public IconRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); } @Override public void setValue(Object value) { setIcon((value instanceof Icon) ? (Icon) value : null); } } /* * re- c&p'd from 1.5 JTable. */ public static class BooleanRenderer extends JCheckBox implements // , UIResource TableCellRenderer { private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); public BooleanRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); setBorderPainted(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setSelected((value != null && ((Boolean) value).booleanValue())); if (hasFocus) { setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); } else { setBorder(noFocusBorder); } return this; } } /** * Creates default cell editors for objects, numbers, and boolean values. * <p> * Overridden to hook enhanced editors plus hacking around * huge memory consumption of UIDefaults (see #6345050 in core Bug parade) * @see DefaultCellEditor */ @Override protected void createDefaultEditors() { Object[] dummies = new Object[] { 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, }; defaultEditorsByColumnClass = new UIDefaults(dummies); defaultEditorsByColumnClass.clear(); // defaultEditorsByColumnClass = new UIDefaults(); // Objects setLazyEditor(Object.class, "org.jdesktop.swingx.JXTable$GenericEditor"); // Numbers setLazyEditor(Number.class, "org.jdesktop.swingx.JXTable$NumberEditor"); // Booleans setLazyEditor(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanEditor"); // setLazyEditor(LinkModel.class, "org.jdesktop.swingx.LinkRenderer"); } /** * Default Editors */ public static class GenericEditor extends DefaultCellEditor { Class[] argTypes = new Class[]{String.class}; java.lang.reflect.Constructor constructor; Object value; public GenericEditor() { this(new JTextField()); } public GenericEditor(JTextField textField) { super(textField); getComponent().setName("Table.editor"); } @Override public boolean stopCellEditing() { String s = (String)super.getCellEditorValue(); // Here we are dealing with the case where a user // has deleted the string value in a cell, possibly // after a failed validation. Return null, so that // they have the option to replace the value with // null or use escape to restore the original. // For Strings, return "" for backward compatibility. if ("".equals(s)) { if (constructor.getDeclaringClass() == String.class) { value = s; } super.stopCellEditing(); } try { value = constructor.newInstance(new Object[]{s}); } catch (Exception e) { ((JComponent)getComponent()).setBorder(new LineBorder(Color.red)); return false; } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { this.value = null; ((JComponent)getComponent()).setBorder(new LineBorder(Color.black)); try { Class type = table.getColumnClass(column); // Since our obligation is to produce a value which is // assignable for the required type it is OK to use the // String constructor for columns which are declared // to contain Objects. A String is an Object. if (type == Object.class) { type = String.class; } constructor = type.getConstructor(argTypes); } catch (Exception e) { return null; } return super.getTableCellEditorComponent(table, value, isSelected, row, column); } @Override public Object getCellEditorValue() { return value; } } public static class NumberEditor extends GenericEditor { public NumberEditor() { ((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT); } } public static class BooleanEditor extends DefaultCellEditor { public BooleanEditor() { super(new JCheckBox()); JCheckBox checkBox = (JCheckBox)getComponent(); checkBox.setHorizontalAlignment(JCheckBox.CENTER); } } // ----------------------------- enhanced editing support /** * Returns the editable property of the <code>JXTable</code> as a whole. * * @return boolean to indicate if the table is editable. * @see #setEditable */ public boolean isEditable() { return editable; } /** * Sets the editable property. This property allows to mark all cells in a * table as read-only, independent of their per-column editability as * returned by <code>TableColumnExt.isEditable()</code> and their per-cell * editability as returned by the <code>TableModel.isCellEditable</code>. * If a cell is read-only in its column or model layer, this property has no * effect. * <p> * * The default value is <code>true</code>. * * @param editable the flag to indicate if the table is editable. * @see #isEditable * @see #isCellEditable(int, int) */ public void setEditable(boolean editable) { boolean old = isEditable(); this.editable = editable; firePropertyChange("editable", old, isEditable()); } /** * Returns the property which determines the edit termination behaviour on * focus lost. * * @return boolean to indicate whether an ongoing edit should be terminated * if the focus is moved to somewhere outside of the table. * @see #setTerminateEditOnFocusLost(boolean) */ public boolean isTerminateEditOnFocusLost() { return Boolean.TRUE .equals(getClientProperty("terminateEditOnFocusLost")); } /** * Sets the property to determine whether an ongoing edit should be * terminated if the focus is moved to somewhere outside of the table. If * true, terminates the edit, does nothing otherwise. The exact behaviour is * implemented in <code>JTable.CellEditorRemover</code>: "outside" is * interpreted to be on a component which is not under the table hierarchy * but inside the same toplevel window, "terminate" does so in any case, * first tries to stop the edit, if that's unsuccessful it cancels the edit. * <p> * The default value is <code>true</code>. * * @param terminate the flag to determine whether or not to terminate the * edit * @see #isTerminateEditOnFocusLost() */ public void setTerminateEditOnFocusLost(boolean terminate) { // JW: we can leave the propertyChange notification to the // putClientProperty - the key and method name are the same putClientProperty("terminateEditOnFocusLost", terminate); } /** * Returns the autoStartsEdit property. * * @return boolean to indicate whether a keyStroke should try to start * editing. * @see #setAutoStartEditOnKeyStroke(boolean) */ public boolean isAutoStartEditOnKeyStroke() { return !Boolean.FALSE .equals(getClientProperty("JTable.autoStartsEdit")); } /** * Sets the autoStartsEdit property. If true, keystrokes are passed-on to * the cellEditor of the lead cell to let it decide whether to start an * edit. * <p> * The default value is <code>true</code>. * <p> * * @param autoStart boolean to determine whether a keyStroke should try to * start editing. * @see #isAutoStartEditOnKeyStroke() */ public void setAutoStartEditOnKeyStroke(boolean autoStart) { boolean old = isAutoStartEditOnKeyStroke(); // JW: we have to take over propertyChange notification // because the key and method name are different. // As a consequence, there are two events fired: one for // the client prop and one for this method. putClientProperty("JTable.autoStartsEdit", autoStart); firePropertyChange("autoStartEditOnKeyStroke", old, isAutoStartEditOnKeyStroke()); } // ---------------------------- updateUI support /** * {@inheritDoc} * <p> * Additionally updates auto-adjusted row height and highlighters. * <p> * Another of the override motivation is to fix core issue (?? ID): super * fails to update <b>all</b> renderers/editors. */ @Override public void updateUI() { super.updateUI(); if (columnControlButton != null) { columnControlButton.updateUI(); } for (Enumeration defaultEditors = defaultEditorsByColumnClass .elements(); defaultEditors.hasMoreElements();) { updateEditorUI(defaultEditors.nextElement()); } for (Enumeration defaultRenderers = defaultRenderersByColumnClass .elements(); defaultRenderers.hasMoreElements();) { updateRendererUI(defaultRenderers.nextElement()); } List columns = getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); updateEditorUI(column.getCellEditor()); updateRendererUI(column.getCellRenderer()); updateRendererUI(column.getHeaderRenderer()); } updateRowHeightUI(true); updateHighlighters(); } /** * Updates highlighter after <code>updateUI</code> changes. * * @see org.jdesktop.swingx.decorator.Highlighter.UIHighlighter */ protected void updateHighlighters() { if (getHighlighters() == null) return; getHighlighters().updateUI(); } /** * Auto-adjusts rowHeight to something more pleasing then the default. This * method is called after instantiation and after updating the UI. Does * nothing if the given parameter is <code>true</code> and the rowHeight * had been already set by client code. The underlying problem is that raw * types can't implement UIResource. * <p> * This implementation asks the UIManager for a default value (stored with * key "JXTable.rowHeight"). If none is available, calculates a "reasonable" * height from the table's fontMetrics, assuming that most renderers/editors * will have a border with top/bottom of 1. * <p> * * @param respectRowSetFlag a boolean to indicate whether client-code flag * should be respected. * @see #isXTableRowHeightSet */ protected void updateRowHeightUI(boolean respectRowSetFlag) { if (respectRowSetFlag && isXTableRowHeightSet) return; int uiHeight = UIManager.getInt(UIPREFIX + "rowHeight"); if (uiHeight > 0) { setRowHeight(uiHeight); } else { int fontBasedHeight = getFontMetrics(getFont()).getHeight() + 2; int magicMinimum = 18; setRowHeight(Math.max(fontBasedHeight, magicMinimum)); } isXTableRowHeightSet = false; } /** * Convenience to set both grid line visibility and default margin for * horizontal/vertical lines. The margin defaults to 1 or 0 if the grid * lines are drawn or not drawn. * <p> * PENDING rename? setShowGrid(boolean, boolean) would let it appear nearer * to the other setShowGrid method. * * @param showHorizontalLines boolean to decide whether to draw horizontal * grid lines. * @param showVerticalLines boolean to decide whether to draw vertical grid * lines. * @see javax.swing.JTable#setShowGrid(boolean) * @see javax.swing.JTable#setIntercellSpacing(Dimension) */ public void setDefaultMargins(boolean showHorizontalLines, boolean showVerticalLines) { int defaultRowMargin = showHorizontalLines ? 1 : 0; setRowMargin(defaultRowMargin); setShowHorizontalLines(showHorizontalLines); int defaultColumnMargin = showVerticalLines ? 1 : 0; setColumnMargin(defaultColumnMargin); setShowVerticalLines(showVerticalLines); } /** * {@inheritDoc} * <p> * Overriden to keep view/model coordinates of SizeSequence in synch. Marks * the request as client-code induced. * * @see #isXTableRowHeightSet */ @Override public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (rowHeight > 0) { isXTableRowHeightSet = true; } updateViewSizeSequence(); } /** * {@inheritDoc} * <p> * Does nothing if support of individual rowHeights is not enabled. * Overriden to keep view/model coordinates of SizeSequence in synch. * * @see #isRowHeightEnabled() */ @Override public void setRowHeight(int row, int rowHeight) { if (!isRowHeightEnabled()) return; super.setRowHeight(row, rowHeight); updateViewSizeSequence(); resizeAndRepaint(); } /** * Sets enablement of individual rowHeight support. Enabling the support * involves reflective access to super's private field rowModel which may * fail due to security issues. If failing the support is not enabled. * <p> * The default value is false. * * @param enabled a boolean to indicate whether per-row heights should be * enabled. * @see #isRowHeightEnabled() * @see #setRowHeight(int, int) */ public void setRowHeightEnabled(boolean enabled) { // PENDING: should we throw an Exception if the enabled fails? // Or silently fail - depends on runtime context, // can't do anything about it. boolean old = isRowHeightEnabled(); if (old == enabled) return; if (enabled && !canEnableRowHeight()) return; rowHeightEnabled = enabled; if (!enabled) { adminSetRowHeight(getRowHeight()); } firePropertyChange("rowHeightEnabled", old, rowHeightEnabled); } /** * Returns a boolean to indicate whether individual row height is enabled. * * @return a boolean to indicate whether individual row height support is * enabled. * @see #setRowHeightEnabled(boolean) * @see #setRowHeight(int, int) */ public boolean isRowHeightEnabled() { return rowHeightEnabled; } /** * Returns if it's possible to enable individual row height support. * * @return a boolean to indicate whether access of super's private * <code>rowModel</code> is allowed. */ private boolean canEnableRowHeight() { return getRowModelField() != null; } /** * Returns super's private <code>rowModel</code> which holds the * individual rowHeights. This method will return <code>null</code> if the * access failed, f.i. in sandbox restricted applications. * * @return super's rowModel field or null if the access was not successful. */ private SizeSequence getSuperRowModel() { try { Field field = getRowModelField(); if (field != null) { return (SizeSequence) field.get(this); } } catch (SecurityException e) { LOG.fine("cannot use reflection " + " - expected behaviour in sandbox"); } catch (IllegalArgumentException e) { LOG .fine("problem while accessing super's private field - private api changed?"); } catch (IllegalAccessException e) { LOG .fine("cannot access private field " + " - expected behaviour in sandbox. " + "Could be program logic running wild in unrestricted contexts"); } return null; } /** * Returns super's private field which holds the individual rowHeights. This * method will return <code>null</code> if the access failed, f.i. in * sandbox restricted applications. * * @return the super's field with access allowed or null if an Exception * caught while trying to access. */ private Field getRowModelField() { if (rowModelField == null) { try { rowModelField = JTable.class.getDeclaredField("rowModel"); rowModelField.setAccessible(true); } catch (SecurityException e) { rowModelField = null; LOG.fine("cannot access JTable private field rowModel " + "- expected behaviour in sandbox"); } catch (NoSuchFieldException e) { LOG.fine("problem while accessing super's private field" + " - private api changed?"); } } return rowModelField; } /** * Returns the mapper used synch individual rowHeights in view/model * coordinates. * * @return the <code>SizeSequenceMapper</code> used to synch view/model * coordinates for individual row heights * @see org.jdesktop.swingx.decorator.SizeSequenceMapper */ protected SizeSequenceMapper getRowModelMapper() { if (rowModelMapper == null) { rowModelMapper = new SizeSequenceMapper(filters); } return rowModelMapper; } /** * Sets the rowHeight for all rows to the given value. Keeps the flag * <code>isXTableRowHeight</code> unchanged. This enables the distinction * between setting the height for internal reasons from doing so by client * code. * * @param rowHeight new height in pixel. * @see #setRowHeight(int) * @see #isXTableRowHeightSet */ protected void adminSetRowHeight(int rowHeight) { boolean heightSet = isXTableRowHeightSet; setRowHeight(rowHeight); isXTableRowHeightSet = heightSet; } /** * Tries its best to <code>updateUI</code> of the potential * <code>TableCellEditor</code>. * * @param maybeEditor the potential editor. */ private void updateEditorUI(Object maybeEditor) { // maybe null or proxyValue if (!(maybeEditor instanceof TableCellEditor)) return; // super handled this if ((maybeEditor instanceof JComponent) || (maybeEditor instanceof DefaultCellEditor)) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellEditor) maybeEditor) .getTableCellEditorComponent(this, null, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } /** * Tries its best to <code>updateUI</code> of the potential * <code>TableCellRenderer</code>. * * @param maybeRenderer the potential renderer. */ private void updateRendererUI(Object maybeRenderer) { // maybe null or proxyValue if (!(maybeRenderer instanceof TableCellRenderer)) return; // super handled this if (maybeRenderer instanceof JComponent) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellRenderer) maybeRenderer) .getTableCellRendererComponent(this, null, false, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } // ---------------------------- overriding super factory methods and buggy /** * {@inheritDoc} * <p> * Overridden to work around core Bug (ID #6291631): negative y is mapped to * row 0). * */ @Override public int rowAtPoint(Point point) { if (point.y < 0) return -1; return super.rowAtPoint(point); } /** * * {@inheritDoc} * <p> * * Overridden to return a <code>JXTableHeader</code>. * @see JXTableHeader */ @Override protected JTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel); } /** * * {@inheritDoc} * <p> * * Overridden to return a <code>DefaultTableColumnModelExt</code>. * @see org.jdesktop.swingx.table.DefaultTableColumnModelExt */ @Override protected TableColumnModel createDefaultColumnModel() { return new DefaultTableColumnModelExt(); } }
c32eb8fcfe1628d019526eed25293c436bd157cd
3cbb73c13e5b4956c03fa62dbda81e4180420222
/PuLSaR/src/main/java/eu/brokeratcloud/opt/engine/sim/RepeatNode.java
eadb460c98f4c707cbc59df6ee8fabe425fa9e94
[]
no_license
torax242/BrokerAtCloud
4b5af0f7ec69446a2be7d91c9e615629bf940039
722638acc3257a2b5f5ab09dea86ba8e7a7346fb
refs/heads/master
2020-04-08T23:47:09.072301
2016-02-02T08:50:01
2016-02-02T08:50:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,888
java
/** * This file (along with RepeatTokenParser) extend Pebble engine with 'repeat' tag * For more information see RepeatTokenParser */ package eu.brokeratcloud.opt.engine.sim; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.mitchellbosecke.pebble.error.PebbleException; import com.mitchellbosecke.pebble.extension.NodeVisitor; import com.mitchellbosecke.pebble.node.AbstractRenderableNode; import com.mitchellbosecke.pebble.node.BodyNode; import com.mitchellbosecke.pebble.node.expression.Expression; import com.mitchellbosecke.pebble.node.expression.LiteralLongExpression; import com.mitchellbosecke.pebble.template.EvaluationContext; import com.mitchellbosecke.pebble.template.PebbleTemplateImpl; /** * Represents a "repeat" loop within the template. */ public class RepeatNode extends AbstractRenderableNode { private final String variableName; private final Expression<?> lowerBoundExpression; private final Expression<?> upperBoundExpression; private final BodyNode body; public RepeatNode(int lineNumber, String variableName, Expression<?> lowerBoundExpression, Expression<?> upperBoundExpression, BodyNode body) { super(lineNumber); this.variableName = variableName; this.lowerBoundExpression = lowerBoundExpression; this.upperBoundExpression = upperBoundExpression; this.body = body; } @Override public void render(PebbleTemplateImpl self, Writer writer, EvaluationContext context) throws PebbleException, IOException { Object lowerEvaluation = lowerBoundExpression.evaluate(self, context); Object upperEvaluation = upperBoundExpression.evaluate(self, context); if (lowerEvaluation == null || upperEvaluation == null) { return; } Long lowerBound = toLong(lowerEvaluation); Long upperBound = toLong(upperEvaluation); if (lowerBound == null || upperBound == null) { return; } long lower = lowerBound.longValue(); long upper = upperBound.longValue(); boolean newScope = false; long length = upper-lower+1; if (length > 0) { /* * Only if there is a variable name conflict between one of the * variables added by the for loop construct and an existing * variable do we push another scope, otherwise we reuse the current * scope for performance purposes. */ if (context.currentScopeContainsVariable("loop") || context.currentScopeContainsVariable(variableName)) { context.pushScope(); newScope = true; } int index = 0; for (long i = lower; i <= upper; i++) { /* * Must create a new map with every iteration instead of * re-using the same one just in case there is a "parallel" tag * within this repeat loop; it's imperative that each thread would * get it's own distinct copy of the context. */ Map<String, Object> loop = new HashMap<String, Object>(); loop.put("index", index++); loop.put("length", length); context.put("loop", loop); context.put(variableName, new Long(i)); body.render(self, writer, context); } if(newScope){ context.popScope(); } } } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } public String getIterationVariable() { return variableName; } public Expression<?> getLowerBoundExpression() { return lowerBoundExpression; } public Expression<?> getUpperBoundExpression() { return upperBoundExpression; } public BodyNode getBody() { return body; } @SuppressWarnings("unchecked") private Long toLong(final Object obj) { Long result = null; if (obj instanceof Long) { result = (Long) obj; } else if (obj instanceof Integer) { result = new Long( ((Integer)obj).intValue() ); } return result; } }
32ed0014eb2a808597a858bfc7fea1d4f58989ae
6e0a777047581b051ad38b61e6ce973846bb5767
/olx_resale/src/main/java/com/pack/ImageController.java
309d21cb1bbbe95270bb6dd2f740dd747c19a1b3
[]
no_license
Abiranjeetha/Spring_Hibernate
046e91d8f58faa0f131698d6b40af616475e7f18
36840546e44ce15617375dbffa73508562d68930
refs/heads/master
2022-12-22T23:01:01.825069
2019-06-19T04:51:49
2019-06-19T04:51:49
192,660,227
0
0
null
2022-12-16T09:51:35
2019-06-19T04:47:50
Java
UTF-8
Java
false
false
11,154
java
package com.pack; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.pack.form.Item; import com.pack.form.User; //import com.pack.form.example; import com.pack.service.ImageService; @Controller public class ImageController { private static Logger log=Logger.getLogger(ImageController.class); @Autowired(required = true) @Qualifier(value = "imageService") ImageService imageService; //List<Item> list = new ArrayList(); @RequestMapping(value = "/insertimage", method = RequestMethod.POST) public ModelAndView save(@RequestParam(required = false, value = "itemname") String itemname, @RequestParam(required = false, value = "categoryname") String categoryname, @RequestParam(required = false, value = "yearsofusage") Integer yearsofusage, @RequestParam(required = false, value = "image") MultipartFile image) { try { imageService.insertRecords(itemname, categoryname, yearsofusage, image); System.out.println("inside image controller"); return new ModelAndView("example", "msg", "Records succesfully inserted into database."); } catch (Exception e) { return new ModelAndView("example", "msg", "Error: " + e.getMessage()); } } /* * @RequestMapping(value = "/fetch") public ModelAndView * listStudent(ModelAndView model) throws IOException { * * List<example> imagelist = imageService.itemList(); * * model.addObject("imagelist", imagelist); model.setViewName("index"); * * return model; } */ @RequestMapping(value = "/getStudentPhoto/{itemname}") public void getStudentPhoto(HttpServletResponse response, @PathVariable("itemname") String itemname) throws Exception { response.setContentType("image/jpeg"); Blob ph = imageService.getPhotoByName(itemname); byte[] bytes = ph.getBytes(1, (int) ph.length()); InputStream inputStream = new ByteArrayInputStream(bytes); IOUtils.copy(inputStream, response.getOutputStream()); } @RequestMapping(value = "/additem", method = RequestMethod.POST) public ModelAndView postItem(@RequestParam(required = false, value = "itemname") String itemname, @RequestParam(required = false, value = "categoryname") String categoryname, @RequestParam(required = false, value = "price") Float price, @RequestParam(required = false, value = "yearsofusage") Integer yearsofusage, @RequestParam(required = false, value = "image") MultipartFile image, @RequestParam(required = false, value = "description") String description, @RequestParam(required = false, value = "quantity") int quantity,HttpSession session) { try { log.info("inside add item method"); System.out.println("Inside post item method"); int userid = (int) session.getAttribute("userid"); System.out.println(userid); int categoryid = imageService.fetchCategoryid(categoryname); System.out.println("The fetched category id is" + categoryid); Random r = new Random(); int itemid = r.nextInt(999) + 100; imageService.insertItem(itemname, categoryid, price, yearsofusage, itemid, image, userid, description,quantity); System.out.println("inside image controller"); List<Item> itemslist = imageService.fetchItemList(); session.setAttribute("itemslist", itemslist); System.out.println("after fetch item list"); return new ModelAndView("afterlogin", "msg", "Records succesfully inserted into database."); } catch (Exception e) { return new ModelAndView("sell", "msg", "Error: " + e.getMessage()); } } @RequestMapping(value = "/getItemImage/{itemid}") public void getStudentPhoto(HttpServletResponse response, @PathVariable("itemid") Integer itemid) throws Exception { response.setContentType("image/jpeg"); log.info("inside get student photo method"); Blob ph = imageService.getImageById(itemid); byte[] bytes = ph.getBytes(1, (int) ph.length()); InputStream inputStream = new ByteArrayInputStream(bytes); IOUtils.copy(inputStream, response.getOutputStream()); } @RequestMapping(value = "/collectitem") public String collectitem(HttpServletRequest request) { List<Item> itemslist = imageService.fetchItemList(); log.info("inside collect item method"); request.setAttribute("items", itemslist); return "homepage"; } @RequestMapping(value = "/inter") public String collectitemforafterlogin(HttpSession session) { log.info("inside collect item after login"); List<Item> itemslist = imageService.fetchItemList(); session.setAttribute("itemslist", itemslist); return "afterlogin"; } @RequestMapping(value = "/sell") public String postAd(HttpSession session) { log.info("inside sell method"); List<String> list = imageService.gatherCategory(); session.setAttribute("categoryname", list); return "sell"; } @RequestMapping(value = "/itempage/{itemid}") public String getSingleItem(HttpSession session, @PathVariable("itemid") Integer itemid) { log.info("inside get single item method"); Item item = imageService.getItemDetails(itemid); session.setAttribute("singleitem", item); return "index2"; } @RequestMapping(value = "/cart/{itemid}") public String addToCart(HttpSession session, @PathVariable("itemid") Integer itemid) { Item item = imageService.getItemDetails(itemid); //list.add(item); imageService.addToCart((int)session.getAttribute("userid"),itemid); log.info("inside add to cart method"); //session.setAttribute("cartitemlist", list); return "intermediate"; } @RequestMapping(value = "/cartpage") public String cartPage(HttpSession session) { log.info("inside cart page method"); List <Integer>list=imageService.cartitemlist((int)session.getAttribute("userid")); List <Item> listOfItem=new ArrayList(); for(int i=0;i<list.size();i++) { Item item=imageService.getItemDetails(list.get(i)); listOfItem.add(item); } session.setAttribute("cartitemlist", listOfItem); return "cart"; } @RequestMapping(value = "/removefromcart/{itemid}") public String removeFromCart(HttpSession session, @PathVariable("itemid") Integer itemid) { log.info("remove from cart method"); imageService.removeFromCart((int)session.getAttribute("userid"),itemid); return "index3"; } @RequestMapping(value = "/myadspage") public String myAdsPage(HttpSession session) { log.info("inside my ads page"); int userid=(int)session.getAttribute("userid"); List<Item>myadslist=imageService.getmyads(userid); session.setAttribute("myads", myadslist); return "myads"; } @RequestMapping(value = "/removemyads/{itemid}") public String removeMyAds(HttpSession session,@PathVariable("itemid") Integer itemid) { log.info("inside remove my ads method"); int item = imageService.removeItemDetails(itemid); return "index5"; } @RequestMapping(value="/buy/{itemid}",method=RequestMethod.POST) public String buyNow(HttpServletRequest request, @PathVariable("itemid") Integer itemid) { System.out.println("inside buy method"); log.info("inside buy now method"); int quantity=Integer.parseInt(request.getParameter("quantity")); Item item=imageService.getItemDetails(itemid); if(quantity<=item.getQuantity()) { if(quantity-item.getQuantity()==0) { imageService.removeItemDetails(itemid); System.out.println("Item removed"); } else { imageService.setNewQuantity(itemid,item.getQuantity()-quantity); System.out.println("Item quantity updated"); } } else { return "index7"; } return "payment"; } @RequestMapping(value="/search",method = RequestMethod.POST) public String searchCategory(HttpServletRequest request,HttpSession session) { log.info("inside search category method"); String search=request.getParameter("search"); List<Item>itemslist=imageService.getParticularItems(search); session.setAttribute("itemslist", itemslist); return "afterlogin"; } @RequestMapping(value="/searchAtHomepage",method = RequestMethod.POST) public String searchCategoryAtHomepage(HttpServletRequest request) { log.info("inside search category method"); String search=request.getParameter("search"); List<Item>itemslist=imageService.getParticularItems(search); request.setAttribute("items", itemslist); return "homepage"; } @RequestMapping(value="/logout") public String logoutFun(HttpSession session,HttpServletRequest request) { log.info("inside logout fun method"); session.invalidate(); request.removeAttribute("msg"); return "index6"; } @RequestMapping(value="/proceedtopay",method=RequestMethod.POST) public String proceedToPay(HttpSession session) { log.info("inside proceed to pay method"); return "intermediate"; } @RequestMapping(value="/load") public String load() { log.info("inside load error method"); return "error"; } @RequestMapping(value = "/editmyad/{itemid}") public String editMyAd(HttpSession session,@PathVariable("itemid") Integer itemid) { log.info("inside edit my ad method"); Item item = imageService.getItemDetails(itemid); String categoryname=imageService.fetchCategoryName(item.getCategoryid()); session.setAttribute("categoryname", categoryname); session.setAttribute("edititem", item); return "editad"; } @RequestMapping(value = "/edititem/{itemid}",method = RequestMethod.POST) public String editItem(HttpSession session,@PathVariable("itemid")Integer itemid,@RequestParam(required = false, value = "itemname") String itemname, @RequestParam(required = false, value = "categoryname") String categoryname, @RequestParam(required = false, value = "price") Float price, @RequestParam(required = false, value = "yearsofusage") Integer yearsofusage, @RequestParam(required = false, value = "image") MultipartFile image, @RequestParam(required = false, value = "description") String description, @RequestParam(required = false, value = "quantity") int quantity) throws IOException { log.info("inside edit item method"); int categoryid = imageService.fetchCategoryid(categoryname); if(image.isEmpty()) { //System.out.println("Photo not updated...."); imageService.editItem(itemname, categoryid, price, yearsofusage, itemid, image, description,quantity); } else { //System.out.println("Photo updated...."); imageService.editItem1(itemname, categoryid, price, yearsofusage, itemid, image, description,quantity); } return "index8"; } }
fa3491c64b3ee23416a7f0913dfdbc379f6ee975
0a205fa06361c526b4d48011834dccb296b1ac79
/app/src/main/java/com/industrialmaster/musicplayer/ThirdActivity.java
eeff4c8c84cfb7db7a52e56da3274fcc3ee8fc4c
[]
no_license
MadurangiChathurika/SmartPlayer
762ae84328c6207a0b5dc13e915406e69d584872
8ce8fd0386d68f0149b19f7078362a1b7e1a1e5c
refs/heads/master
2022-11-26T00:50:18.133983
2020-07-20T14:15:38
2020-07-20T14:15:38
281,131,280
0
0
null
null
null
null
UTF-8
Java
false
false
1,428
java
package com.industrialmaster.musicplayer; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.industrialmaster.musicplayer.audio.background.PlayBackgroundAudioActivity; public class ThirdActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); } public void Music(View v){ Intent intent = new Intent(this, PlayBackgroundAudioActivity.class); startActivity(intent); } public void Home(View v){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void song1(View v){ Intent intent = new Intent(this, Song1Activity.class); startActivity(intent); } public void song2(View v){ Intent intent = new Intent(this, Song2Activity.class); startActivity(intent); } public void song3(View v){ Intent intent = new Intent(this, Song3Activity.class); startActivity(intent); } public void song4(View v){ Intent intent = new Intent(this, Song4Activity.class); startActivity(intent); } public void song5(View v){ Intent intent = new Intent(this, Song5Activity.class); startActivity(intent); } }
31d46ed70e4ba76098c827adcfa45c822bf9ff69
14afb443c01f2c1dd8f9d7cf1e5b5337c1e9ce2c
/src/main/java/com/example/latlongretrieval/Place.java
6519d479e61e78d52428726382fbedbba44ff08b
[]
no_license
herbsleb1708/latlong-retrieval
ba4186e153858e64c07885459019792c32e4f570
c27a62c0d448d2ea048c8934cb4078f11062a323
refs/heads/master
2021-07-09T01:37:20.056182
2017-10-04T18:35:51
2017-10-04T18:35:51
105,799,557
0
0
null
null
null
null
UTF-8
Java
false
false
512
java
package com.example.latlongretrieval; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @JsonIgnoreProperties(ignoreUnknown = true) @Data public class Place { @JsonProperty(value = "place name") private String name; @JsonProperty(value = "longitude") private double longitude; @JsonProperty(value = "state abbreviation") private String state; @JsonProperty(value = "latitude") private double latitude; }
4f24b60bca29cfc75bbaf02592ef87fc3bd27c20
926a628796557c976c4a558a8999b3c1925f62d5
/domino-game/src/main/java/com/jule/domino/game/service/GameMaintentService.java
a8fa72502402499d3a1547f90fa527d0dbbbd71e
[]
no_license
cubemoon/domino
7f4557b04ae5730be92edbd9b19389dd180c5d89
c7c490e8f7547e13ac6cd8fa344819a4d8625667
refs/heads/master
2023-04-15T22:36:18.587446
2019-08-01T03:15:43
2019-08-01T03:15:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package com.jule.domino.game.service; import java.util.concurrent.atomic.AtomicBoolean; /** * 游戏维护 * @author * @since 2019/2/20 13:25 */ public class GameMaintentService { public static final GameMaintentService OBJ = new GameMaintentService(); //游戏开关 - 默认是关闭的,能正常游戏,如果开启,则游戏无法正常开局 private static AtomicBoolean switched = new AtomicBoolean(false); /** * 开启维护墙 */ public void turnOn(){ switched.set(true); } /** * 关闭维护墙 */ public void turnOff(){ switched.set(false); } /** * 维护状态 * true 维护中 false 正常 */ public boolean isDefense(){ return switched.get(); } }
51983219b05bce05f78ac620e8147388b90a019e
f6dc9a904976f00e0b8b8829e618794c9338de7f
/java/com/occamsrazor/web/util/FileTest.java
3e7a1fe5c9f10f03546c98733ae0da5aff39be19
[]
no_license
dlehgml0901/Spring
52d6e61fd3c71ee8f38a6fc63888de3ebaa72bb3
3ad6c1aa0e05f2989d63856419b922530d018177
refs/heads/master
2022-05-31T19:49:18.559580
2020-04-28T03:00:50
2020-04-28T03:00:50
256,454,531
0
0
null
null
null
null
UTF-8
Java
false
false
1,249
java
package com.occamsrazor.web.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class FileTest { public final static String FILE_PATH = "C:\\Users\\user\\spring-workspace\\occamsrazor\\src\\main\\resources\\static\\member\\"; public static void main(String[] args) { try { File file = new File(FILE_PATH + "list.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(file, true)); BufferedReader br = new BufferedReader(new FileReader(file)); List<String> list = new ArrayList<>(); while (true) { switch (JOptionPane.showInputDialog("0.종료 1.쓰기 2.읽기")) { case "0": return; case "1": String message = JOptionPane.showInputDialog("메시지 입력"); bw.write(message); bw.newLine(); bw.flush(); break; case "2": while ((message = br.readLine()) != null) { list.add(message + "/"); } JOptionPane.showMessageDialog(null, list); br.close(); return; } } } catch (Exception e) { System.out.println("에러 발생"); e.printStackTrace(); } } }
8929b1d6b7e59787519ffd6d6b9330565b81f8c1
fbfd34b6b02daa6d5da0ded632078bf26fd16cea
/Robot.java
124df679e7509c427f3960edcde5cd44994961fb
[]
no_license
octopodidae/robot
e851a418117ebf4b46217d2b05d192abb1276812
a809d51e63f0d98e09d74d9dd6d657546134ca0c
refs/heads/master
2021-01-25T09:26:17.580473
2017-06-09T07:52:29
2017-06-09T07:52:29
93,833,718
0
0
null
null
null
null
UTF-8
Java
false
false
2,498
java
import java.util.ArrayList; import java.io.*; public class Robot { Programme thisProg; private int positionX; private int positionY; private boolean etat; int totalMinerai; int temps; // Constructeur Robot(String fileProg) throws FileNotFoundException, IOException { positionX = -1; positionY = -1; thisProg = new Programme(fileProg); etat = true; totalMinerai = 0; } // Afficher quantité minerai extrait public void afficherScore() { System.out.println("Score : " + totalMinerai + " tonnes de minerai extrait"); } // Get etat public boolean getEtat() { return this.etat; } // Set etat public void setEtat(boolean b) { this.etat = b; } // Get PositionX public int getPositionX() { return positionX; } // Get PositionY public int getPositionY() { return positionY; } // set PositionX public void setPositionX(int x) { positionX = x; } // Set PositionY public void setPositionY(int y) { positionY = y; } // Calculer la coordonnée X de destination public int calculerCoordX(int direction){ switch (direction) { // calculer coordonnées X destination case 0: // advance:0 (nord) return positionX; case 1: // advance:1 (est) return positionX+1; case 2: // advance:2 (sud) return positionX; case 3: // advance:0 (ouest) return positionX-1; default: return -1; } } // Calculer la coordonnée Y de destination public int calculerCoordY(int direction){ switch (direction) { // calculer coordonnées Y destination case 0: // advance:0 (nord) return positionY-1; case 1: // advance:1 (est) return positionY; case 2: // advance:2 (sud) return positionY+1; case 3: // advance:0 (ouest) return positionY; default: return -1; } } // Changer la position du robot; void vaVers(int direction) { switch(direction) { case 0: // va vers nord positionY = positionY - 1; break; case 1: // va vers est positionX = positionX + 1; break; case 2: // va vers sud positionY = positionY + 1; break; case 3: // va vers ouest positionX = positionX - 1; break; } } // Get String direction public String getStrDirection(int direction){ switch (direction) { case 0: // advance:0 (nord) return "nord"; case 1: // advance:1 (est) return "est"; case 2: // advance:2 (sud) return "sud"; case 3: // advance:0 (ouest) return "ouest"; default: return "Erreur direction"; } } }
70dd928d3e18cd1d36eba8f35dd9af608c338720
040937ae86f911a2fbf70cec46e05700bf951906
/proj1b/OffByOne.java
1a2673bb891aa9cbd5c165d2cddb1d2f3aa0a660
[]
no_license
evanxjh/cs61b-study
cd0284db89be259823a05fe81cb749cb21f5fb05
ad3bd9cf7f01d6c753606ae68a5c265a75b7d127
refs/heads/master
2020-06-13T01:06:02.751687
2019-07-18T13:32:56
2019-07-18T13:32:56
194,483,327
0
0
null
null
null
null
UTF-8
Java
false
false
391
java
/** * @author EvenHsia * @ClassName OffByOne.java * @Description A class for off-by-1 comparators * @createTime 2019-06-30- 16:38 */ public class OffByOne implements CharacterComparator { @Override public boolean equalChars(char x,char y){ int diff=x-y; if (Math.abs(diff)<=1){ return true; }else{ return false; } } }
f997738870f7c3eb7aff7d11b39ae7389b8e3366
a3867b7f43449c35aacac9b5add7d0eae92ea6ec
/maill-product/src/main/java/com/xy/maill/maillproduct/vo/MemberPrice.java
5747959484fa81f5a20f1cebf4eb2e541ab6bd60
[ "Apache-2.0" ]
permissive
xy200919910128/xyMaill
3ec9c5b14505874baccbf0838c359a9e06f79118
e472f6b5115b88ce08de0ecd6d1fe6eb1681d4ff
refs/heads/master
2023-07-27T10:16:57.972462
2021-09-13T01:48:25
2021-09-13T01:48:25
285,762,110
0
0
null
null
null
null
UTF-8
Java
false
false
374
java
/** * Copyright 2019 bejson.com */ package com.xy.maill.maillproduct.vo; import lombok.Data; import java.math.BigDecimal; /** * Auto-generated: 2019-11-26 10:50:34 * * @author bejson.com ([email protected]) * @website http://www.bejson.com/java2pojo/ */ @Data public class MemberPrice { private Long id; private String name; private BigDecimal price; }
b25a1d8806e4b91dc4069edee93bc35abc41fb1e
da298924ddac97a4674ff55f565fddefefcd34a6
/leetcode1406.java
0c3d5d7a6d070608da740fbba75cc35d3f3f34a0
[]
no_license
LeetCode666/LeetCode
150be00bf0a71953aa7415f66a57d58efe87265c
871228fddb1ca8c28ee1be13ba91624673f6967e
refs/heads/main
2023-03-24T01:34:44.971856
2021-03-24T19:44:23
2021-03-24T19:44:23
305,584,118
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package exam; public class leetcode1406 { public String stoneGameIII(int[] stoneValue) { int len = stoneValue.length; int[] dp = new int[len + 1]; for (int i = len - 1; i >= 0; i--) { int sum = 0; dp[i] = Integer.MIN_VALUE; for (int j = i; j < Math.min(len, i + 3); j++) { sum += stoneValue[j]; dp[i] = Math.max(dp[i], sum - dp[j + 1]); } } int diff = dp[0]; if (diff > 0) return "Alice"; if (diff < 0) return "Bob"; return "Tie"; } }
7fb74563b5180b00442c3aae71dfde8184710b71
56d6351a6e1552ad25277e594a0b9fb017009e90
/day31_hibernate_day03/src/com/weiwei/domain/Course.java
13ee9fbe8f1671d60bda3d82a54a06242d5f9b50
[]
no_license
liuweicom/javaPrac
f363250ff7dcab122aa8e810ad8c649c0429c9a3
159d720fac55e3a6d0287cea9aa0b04050b893d0
refs/heads/master
2021-09-14T23:15:30.211174
2018-05-22T02:35:56
2018-05-22T02:36:27
120,065,502
0
0
null
null
null
null
UTF-8
Java
false
false
581
java
package com.weiwei.domain; import java.util.HashSet; import java.util.Set; public class Course { private Integer id; private String name; private Set<Student> student = new HashSet<Student>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Student> getStudent() { return student; } public void setStudent(Set<Student> student) { this.student = student; } }
e57b2a687b0286f78a5ae6ca5a24eab7c136b7a6
daf4c85103ebeeadf2e5ddfa530aeae9574e4ad6
/src/test/java/org/wso2/apimgt/AppTest.java
f242261805df3f8c7bc86af5629d4234b513e8a8
[]
no_license
dineshjweerakkody/apimgt-bpmn-workflow
ea43c3ce155e40521fa2e6a5c96fe1fe6fbb14de
982c85cd3772d979b5b2180950410ea6c04add99
refs/heads/master
2021-04-29T07:19:12.643207
2017-01-04T09:36:29
2017-01-04T09:36:29
77,985,366
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package org.wso2.apimgt; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
770d5bd885e40a2c6af57e9c760ab3b248345ec6
7d85e9d72822b96447f2c6338fdb36f32be4458d
/app/src/main/java/com/slidenote/www/slidenotev2/Utils/Util.java
ce8eb843cfb529c00de369acdd53c769273da108
[]
no_license
Cieo/SlideNoteV2
2722683ee3eb917c3f850a61134aa6a4f9ad4d61
cea5c57eeb75612e8311ea30ee3fa3f55ddbb8c2
refs/heads/master
2021-01-18T20:02:22.841009
2017-04-28T06:42:42
2017-04-28T06:42:52
86,928,437
1
0
null
null
null
null
UTF-8
Java
false
false
768
java
package com.slidenote.www.slidenotev2.Utils; import com.slidenote.www.slidenotev2.Model.ImageFolder; import com.slidenote.www.slidenotev2.Model.NoteFolder; import java.util.List; /** * Created by Cieo233 on 3/28/2017. */ public class Util { public static ImageFolder findImageFolder(List<ImageFolder> folders, String name){ for (ImageFolder folder : folders){ if (folder.getName().equals(name)){ return folder; } } return null; } public static NoteFolder findNoteFolder(List<NoteFolder> folders, String name){ for (NoteFolder folder : folders){ if (folder.getName().equals(name)){ return folder; } } return null; } }
585849f1bbc7755d6d7941d254f611bdc4f7f0fa
757ad32747c221360fb857215b1f10a75a3c6a3f
/3481_Java_Cryptography/EECS3481/src/hash/Q4_1.java
9d7d4588e8c96cfe9c8dafaef72268d6a5e02527
[]
no_license
rd10018/EECS
ecfef7420d2bef7ce7592db1ec7397de8891658e
5f0fef8df2d7a8925d1cf59be4c6ca683a0c3fac
refs/heads/master
2023-01-11T00:55:49.777120
2020-09-18T16:37:23
2020-09-18T16:37:23
236,035,032
0
0
null
2023-01-07T14:05:31
2020-01-24T16:05:36
Java
UTF-8
Java
false
false
622
java
package hash; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import util.CryptoTools; public class Q4_1 { private static final byte[] PASSWORD_MD5_HASH = CryptoTools.hexToBytes("5ae9b7f211e23aac3df5f2b8f3b8eada"); public static void main(String[] args) throws NoSuchAlgorithmException { final MessageDigest digester = MessageDigest.getInstance("MD5"); // Using https://crackstation.net/, can crack D1Q5.PASSWORD_MD5_HASH to "crypto". System.out.println(Arrays.equals(digester.digest("crypto".getBytes()), Q4_1.PASSWORD_MD5_HASH) + "\n"); } }
1c974a5262c69d516ad313e716e3ed810e423af9
a2da50c214b2f32b9acd24909a84c43dc8b5c121
/src/test/java/pom/LoginPom.java
f842236e329851816220b558ab10242c9f6cb8c2
[]
no_license
DaminiK21/PM_portal
001bc5bfdade851c491fba8ac10e4e813343e9e7
d3be10991777ce2fca82e89c3058d595f0cd3c24
refs/heads/master
2023-03-21T20:13:36.807960
2021-03-18T09:02:21
2021-03-18T09:02:21
349,004,203
0
0
null
null
null
null
UTF-8
Java
false
false
1,862
java
package pom; import java.util.List; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class LoginPom { WebDriver driver; public LoginPom(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } @FindBy(xpath = "//input[@formcontrolname='email']") WebElement username; @FindBy(xpath = "//input[@formcontrolname='password']") WebElement password; @FindBy(xpath = "//button[@class='btn btn-primary']") WebElement signIn; @FindBy(xpath="//datatable-body[@class='datatable-body']//datatable-row-wrapper[1]") WebElement clickongrp; @FindBy(xpath="//div[@class='datatable-row-left datatable-row-group ng-star-inserted']") List<WebElement> allGroups; @FindBy(id="sign-out") WebElement SignOutlink; @FindBy(xpath="//span[@class='user-details']") WebElement profileHover; public void displayAllGroups() { int count= allGroups.size(); for(int i=1;i<=count-1;i++) { String Groupname=allGroups.get(i).getText(); System.out.println(Groupname); } } public void clickOnFirstGroup() throws InterruptedException { /*WebDriverWait wt= new WebDriverWait(driver,15); wt.until(ExpectedConditions.visibilityOf(clickongrp)); System.out.println(clickongrp.getText());*/ clickongrp.click(); } public void creddetail(String user, String pass) throws InterruptedException { username.sendKeys(user); password.sendKeys(pass); signIn.click(); } public void signOut() { Actions act= new Actions(driver); act.moveToElement(profileHover).build().perform(); SignOutlink.click(); } }
1d264c936f13408e55c4ea951f1145ac35c65af7
160eb2299546cbc95ba4e1b966d2e15b315da14c
/src/Forms/FormCadastrarFiscal.java
1eab35456e3caf1afebf13b103e728046cc0af97
[]
no_license
HexaDC/TrDoc
330447f0ddeb42817d9fa46d49b78553ac9ee821
f7b994f56eb90d2590204823216b50dd5c8144ee
refs/heads/master
2016-09-06T02:18:59.839630
2013-06-21T20:59:59
2013-06-21T20:59:59
10,852,366
0
1
null
null
null
null
UTF-8
Java
false
false
9,604
java
/* Created on 18/01/2011, 09:30:26 */ package Forms; import Classes.Cadastra.ClassCadastrarFiscal; import com.nilo.plaf.nimrod.NimRODLookAndFeel; import com.nilo.plaf.nimrod.NimRODTheme; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class FormCadastrarFiscal extends javax.swing.JFrame { ClassCadastrarFiscal cad = new ClassCadastrarFiscal(); private int largura = 431; private int altura = 241; public FormCadastrarFiscal() { initComponents(); /////////////////////// Formato - Localização - Ícone /////////////////// try { URL url_th = this.getClass().getResource("/Util/trdoc.theme"); NimRODTheme nt = new NimRODTheme(url_th); NimRODLookAndFeel nf = new NimRODLookAndFeel(); nf.setCurrentTheme(nt); UIManager.setLookAndFeel(nf); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { e.printStackTrace(); } // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the new location of the window this.setSize(largura, altura); int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; // Move the window this.setLocation(x, y); this.setBounds(x, y, w, h); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); URL url = this.getClass().getResource("/Icons/vistoria.png"); Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(imagemTitulo); //////////////////////////////////////////////////////////////////////////// } FormCadastrarFiscal(FormRelatorioComunique aThis, boolean b) { initComponents(); /////////////////////// Formato - Localização - Ícone /////////////////// try { URL url_th = this.getClass().getResource("/Util/trdoc.theme"); NimRODTheme nt = new NimRODTheme(url_th); NimRODLookAndFeel nf = new NimRODLookAndFeel(); nf.setCurrentTheme(nt); UIManager.setLookAndFeel(nf); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { e.printStackTrace(); } // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the new location of the window this.setSize(largura, altura); int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; // Move the window this.setLocation(x, y); this.setBounds(x, y, w, h); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); URL url = this.getClass().getResource("/Icons/vistoria.png"); Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(imagemTitulo); //////////////////////////////////////////////////////////////////////////// } FormCadastrarFiscal(FormRelatorioHabite aThis, boolean b) { initComponents(); /////////////////////// Formato - Localização - Ícone /////////////////// try { URL url_th = this.getClass().getResource("/Util/trdoc.theme"); NimRODTheme nt = new NimRODTheme(url_th); NimRODLookAndFeel nf = new NimRODLookAndFeel(); nf.setCurrentTheme(nt); UIManager.setLookAndFeel(nf); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { e.printStackTrace(); } // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the new location of the window this.setSize(largura, altura); int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; // Move the window this.setLocation(x, y); this.setBounds(x, y, w, h); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); URL url = this.getClass().getResource("/Icons/vistoria.png"); Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(imagemTitulo); //////////////////////////////////////////////////////////////////////////// } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); txtNome = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtCargo = new javax.swing.JTextField(); jSeparator2 = new javax.swing.JSeparator(); btnConcluir = new javax.swing.JButton(); btnVoltar = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); txtFormacao = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("TRDoc - Tramitação de Documentos"); setResizable(false); setUndecorated(true); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setText("Cadastrar Fiscal"); getContentPane().add(jLabel1); jLabel1.setBounds(10, 10, 94, 15); getContentPane().add(jSeparator1); jSeparator1.setBounds(10, 30, 410, 10); jLabel2.setFont(new java.awt.Font("SansSerif", 1, 12)); jLabel2.setText("Nome"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 30, 33, 20); getContentPane().add(txtNome); txtNome.setBounds(10, 50, 410, 30); jLabel3.setFont(new java.awt.Font("SansSerif", 1, 12)); jLabel3.setText("Cargo"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 80, 34, 20); getContentPane().add(txtCargo); txtCargo.setBounds(10, 100, 410, 30); getContentPane().add(jSeparator2); jSeparator2.setBounds(10, 190, 410, 10); btnConcluir.setFont(new java.awt.Font("SansSerif", 1, 12)); // NOI18N btnConcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icons/concluir.png"))); // NOI18N btnConcluir.setText("Concluir"); btnConcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConcluirActionPerformed(evt); } }); getContentPane().add(btnConcluir); btnConcluir.setBounds(320, 200, 100, 30); btnVoltar.setFont(new java.awt.Font("SansSerif", 1, 12)); // NOI18N btnVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icons/voltar.png"))); // NOI18N btnVoltar.setText("Voltar"); btnVoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVoltarActionPerformed(evt); } }); getContentPane().add(btnVoltar); btnVoltar.setBounds(10, 200, 90, 30); jLabel4.setFont(new java.awt.Font("SansSerif", 1, 12)); jLabel4.setText("Formação"); getContentPane().add(jLabel4); jLabel4.setBounds(10, 130, 57, 20); getContentPane().add(txtFormacao); txtFormacao.setBounds(10, 150, 410, 30); pack(); }// </editor-fold>//GEN-END:initComponents private void btnConcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConcluirActionPerformed String nome = txtNome.getText().toUpperCase(); String cargo = txtCargo.getText().toUpperCase(); String form = txtFormacao.getText().toUpperCase(); cad.cadastrarFiscal(nome, cargo, form); JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!"); txtNome.setText(""); txtCargo.setText(""); txtFormacao.setText(""); }//GEN-LAST:event_btnConcluirActionPerformed private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed dispose(); }//GEN-LAST:event_btnVoltarActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormCadastrarFiscal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConcluir; private javax.swing.JButton btnVoltar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTextField txtCargo; private javax.swing.JTextField txtFormacao; private javax.swing.JTextField txtNome; // End of variables declaration//GEN-END:variables }
96e8892b31210a74818092df36453fd5647db1ad
7822eb2f86317aebf6e689da2a6708e9cc4ee1ea
/Rachio_apk/sources/com/google/android/gms/internal/zzcew.java
226b200880129b1564edfdbd52f9573f1ef19397
[ "BSD-2-Clause" ]
permissive
UCLA-ECE209AS-2018W/Haoming-Liang
9abffa33df9fc7be84c993873dac39159b05ef04
f567ae0adc327b669259c94cc49f9b29f50d1038
refs/heads/master
2021-04-06T20:29:41.296769
2018-03-21T05:39:43
2018-03-21T05:39:43
125,328,864
0
0
null
null
null
null
UTF-8
Java
false
false
1,082
java
package com.google.android.gms.internal; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.zza; import com.google.android.gms.common.internal.safeparcel.zzd; import java.util.Iterator; public final class zzcew extends zza implements Iterable<String> { public static final Creator<zzcew> CREATOR = new zzcey(); private final Bundle zzbpJ; zzcew(Bundle bundle) { this.zzbpJ = bundle; } final Object get(String str) { return this.zzbpJ.get(str); } public final Iterator<String> iterator() { return new zzcex(this); } public final int size() { return this.zzbpJ.size(); } public final String toString() { return this.zzbpJ.toString(); } public final void writeToParcel(Parcel parcel, int i) { int zze = zzd.zze(parcel); zzd.zza$f7bef55(parcel, 2, zzyt()); zzd.zzI(parcel, zze); } public final Bundle zzyt() { return new Bundle(this.zzbpJ); } }
91b572d7283fa949c12639d31ebf2988e319b435
71a3d16688959b3bcac453cd769e0d3f1be9c742
/src/main/java/com/lhl/personal/mongodboperation/MongoApp.java
ff517b2ab51e6f2ec71c10f1fb5ff46763125bdf
[ "MIT" ]
permissive
LiuHuilong528/lhl-springmongodb-exmaple
c42ace00b870528678e28ac7854bea5529108360
8812b8ff1b2fa146ed7454a5e76865534a010a13
refs/heads/master
2020-12-03T09:29:23.016136
2017-09-07T08:42:55
2017-09-07T08:42:55
95,624,887
0
0
null
null
null
null
UTF-8
Java
false
false
3,801
java
package com.lhl.personal.mongodboperation; import static org.springframework.data.mongodb.core.query.Criteria.where; import java.net.UnknownHostException; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationOperation; import org.springframework.data.mongodb.core.aggregation.AggregationOptions; import org.springframework.data.mongodb.core.mapreduce.MapReduceResults; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import com.mongodb.MongoClient; public class MongoApp { private static final Log log = LogFactory.getLog(MongoApp.class); public static void main(String[] args) { try { MongoClient mongo = new MongoClient("192.168.1.55", 27018); MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(mongo, "classiyfy")); Person p = new Person("Joe", 34); // insert mongoOps.insert(p); log.info("insert:" + p); // Find p = mongoOps.findById(p.getId(), Person.class); log.info("Found: " + p); // Update mongoOps.updateFirst(Query.query(where("name").is("Joe")), Update.update("age", 35), Person.class); p = mongoOps.findOne(Query.query(where("name").is("Joe")), Person.class); log.info("Updated: " + p); // Delete mongoOps.remove(p); // Check that deletion worked List<Person> people = mongoOps.findAll(Person.class); log.info("Number of people = : " + people.size()); // findAddUpdate sample mongoOps.insert(new Person("Tom", 22)); mongoOps.insert(new Person("Dicky", 22)); mongoOps.insert(new Person("Harry", 22)); mongoOps.insert(new Person("Susan", 22)); mongoOps.insert(new Person("Kobe", 32)); Query query = new Query(where("name").is("Harry")); Update update = new Update().inc("age", 2); // findAndModify 返回query查到的记录,更新前的 age-22 Person p1 = mongoOps.findAndModify(query, update, Person.class); System.out.println(p1.getAge()); // 更新后的 记录 p = mongoOps.findOne(query, Person.class); System.out.println(p.getAge()); // 筛选字段,不用返回全部的字段 - 建造者模式 query.fields().exclude("id"); // 此操作对比之前的 返回的 是更新后的记录 p1 = mongoOps.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Person.class); System.out.println(p1.getAge()); // Example Query - Repository 实现QueryByExampleExecutor 接口 Person person = new Person("Cart", 40); // 默认的匹配模式方法 Example<Person> example = Example.of(person); // 自定义匹配模式 ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreCase("name").withIncludeNullValues(); Example<Person> ex = Example.of(person, matcher); // MapReduce 操作 读取js 文件操作数据库获取结果 MapReduceResults<Person> results = mongoOps.mapReduce("jmr1", "classpath:map.js", "classpath:reduce.js", Person.class); // 聚合查询 - Aggregation Aggregation aggregation = Aggregation.newAggregation((List<? extends AggregationOperation>) new AggregationOptions(false, false, null)); // 删除表格 mongoOps.dropCollection(Person.class); } catch (UnknownHostException e) { e.printStackTrace(); } } }
7b96540d745151104cc4c8976ffb5fbf25587d68
9f7c268ddd03e2acac2d474ab14ed52a1aa917c4
/currency/Currencies.java
09572bf3a392f0021e9b4539568ee885ad29b8f2
[]
no_license
omraz/Currency
49077692b8851222bb202f4e00af4a7e307544be
33c61923bcfd5537527bf68c37f36af288743ab9
refs/heads/master
2023-02-16T16:55:53.002586
2021-01-19T15:48:18
2021-01-19T15:48:18
331,027,406
0
0
null
null
null
null
UTF-8
Java
false
false
1,944
java
/* */ package currency; import java.net.HttpURLConnection; import java.net.URL; import java.net.MalformedURLException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; //import org.json.simple.JSONObject; import org.json.simple.*; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Currencies { public static String apiKey = "c26e32e388c84aac4872"; public static void main(String args[]) { System.out.println("Currencies"); String apiURL = "https://free.currconv.com/api/v7/currencies?apiKey=" + apiKey; long startTime = System.currentTimeMillis(); try { URL url = new URL(apiURL); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Connection failed! HTTP error code: " + conn.getResponseCode()); } BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output = reader.readLine(); conn.disconnect(); long endTime = System.currentTimeMillis(); System.out.println("Request status: 200 (OK)\tResponse time: " + (endTime - startTime) + " ms"); //System.out.println(output); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(output); //System.out.println(obj); JSONArray results = (JSONObject) obj.get("results"); System.out.println(results); //for (JSONObject cur : obj) { // System.out.println(cur); //} } catch (MalformedURLException e) { e.printStackTrace(); System.out.println("MalformedURLException"); } catch (IOException e) { e.printStackTrace(); //System.out.println("IOException " + conn.getResponseCode()); } catch (ParseException e) { e.printStackTrace(); System.out.println("ParseException"); } } }
b7919f927ce97c65ed89b2d51ef8902026846009
e68e52d4d5eb691ba99ce9589871723777dedce4
/src/lec21/v7/Main.java
15b726f1488a6ef1914743235285b25810d16bfb
[]
no_license
Spring2019COMP401-001/Lec21
4649a6012d716a8bc4df9569b71547881ba9f862
757d9a0deb1835dc2709c9c31ea50b641a8be2d6
refs/heads/master
2020-05-07T01:23:39.987412
2018-11-19T15:48:34
2018-11-19T15:48:34
180,273,490
0
1
null
2019-04-09T02:59:04
2019-04-09T02:59:04
null
UTF-8
Java
false
false
1,010
java
package lec21.v7; public class Main { public static void main(String[] args) { CountingThread ct_a = new CountingThread("A", 5); CountingThread ct_b = new CountingThread("B", 7); CountingThread ct_c = new CountingThread("C", 10); ct_a.start(); ct_b.start(); ct_c.start(); try { ct_c.join(); System.out.println("Joined back with C"); ct_a.join(); System.out.println("Joined back with A"); ct_b.join(); System.out.println("Joined back with B"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Main thread done"); } } class CountingThread extends Thread { private String prefix; private int count; public CountingThread(String prefix, int count) { this.prefix = prefix; this.count = count; } public void run() { for (int i=0; i<count; i++) { System.out.println(prefix + ": " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } }
6c0e152659f174fabfb0691821283d79a8dc42f9
7e159834d965d085daac4e0b506d2e4a93d878c7
/app/controllers/Application.java
e545f9849d5c192c17d74004e69fa5a65b660cfa
[ "Apache-2.0" ]
permissive
psoulier/Hulinalu
9e78973e39150b7d0b0255017e80683d77a53991
3f756fe4802d421ec9f5750d8de05478a73f230e
refs/heads/master
2020-12-24T15:58:15.644417
2015-05-13T09:33:44
2015-05-13T09:33:44
32,572,271
0
0
null
null
null
null
UTF-8
Java
false
false
9,360
java
package controllers; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import models.Account; import models.Feature; import models.Location; import models.LocationDB; import models.Tag; import models.UpdateInterface; import play.Routes; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import views.html.CurrentLoc; import views.html.HelpIcons; import views.html.Index; import views.html.LocationPage; import views.html.NewAccount; import views.html.SearchResults; import views.html.SignIn; import java.util.List; /** * Provides controller functionality. */ public class Application extends Controller { /** * Form to handle form data from sign in page. */ public static class SignInForm { /** * Either email or mobile number for sign in. */ public String username; /** * Password that goes with username. */ public String password; /** * Validates user sign in data. * * @return Returns null if credentials ok or an error string if not. */ public String validate() { String authenticated; if (Account.authenticate(username, password) != null) { authenticated = null; } else { authenticated = "Invalid user name or password"; } return authenticated; } } /** * Contains form data for a new account. */ public static class NewAccountForm { /** * First name for account. */ public String firstName; /** * Last name for account. */ public String lastName; /** * Email address for account. */ public String email; /** * Password for account. */ public String password; /** * Confirm password. */ public String confirmPassword; /** * Performs validation of new account data. * * @return Returns null if ok, or string if an error occurred. */ public String validate() { return null; } } /** * Gets the Account object for the currently signed in user. * * @return Account object of current user or null if no user signed in. */ public static Account getCurrentAccount() { String userid = session("userid"); Account account = null; if (userid != null) { account = Account.find().byId(Long.parseLong(session("userid"))); } return account; } /** * Handles GET requests for the main/index page. * * @return Return a Result object for the rendered page. */ public static Result index() { String queryData = Form.form().bindFromRequest().get("q"); /* The index page can be accessed two ways: by going to the home page * or with additional search text tagged onto the get request (e.g.: from * a link bookmark). If the query data is an empty string, the normal * index page is shown, otherwise a search results page is rendered. */ if (queryData == null) { return ok(Index.render()); } else { List<Location> locationList; /* Get a list of locations matching the search criteria and render a * results page. */ locationList = LocationDB.searchLocations(queryData); return ok(SearchResults.render(locationList, queryData)); } } /** * Renders the account creation page. * * @return Rendered Result object. */ public static Result newAccount() { return ok(NewAccount.render(Form.form(NewAccountForm.class))); } /** * Handles POST request for a new account creation and validates form. * * @return Rendered result page. */ public static Result createAccount() { Form<NewAccountForm> newAccountForm = Form.form(NewAccountForm.class).bindFromRequest(); Account newAccount; newAccount = new Account(newAccountForm.get().firstName, newAccountForm.get().lastName, newAccountForm.get().email, "", newAccountForm.get().password); LocationDB.addAccount(newAccount); session().clear(); session("userid", Long.toString(newAccount.getId())); return redirect(routes.Application.index()); } /** * Provides user sign in. * * @return Rendered Result object. */ public static Result signIn() { return ok(SignIn.render(Form.form(SignInForm.class))); } /** * Handles user sign-out. * * @return Result object. */ public static Result signOut() { session().clear(); return redirect(routes.Application.index()); } /** * Performs user/account authentication. * * @return Result object. */ public static Result authenticate() { Form<SignInForm> signInForm = Form.form(SignInForm.class).bindFromRequest(); Result result; if (signInForm.hasErrors()) { result = badRequest(SignIn.render(signInForm)); } else { Account account; account = Account.authenticate(signInForm.get().username, signInForm.get().password); session().clear(); session("userid", Long.toString(account.getId())); result = redirect(routes.Application.index()); } return result; } /** * Renders a portion of the index page depending on where the user is located. * <p> * This is an Ajax GET request that is called once the client's location is * determined. This routine is initiated from JavaScript. When the index page * loads, there is an indicator. Once this GET request is called, that message * is replaced by whatever this method returns. * * @param lat Client's current latitude. * @param lng Client's current longitude. * @return Rendered Result object. */ public static Result currentLocation(String lat, String lng) { return ok(CurrentLoc.render(Float.valueOf(lat), Float.valueOf(lng))); } /** * Returns a specific location page for the given location name. * * @param locId Name of the location to be found. * @return Rendered Result object. */ public static Result locationPage(long locId) { return ok(LocationPage.render(Location.find().byId(locId))); } /** * Handles POST request for location page updates. * <p> * This receives data from a client to store updates for a specific feature * in DB and returns current information for the feature. * * @return Rendered Result object. */ public static Result update() { JsonNode json = request().body().asJson(); // Decode the Json POST request data containing the update information. // This should never be null. if (json == null) { return badRequest("Expecting Json data"); } else { Account account = getCurrentAccount(); /* The unique ID of each location is encoded into the location page HTML. * The Json data includes this so this code can find the correct location * object. */ String uwId = json.findPath("uw_id").textValue(); // This had better be valid all the time. if (uwId == null) { return badRequest("Missing parameter in update POST request."); } else { ObjectNode result = Json.newObject(); UpdateInterface update; int userScore; String[] typeId; /* Decode the ID field. Both the location ID and the feature name are * included in this data. The IDs are of the form: <location-id>_<feature-name> */ typeId = uwId.split("-"); if (typeId[0].equals("tag")) { update = Tag.find().byId(Long.parseLong(typeId[1])); } else if (typeId[0].equals("feature")) { update = Feature.find().byId(Long.parseLong(typeId[1])); } else { throw new RuntimeException("Unknown type tag."); } userScore = Integer.parseInt(json.findPath("userScore").textValue()); // User may not have set a value, only update if provided. if (userScore != 0 && account != null) { update.update(account, userScore); } update.fetchUpdate(result); // Return the current feature data to the client. /* result.put("score", Integer.toString(update.getValue())); result.put("userScore", Integer.toString(update.getUserValue())); result.put("award", Integer.toString(0)); result.put("accuracy", Integer.toString(update.getAccuracy())); result.put("scoreLabel", update.getValueText()); result.put("scoreList", update.getValueList()); */ return ok(result); } } } /** * Renders a help page for the various iconns seen on the website. * * @return Rendered result object. */ public static Result helpIcons() { return ok(HelpIcons.render()); } /** * Allows JavaScript to access routes. * <p> * This is necessary to allow JavaScript issue GET/POST requests to the * correct route. * * @return Result object. */ public static Result javascriptRoutes() { response().setContentType("text/javascript"); return ok( // Every route accessible to JavaScript needs to be added here. Routes.javascriptRouter("jsRoutes", controllers.routes.javascript.Application.currentLocation(), controllers.routes.javascript.Application.update())); } }
c050ae10089523cc0f512925142ad80cff712fe5
c7be2cdb3209ddfc93ac86cccb30c9b768862468
/src/main/java/com/example/ecommerce/entity/Authority.java
e4a0fee19e571fcaa132f292d38a5727d3a6d2fd
[]
no_license
MhmodElsadany/shoping-store
3fb3d5103d1080804e7ce487c1dffea4e6238cd6
dff4399a0bcd2c43654f280db873eed994da3f62
refs/heads/master
2021-05-22T00:36:59.367365
2020-04-04T02:37:17
2020-04-04T02:37:17
252,887,601
0
0
null
null
null
null
UTF-8
Java
false
false
517
java
package com.example.ecommerce.entity; import java.io.Serializable; import org.springframework.security.core.GrantedAuthority; public class Authority implements GrantedAuthority , Serializable{ private static final long serialVersionUID=123123L; private final String authority; public Authority(String authority) { super(); this.authority = authority; } @Override public String getAuthority() { // TODO Auto-generated method stub return authority; } }
8d3b7338a5e001bbbb25545c143cbaa893d78034
7c238b610c65fd5825dfa63a2fba663ce51e9842
/app/build/generated/source/buildConfig/debug/com/helwigdev/solarwindshelpdesk/BuildConfig.java
2a665903149a5f2b1194eaf93083753b9090c7e7
[]
no_license
Fibonacci-/SolarwindsAPITestApp
c45351c73a3c63d85e9d5cdbffafb3b3890c88d3
7e0368c24694f5ae293504b5286ed808d24787e9
refs/heads/master
2016-09-06T20:00:40.975236
2015-07-06T19:25:57
2015-07-06T19:25:57
38,641,030
2
0
null
null
null
null
UTF-8
Java
false
false
468
java
/** * Automatically generated file. DO NOT MODIFY */ package com.helwigdev.solarwindshelpdesk; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.helwigdev.solarwindshelpdesk"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = ""; }
aa690682c09780642c329202818b3b6ee2361c20
531a070afb140c0fb98926f2a0f2dc88ed3ae7b7
/src/com/igomall/util/HttpUtils.java
49c2f752f055bb009ca0bbb5a8e7ec66142d9238
[]
no_license
javaknow/mall
25985534dd4cfa7512c68f67a08d029461b864b9
31a327a3fad8aecd949d82c7ce8e266eaac4b900
refs/heads/master
2021-01-21T19:19:55.867750
2016-06-16T04:37:17
2016-06-16T04:37:39
65,459,518
1
2
null
2016-08-11T10:04:01
2016-08-11T10:04:01
null
UTF-8
Java
false
false
12,791
java
package com.igomall.util; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * http工具类 * @author lingxiang * */ public class HttpUtils { // 连接超时时间 private static final int CONNECTION_TIMEOUT = 3000; //读取超时时间 private static final int READ_TIMEOUT = 5000; // 参数编码 private static final String ENCODE_CHARSET = "utf-8"; /** * 发送HTTP_POST请求 * * @see 本方法默认的连接和读取超时均为30秒 * @param reqURL * 请求地址 * @param params * 发送到远程主机的正文数据[a:1,b:2] * @return String */ public static String postRequest(String reqURL, String... params) { StringBuilder resultData = new StringBuilder(); URL url = null; try { url = new URL(reqURL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection urlConn = null; InputStreamReader in = null; BufferedReader buffer = null; String inputLine = null; DataOutputStream out = null; if (url != null) { try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); urlConn.setDoInput(true);// 设置输入流采用字节流 urlConn.setDoOutput(true);// 设置输出流采用字节流 urlConn.setRequestMethod("POST"); urlConn.setUseCaches(false); // POST请求不能使用缓存 urlConn.setInstanceFollowRedirects(true); urlConn.setConnectTimeout(CONNECTION_TIMEOUT);// 设置连接超时 urlConn.setReadTimeout(READ_TIMEOUT); // 设置读取超时 // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Charset", ENCODE_CHARSET);// String param = sendPostParams(params); urlConn.setRequestProperty("Content-Length", param.getBytes().length + "");// // urlConn.setRequestProperty("Connection", "Keep-Alive"); // //设置长连接 urlConn.connect();// 连接服务器发送消息 if (!"".equals(param)) { out = new DataOutputStream(urlConn.getOutputStream()); // 将要上传的内容写入流中 out.writeBytes(param); // 刷新、关闭 out.flush(); out.close(); } in = new InputStreamReader(urlConn.getInputStream(), HttpUtils.ENCODE_CHARSET); buffer = new BufferedReader(in); if (urlConn.getResponseCode() == 200) { while ((inputLine = buffer.readLine()) != null) { resultData.append(inputLine); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (buffer != null) { buffer.close(); } if (in != null) { in.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } return resultData.toString(); } /** * 发送HTTP_GET请求 * * @see 本方法默认的连接和读取超时均为30秒 * @param httpUrl * 请求地址 * @param map * 发送到远程主机的正文数据[a:1,b:2] * @return String */ public static String getRequest(String httpUrl,String charset, String... params) { StringBuilder resultData = new StringBuilder(); URL url = null; try { String paramurl = sendGetParams(httpUrl, params); url = new URL(paramurl); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection urlConn = null; InputStreamReader in = null; BufferedReader buffer = null; String inputLine = null; if (url != null) { try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); urlConn.setRequestMethod("GET"); urlConn.setConnectTimeout(CONNECTION_TIMEOUT); in = new InputStreamReader(urlConn.getInputStream(), charset); buffer = new BufferedReader(in); if (urlConn.getResponseCode() == 200) { while ((inputLine = buffer.readLine()) != null) { resultData.append(inputLine); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (buffer != null) { buffer.close(); } if (in != null) { in.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } return resultData.toString(); } /** * Post追加参数 * * @see <code>params</code> * @param reqURL * 请求地址 * @param params * 发送到远程主机的正文数据[a:1,b:2] * @return */ private static String sendPostParams(String... params) { StringBuilder sbd = new StringBuilder(""); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { String[] temp = params[i].split(":"); sbd.append(temp[0]); sbd.append("="); sbd.append(urlEncode(temp[1])); sbd.append("&"); } sbd.setLength(sbd.length() - 1);// 删掉最后一个 } return sbd.toString(); } /** * Get追加参数 * * @see <code>params</code> * @param reqURL * 请求地址 * @param params * 发送到远程主机的正文数据[a:1,b:2] * @return */ private static String sendGetParams(String reqURL, String... params) { StringBuilder sbd = new StringBuilder(reqURL); if (params != null && params.length > 0) { if (isexist(reqURL, "?")) {// 存在? sbd.append("&"); } else { sbd.append("?"); } for (int i = 0; i < params.length; i++) { String[] temp = params[i].split(":"); sbd.append(temp[0]); sbd.append("="); sbd.append(urlEncode(temp[1])); sbd.append("&"); } sbd.setLength(sbd.length() - 1);// 删掉最后一个 } return sbd.toString(); } // 查找某个字符串是否存在 private static boolean isexist(String str, String fstr) { return str.indexOf(fstr) == -1 ? false : true; } /** * 编码 * * @param source * @return */ public static String urlEncode(String source) { String result = source; try { result = java.net.URLEncoder.encode(source, HttpUtils.ENCODE_CHARSET); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static String postRequest1(String reqURL, String params) { StringBuilder resultData = new StringBuilder(); URL url = null; try { url = new URL(reqURL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection urlConn = null; InputStreamReader in = null; BufferedReader buffer = null; String inputLine = null; DataOutputStream out = null; if (url != null) { try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); urlConn.setDoInput(true);// 设置输入流采用字节流 urlConn.setDoOutput(true);// 设置输出流采用字节流 urlConn.setRequestMethod("POST"); urlConn.setUseCaches(false); // POST请求不能使用缓存 urlConn.setInstanceFollowRedirects(true); urlConn.setConnectTimeout(CONNECTION_TIMEOUT);// 设置连接超时 urlConn.setReadTimeout(READ_TIMEOUT); // 设置读取超时 // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type", "application/json; encoding=utf-8"); //String param = sendPostParams1(params); urlConn.setRequestProperty("Content-Length", params.getBytes().length + "");// // urlConn.setRequestProperty("Connection", "Keep-Alive"); // //设置长连接 urlConn.connect();// 连接服务器发送消息 if (!"".equals(params)) { out = new DataOutputStream(urlConn.getOutputStream()); // 将要上传的内容写入流中 out.writeBytes(params); // 刷新、关闭 out.flush(); out.close(); } in = new InputStreamReader(urlConn.getInputStream(), HttpUtils.ENCODE_CHARSET); buffer = new BufferedReader(in); if (urlConn.getResponseCode() == 200) { while ((inputLine = buffer.readLine()) != null) { resultData.append(inputLine); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (buffer != null) { buffer.close(); } if (in != null) { in.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } return resultData.toString(); } public static void main(String[] args) { System.out.println(urlEncode("http://www.i-gomall.com/wechat/index/index.jhtml?method=hotProduct")); System.out.println(urlEncode("http://www.i-gomall.com/wechat/index/index.jhtml?method=newProduct")); System.out.println(urlEncode("http://www.i-gomall.com/wechat/index/index.jhtml?method=doublePoint")); System.out.println(urlEncode("http://www.i-gomall.com/wechat/index/index.jhtml?method=promotionProduct&promotionId=2")); } }
afae5e25efbfa772ef71378ee483a94512018bf8
fe26b91fb452f667fa39819eb2a0f002b270c4c5
/DeltaAbstraction/app/src/main/java/com/randstad/deltaabstraction/Switchable.java
2903f2d2c9a1e088a20412c62989e7bf3428f14f
[]
no_license
qxs820624/AndroidStudioProjects
e879d1956a0a712b747d945971cba247e3ed7d34
e205c0fe9d006863a61f71e409077500ba8489ef
refs/heads/master
2021-01-23T03:59:24.988965
2015-12-03T06:39:07
2015-12-03T06:39:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
182
java
package com.randstad.deltaabstraction; /** * Created by robertsg on 12/11/2014. */ public interface Switchable { public void turnOn(); public void turnOff(); }
1a1178977b53aa2b4d272409ed621b86db585e06
4a25a716a16b2c058e90af23ae09fb1e2adaa6d3
/pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/pendingack/impl/PendingAckHandleImpl.java
289e3646e48312b37705d4ee1ba5a920a5f358b4
[ "Zlib", "LicenseRef-scancode-protobuf", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown" ]
permissive
yujianfei1986/pulsar
3cb1f8c352d4a5ee6e4335c17337397a9be1416a
4d4855a09981204185b4b1b6891522f07f057873
refs/heads/master
2022-06-14T13:44:51.119074
2022-06-02T08:37:26
2022-06-02T08:37:26
172,813,266
0
0
Apache-2.0
2019-02-27T00:33:42
2019-02-27T00:33:41
null
UTF-8
Java
false
false
48,052
java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.transaction.pendingack.impl; import static org.apache.bookkeeper.mledger.util.PositionAckSetUtil.andAckSet; import static org.apache.bookkeeper.mledger.util.PositionAckSetUtil.compareToWithAckSet; import static org.apache.bookkeeper.mledger.util.PositionAckSetUtil.isAckSetOverlap; import static org.apache.pulsar.common.protocol.Commands.DEFAULT_CONSUMER_EPOCH; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.mledger.ManagedLedger; import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.impl.ManagedCursorImpl; import org.apache.bookkeeper.mledger.impl.PositionImpl; import org.apache.commons.collections4.map.LinkedMap; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException; import org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.persistent.PersistentSubscription; import org.apache.pulsar.broker.transaction.pendingack.PendingAckHandle; import org.apache.pulsar.broker.transaction.pendingack.PendingAckStore; import org.apache.pulsar.broker.transaction.pendingack.TransactionPendingAckStoreProvider; import org.apache.pulsar.client.api.transaction.TxnID; import org.apache.pulsar.common.api.proto.CommandAck.AckType; import org.apache.pulsar.common.policies.data.TransactionInPendingAckStats; import org.apache.pulsar.common.policies.data.TransactionPendingAckStats; import org.apache.pulsar.common.util.FutureUtil; import org.apache.pulsar.common.util.collections.BitSetRecyclable; import org.apache.pulsar.transaction.common.exception.TransactionConflictException; /** * The default implementation of {@link PendingAckHandle}. */ @Slf4j public class PendingAckHandleImpl extends PendingAckHandleState implements PendingAckHandle { /** * The map is for transaction with position witch was individual acked by this transaction. * <p> * If the position is no batch position, it will be added to the map. * <p> * If the position is batch position and it does not exits the map, will be added to the map. * If the position is batch position and it exits the map, will do operation `and` for this * two positions bit set. */ private LinkedMap<TxnID, HashMap<PositionImpl, PositionImpl>> individualAckOfTransaction; /** * The map is for individual ack of positions for transaction. * <p> * When no batch position was acked by transaction, it will be checked to see if it exists in the map. * If it exits in the map, prove than it has been acked by another transaction. Broker will throw the * TransactionConflictException {@link TransactionConflictException}. * If it does not exits int the map, the position will be added to the map. * <p> * When batch position was acked by transaction, it will be checked to see if it exists in the map. * <p> * If it exits in the map, it will checked to see if it duplicates the existing bit set point. * If it exits at the bit set point, broker will throw the * TransactionConflictException {@link TransactionConflictException}. * If it exits at the bit set point, the bit set of the acked position will do the operation `and` for the * two positions bit set. * <p> * If it does not exits the map, the position will be added to the map. */ private Map<PositionImpl, MutablePair<PositionImpl, Integer>> individualAckPositions; /** * The map is for transaction with position witch was cumulative acked by this transaction. * Only one cumulative ack position was acked by one transaction at the same time. */ private Pair<TxnID, PositionImpl> cumulativeAckOfTransaction; private final String topicName; private final String subName; private final PersistentSubscription persistentSubscription; private CompletableFuture<PendingAckStore> pendingAckStoreFuture; private final CompletableFuture<PendingAckHandle> pendingAckHandleCompletableFuture = new CompletableFuture<>(); private final TransactionPendingAckStoreProvider pendingAckStoreProvider; private final BlockingQueue<Runnable> acceptQueue = new LinkedBlockingDeque<>(); /** * The map is used to store the lowWaterMarks which key is TC ID and value is lowWaterMark of the TC. */ private final ConcurrentHashMap<Long, Long> lowWaterMarks = new ConcurrentHashMap<>(); private final Semaphore handleLowWaterMark = new Semaphore(1); @Getter private final ExecutorService internalPinnedExecutor; public PendingAckHandleImpl(PersistentSubscription persistentSubscription) { super(State.None); this.topicName = persistentSubscription.getTopicName(); this.subName = persistentSubscription.getName(); this.persistentSubscription = persistentSubscription; internalPinnedExecutor = persistentSubscription .getTopic() .getBrokerService() .getPulsar() .getTransactionExecutorProvider() .getExecutor(this); this.pendingAckStoreProvider = this.persistentSubscription.getTopic() .getBrokerService().getPulsar().getTransactionPendingAckStoreProvider(); pendingAckStoreProvider.checkInitializedBefore(persistentSubscription).thenAccept(init -> { if (init) { initPendingAckStore(); } else { completeHandleFuture(); } }); } private void initPendingAckStore() { if (changeToInitializingState()) { if (!checkIfClose()) { this.pendingAckStoreFuture = pendingAckStoreProvider.newPendingAckStore(persistentSubscription); this.pendingAckStoreFuture.thenAccept(pendingAckStore -> { pendingAckStore.replayAsync(this, (ScheduledExecutorService) internalPinnedExecutor); }).exceptionally(e -> { acceptQueue.clear(); changeToErrorState(); log.error("PendingAckHandleImpl init fail! TopicName : {}, SubName: {}", topicName, subName, e); exceptionHandleFuture(e.getCause()); return null; }); } } } private void addIndividualAcknowledgeMessageRequest(TxnID txnID, List<MutablePair<PositionImpl, Integer>> positions, CompletableFuture<Void> completableFuture) { acceptQueue.add(() -> internalIndividualAcknowledgeMessage(txnID, positions, completableFuture)); } public void internalIndividualAcknowledgeMessage(TxnID txnID, List<MutablePair<PositionImpl, Integer>> positions, CompletableFuture<Void> completableFuture) { if (txnID == null) { completableFuture.completeExceptionally(new NotAllowedException("Positions can not be null.")); return; } if (positions == null) { completableFuture.completeExceptionally(new NotAllowedException("Positions can not be null.")); return; } this.pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore.appendIndividualAck(txnID, positions).thenAccept(v -> { synchronized (org.apache.pulsar.broker.transaction.pendingack.impl.PendingAckHandleImpl.this) { for (MutablePair<PositionImpl, Integer> positionIntegerMutablePair : positions) { if (log.isDebugEnabled()) { log.debug("[{}] individualAcknowledgeMessage position: [{}], " + "txnId: [{}], subName: [{}]", topicName, positionIntegerMutablePair.left, txnID, subName); } PositionImpl position = positionIntegerMutablePair.left; // If try to ack message already acked by committed transaction or // normal acknowledge,throw exception. if (((ManagedCursorImpl) persistentSubscription.getCursor()) .isMessageDeleted(position)) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to ack message:" + position + " already acked before."; log.error(errorMsg); completableFuture .completeExceptionally(new TransactionConflictException(errorMsg)); return; } if (position.hasAckSet()) { //in order to jude the bit set is over lap, so set the covering // the batch size bit to 1,should know the two // bit set don't have the same point is 0 BitSetRecyclable bitSetRecyclable = BitSetRecyclable.valueOf(position.getAckSet()); if (positionIntegerMutablePair.right > bitSetRecyclable.size()) { bitSetRecyclable.set(positionIntegerMutablePair.right); } bitSetRecyclable.set(positionIntegerMutablePair.right, bitSetRecyclable.size()); long[] ackSetOverlap = bitSetRecyclable.toLongArray(); bitSetRecyclable.recycle(); if (isAckSetOverlap(ackSetOverlap, ((ManagedCursorImpl) persistentSubscription.getCursor()) .getBatchPositionAckSet(position))) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to ack message:" + position + " already acked before."; log.error(errorMsg); completableFuture .completeExceptionally(new TransactionConflictException(errorMsg)); return; } if (individualAckPositions != null && individualAckPositions.containsKey(position) && isAckSetOverlap(individualAckPositions .get(position).getLeft().getAckSet(), ackSetOverlap)) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to ack batch message:" + position + " in pending ack status."; log.error(errorMsg); completableFuture .completeExceptionally(new TransactionConflictException(errorMsg)); return; } } else { if (individualAckPositions != null && individualAckPositions.containsKey(position)) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to ack message:" + position + " in pending ack status."; log.error(errorMsg); completableFuture .completeExceptionally(new TransactionConflictException(errorMsg)); return; } } } handleIndividualAck(txnID, positions); completableFuture.complete(null); } }).exceptionally(e -> { synchronized (PendingAckHandleImpl.this) { // we also modify the in memory state when append fail, // because we don't know the persistent state, when were replay it, // it will produce the wrong operation. so we append fail, // we should wait tc time out or client abort this transaction. handleIndividualAck(txnID, positions); completableFuture.completeExceptionally(e.getCause()); } return null; })).exceptionally(e -> { completableFuture.completeExceptionally(e); return null; }); } @Override public CompletableFuture<Void> individualAcknowledgeMessage(TxnID txnID, List<MutablePair<PositionImpl, Integer>> positions) { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); internalPinnedExecutor.execute(() -> { if (!checkIfReady()) { switch (state) { case Initializing: addIndividualAcknowledgeMessageRequest(txnID, positions, completableFuture); return; case None: addIndividualAcknowledgeMessageRequest(txnID, positions, completableFuture); initPendingAckStore(); return; case Error: completableFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle not replay error!")); return; case Close: completableFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle have been closed!")); return; default: break; } } internalIndividualAcknowledgeMessage(txnID, positions, completableFuture); }); return completableFuture; } private void addCumulativeAcknowledgeMessageRequest(TxnID txnID, List<PositionImpl> positions, CompletableFuture<Void> completableFuture) { acceptQueue.add(() -> internalCumulativeAcknowledgeMessage(txnID, positions, completableFuture)); } public void internalCumulativeAcknowledgeMessage(TxnID txnID, List<PositionImpl> positions, CompletableFuture<Void> completableFuture) { if (txnID == null) { completableFuture.completeExceptionally(new NotAllowedException("TransactionID can not be null.")); return; } if (positions == null) { completableFuture.completeExceptionally(new NotAllowedException("Positions can not be null.")); return; } if (positions.size() != 1) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " invalid cumulative ack received with multiple message ids."; log.error(errorMsg); completableFuture.completeExceptionally(new NotAllowedException(errorMsg)); return; } PositionImpl position = positions.get(0); this.pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore.appendCumulativeAck(txnID, position).thenAccept(v -> { if (log.isDebugEnabled()) { log.debug("[{}] cumulativeAcknowledgeMessage position: [{}], " + "txnID:[{}], subName: [{}].", topicName, txnID, position, subName); } if (position.compareTo((PositionImpl) persistentSubscription.getCursor() .getMarkDeletedPosition()) <= 0) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to cumulative ack position: " + position + " within range of cursor's " + "markDeletePosition: " + persistentSubscription.getCursor().getMarkDeletedPosition(); log.error(errorMsg); completableFuture.completeExceptionally(new TransactionConflictException(errorMsg)); return; } if (cumulativeAckOfTransaction != null && (!cumulativeAckOfTransaction.getKey().equals(txnID) || compareToWithAckSet(position, cumulativeAckOfTransaction.getValue()) <= 0)) { String errorMsg = "[" + topicName + "][" + subName + "] Transaction:" + txnID + " try to cumulative batch ack position: " + position + " within range of current " + "currentPosition: " + cumulativeAckOfTransaction.getValue(); log.error(errorMsg); completableFuture.completeExceptionally(new TransactionConflictException(errorMsg)); return; } handleCumulativeAck(txnID, position); completableFuture.complete(null); }).exceptionally(e -> { //we also modify the in memory state when append fail, because we don't know the persistent // state, when wereplay it, it will produce the wrong operation. so we append fail, we should // wait tc time out or client abort this transaction. handleCumulativeAck(txnID, position); completableFuture.completeExceptionally(e.getCause()); return null; }) ).exceptionally(e -> { completableFuture.completeExceptionally(e); return null; }); } @Override public CompletableFuture<Void> cumulativeAcknowledgeMessage(TxnID txnID, List<PositionImpl> positions) { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); internalPinnedExecutor.execute(() -> { if (!checkIfReady()) { switch (state) { case Initializing: addCumulativeAcknowledgeMessageRequest(txnID, positions, completableFuture); return; case None: addCumulativeAcknowledgeMessageRequest(txnID, positions, completableFuture); initPendingAckStore(); return; case Error: completableFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle not replay error!")); return; case Close: completableFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle have been closed!")); return; default: break; } } internalCumulativeAcknowledgeMessage(txnID, positions, completableFuture); }); return completableFuture; } private void addCommitTxnRequest(TxnID txnId, Map<String, Long> properties, long lowWaterMark, CompletableFuture<Void> completableFuture) { acceptQueue.add(() -> internalCommitTxn(txnId, properties, lowWaterMark, completableFuture)); } private void internalCommitTxn(TxnID txnID, Map<String, Long> properties, long lowWaterMark, CompletableFuture<Void> commitFuture) { // It's valid to create transaction then commit without doing any operation, which will cause // pendingAckMessagesMap to be null. if (this.cumulativeAckOfTransaction != null) { if (cumulativeAckOfTransaction.getKey().equals(txnID)) { pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore .appendCommitMark(txnID, AckType.Cumulative).thenAccept(v -> { if (log.isDebugEnabled()) { log.debug("[{}] Transaction pending ack store commit txnId : [{}] " + "success! subName: [{}]", topicName, txnID, subName); } persistentSubscription.acknowledgeMessage( Collections.singletonList(cumulativeAckOfTransaction.getValue()), AckType.Cumulative, properties); cumulativeAckOfTransaction = null; commitFuture.complete(null); }).exceptionally(e -> { log.error("[{}] Transaction pending ack store commit txnId : [{}] fail!", topicName, txnID, e); commitFuture.completeExceptionally(e); return null; })).exceptionally(e -> { commitFuture.completeExceptionally(e); return null; }); } else { commitFuture.complete(null); } } else { pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore.appendCommitMark(txnID, AckType.Individual).thenAccept(v -> { synchronized (PendingAckHandleImpl.this) { if (individualAckOfTransaction != null && individualAckOfTransaction.containsKey(txnID)) { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.get(txnID); if (log.isDebugEnabled()) { log.debug("[{}] Transaction pending ack store commit txnId : " + "[{}] success! subName: [{}]", topicName, txnID, subName); } individualAckCommitCommon(txnID, pendingAckMessageForCurrentTxn, properties); commitFuture.complete(null); handleLowWaterMark(txnID, lowWaterMark); } else { commitFuture.complete(null); } } }).exceptionally(e -> { log.error("[{}] Transaction pending ack store commit txnId : [{}] fail!", topicName, txnID, e); commitFuture.completeExceptionally(e.getCause()); return null; })).exceptionally(e -> { commitFuture.completeExceptionally(e); return null; }); } } @Override public CompletableFuture<Void> commitTxn(TxnID txnID, Map<String, Long> properties, long lowWaterMark) { CompletableFuture<Void> commitFuture = new CompletableFuture<>(); internalPinnedExecutor.execute(() -> { if (!checkIfReady()) { switch (state) { case Initializing: addCommitTxnRequest(txnID, properties, lowWaterMark, commitFuture); return; case None: addCommitTxnRequest(txnID, properties, lowWaterMark, commitFuture); initPendingAckStore(); return; case Error: if (state == State.Error) { commitFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle not replay error!")); } else { commitFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle have been closed!")); } return; } } internalCommitTxn(txnID, properties, lowWaterMark, commitFuture); }); return commitFuture; } private void addAbortTxnRequest(TxnID txnId, Consumer consumer, long lowWaterMark, CompletableFuture<Void> completableFuture) { acceptQueue.add(() -> internalAbortTxn(txnId, consumer, lowWaterMark, completableFuture)); } public CompletableFuture<Void> internalAbortTxn(TxnID txnId, Consumer consumer, long lowWaterMark, CompletableFuture<Void> abortFuture) { if (this.cumulativeAckOfTransaction != null) { pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore.appendAbortMark(txnId, AckType.Cumulative).thenAccept(v -> { if (log.isDebugEnabled()) { log.debug("[{}] Transaction pending ack store abort txnId : [{}] success! subName: [{}]", topicName, txnId, subName); } if (cumulativeAckOfTransaction.getKey().equals(txnId)) { cumulativeAckOfTransaction = null; } //TODO: pendingAck handle next pr will fix persistentSubscription.redeliverUnacknowledgedMessages(consumer, DEFAULT_CONSUMER_EPOCH); abortFuture.complete(null); }).exceptionally(e -> { log.error("[{}] Transaction pending ack store abort txnId : [{}] fail!", topicName, txnId, e); abortFuture.completeExceptionally(e); return null; }) ).exceptionally(e -> { abortFuture.completeExceptionally(e); return null; }); } else if (this.individualAckOfTransaction != null) { pendingAckStoreFuture.thenAccept(pendingAckStore -> pendingAckStore.appendAbortMark(txnId, AckType.Individual).thenAccept(v -> { synchronized (PendingAckHandleImpl.this) { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.get(txnId); if (pendingAckMessageForCurrentTxn != null) { if (log.isDebugEnabled()) { log.debug("[{}] Transaction pending ack store abort txnId : [{}] success! " + "subName: [{}]", topicName, txnId, subName); } individualAckAbortCommon(txnId, pendingAckMessageForCurrentTxn); persistentSubscription.redeliverUnacknowledgedMessages(consumer, new ArrayList<>(pendingAckMessageForCurrentTxn.values())); abortFuture.complete(null); handleLowWaterMark(txnId, lowWaterMark); } else { abortFuture.complete(null); } } }).exceptionally(e -> { log.error("[{}] Transaction pending ack store abort txnId : [{}] fail!", topicName, txnId, e); abortFuture.completeExceptionally(e); return null; }) ).exceptionally(e -> { log.error("[{}] abortTxn", txnId, e); abortFuture.completeExceptionally(e); return null; }); } else { abortFuture.complete(null); } return abortFuture; } @Override public CompletableFuture<Void> abortTxn(TxnID txnId, Consumer consumer, long lowWaterMark) { CompletableFuture<Void> abortFuture = new CompletableFuture<>(); internalPinnedExecutor.execute(() -> { if (!checkIfReady()) { switch (state) { case Initializing: addAbortTxnRequest(txnId, consumer, lowWaterMark, abortFuture); return; case None: addAbortTxnRequest(txnId, consumer, lowWaterMark, abortFuture); initPendingAckStore(); return; default: if (state == State.Error) { abortFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle not replay error!")); } else { abortFuture.completeExceptionally( new ServiceUnitNotReadyException("PendingAckHandle have been closed!")); } return; } } internalAbortTxn(txnId, consumer, lowWaterMark, abortFuture); }); return abortFuture; } private void handleLowWaterMark(TxnID txnID, long lowWaterMark) { lowWaterMarks.compute(txnID.getMostSigBits(), (tcId, oldLowWaterMark) -> { if (oldLowWaterMark == null || oldLowWaterMark < lowWaterMark) { return lowWaterMark; } else { return oldLowWaterMark; } }); if (handleLowWaterMark.tryAcquire()) { if (individualAckOfTransaction != null && !individualAckOfTransaction.isEmpty()) { TxnID firstTxn = individualAckOfTransaction.firstKey(); long tCId = firstTxn.getMostSigBits(); Long lowWaterMarkOfFirstTxnId = lowWaterMarks.get(tCId); if (lowWaterMarkOfFirstTxnId != null && firstTxn.getLeastSigBits() <= lowWaterMarkOfFirstTxnId) { abortTxn(firstTxn, null, lowWaterMarkOfFirstTxnId).thenRun(() -> { log.warn("[{}] Transaction pending ack handle low water mark success! txnId : [{}], " + "lowWaterMark : [{}]", topicName, firstTxn, lowWaterMarkOfFirstTxnId); handleLowWaterMark.release(); }).exceptionally(ex -> { log.warn("[{}] Transaction pending ack handle low water mark fail! txnId : [{}], " + "lowWaterMark : [{}]", topicName, firstTxn, lowWaterMarkOfFirstTxnId); handleLowWaterMark.release(); return null; }); return; } } handleLowWaterMark.release(); } } @Override public synchronized void syncBatchPositionAckSetForTransaction(PositionImpl position) { if (individualAckPositions == null) { individualAckPositions = new ConcurrentSkipListMap<>(); } // sync don't carry the batch size // when one position is ack by transaction the batch size is for `and` operation. if (!individualAckPositions.containsKey(position)) { this.individualAckPositions.put(position, new MutablePair<>(position, 0)); } else { andAckSet(this.individualAckPositions.get(position).left, position); } } @Override public synchronized boolean checkIsCanDeleteConsumerPendingAck(PositionImpl position) { if (!individualAckPositions.containsKey(position)) { return true; } else { position = individualAckPositions.get(position).left; if (position.hasAckSet()) { BitSetRecyclable bitSetRecyclable = BitSetRecyclable.valueOf(position.getAckSet()); if (bitSetRecyclable.isEmpty()) { bitSetRecyclable.recycle(); return true; } else { bitSetRecyclable.recycle(); return false; } } else { return true; } } } protected void handleAbort(TxnID txnID, AckType ackType) { if (ackType == AckType.Cumulative) { this.cumulativeAckOfTransaction = null; } else { if (this.individualAckOfTransaction != null) { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.get(txnID); if (pendingAckMessageForCurrentTxn != null) { individualAckAbortCommon(txnID, pendingAckMessageForCurrentTxn); } } } } private void individualAckAbortCommon(TxnID txnID, HashMap<PositionImpl, PositionImpl> currentTxn) { for (Map.Entry<PositionImpl, PositionImpl> entry : currentTxn.entrySet()) { if (entry.getValue().hasAckSet() && individualAckPositions.containsKey(entry.getValue())) { BitSetRecyclable thisBitSet = BitSetRecyclable.valueOf(entry.getValue().getAckSet()); int batchSize = individualAckPositions.get(entry.getValue()).right; thisBitSet.flip(0, batchSize); BitSetRecyclable otherBitSet = BitSetRecyclable.valueOf(individualAckPositions .get(entry.getValue()).left.getAckSet()); otherBitSet.or(thisBitSet); if (otherBitSet.cardinality() == batchSize) { individualAckPositions.remove(entry.getValue()); } else { individualAckPositions.get(entry.getKey()) .left.setAckSet(otherBitSet.toLongArray()); } otherBitSet.recycle(); thisBitSet.recycle(); } else { individualAckPositions.remove(entry.getValue()); } } individualAckOfTransaction.remove(txnID); } protected void handleCommit(TxnID txnID, AckType ackType, Map<String, Long> properties) { if (ackType == AckType.Cumulative) { if (this.cumulativeAckOfTransaction != null) { persistentSubscription.acknowledgeMessage( Collections.singletonList(this.cumulativeAckOfTransaction.getValue()), AckType.Cumulative, properties); } this.cumulativeAckOfTransaction = null; } else { if (this.individualAckOfTransaction != null) { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.get(txnID); if (pendingAckMessageForCurrentTxn != null) { individualAckCommitCommon(txnID, pendingAckMessageForCurrentTxn, null); } } } } private void individualAckCommitCommon(TxnID txnID, HashMap<PositionImpl, PositionImpl> currentTxn, Map<String, Long> properties) { if (currentTxn != null) { persistentSubscription.acknowledgeMessage(new ArrayList<>(currentTxn.values()), AckType.Individual, properties); individualAckOfTransaction.remove(txnID); } } private void handleIndividualAck(TxnID txnID, List<MutablePair<PositionImpl, Integer>> positions) { for (int i = 0; i < positions.size(); i++) { if (log.isDebugEnabled()) { log.debug("[{}][{}] TxnID:[{}] Individual acks on {}", topicName, subName, txnID.toString(), positions); } if (individualAckOfTransaction == null) { individualAckOfTransaction = new LinkedMap<>(); } if (individualAckPositions == null) { individualAckPositions = new ConcurrentSkipListMap<>(); } PositionImpl position = positions.get(i).left; if (position.hasAckSet()) { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.computeIfAbsent(txnID, txn -> new HashMap<>()); if (pendingAckMessageForCurrentTxn.containsKey(position)) { andAckSet(pendingAckMessageForCurrentTxn.get(position), position); } else { pendingAckMessageForCurrentTxn.put(position, position); } if (!individualAckPositions.containsKey(position)) { this.individualAckPositions.put(position, positions.get(i)); } else { MutablePair<PositionImpl, Integer> positionPair = this.individualAckPositions.get(position); positionPair.setRight(positions.get(i).right); andAckSet(positionPair.getLeft(), position); } } else { HashMap<PositionImpl, PositionImpl> pendingAckMessageForCurrentTxn = individualAckOfTransaction.computeIfAbsent(txnID, txn -> new HashMap<>()); pendingAckMessageForCurrentTxn.put(position, position); this.individualAckPositions.putIfAbsent(position, positions.get(i)); } } } private void handleCumulativeAck(TxnID txnID, PositionImpl position) { if (this.cumulativeAckOfTransaction == null) { this.cumulativeAckOfTransaction = MutablePair.of(txnID, position); } else if (this.cumulativeAckOfTransaction.getKey().equals(txnID) && compareToWithAckSet(position, this.cumulativeAckOfTransaction.getValue()) > 0) { this.cumulativeAckOfTransaction.setValue(position); } } protected void handleCumulativeAckRecover(TxnID txnID, PositionImpl position) { if ((position.compareTo((PositionImpl) persistentSubscription.getCursor() .getMarkDeletedPosition()) > 0) && (cumulativeAckOfTransaction == null || (cumulativeAckOfTransaction.getKey().equals(txnID) && compareToWithAckSet(position, cumulativeAckOfTransaction.getValue()) > 0))) { handleCumulativeAck(txnID, position); } } protected void handleIndividualAckRecover(TxnID txnID, List<MutablePair<PositionImpl, Integer>> positions) { for (MutablePair<PositionImpl, Integer> positionIntegerMutablePair : positions) { PositionImpl position = positionIntegerMutablePair.left; // If try to ack message already acked by committed transaction or // normal acknowledge,throw exception. if (((ManagedCursorImpl) persistentSubscription.getCursor()) .isMessageDeleted(position)) { return; } if (position.hasAckSet()) { //in order to jude the bit set is over lap, so set the covering // the batch size bit to 1,should know the two // bit set don't have the same point is 0 BitSetRecyclable bitSetRecyclable = BitSetRecyclable.valueOf(position.getAckSet()); if (positionIntegerMutablePair.right > bitSetRecyclable.size()) { bitSetRecyclable.set(positionIntegerMutablePair.right); } bitSetRecyclable.set(positionIntegerMutablePair.right, bitSetRecyclable.size()); long[] ackSetOverlap = bitSetRecyclable.toLongArray(); bitSetRecyclable.recycle(); if (isAckSetOverlap(ackSetOverlap, ((ManagedCursorImpl) persistentSubscription.getCursor()) .getBatchPositionAckSet(position))) { return; } if (individualAckPositions != null && individualAckPositions.containsKey(position) && isAckSetOverlap(individualAckPositions .get(position).getLeft().getAckSet(), ackSetOverlap)) { return; } } else { if (individualAckPositions != null && individualAckPositions.containsKey(position)) { return; } } } handleIndividualAck(txnID, positions); } public String getTopicName() { return topicName; } public String getSubName() { return subName; } @Override public synchronized void clearIndividualPosition(Position position) { if (individualAckPositions == null) { return; } if (position instanceof PositionImpl) { individualAckPositions.remove(position); } individualAckPositions.forEach((persistentPosition, positionIntegerMutablePair) -> { if (persistentPosition.compareTo((PositionImpl) persistentSubscription .getCursor().getMarkDeletedPosition()) < 0) { individualAckPositions.remove(persistentPosition); } }); } @Override public CompletableFuture<PendingAckHandle> pendingAckHandleFuture() { return pendingAckHandleCompletableFuture; } @Override public TransactionPendingAckStats getStats() { TransactionPendingAckStats transactionPendingAckStats = new TransactionPendingAckStats(); transactionPendingAckStats.state = this.getState().name(); return transactionPendingAckStats; } public synchronized void completeHandleFuture() { if (!this.pendingAckHandleCompletableFuture.isDone()) { this.pendingAckHandleCompletableFuture.complete(PendingAckHandleImpl.this); } } public synchronized void exceptionHandleFuture(Throwable t) { if (!this.pendingAckHandleCompletableFuture.isDone()) { this.pendingAckHandleCompletableFuture.completeExceptionally(t); } } @Override public TransactionInPendingAckStats getTransactionInPendingAckStats(TxnID txnID) { TransactionInPendingAckStats transactionInPendingAckStats = new TransactionInPendingAckStats(); if (cumulativeAckOfTransaction != null && cumulativeAckOfTransaction.getLeft().equals(txnID)) { PositionImpl position = cumulativeAckOfTransaction.getRight(); StringBuilder stringBuilder = new StringBuilder() .append(position.getLedgerId()) .append(':') .append(position.getEntryId()); if (cumulativeAckOfTransaction.getRight().hasAckSet()) { BitSetRecyclable bitSetRecyclable = BitSetRecyclable.valueOf(cumulativeAckOfTransaction.getRight().getAckSet()); if (!bitSetRecyclable.isEmpty()) { stringBuilder.append(":").append(bitSetRecyclable.nextSetBit(0) - 1); } } transactionInPendingAckStats.cumulativeAckPosition = stringBuilder.toString(); } return transactionInPendingAckStats; } @Override public CompletableFuture<Void> close() { changeToCloseState(); synchronized (PendingAckHandleImpl.this) { if (this.pendingAckStoreFuture != null) { return this.pendingAckStoreFuture.thenAccept(PendingAckStore::closeAsync); } else { return CompletableFuture.completedFuture(null); } } } public CompletableFuture<ManagedLedger> getStoreManageLedger() { if (this.pendingAckStoreFuture != null && this.pendingAckStoreFuture.isDone()) { return this.pendingAckStoreFuture.thenCompose(pendingAckStore -> { if (pendingAckStore instanceof MLPendingAckStore) { return ((MLPendingAckStore) pendingAckStore).getManagedLedger(); } else { return FutureUtil.failedFuture( new NotAllowedException("Pending ack handle don't use managedLedger!")); } }); } else { return FutureUtil.failedFuture(new ServiceUnitNotReadyException("Pending ack have not init success!")); } } @Override public boolean checkIfPendingAckStoreInit() { return this.pendingAckStoreFuture != null && this.pendingAckStoreFuture.isDone(); } protected void handleCacheRequest() { while (true) { Runnable runnable = acceptQueue.poll(); if (runnable != null) { runnable.run(); } else { break; } } } }
9858be7ac9f205151851847664af0b3d8a6c8dbb
e4776d31e99be03c7158d01a038ccd0dc30a4b02
/bierman/impl/src/main/java/org/opendaylight/bierman/impl/BierDataAdapter.java
f73b7c374342e816c61c474e88e987fda5f9b7ed
[]
no_license
opendaylight/bier
d1cc4618bea310d6094d2aa3975e08e1f6f995af
d0983a3bda150053132d2efe1fab28125062416c
refs/heads/master
2023-06-11T01:58:04.876567
2020-07-11T03:43:32
2020-07-11T03:43:32
75,059,361
2
0
null
null
null
null
UTF-8
Java
false
false
14,108
java
/* * Copyright © 2016 ZTE,Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.bierman.impl; import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.ReadTransaction; import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.link.LinkDestBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.link.LinkSourceBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.BierTopology; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.BierTopologyBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.BierTopologyKey; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierLink; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierLinkBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierLinkKey; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierNode; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierNodeBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.network.topology.bier.topology.BierNodeKey; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.BierNodeParamsBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.BierTeNodeParamsBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.BierTerminationPoint; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.BierTerminationPointBuilder; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.BierTerminationPointKey; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.node.params.Domain; import org.opendaylight.yang.gen.v1.urn.bier.topology.rev161102.bier.te.node.params.TeDomain; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.Destination; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.Source; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Link1; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BierDataAdapter { private static final Logger LOG = LoggerFactory.getLogger(BierDataAdapter.class); private final ExecutorService executor = Executors.newFixedThreadPool(7); public BierDataAdapter() { } public BierTopology getBierTopology(DataBroker dataBroker,String topologyId) { Topology topo = getInitTopology(dataBroker,topologyId); BierTopology bierTopo = null; if (topo != null) { bierTopo = toBierTopology(topo); } return bierTopo; } private boolean isTopologyExist(DataBroker dataBroker,final InstanceIdentifier<Topology> path) { final ReadTransaction tx = dataBroker.newReadOnlyTransaction(); try { Optional<Topology> bierTopology = tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet(); LOG.debug("BGP-LS topology exist in the operational data store at {}",path); if (bierTopology.isPresent()) { return true; } } catch (ReadFailedException e) { LOG.warn("BGP-LS topology read operation failed!", e); } return false; } public Topology getInitTopology(DataBroker dataBroker,String topologyId) { BierDataProcess<Topology> processor = new BierDataProcess<Topology>(dataBroker, BierDataProcess.FLAG_READ,(new TopologyBuilder()).build()); final InstanceIdentifier<Topology> path = InstanceIdentifier.create(NetworkTopology.class) .child(Topology.class, new TopologyKey(new TopologyId(topologyId))); if (!isTopologyExist(dataBroker,path)) { return null; } processor.enqueueOperation(new BierDataOperation() { @Override public void writeOperation(ReadWriteTransaction transaction) { // Auto-generated method stub } @SuppressWarnings("unchecked") @Override public ListenableFuture<Optional<Topology>> readOperation(ReadWriteTransaction transaction) { ListenableFuture<Optional<Topology>> listenableFuture = transaction.read(LogicalDatastoreType.OPERATIONAL, path); return listenableFuture; } }); Future<ListenableFuture<Topology>> future = executor.submit(processor); try { ListenableFuture<Topology> result = future.get(); Topology topology = result.get(); if (null == topology || null == topology.getTopologyId()) { LOG.error("Get topology is faild!"); return null; } return topology; } catch (InterruptedException e) { LOG.error("Get topology is Interrupted by", e); } catch (ExecutionException e) { LOG.error("Get topology is faild cause by", e); } LOG.error("Get topology is faild!"); return null; } public BierTopology toBierTopology(Topology topo) { BierTopologyBuilder bierTopoBuilder = new BierTopologyBuilder(); TopologyBuilder topoBuilder = new TopologyBuilder(topo); bierTopoBuilder.setTopologyId(topoBuilder.getTopologyId().getValue()); BierTopologyKey bierTopoKey = new BierTopologyKey(topoBuilder.getTopologyId().getValue()); bierTopoBuilder.setKey(bierTopoKey); List<BierNode> bierNodeList = new ArrayList<BierNode>(); List<Node> nodeList = topoBuilder.getNode(); if (nodeList != null) { int nodeSize = nodeList.size(); for (int iloop = 0; iloop < nodeSize; ++iloop) { Node node = nodeList.get(iloop); BierNode bierNode = toBierNode(node); bierNodeList.add(bierNode); } } bierTopoBuilder.setBierNode(bierNodeList); List<BierLink> bierLinkList = new ArrayList<BierLink>(); List<Link> linkList = topoBuilder.getLink(); if (linkList != null) { int linkSize = linkList.size(); for (int iloop = 0; iloop < linkSize; ++iloop) { Link link = linkList.get(iloop); BierLink bierLink = toBierLink(link); bierLinkList.add(bierLink); } } bierTopoBuilder.setBierLink(bierLinkList); return bierTopoBuilder.build(); } public BierNode toBierNode(Node node) { NodeBuilder nodeBuilder = new NodeBuilder(node); BierNodeBuilder bierNodeBuilder = new BierNodeBuilder(); String nodeId = nodeBuilder.getNodeId().getValue(); String bierNodeId = toBierNodeId(nodeId); bierNodeBuilder.setNodeId(bierNodeId); BierNodeKey bierNodeKey = new BierNodeKey(bierNodeId); bierNodeBuilder.setKey(bierNodeKey); List<BierTerminationPoint> bierTpList = new ArrayList<BierTerminationPoint>(); List<TerminationPoint> tpList = nodeBuilder.getTerminationPoint(); if (tpList != null) { int tpSize = tpList.size(); for (int iloop = 0; iloop < tpSize; ++iloop) { TerminationPoint tp = tpList.get(iloop); BierTerminationPoint bierTp = toBierTp(tp); bierTpList.add(bierTp); } } bierNodeBuilder.setBierTerminationPoint(bierTpList); BierNodeParamsBuilder nodeParamsBuilder = new BierNodeParamsBuilder(); List<Domain> domainList = new ArrayList<Domain>(); nodeParamsBuilder.setDomain(domainList); bierNodeBuilder.setBierNodeParams(nodeParamsBuilder.build()); BierTeNodeParamsBuilder teNodeParamsBuilder = new BierTeNodeParamsBuilder(); List<TeDomain> teDomainList = new ArrayList<TeDomain>(); teNodeParamsBuilder.setTeDomain(teDomainList); bierNodeBuilder.setBierTeNodeParams(teNodeParamsBuilder.build()); bierNodeBuilder.setRouterId(bierNodeId); bierNodeBuilder.setName(bierNodeId); return bierNodeBuilder.build(); } public String toBierNodeId(String id) { String bierNodeId = id; int index = id.indexOf("router="); if (index != -1) { bierNodeId = id.substring(index + 7); } return bierNodeId; } public String toBierLinkId(String id) { String bierLinkId = id; String sourceNodeId = getSubStr(id,"local-router=","&"); String sourceTpId = getSubStr(id,"ipv4-iface=","&"); String destNodeId = getSubStr(id,"remote-router=","&"); String destTpId = getSubStr(id,"ipv4-neigh=",""); if (!sourceNodeId.equals("") && !sourceTpId.equals("") && !destNodeId.equals("") && !destTpId.equals("")) { bierLinkId = sourceNodeId + "," + sourceTpId + "-" + destNodeId + "," + destTpId; } return bierLinkId; } private String getSubStr(String str,String str1,String str2) { String subStr = ""; int index1 = str.indexOf(str1); int index2 = -1; if (index1 != -1) { if (str2.equals("")) { subStr = str.substring(index1 + str1.length()); } else { index2 = str.indexOf(str2,index1); if (index2 != -1) { subStr = str.substring(index1 + str1.length(),index2); } } } return subStr; } public String toBierTpId(String id) { String bierTpId = id; int index = id.indexOf("ipv4="); if (index != -1) { bierTpId = id.substring(index + 5); } return bierTpId; } public BierTerminationPoint toBierTp(TerminationPoint tp) { TerminationPointBuilder tpBuilder = new TerminationPointBuilder(tp); BierTerminationPointBuilder bierTpBuilder = new BierTerminationPointBuilder(); String tpId = toBierTpId(tpBuilder.getTpId().getValue()); bierTpBuilder.setTpId(tpId); BierTerminationPointKey bierTpKey = new BierTerminationPointKey(tpId); bierTpBuilder.setKey(bierTpKey); return bierTpBuilder.build(); } public BierLink toBierLink(Link link) { BierLinkBuilder bierLinkBuilder = new BierLinkBuilder(); String linkId = toBierLinkId(link.getLinkId().getValue()); bierLinkBuilder.setLinkId(linkId); BierLinkKey bierLinkKey = new BierLinkKey(linkId); bierLinkBuilder.setKey(bierLinkKey); Source source = link.getSource(); LinkSourceBuilder bierSource = new LinkSourceBuilder(); String sourceNodeId = source.getSourceNode().getValue(); bierSource.setSourceNode(toBierNodeId(sourceNodeId)); bierSource.setSourceTp(toBierTpId(source.getSourceTp().getValue())); bierLinkBuilder.setLinkSource(bierSource.build()); Destination dest = link.getDestination(); LinkDestBuilder bierDest = new LinkDestBuilder(); String destNodeId = dest.getDestNode().getValue(); bierDest.setDestNode(toBierNodeId(destNodeId)); bierDest.setDestTp(toBierTpId(dest.getDestTp().getValue())); bierLinkBuilder.setLinkDest(bierDest.build()); Long metric = link.getAugmentation(Link1.class).getIgpLinkAttributes().getMetric(); bierLinkBuilder.setMetric(BigInteger.valueOf(metric)); bierLinkBuilder.setDelay(BigInteger.valueOf(0)); bierLinkBuilder.setLoss(BigInteger.valueOf(0)); return bierLinkBuilder.build(); } }
5412ef096fbfbc741f8bd94d7624b85b278e04f2
6da9b40d6d5db257e2f3c22f9416fa7ca53f0c9f
/13.spring-el-three-mesh/src/com/yiidian/domain/Customer.java
a02d14fe99345ee8c605c1e4a91e55ed962e09b3
[]
no_license
okeyLiu/spring
1b82b8040f45d45dae46cd24a4cc7304517f80c6
c24c52d20f7d84927e3a858e78aec503c9efdcc8
refs/heads/master
2020-04-04T19:24:48.964829
2017-11-14T00:08:23
2017-11-14T00:08:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
461
java
package com.yiidian.domain; import java.io.Serializable; /** * * @author http://www.yiidian.com * */ public class Customer implements Serializable{ private boolean warning; public boolean isWarning() { return warning; } public void setWarning(boolean warning) { this.warning = warning; } @Override public String toString() { return "Customer [warning=" + warning + "]"; } }
699c8e2a783430332fd13c3df0d70fd05339f32e
e7532a0bec96e1f4d8356a68f456f92ed07599b4
/src/TeachingAffairSystem/src/teaching/affair/system/model/TeacherCourse.java
0b118849524463e00ae404735902f95132016460
[]
no_license
breezefaith/TeachingAffairSystem
daf3a712ed59c413603f69e655666250cccb09ee
e5c8f5dcedb5d32a14ad4da630c2f473a49b5387
refs/heads/master
2020-12-03T04:14:06.562266
2017-06-30T02:15:02
2017-06-30T02:15:02
95,836,794
0
0
null
null
null
null
UTF-8
Java
false
false
2,619
java
package teaching.affair.system.model; import java.sql.ResultSet; import java.sql.SQLException; import teaching.affair.system.util.ConnectionUtil; public class TeacherCourse { public static String getJsonString(String teacherNo) { StringBuffer info=new StringBuffer("["); String sql="select * from select_course_result_view where teacher_no='"+teacherNo+"' "; ConnectionUtil connectionUtil=new ConnectionUtil(); ResultSet resultSet=null; resultSet=connectionUtil.executeQuery(sql); try { while(resultSet.next()){ info.append("{"); info.append(formatString("studentNo",resultSet.getString("student_no"))); info.append(formatString("studentName",resultSet.getString("student_name"))); info.append(formatString("studentAcademy",resultSet.getString("student_academy"))); info.append(formatString("studentMajor",resultSet.getString("student_major"))); info.append(formatString("studentClass",resultSet.getString("student_class"))); info.append(formatString("teacherNo",resultSet.getString("teacher_no"))); info.append(formatString("teacherName",resultSet.getString("teacher_name"))); info.append(formatString("teacherAcademy",resultSet.getString("teacher_academy"))); info.append(formatString("teacherTitle",resultSet.getString("teacher_title"))); info.append(formatString("email",resultSet.getString("teacher_email"))); info.append(formatString("courseNo",resultSet.getString("course_no"))); info.append(formatString("courseName",resultSet.getString("course_name"))); info.append(formatString("courseAcademy",resultSet.getString("course_academy"))); info.append(formatString("courseCategory",resultSet.getString("course_category"))); info.append(formatString("startWeek",resultSet.getString("start_week"))); info.append(formatString("endWeek",resultSet.getString("end_week"))); info.append(formatString("semesterNo",resultSet.getString("semester_no"))); info.append(formatString("semesterName",resultSet.getString("semester_name"))); info.append(formatString("score",resultSet.getString("score"))); info.deleteCharAt(info.length()-1); info.append("},"); } info.deleteCharAt(info.length()-1); info.append("]"); return new String(info); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return "[]"; } } private static String formatString(String key,String value){ return "\""+key+"\":"+"\""+value+"\","; } public static void main(String[] args) { System.out.println(getJsonString("t2")); } }
e915b92dd085207df44fabdea9bfbffe45fc6a7c
5989e641cf6c046869b724a70e5049b3909cc001
/src/main/java/org/hzero/halm/atn/infra/repository/impl/DisposeOrderLineRepositoryImpl.java
ec7a1279a739158b4ce9ba20f915dbef294ec283
[]
no_license
chuanshang/halm_atn
a35c30f652c06e12abda9736ca88096299acc454
714ce6c2ed01584ddf924a4b0359797f43cf7de1
refs/heads/master
2020-06-11T02:32:23.445726
2019-06-26T04:08:24
2019-06-26T04:08:24
193,826,841
0
0
null
null
null
null
UTF-8
Java
false
false
2,744
java
package org.hzero.halm.atn.infra.repository.impl; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.hzero.core.base.BaseConstants; import org.hzero.halm.afm.domain.entity.TransactionTypeFields; import org.hzero.halm.afm.domain.entity.TransactionTypes; import org.hzero.halm.afm.domain.repository.TransactionTypeFieldsRepository; import org.hzero.halm.atn.infra.constant.AatnDisposeOrderConstans; import org.hzero.halm.atn.infra.mapper.DisposeOrderLineMapper; import org.hzero.mybatis.base.impl.BaseRepositoryImpl; import org.hzero.halm.atn.domain.entity.DisposeOrderLine; import org.hzero.halm.atn.domain.repository.DisposeOrderLineRepository; import org.hzero.mybatis.domian.Condition; import org.hzero.mybatis.util.Sqls; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.hzero.halm.atn.infra.constant.AatnConstans; import io.choerodon.core.exception.CommonException; /** * 资产处置单行 资源库实现 * * @author [email protected] 2019-03-25 15:48:13 */ @Component public class DisposeOrderLineRepositoryImpl extends BaseRepositoryImpl<DisposeOrderLine> implements DisposeOrderLineRepository { @Autowired private DisposeOrderLineMapper disposeOrderLineMapper; @Override @Transactional(rollbackFor = Exception.class) public void insertDisposeOrderLine(Long tenantId, Long disposeOrderHeaderId, String disposeNum, DisposeOrderLine disposeOrderLine) { disposeOrderLine.setTenantId(tenantId); disposeOrderLine.setDisposeHeaderId(disposeOrderHeaderId); disposeOrderLine.setProcessStatus(AatnDisposeOrderConstans.DisposeLineStatus.NEW); //给目标资产状态id 赋固定值,“已处置”,需要查询 Long targetAssetStatusId = disposeOrderLineMapper.getTargetAssetStatusId(tenantId); if(targetAssetStatusId != null){ disposeOrderLine.setTargetAssetStatusId(targetAssetStatusId); } Integer maxLineNum = disposeOrderLineMapper.selectMaxLineNum(disposeOrderHeaderId); disposeOrderLine.setLineNum((Integer) ObjectUtils.defaultIfNull(maxLineNum, AatnConstans.DEFAULT_LINE_NUMBER) + 1); if (StringUtils.isEmpty(disposeOrderLine.getDescription())) { disposeOrderLine.setDescription(StringUtils.EMPTY); } this.insertSelective(disposeOrderLine); } }
3faaee27ab3049b8b1379f2ed93b5e7969338b42
1b5fadeeb3718efb7b510bfdae19651017488a36
/app/src/main/java/com/jdd/sample/studyapp/broadcast/StaticReceiver.java
1269b3b73f6b3898467c76ff934476e96964c529
[]
no_license
jdd-android/StudyApp
302a6cce632446b1f8ca2a311dcb37a508af4904
7426892217b23c89669bc5a38c9784f012fded63
refs/heads/master
2021-05-11T05:26:45.836758
2018-03-13T07:23:14
2018-03-13T07:23:14
117,962,355
0
0
null
null
null
null
UTF-8
Java
false
false
672
java
package com.jdd.sample.studyapp.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.jdd.sample.studyapp.utils.LogUtils; /** * @author lc. 2018-01-18 10:47 * @since 1.0.0 */ public class StaticReceiver extends BroadcastReceiver { private static final String TAG = LogUtils.makeLogTag(StaticReceiver.class); @Override public void onReceive(Context context, Intent intent) { LogUtils.LOGI(TAG, "== onReceiver action: " + intent.getAction()); Toast.makeText(context, TAG + " " + intent.getAction(), Toast.LENGTH_SHORT).show(); } }
89df4000a0af701a734bddb94c449d36905130f8
090cb825421f85102d41414933c2d263c1035785
/src/main/java/ru/itpark/secureside/service/JwtTokenProvider.java
af4e041d173547b5413a0a775e9707fa49c5ed47
[]
no_license
AliAlievALive/spring-course-secure
b6fb0b7345440113b6ae62dd5f79d80393aabb57
a005d2ba29fecef57a430c3796b2fdb9ee8c3e37
refs/heads/master
2023-06-12T18:57:35.762122
2021-06-27T20:10:09
2021-06-27T20:10:09
377,537,583
0
0
null
null
null
null
UTF-8
Java
false
false
277
java
package ru.itpark.secureside.service; import com.nimbusds.jwt.JWTClaimsSet; import ru.itpark.secureside.dto.User; public interface JwtTokenProvider { String generateToken(User user); boolean validateToken(String token); JWTClaimsSet parseToken(String token); }
e809198493ed4da5e522036a2573cc6cdb92c62c
a66a4d91639836e97637790b28b0632ba8d0a4f9
/src/animal/vhdl/graphics/PTD.java
dc2842fde0feae8e430f2135642d0138a1d30235
[]
no_license
roessling/animal-av
7d0ba53dda899b052a6ed19992fbdfbbc62cf1c9
043110cadf91757b984747750aa61924a869819f
refs/heads/master
2021-07-13T05:31:42.223775
2020-02-26T14:47:31
2020-02-26T14:47:31
206,062,707
0
2
null
2020-10-13T15:46:14
2019-09-03T11:37:11
Java
UTF-8
Java
false
false
1,537
java
/** * */ package animal.vhdl.graphics; import java.awt.Graphics; /** * @author p_li * */ public class PTD extends PTFlipFlop { private static int dNr = 0; public static final String D_FLIPFLOP_TYPE_LABEL = "D"; public PTD() { this(DEFAULT_LOCATION.x, DEFAULT_LOCATION.y); } public PTD(int x, int y) { this(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public PTD(int x, int y, int width, int height) { super(x, y, width, height, " D", null); this.setObjectName("d" + dNr); dNr++; } public void paint(Graphics g) { super.paint(g); // input pin inputPins.get(0).setColor(elementBody.getColor()); inputPins.get(0).paint(g); // output pin outputPins.get(0).setColor(elementBody.getColor()); outputPins.get(0).paint(g); } public Object clone() { PTD ff = new PTD(); cloneCommonFeaturesInto(ff); return ff; } protected void cloneCommonFeaturesInto(PTRS ff) { super.cloneCommonFeaturesInto(ff); ff.setObjectName(getObjectName()); } /** * @return the dNr */ public static int getDNr() { return dNr; } /** * @return the tYPE_LABEL */ public String getType() { return PTD.D_FLIPFLOP_TYPE_LABEL; } /** * returns the flip flop's object name, if the name was empty, create a new * one. * * @return the flip flop's object's name */ public String getObjectName() { if (objectName == null || objectName.length() == 0) setObjectName("d" + dNr); return objectName; } }
8ee0b0a97ea0d077d287b0935ff749b24204f1bb
055779c3d5eec2947d0224f615741406b2b208fb
/src/xtc/lang/jeannie/JeannieCFactory.java
278838c7726f7b70701922f9c6bcfd51d5ce4d84
[]
no_license
copton/xtc
4925c24310bf3783d82f57ab6fa30177a4719885
77b93130afb4c5698332ca125834cc3b1ad0ec47
refs/heads/master
2016-09-06T05:31:02.812648
2010-01-16T01:58:27
2010-01-22T08:39:08
474,465
0
2
null
null
null
null
UTF-8
Java
false
false
86,405
java
// =========================================================================== // This file has been generated by // xtc Factory Factory, version 1.13.1, // (C) 2004-2007 Robert Grimm, // on Tuesday, September 25, 2007 at 8:00:25 PM. // Edit at your own risk. // =========================================================================== package xtc.lang.jeannie; import java.util.List; import xtc.tree.Node; import xtc.tree.GNode; /** * Node factory <code>xtc.lang.jeannie.JeannieCFactory</code>. * * <p />This class has been generated by * the xtc Factory Factory, version 1.13.1, * (C) 2004-2007 Robert Grimm. */ public class JeannieCFactory { /** Create a new node factory. */ public JeannieCFactory() { // Nothing to do. } /** * Create an if statement. * * @param fieldName The fieldName. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node abruptFlowCheck(Node fieldName, Node abruptFlowJump) { Node v$1 = GNode.create("PrimaryIdentifier", "env"); Node v$2 = GNode.create("IndirectionExpression", v$1); Node v$3 = GNode.create("IndirectComponentSelection", v$2, "ExceptionCheck"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("ExpressionList", v$4); Node v$6 = GNode.create("FunctionCall", v$3, v$5); Node v$7 = GNode.create("TypedefName", "jclass"); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("SimpleDeclarator", "cls"); Node v$10 = GNode.create("PrimaryIdentifier", "env"); Node v$11 = GNode.create("IndirectionExpression", v$10); Node v$12 = GNode.create("IndirectComponentSelection", v$11, "GetObjectClass"); Node v$13 = GNode.create("PrimaryIdentifier", "env"); Node v$14 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$15 = GNode.create("ExpressionList", v$13, v$14); Node v$16 = GNode.create("FunctionCall", v$12, v$15); Node v$17 = GNode.create("InitializedDeclarator", null, v$9, null, null, v$16); Node v$18 = GNode.create("InitializedDeclaratorList", v$17); Node v$19 = GNode.create("Declaration", null, v$8, v$18); Node v$20 = GNode.create("TypedefName", "jfieldID"); Node v$21 = GNode.create("DeclarationSpecifiers", v$20); Node v$22 = GNode.create("SimpleDeclarator", "fid"); Node v$23 = GNode.create("PrimaryIdentifier", "env"); Node v$24 = GNode.create("IndirectionExpression", v$23); Node v$25 = GNode.create("IndirectComponentSelection", v$24, "GetFieldID"); Node v$26 = GNode.create("PrimaryIdentifier", "env"); Node v$27 = GNode.create("PrimaryIdentifier", "cls"); Node v$28 = GNode.create("StringConstant", "\"Z\""); Node v$29 = GNode.create("ExpressionList", v$26, v$27, fieldName, v$28); Node v$30 = GNode.create("FunctionCall", v$25, v$29); Node v$31 = GNode.create("InitializedDeclarator", null, v$22, null, null, v$30); Node v$32 = GNode.create("InitializedDeclaratorList", v$31); Node v$33 = GNode.create("Declaration", null, v$21, v$32); Node v$34 = GNode.create("TypedefName", "jboolean"); Node v$35 = GNode.create("DeclarationSpecifiers", v$34); Node v$36 = GNode.create("SimpleDeclarator", "tmp"); Node v$37 = GNode.create("PrimaryIdentifier", "env"); Node v$38 = GNode.create("IndirectionExpression", v$37); Node v$39 = GNode.create("IndirectComponentSelection", v$38, "GetBooleanField"); Node v$40 = GNode.create("PrimaryIdentifier", "env"); Node v$41 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$42 = GNode.create("PrimaryIdentifier", "fid"); Node v$43 = GNode.create("ExpressionList", v$40, v$41, v$42); Node v$44 = GNode.create("FunctionCall", v$39, v$43); Node v$45 = GNode.create("InitializedDeclarator", null, v$36, null, null, v$44); Node v$46 = GNode.create("InitializedDeclaratorList", v$45); Node v$47 = GNode.create("Declaration", null, v$35, v$46); Node v$48 = GNode.create("PrimaryIdentifier", "env"); Node v$49 = GNode.create("IndirectionExpression", v$48); Node v$50 = GNode.create("IndirectComponentSelection", v$49, "DeleteLocalRef"); Node v$51 = GNode.create("PrimaryIdentifier", "env"); Node v$52 = GNode.create("PrimaryIdentifier", "cls"); Node v$53 = GNode.create("ExpressionList", v$51, v$52); Node v$54 = GNode.create("FunctionCall", v$50, v$53); Node v$55 = GNode.create("ExpressionStatement", v$54); Node v$56 = GNode.create("PrimaryIdentifier", "tmp"); Node v$57 = GNode.create("ExpressionStatement", v$56); Node v$58 = GNode.create("CompoundStatement", v$19, v$33, v$47, v$55, v$57, null); Node v$59 = GNode.create("StatementAsExpression", v$58); Node v$60 = GNode.create("LogicalOrExpression", v$6, v$59); Node v$61 = GNode.create("CompoundStatement", abruptFlowJump, null); Node v$62 = GNode.create("IfStatement", v$60, v$61); return v$62; } /** * Create a compound statement. * * @param releaseAbrupt The releaseAbrupt. * @param fieldName The fieldName. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node abruptFlowCheckOpenArray(String releaseAbrupt, Node fieldName, Node abruptFlowJump) { Node v$1 = GNode.create("PrimaryIdentifier", "env"); Node v$2 = GNode.create("IndirectionExpression", v$1); Node v$3 = GNode.create("IndirectComponentSelection", v$2, "ExceptionCheck"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("ExpressionList", v$4); Node v$6 = GNode.create("FunctionCall", v$3, v$5); Node v$7 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$8 = GNode.create("IndirectComponentSelection", v$7, releaseAbrupt); Node v$9 = GNode.create("IntegerConstant", "2"); Node v$10 = GNode.create("AssignmentExpression", v$8, "=", v$9); Node v$11 = GNode.create("ExpressionStatement", v$10); Node v$12 = GNode.create("IfStatement", v$6, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$14 = GNode.create("IndirectComponentSelection", v$13, releaseAbrupt); Node v$15 = GNode.create("TypedefName", "jclass"); Node v$16 = GNode.create("DeclarationSpecifiers", v$15); Node v$17 = GNode.create("SimpleDeclarator", "cls"); Node v$18 = GNode.create("PrimaryIdentifier", "env"); Node v$19 = GNode.create("IndirectionExpression", v$18); Node v$20 = GNode.create("IndirectComponentSelection", v$19, "GetObjectClass"); Node v$21 = GNode.create("PrimaryIdentifier", "env"); Node v$22 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$23 = GNode.create("ExpressionList", v$21, v$22); Node v$24 = GNode.create("FunctionCall", v$20, v$23); Node v$25 = GNode.create("InitializedDeclarator", null, v$17, null, null, v$24); Node v$26 = GNode.create("InitializedDeclaratorList", v$25); Node v$27 = GNode.create("Declaration", null, v$16, v$26); Node v$28 = GNode.create("TypedefName", "jfieldID"); Node v$29 = GNode.create("DeclarationSpecifiers", v$28); Node v$30 = GNode.create("SimpleDeclarator", "fid"); Node v$31 = GNode.create("PrimaryIdentifier", "env"); Node v$32 = GNode.create("IndirectionExpression", v$31); Node v$33 = GNode.create("IndirectComponentSelection", v$32, "GetFieldID"); Node v$34 = GNode.create("PrimaryIdentifier", "env"); Node v$35 = GNode.create("PrimaryIdentifier", "cls"); Node v$36 = GNode.create("StringConstant", "\"Z\""); Node v$37 = GNode.create("ExpressionList", v$34, v$35, fieldName, v$36); Node v$38 = GNode.create("FunctionCall", v$33, v$37); Node v$39 = GNode.create("InitializedDeclarator", null, v$30, null, null, v$38); Node v$40 = GNode.create("InitializedDeclaratorList", v$39); Node v$41 = GNode.create("Declaration", null, v$29, v$40); Node v$42 = GNode.create("TypedefName", "jboolean"); Node v$43 = GNode.create("DeclarationSpecifiers", v$42); Node v$44 = GNode.create("SimpleDeclarator", "tmp"); Node v$45 = GNode.create("PrimaryIdentifier", "env"); Node v$46 = GNode.create("IndirectionExpression", v$45); Node v$47 = GNode.create("IndirectComponentSelection", v$46, "GetBooleanField"); Node v$48 = GNode.create("PrimaryIdentifier", "env"); Node v$49 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$50 = GNode.create("PrimaryIdentifier", "fid"); Node v$51 = GNode.create("ExpressionList", v$48, v$49, v$50); Node v$52 = GNode.create("FunctionCall", v$47, v$51); Node v$53 = GNode.create("InitializedDeclarator", null, v$44, null, null, v$52); Node v$54 = GNode.create("InitializedDeclaratorList", v$53); Node v$55 = GNode.create("Declaration", null, v$43, v$54); Node v$56 = GNode.create("PrimaryIdentifier", "env"); Node v$57 = GNode.create("IndirectionExpression", v$56); Node v$58 = GNode.create("IndirectComponentSelection", v$57, "DeleteLocalRef"); Node v$59 = GNode.create("PrimaryIdentifier", "env"); Node v$60 = GNode.create("PrimaryIdentifier", "cls"); Node v$61 = GNode.create("ExpressionList", v$59, v$60); Node v$62 = GNode.create("FunctionCall", v$58, v$61); Node v$63 = GNode.create("ExpressionStatement", v$62); Node v$64 = GNode.create("PrimaryIdentifier", "tmp"); Node v$65 = GNode.create("ExpressionStatement", v$64); Node v$66 = GNode.create("CompoundStatement", v$27, v$41, v$55, v$63, v$65, null); Node v$67 = GNode.create("StatementAsExpression", v$66); Node v$68 = GNode.create("LogicalOrExpression", v$14, v$67); Node v$69 = GNode.create("CompoundStatement", abruptFlowJump, null); Node v$70 = GNode.create("IfStatement", v$68, v$69); Node v$71 = GNode.create("CompoundStatement", v$12, v$70, null); return v$71; } /** * Create a goto statement. * * @param label The label. * @return The generic node. */ public Node abruptFlowJumpOpenArray(String label) { Node v$1 = GNode.create("PrimaryIdentifier", label); Node v$2 = GNode.create("GotoStatement", null, v$1); return v$2; } /** * Create a compound statement. * * @param statements The statements. * @return The generic node. */ public Node block(List<Node> statements) { Node v$1 = GNode.create("CompoundStatement", statements.size() + 1). addAll(statements).add(null); return v$1; } /** * Create a compound statement. * * @param releaseAbrupt The releaseAbrupt. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node cancel(String releaseAbrupt, Node abruptFlowJump) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, releaseAbrupt); Node v$3 = GNode.create("IntegerConstant", "2"); Node v$4 = GNode.create("AssignmentExpression", v$2, "=", v$3); Node v$5 = GNode.create("ExpressionStatement", v$4); Node v$6 = GNode.create("CompoundStatement", v$5, abruptFlowJump, null); return v$6; } /** * Create a statement as expression. * * @param tmpDeclaration The tmpDeclaration. * @param call The call. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node checkedFunctionCallResult(Node tmpDeclaration, Node call, Node abruptFlowCheck) { Node v$1 = GNode.create("PrimaryIdentifier", "tmp"); Node v$2 = GNode.create("AssignmentExpression", v$1, "=", call); Node v$3 = GNode.create("ExpressionStatement", v$2); Node v$4 = GNode.create("PrimaryIdentifier", "tmp"); Node v$5 = GNode.create("ExpressionStatement", v$4); Node v$6 = GNode.create("CompoundStatement", tmpDeclaration, v$3, abruptFlowCheck, v$5, null); Node v$7 = GNode.create("StatementAsExpression", v$6); return v$7; } /** * Create a compound statement. * * @param call The call. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node checkedFunctionCallVoid(Node call, Node abruptFlowCheck) { Node v$1 = GNode.create("ExpressionStatement", call); Node v$2 = GNode.create("CompoundStatement", v$1, abruptFlowCheck, null); return v$2; } /** * Create a compound statement. * * @param tag The tag. * @param expression The expression. * @return The generic node. */ public Node cInJavaExpressionWithCEnv(String tag, Node expression) { Node v$1 = GNode.create("StructureTypeReference", null, tag); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("TypeQualifierList", false); Node v$4 = GNode.create("Pointer", v$3, null); Node v$5 = GNode.create("SimpleDeclarator", "pcEnv"); Node v$6 = GNode.create("PointerDeclarator", v$4, v$5); Node v$7 = GNode.create("StructureTypeReference", null, tag); Node v$8 = GNode.create("SpecifierQualifierList", v$7); Node v$9 = GNode.create("TypeQualifierList", false); Node v$10 = GNode.create("Pointer", v$9, null); Node v$11 = GNode.create("AbstractDeclarator", v$10, null); Node v$12 = GNode.create("TypeName", v$8, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "cEnv"); Node v$14 = GNode.create("CastExpression", v$12, v$13); Node v$15 = GNode.create("InitializedDeclarator", null, v$6, null, null, v$14); Node v$16 = GNode.create("InitializedDeclaratorList", v$15); Node v$17 = GNode.create("Declaration", null, v$2, v$16); Node v$18 = GNode.create("ReturnStatement", expression); Node v$19 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$20 = GNode.create("IntegerConstant", "0"); Node v$21 = GNode.create("AssignmentExpression", v$19, "=", v$20); Node v$22 = GNode.create("ExpressionStatement", v$21); Node v$23 = GNode.create("CompoundStatement", v$17, v$18, v$22, null); return v$23; } /** * Create a compound statement. * * @param tag The tag. * @param expression The expression. * @return The generic node. */ public Node cInJavaExpressionWithoutCEnv(String tag, Node expression) { Node v$1 = GNode.create("StructureTypeReference", null, tag); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cEnv"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, null); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("StructureTypeReference", null, tag); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("TypeQualifierList", false); Node v$10 = GNode.create("Pointer", v$9, null); Node v$11 = GNode.create("SimpleDeclarator", "pcEnv"); Node v$12 = GNode.create("PointerDeclarator", v$10, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "cEnv"); Node v$14 = GNode.create("AddressExpression", v$13); Node v$15 = GNode.create("InitializedDeclarator", null, v$12, null, null, v$14); Node v$16 = GNode.create("InitializedDeclaratorList", v$15); Node v$17 = GNode.create("Declaration", null, v$8, v$16); Node v$18 = GNode.create("ReturnStatement", expression); Node v$19 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$20 = GNode.create("IntegerConstant", "0"); Node v$21 = GNode.create("AssignmentExpression", v$19, "=", v$20); Node v$22 = GNode.create("ExpressionStatement", v$21); Node v$23 = GNode.create("CompoundStatement", v$6, v$17, v$18, v$22, null); return v$23; } /** * Create a compound statement. * * @param tag The tag. * @param statement The statement. * @return The generic node. */ public Node cInJavaStatementWithCEnv(String tag, Node statement) { Node v$1 = GNode.create("StructureTypeReference", null, tag); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("TypeQualifierList", false); Node v$4 = GNode.create("Pointer", v$3, null); Node v$5 = GNode.create("SimpleDeclarator", "pcEnv"); Node v$6 = GNode.create("PointerDeclarator", v$4, v$5); Node v$7 = GNode.create("StructureTypeReference", null, tag); Node v$8 = GNode.create("SpecifierQualifierList", v$7); Node v$9 = GNode.create("TypeQualifierList", false); Node v$10 = GNode.create("Pointer", v$9, null); Node v$11 = GNode.create("AbstractDeclarator", v$10, null); Node v$12 = GNode.create("TypeName", v$8, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "cEnv"); Node v$14 = GNode.create("CastExpression", v$12, v$13); Node v$15 = GNode.create("InitializedDeclarator", null, v$6, null, null, v$14); Node v$16 = GNode.create("InitializedDeclaratorList", v$15); Node v$17 = GNode.create("Declaration", null, v$2, v$16); Node v$18 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$19 = GNode.create("IntegerConstant", "0"); Node v$20 = GNode.create("AssignmentExpression", v$18, "=", v$19); Node v$21 = GNode.create("ExpressionStatement", v$20); Node v$22 = GNode.create("CompoundStatement", v$17, statement, v$21, null); return v$22; } /** * Create a compound statement. * * @param tag The tag. * @param statement The statement. * @return The generic node. */ public Node cInJavaStatementWithoutCEnv(String tag, Node statement) { Node v$1 = GNode.create("StructureTypeReference", null, tag); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cEnv"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, null); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("StructureTypeReference", null, tag); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("TypeQualifierList", false); Node v$10 = GNode.create("Pointer", v$9, null); Node v$11 = GNode.create("SimpleDeclarator", "pcEnv"); Node v$12 = GNode.create("PointerDeclarator", v$10, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "cEnv"); Node v$14 = GNode.create("AddressExpression", v$13); Node v$15 = GNode.create("InitializedDeclarator", null, v$12, null, null, v$14); Node v$16 = GNode.create("InitializedDeclaratorList", v$15); Node v$17 = GNode.create("Declaration", null, v$8, v$16); Node v$18 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$19 = GNode.create("IntegerConstant", "0"); Node v$20 = GNode.create("AssignmentExpression", v$18, "=", v$19); Node v$21 = GNode.create("ExpressionStatement", v$20); Node v$22 = GNode.create("CompoundStatement", v$6, v$17, statement, v$21, null); return v$22; } /** * Create a compound statement. * * @param tag The tag. * @param copyFormals The copyFormals. * @param className The className. * @param statement The statement. * @return The generic node. */ public Node closureStatement(String tag, Node copyFormals, Node className, Node statement) { Node v$1 = GNode.create("StructureTypeReference", null, tag); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cEnv"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, null); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("StructureTypeReference", null, tag); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("TypeQualifierList", false); Node v$10 = GNode.create("Pointer", v$9, null); Node v$11 = GNode.create("SimpleDeclarator", "pcEnv"); Node v$12 = GNode.create("PointerDeclarator", v$10, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "cEnv"); Node v$14 = GNode.create("AddressExpression", v$13); Node v$15 = GNode.create("InitializedDeclarator", null, v$12, null, null, v$14); Node v$16 = GNode.create("InitializedDeclaratorList", v$15); Node v$17 = GNode.create("Declaration", null, v$8, v$16); Node v$18 = GNode.create("TypedefName", "jobject"); Node v$19 = GNode.create("DeclarationSpecifiers", v$18); Node v$20 = GNode.create("SimpleDeclarator", "jEnv"); Node v$21 = GNode.create("TypedefName", "jclass"); Node v$22 = GNode.create("DeclarationSpecifiers", v$21); Node v$23 = GNode.create("SimpleDeclarator", "cls"); Node v$24 = GNode.create("PrimaryIdentifier", "env"); Node v$25 = GNode.create("IndirectionExpression", v$24); Node v$26 = GNode.create("IndirectComponentSelection", v$25, "FindClass"); Node v$27 = GNode.create("PrimaryIdentifier", "env"); Node v$28 = GNode.create("ExpressionList", v$27, className); Node v$29 = GNode.create("FunctionCall", v$26, v$28); Node v$30 = GNode.create("InitializedDeclarator", null, v$23, null, null, v$29); Node v$31 = GNode.create("InitializedDeclaratorList", v$30); Node v$32 = GNode.create("Declaration", null, v$22, v$31); Node v$33 = GNode.create("TypedefName", "jmethodID"); Node v$34 = GNode.create("DeclarationSpecifiers", v$33); Node v$35 = GNode.create("SimpleDeclarator", "mid"); Node v$36 = GNode.create("PrimaryIdentifier", "env"); Node v$37 = GNode.create("IndirectionExpression", v$36); Node v$38 = GNode.create("IndirectComponentSelection", v$37, "GetMethodID"); Node v$39 = GNode.create("PrimaryIdentifier", "env"); Node v$40 = GNode.create("PrimaryIdentifier", "cls"); Node v$41 = GNode.create("StringConstant", "\"<init>\""); Node v$42 = GNode.create("StringConstant", "\"()V\""); Node v$43 = GNode.create("ExpressionList", v$39, v$40, v$41, v$42); Node v$44 = GNode.create("FunctionCall", v$38, v$43); Node v$45 = GNode.create("InitializedDeclarator", null, v$35, null, null, v$44); Node v$46 = GNode.create("InitializedDeclaratorList", v$45); Node v$47 = GNode.create("Declaration", null, v$34, v$46); Node v$48 = GNode.create("TypedefName", "jobject"); Node v$49 = GNode.create("DeclarationSpecifiers", v$48); Node v$50 = GNode.create("SimpleDeclarator", "tmp"); Node v$51 = GNode.create("PrimaryIdentifier", "env"); Node v$52 = GNode.create("IndirectionExpression", v$51); Node v$53 = GNode.create("IndirectComponentSelection", v$52, "NewObject"); Node v$54 = GNode.create("PrimaryIdentifier", "env"); Node v$55 = GNode.create("PrimaryIdentifier", "cls"); Node v$56 = GNode.create("PrimaryIdentifier", "mid"); Node v$57 = GNode.create("ExpressionList", v$54, v$55, v$56); Node v$58 = GNode.create("FunctionCall", v$53, v$57); Node v$59 = GNode.create("InitializedDeclarator", null, v$50, null, null, v$58); Node v$60 = GNode.create("InitializedDeclaratorList", v$59); Node v$61 = GNode.create("Declaration", null, v$49, v$60); Node v$62 = GNode.create("PrimaryIdentifier", "env"); Node v$63 = GNode.create("IndirectionExpression", v$62); Node v$64 = GNode.create("IndirectComponentSelection", v$63, "DeleteLocalRef"); Node v$65 = GNode.create("PrimaryIdentifier", "env"); Node v$66 = GNode.create("PrimaryIdentifier", "cls"); Node v$67 = GNode.create("ExpressionList", v$65, v$66); Node v$68 = GNode.create("FunctionCall", v$64, v$67); Node v$69 = GNode.create("ExpressionStatement", v$68); Node v$70 = GNode.create("PrimaryIdentifier", "tmp"); Node v$71 = GNode.create("ExpressionStatement", v$70); Node v$72 = GNode.create("CompoundStatement", v$32, v$47, v$61, v$69, v$71, null); Node v$73 = GNode.create("StatementAsExpression", v$72); Node v$74 = GNode.create("InitializedDeclarator", null, v$20, null, null, v$73); Node v$75 = GNode.create("InitializedDeclaratorList", v$74); Node v$76 = GNode.create("Declaration", null, v$19, v$75); Node v$77 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$78 = GNode.create("IntegerConstant", "0"); Node v$79 = GNode.create("AssignmentExpression", v$77, "=", v$78); Node v$80 = GNode.create("ExpressionStatement", v$79); Node v$81 = GNode.create("CompoundStatement", v$6, v$17, copyFormals, v$76, statement, v$80, null); return v$81; } /** * Create a compound statement. * * @param releaseAbrupt The releaseAbrupt. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node commit(String releaseAbrupt, Node abruptFlowJump) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, releaseAbrupt); Node v$3 = GNode.create("IntegerConstant", "1"); Node v$4 = GNode.create("AssignmentExpression", v$2, "=", v$3); Node v$5 = GNode.create("ExpressionStatement", v$4); Node v$6 = GNode.create("CompoundStatement", v$5, abruptFlowJump, null); return v$6; } /** * Create a statement as expression. * * @param apiFunction The apiFunction. * @param javaArray The javaArray. * @param javaArrayStart The javaArrayStart. * @param length The length. * @param cArray The cArray. * @param cArrayStart The cArrayStart. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node copyBetweenJavaAndC(String apiFunction, Node javaArray, Node javaArrayStart, Node length, Node cArray, Node cArrayStart, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jint"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "length"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, null); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("IndirectionExpression", v$7); Node v$9 = GNode.create("IndirectComponentSelection", v$8, apiFunction); Node v$10 = GNode.create("PrimaryIdentifier", "env"); Node v$11 = GNode.create("PrimaryIdentifier", "length"); Node v$12 = GNode.create("AssignmentExpression", v$11, "=", length); Node v$13 = GNode.create("AdditiveExpression", cArray, "+", cArrayStart); Node v$14 = GNode.create("ExpressionList", v$10, javaArray, javaArrayStart, v$12, v$13); Node v$15 = GNode.create("FunctionCall", v$9, v$14); Node v$16 = GNode.create("ExpressionStatement", v$15); Node v$17 = GNode.create("PrimaryIdentifier", "length"); Node v$18 = GNode.create("ExpressionStatement", v$17); Node v$19 = GNode.create("CompoundStatement", v$6, v$16, abruptFlowCheck, v$18, null); Node v$20 = GNode.create("StatementAsExpression", v$19); return v$20; } /** * Create a statement as expression. * * @param javaArray The javaArray. * @param javaArrayStart The javaArrayStart. * @param length The length. * @param apiFunction The apiFunction. * @param cArray The cArray. * @param cArrayStart The cArrayStart. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node copyBetweenJavaAndCUTF(Node javaArray, Node javaArrayStart, Node length, String apiFunction, Node cArray, Node cArrayStart, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jstring"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "javaArray"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, javaArray); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("TypedefName", "jint"); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("SimpleDeclarator", "start"); Node v$10 = GNode.create("InitializedDeclarator", null, v$9, null, null, javaArrayStart); Node v$11 = GNode.create("SimpleDeclarator", "length"); Node v$12 = GNode.create("InitializedDeclarator", null, v$11, null, null, length); Node v$13 = GNode.create("InitializedDeclaratorList", v$10, v$12); Node v$14 = GNode.create("Declaration", null, v$8, v$13); Node v$15 = GNode.create("PrimaryIdentifier", "env"); Node v$16 = GNode.create("IndirectionExpression", v$15); Node v$17 = GNode.create("IndirectComponentSelection", v$16, apiFunction); Node v$18 = GNode.create("PrimaryIdentifier", "env"); Node v$19 = GNode.create("PrimaryIdentifier", "javaArray"); Node v$20 = GNode.create("PrimaryIdentifier", "start"); Node v$21 = GNode.create("PrimaryIdentifier", "length"); Node v$22 = GNode.create("Char", false); Node v$23 = GNode.create("SpecifierQualifierList", v$22); Node v$24 = GNode.create("TypeQualifierList", false); Node v$25 = GNode.create("Pointer", v$24, null); Node v$26 = GNode.create("AbstractDeclarator", v$25, null); Node v$27 = GNode.create("TypeName", v$23, v$26); Node v$28 = GNode.create("AdditiveExpression", cArray, "+", cArrayStart); Node v$29 = GNode.create("CastExpression", v$27, v$28); Node v$30 = GNode.create("ExpressionList", v$18, v$19, v$20, v$21, v$29); Node v$31 = GNode.create("FunctionCall", v$17, v$30); Node v$32 = GNode.create("ExpressionStatement", v$31); Node v$33 = GNode.create("PrimaryIdentifier", "_stringUTFLength"); Node v$34 = GNode.create("PrimaryIdentifier", "env"); Node v$35 = GNode.create("PrimaryIdentifier", "javaArray"); Node v$36 = GNode.create("PrimaryIdentifier", "start"); Node v$37 = GNode.create("PrimaryIdentifier", "length"); Node v$38 = GNode.create("ExpressionList", v$34, v$35, v$36, v$37); Node v$39 = GNode.create("FunctionCall", v$33, v$38); Node v$40 = GNode.create("ExpressionStatement", v$39); Node v$41 = GNode.create("CompoundStatement", v$6, v$14, v$32, abruptFlowCheck, v$40, null); Node v$42 = GNode.create("StatementAsExpression", v$41); return v$42; } /** * Create a statement as expression. * * @param javaArray The javaArray. * @param javaArrayStart The javaArrayStart. * @param length The length. * @param cArray The cArray. * @param cArrayStart The cArrayStart. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node copyFromJavaReference(Node javaArray, Node javaArrayStart, Node length, Node cArray, Node cArrayStart, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jobjectArray"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "javaArray"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, javaArray); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("TypedefName", "jint"); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("SimpleDeclarator", "start"); Node v$10 = GNode.create("InitializedDeclarator", null, v$9, null, null, javaArrayStart); Node v$11 = GNode.create("SimpleDeclarator", "length"); Node v$12 = GNode.create("InitializedDeclarator", null, v$11, null, null, length); Node v$13 = GNode.create("InitializedDeclaratorList", v$10, v$12); Node v$14 = GNode.create("Declaration", null, v$8, v$13); Node v$15 = GNode.create("TypedefName", "jobject"); Node v$16 = GNode.create("DeclarationSpecifiers", v$15); Node v$17 = GNode.create("TypeQualifierList", false); Node v$18 = GNode.create("Pointer", v$17, null); Node v$19 = GNode.create("SimpleDeclarator", "cArray"); Node v$20 = GNode.create("PointerDeclarator", v$18, v$19); Node v$21 = GNode.create("AdditiveExpression", cArray, "+", cArrayStart); Node v$22 = GNode.create("InitializedDeclarator", null, v$20, null, null, v$21); Node v$23 = GNode.create("InitializedDeclaratorList", v$22); Node v$24 = GNode.create("Declaration", null, v$16, v$23); Node v$25 = GNode.create("TypedefName", "jint"); Node v$26 = GNode.create("DeclarationSpecifiers", v$25); Node v$27 = GNode.create("SimpleDeclarator", "i"); Node v$28 = GNode.create("InitializedDeclarator", null, v$27, null, null, null); Node v$29 = GNode.create("InitializedDeclaratorList", v$28); Node v$30 = GNode.create("Declaration", null, v$26, v$29); Node v$31 = GNode.create("PrimaryIdentifier", "i"); Node v$32 = GNode.create("IntegerConstant", "0"); Node v$33 = GNode.create("AssignmentExpression", v$31, "=", v$32); Node v$34 = GNode.create("PrimaryIdentifier", "i"); Node v$35 = GNode.create("PrimaryIdentifier", "length"); Node v$36 = GNode.create("RelationalExpression", v$34, "<", v$35); Node v$37 = GNode.create("PrimaryIdentifier", "i"); Node v$38 = GNode.create("PostincrementExpression", v$37); Node v$39 = GNode.create("PrimaryIdentifier", "cArray"); Node v$40 = GNode.create("PrimaryIdentifier", "i"); Node v$41 = GNode.create("SubscriptExpression", v$39, v$40); Node v$42 = GNode.create("PrimaryIdentifier", "env"); Node v$43 = GNode.create("IndirectionExpression", v$42); Node v$44 = GNode.create("IndirectComponentSelection", v$43, "GetObjectArrayElement"); Node v$45 = GNode.create("PrimaryIdentifier", "env"); Node v$46 = GNode.create("PrimaryIdentifier", "javaArray"); Node v$47 = GNode.create("PrimaryIdentifier", "start"); Node v$48 = GNode.create("PrimaryIdentifier", "i"); Node v$49 = GNode.create("AdditiveExpression", v$47, "+", v$48); Node v$50 = GNode.create("ExpressionList", v$45, v$46, v$49); Node v$51 = GNode.create("FunctionCall", v$44, v$50); Node v$52 = GNode.create("AssignmentExpression", v$41, "=", v$51); Node v$53 = GNode.create("ExpressionStatement", v$52); Node v$54 = GNode.create("PrimaryIdentifier", "env"); Node v$55 = GNode.create("IndirectionExpression", v$54); Node v$56 = GNode.create("IndirectComponentSelection", v$55, "ExceptionCheck"); Node v$57 = GNode.create("PrimaryIdentifier", "env"); Node v$58 = GNode.create("ExpressionList", v$57); Node v$59 = GNode.create("FunctionCall", v$56, v$58); Node v$60 = GNode.create("BreakStatement", false); Node v$61 = GNode.create("IfStatement", v$59, v$60); Node v$62 = GNode.create("CompoundStatement", v$53, v$61, null); Node v$63 = GNode.create("ForStatement", v$33, v$36, v$38, v$62); Node v$64 = GNode.create("PrimaryIdentifier", "length"); Node v$65 = GNode.create("ExpressionStatement", v$64); Node v$66 = GNode.create("CompoundStatement", v$6, v$14, v$24, v$30, v$63, abruptFlowCheck, v$65, null); Node v$67 = GNode.create("StatementAsExpression", v$66); return v$67; } /** * Create a statement as expression. * * @param javaArray The javaArray. * @param javaArrayStart The javaArrayStart. * @param length The length. * @param cArray The cArray. * @param cArrayStart The cArrayStart. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node copyToJavaReference(Node javaArray, Node javaArrayStart, Node length, Node cArray, Node cArrayStart, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jobjectArray"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "javaArray"); Node v$4 = GNode.create("InitializedDeclarator", null, v$3, null, null, javaArray); Node v$5 = GNode.create("InitializedDeclaratorList", v$4); Node v$6 = GNode.create("Declaration", null, v$2, v$5); Node v$7 = GNode.create("TypedefName", "jint"); Node v$8 = GNode.create("DeclarationSpecifiers", v$7); Node v$9 = GNode.create("SimpleDeclarator", "start"); Node v$10 = GNode.create("InitializedDeclarator", null, v$9, null, null, javaArrayStart); Node v$11 = GNode.create("SimpleDeclarator", "length"); Node v$12 = GNode.create("InitializedDeclarator", null, v$11, null, null, length); Node v$13 = GNode.create("InitializedDeclaratorList", v$10, v$12); Node v$14 = GNode.create("Declaration", null, v$8, v$13); Node v$15 = GNode.create("TypedefName", "jobject"); Node v$16 = GNode.create("DeclarationSpecifiers", v$15); Node v$17 = GNode.create("TypeQualifierList", false); Node v$18 = GNode.create("Pointer", v$17, null); Node v$19 = GNode.create("SimpleDeclarator", "cArray"); Node v$20 = GNode.create("PointerDeclarator", v$18, v$19); Node v$21 = GNode.create("AdditiveExpression", cArray, "+", cArrayStart); Node v$22 = GNode.create("InitializedDeclarator", null, v$20, null, null, v$21); Node v$23 = GNode.create("InitializedDeclaratorList", v$22); Node v$24 = GNode.create("Declaration", null, v$16, v$23); Node v$25 = GNode.create("TypedefName", "jint"); Node v$26 = GNode.create("DeclarationSpecifiers", v$25); Node v$27 = GNode.create("SimpleDeclarator", "i"); Node v$28 = GNode.create("InitializedDeclarator", null, v$27, null, null, null); Node v$29 = GNode.create("InitializedDeclaratorList", v$28); Node v$30 = GNode.create("Declaration", null, v$26, v$29); Node v$31 = GNode.create("PrimaryIdentifier", "i"); Node v$32 = GNode.create("IntegerConstant", "0"); Node v$33 = GNode.create("AssignmentExpression", v$31, "=", v$32); Node v$34 = GNode.create("PrimaryIdentifier", "i"); Node v$35 = GNode.create("PrimaryIdentifier", "length"); Node v$36 = GNode.create("RelationalExpression", v$34, "<", v$35); Node v$37 = GNode.create("PrimaryIdentifier", "i"); Node v$38 = GNode.create("PostincrementExpression", v$37); Node v$39 = GNode.create("PrimaryIdentifier", "env"); Node v$40 = GNode.create("IndirectionExpression", v$39); Node v$41 = GNode.create("IndirectComponentSelection", v$40, "SetObjectArrayElement"); Node v$42 = GNode.create("PrimaryIdentifier", "env"); Node v$43 = GNode.create("PrimaryIdentifier", "javaArray"); Node v$44 = GNode.create("PrimaryIdentifier", "start"); Node v$45 = GNode.create("PrimaryIdentifier", "i"); Node v$46 = GNode.create("AdditiveExpression", v$44, "+", v$45); Node v$47 = GNode.create("PrimaryIdentifier", "cArray"); Node v$48 = GNode.create("PrimaryIdentifier", "i"); Node v$49 = GNode.create("SubscriptExpression", v$47, v$48); Node v$50 = GNode.create("ExpressionList", v$42, v$43, v$46, v$49); Node v$51 = GNode.create("FunctionCall", v$41, v$50); Node v$52 = GNode.create("ExpressionStatement", v$51); Node v$53 = GNode.create("PrimaryIdentifier", "env"); Node v$54 = GNode.create("IndirectionExpression", v$53); Node v$55 = GNode.create("IndirectComponentSelection", v$54, "ExceptionCheck"); Node v$56 = GNode.create("PrimaryIdentifier", "env"); Node v$57 = GNode.create("ExpressionList", v$56); Node v$58 = GNode.create("FunctionCall", v$55, v$57); Node v$59 = GNode.create("BreakStatement", false); Node v$60 = GNode.create("IfStatement", v$58, v$59); Node v$61 = GNode.create("CompoundStatement", v$52, v$60, null); Node v$62 = GNode.create("ForStatement", v$33, v$36, v$38, v$61); Node v$63 = GNode.create("PrimaryIdentifier", "length"); Node v$64 = GNode.create("ExpressionStatement", v$63); Node v$65 = GNode.create("CompoundStatement", v$6, v$14, v$24, v$30, v$62, abruptFlowCheck, v$64, null); Node v$66 = GNode.create("StatementAsExpression", v$65); return v$66; } /** * Create a declaration. * * @param tag The tag. * @param members The members. * @return The generic node. */ public Node declareStruct(String tag, List<Node> members) { Node v$1 = GNode.create("StructureDeclarationList", members.size() + 1). addAll(members).add(null); Node v$2 = GNode.create("StructureTypeDefinition", null, tag, v$1, null); Node v$3 = GNode.create("DeclarationSpecifiers", v$2); Node v$4 = GNode.create("Declaration", null, v$3, null); return v$4; } /** * Create an indirect component selection. * * @param name The name. * @return The generic node. */ public Node getPCEnvField(String name) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, name); return v$2; } /** * Create a statement as expression. * * @param name The name. * @param signature The signature. * @param tmpDeclaration The tmpDeclaration. * @param apiFunction The apiFunction. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node javaInCExpression32(Node name, Node signature, Node tmpDeclaration, String apiFunction, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jmethodID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "mid"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetMethodID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("ExpressionList", v$20, v$21, name, signature); Node v$23 = GNode.create("FunctionCall", v$19, v$22); Node v$24 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$23); Node v$25 = GNode.create("InitializedDeclaratorList", v$24); Node v$26 = GNode.create("Declaration", null, v$15, v$25); Node v$27 = GNode.create("PrimaryIdentifier", "tmp"); Node v$28 = GNode.create("PrimaryIdentifier", "env"); Node v$29 = GNode.create("IndirectionExpression", v$28); Node v$30 = GNode.create("IndirectComponentSelection", v$29, apiFunction); Node v$31 = GNode.create("PrimaryIdentifier", "env"); Node v$32 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$33 = GNode.create("PrimaryIdentifier", "cls"); Node v$34 = GNode.create("PrimaryIdentifier", "mid"); Node v$35 = GNode.create("TypedefName", "jint"); Node v$36 = GNode.create("SpecifierQualifierList", v$35); Node v$37 = GNode.create("TypeName", v$36, null); Node v$38 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$39 = GNode.create("CastExpression", v$37, v$38); Node v$40 = GNode.create("ExpressionList", v$31, v$32, v$33, v$34, v$39); Node v$41 = GNode.create("FunctionCall", v$30, v$40); Node v$42 = GNode.create("AssignmentExpression", v$27, "=", v$41); Node v$43 = GNode.create("ExpressionStatement", v$42); Node v$44 = GNode.create("PrimaryIdentifier", "env"); Node v$45 = GNode.create("IndirectionExpression", v$44); Node v$46 = GNode.create("IndirectComponentSelection", v$45, "DeleteLocalRef"); Node v$47 = GNode.create("PrimaryIdentifier", "env"); Node v$48 = GNode.create("PrimaryIdentifier", "cls"); Node v$49 = GNode.create("ExpressionList", v$47, v$48); Node v$50 = GNode.create("FunctionCall", v$46, v$49); Node v$51 = GNode.create("ExpressionStatement", v$50); Node v$52 = GNode.create("PrimaryIdentifier", "tmp"); Node v$53 = GNode.create("ExpressionStatement", v$52); Node v$54 = GNode.create("CompoundStatement", v$13, v$26, tmpDeclaration, v$43, v$51, abruptFlowCheck, v$53, null); Node v$55 = GNode.create("StatementAsExpression", v$54); return v$55; } /** * Create a statement as expression. * * @param name The name. * @param signature The signature. * @param tmpDeclaration The tmpDeclaration. * @param apiFunction The apiFunction. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node javaInCExpression64(Node name, Node signature, Node tmpDeclaration, String apiFunction, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jmethodID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "mid"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetMethodID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("ExpressionList", v$20, v$21, name, signature); Node v$23 = GNode.create("FunctionCall", v$19, v$22); Node v$24 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$23); Node v$25 = GNode.create("InitializedDeclaratorList", v$24); Node v$26 = GNode.create("Declaration", null, v$15, v$25); Node v$27 = GNode.create("PrimaryIdentifier", "tmp"); Node v$28 = GNode.create("PrimaryIdentifier", "env"); Node v$29 = GNode.create("IndirectionExpression", v$28); Node v$30 = GNode.create("IndirectComponentSelection", v$29, apiFunction); Node v$31 = GNode.create("PrimaryIdentifier", "env"); Node v$32 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$33 = GNode.create("PrimaryIdentifier", "cls"); Node v$34 = GNode.create("PrimaryIdentifier", "mid"); Node v$35 = GNode.create("TypedefName", "jlong"); Node v$36 = GNode.create("SpecifierQualifierList", v$35); Node v$37 = GNode.create("TypeName", v$36, null); Node v$38 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$39 = GNode.create("CastExpression", v$37, v$38); Node v$40 = GNode.create("ExpressionList", v$31, v$32, v$33, v$34, v$39); Node v$41 = GNode.create("FunctionCall", v$30, v$40); Node v$42 = GNode.create("AssignmentExpression", v$27, "=", v$41); Node v$43 = GNode.create("ExpressionStatement", v$42); Node v$44 = GNode.create("PrimaryIdentifier", "env"); Node v$45 = GNode.create("IndirectionExpression", v$44); Node v$46 = GNode.create("IndirectComponentSelection", v$45, "DeleteLocalRef"); Node v$47 = GNode.create("PrimaryIdentifier", "env"); Node v$48 = GNode.create("PrimaryIdentifier", "cls"); Node v$49 = GNode.create("ExpressionList", v$47, v$48); Node v$50 = GNode.create("FunctionCall", v$46, v$49); Node v$51 = GNode.create("ExpressionStatement", v$50); Node v$52 = GNode.create("PrimaryIdentifier", "tmp"); Node v$53 = GNode.create("ExpressionStatement", v$52); Node v$54 = GNode.create("CompoundStatement", v$13, v$26, tmpDeclaration, v$43, v$51, abruptFlowCheck, v$53, null); Node v$55 = GNode.create("StatementAsExpression", v$54); return v$55; } /** * Create a compound statement. * * @param name The name. * @param signature The signature. * @param apiFunction The apiFunction. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node javaInCStatement32(Node name, Node signature, String apiFunction, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jmethodID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "mid"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetMethodID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("ExpressionList", v$20, v$21, name, signature); Node v$23 = GNode.create("FunctionCall", v$19, v$22); Node v$24 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$23); Node v$25 = GNode.create("InitializedDeclaratorList", v$24); Node v$26 = GNode.create("Declaration", null, v$15, v$25); Node v$27 = GNode.create("PrimaryIdentifier", "env"); Node v$28 = GNode.create("IndirectionExpression", v$27); Node v$29 = GNode.create("IndirectComponentSelection", v$28, apiFunction); Node v$30 = GNode.create("PrimaryIdentifier", "env"); Node v$31 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$32 = GNode.create("PrimaryIdentifier", "cls"); Node v$33 = GNode.create("PrimaryIdentifier", "mid"); Node v$34 = GNode.create("TypedefName", "jint"); Node v$35 = GNode.create("SpecifierQualifierList", v$34); Node v$36 = GNode.create("TypeName", v$35, null); Node v$37 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$38 = GNode.create("CastExpression", v$36, v$37); Node v$39 = GNode.create("ExpressionList", v$30, v$31, v$32, v$33, v$38); Node v$40 = GNode.create("FunctionCall", v$29, v$39); Node v$41 = GNode.create("ExpressionStatement", v$40); Node v$42 = GNode.create("PrimaryIdentifier", "env"); Node v$43 = GNode.create("IndirectionExpression", v$42); Node v$44 = GNode.create("IndirectComponentSelection", v$43, "DeleteLocalRef"); Node v$45 = GNode.create("PrimaryIdentifier", "env"); Node v$46 = GNode.create("PrimaryIdentifier", "cls"); Node v$47 = GNode.create("ExpressionList", v$45, v$46); Node v$48 = GNode.create("FunctionCall", v$44, v$47); Node v$49 = GNode.create("ExpressionStatement", v$48); Node v$50 = GNode.create("CompoundStatement", v$13, v$26, v$41, v$49, abruptFlowCheck, null); return v$50; } /** * Create a compound statement. * * @param name The name. * @param signature The signature. * @param apiFunction The apiFunction. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node javaInCStatement64(Node name, Node signature, String apiFunction, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jmethodID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "mid"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetMethodID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("ExpressionList", v$20, v$21, name, signature); Node v$23 = GNode.create("FunctionCall", v$19, v$22); Node v$24 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$23); Node v$25 = GNode.create("InitializedDeclaratorList", v$24); Node v$26 = GNode.create("Declaration", null, v$15, v$25); Node v$27 = GNode.create("PrimaryIdentifier", "env"); Node v$28 = GNode.create("IndirectionExpression", v$27); Node v$29 = GNode.create("IndirectComponentSelection", v$28, apiFunction); Node v$30 = GNode.create("PrimaryIdentifier", "env"); Node v$31 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$32 = GNode.create("PrimaryIdentifier", "cls"); Node v$33 = GNode.create("PrimaryIdentifier", "mid"); Node v$34 = GNode.create("TypedefName", "jlong"); Node v$35 = GNode.create("SpecifierQualifierList", v$34); Node v$36 = GNode.create("TypeName", v$35, null); Node v$37 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$38 = GNode.create("CastExpression", v$36, v$37); Node v$39 = GNode.create("ExpressionList", v$30, v$31, v$32, v$33, v$38); Node v$40 = GNode.create("FunctionCall", v$29, v$39); Node v$41 = GNode.create("ExpressionStatement", v$40); Node v$42 = GNode.create("PrimaryIdentifier", "env"); Node v$43 = GNode.create("IndirectionExpression", v$42); Node v$44 = GNode.create("IndirectComponentSelection", v$43, "DeleteLocalRef"); Node v$45 = GNode.create("PrimaryIdentifier", "env"); Node v$46 = GNode.create("PrimaryIdentifier", "cls"); Node v$47 = GNode.create("ExpressionList", v$45, v$46); Node v$48 = GNode.create("FunctionCall", v$44, v$47); Node v$49 = GNode.create("ExpressionStatement", v$48); Node v$50 = GNode.create("CompoundStatement", v$13, v$26, v$41, v$49, abruptFlowCheck, null); return v$50; } /** * Create a statement as expression. * * @param apiFunction The apiFunction. * @param cString The cString. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node newJavaString(String apiFunction, Node cString, Node abruptFlowCheck) { Node v$1 = GNode.create("TypedefName", "jstring"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "tmp"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, apiFunction); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("ExpressionList", v$7, cString); Node v$9 = GNode.create("FunctionCall", v$6, v$8); Node v$10 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$9); Node v$11 = GNode.create("InitializedDeclaratorList", v$10); Node v$12 = GNode.create("Declaration", null, v$2, v$11); Node v$13 = GNode.create("PrimaryIdentifier", "tmp"); Node v$14 = GNode.create("ExpressionStatement", v$13); Node v$15 = GNode.create("CompoundStatement", v$12, abruptFlowCheck, v$14, null); Node v$16 = GNode.create("StatementAsExpression", v$15); return v$16; } /** * Create an expression statement. * * @param name The name. * @param value The value. * @return The generic node. */ public Node setPCEnvField(String name, Node value) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, name); Node v$3 = GNode.create("AssignmentExpression", v$2, "=", value); Node v$4 = GNode.create("ExpressionStatement", v$3); return v$4; } /** * Create a function call. * * @param javaString The javaString. * @return The generic node. */ public Node stringUTFLength1(Node javaString) { Node v$1 = GNode.create("PrimaryIdentifier", "env"); Node v$2 = GNode.create("IndirectionExpression", v$1); Node v$3 = GNode.create("IndirectComponentSelection", v$2, "GetStringUTFLength"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("ExpressionList", v$4, javaString); Node v$6 = GNode.create("FunctionCall", v$3, v$5); return v$6; } /** * Create a function call. * * @param javaString The javaString. * @param start The start. * @param length The length. * @return The generic node. */ public Node stringUTFLength3(Node javaString, Node start, Node length) { Node v$1 = GNode.create("PrimaryIdentifier", "_stringUTFLength"); Node v$2 = GNode.create("PrimaryIdentifier", "env"); Node v$3 = GNode.create("ExpressionList", v$2, javaString, start, length); Node v$4 = GNode.create("FunctionCall", v$1, v$3); return v$4; } /** * Create a compound statement. * * @param result The result. * @param signature The signature. * @param apiFunction The apiFunction. * @param value The value. * @param abrupt The abrupt. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node returnResult(Node result, Node signature, String apiFunction, Node value, Node abrupt, Node abruptFlowJump) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jfieldID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "fidResult"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetFieldID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("ExpressionList", v$20, v$21, result, signature); Node v$23 = GNode.create("FunctionCall", v$19, v$22); Node v$24 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$23); Node v$25 = GNode.create("InitializedDeclaratorList", v$24); Node v$26 = GNode.create("Declaration", null, v$15, v$25); Node v$27 = GNode.create("PrimaryIdentifier", "env"); Node v$28 = GNode.create("IndirectionExpression", v$27); Node v$29 = GNode.create("IndirectComponentSelection", v$28, apiFunction); Node v$30 = GNode.create("PrimaryIdentifier", "env"); Node v$31 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$32 = GNode.create("PrimaryIdentifier", "fidResult"); Node v$33 = GNode.create("ExpressionList", v$30, v$31, v$32, value); Node v$34 = GNode.create("FunctionCall", v$29, v$33); Node v$35 = GNode.create("ExpressionStatement", v$34); Node v$36 = GNode.create("TypedefName", "jfieldID"); Node v$37 = GNode.create("DeclarationSpecifiers", v$36); Node v$38 = GNode.create("SimpleDeclarator", "fidAbrupt"); Node v$39 = GNode.create("PrimaryIdentifier", "env"); Node v$40 = GNode.create("IndirectionExpression", v$39); Node v$41 = GNode.create("IndirectComponentSelection", v$40, "GetFieldID"); Node v$42 = GNode.create("PrimaryIdentifier", "env"); Node v$43 = GNode.create("PrimaryIdentifier", "cls"); Node v$44 = GNode.create("StringConstant", "\"Z\""); Node v$45 = GNode.create("ExpressionList", v$42, v$43, abrupt, v$44); Node v$46 = GNode.create("FunctionCall", v$41, v$45); Node v$47 = GNode.create("InitializedDeclarator", null, v$38, null, null, v$46); Node v$48 = GNode.create("InitializedDeclaratorList", v$47); Node v$49 = GNode.create("Declaration", null, v$37, v$48); Node v$50 = GNode.create("PrimaryIdentifier", "env"); Node v$51 = GNode.create("IndirectionExpression", v$50); Node v$52 = GNode.create("IndirectComponentSelection", v$51, "SetBooleanField"); Node v$53 = GNode.create("PrimaryIdentifier", "env"); Node v$54 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$55 = GNode.create("PrimaryIdentifier", "fidAbrupt"); Node v$56 = GNode.create("IntegerConstant", "1"); Node v$57 = GNode.create("ExpressionList", v$53, v$54, v$55, v$56); Node v$58 = GNode.create("FunctionCall", v$52, v$57); Node v$59 = GNode.create("ExpressionStatement", v$58); Node v$60 = GNode.create("CompoundStatement", v$13, v$26, v$35, v$49, v$59, abruptFlowJump, null); return v$60; } /** * Create a compound statement. * * @param abrupt The abrupt. * @param abruptFlowJump The abruptFlowJump. * @return The generic node. */ public Node returnVoid(Node abrupt, Node abruptFlowJump) { Node v$1 = GNode.create("TypedefName", "jclass"); Node v$2 = GNode.create("DeclarationSpecifiers", v$1); Node v$3 = GNode.create("SimpleDeclarator", "cls"); Node v$4 = GNode.create("PrimaryIdentifier", "env"); Node v$5 = GNode.create("IndirectionExpression", v$4); Node v$6 = GNode.create("IndirectComponentSelection", v$5, "GetObjectClass"); Node v$7 = GNode.create("PrimaryIdentifier", "env"); Node v$8 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$9 = GNode.create("ExpressionList", v$7, v$8); Node v$10 = GNode.create("FunctionCall", v$6, v$9); Node v$11 = GNode.create("InitializedDeclarator", null, v$3, null, null, v$10); Node v$12 = GNode.create("InitializedDeclaratorList", v$11); Node v$13 = GNode.create("Declaration", null, v$2, v$12); Node v$14 = GNode.create("TypedefName", "jfieldID"); Node v$15 = GNode.create("DeclarationSpecifiers", v$14); Node v$16 = GNode.create("SimpleDeclarator", "fidAbrupt"); Node v$17 = GNode.create("PrimaryIdentifier", "env"); Node v$18 = GNode.create("IndirectionExpression", v$17); Node v$19 = GNode.create("IndirectComponentSelection", v$18, "GetFieldID"); Node v$20 = GNode.create("PrimaryIdentifier", "env"); Node v$21 = GNode.create("PrimaryIdentifier", "cls"); Node v$22 = GNode.create("StringConstant", "\"Z\""); Node v$23 = GNode.create("ExpressionList", v$20, v$21, abrupt, v$22); Node v$24 = GNode.create("FunctionCall", v$19, v$23); Node v$25 = GNode.create("InitializedDeclarator", null, v$16, null, null, v$24); Node v$26 = GNode.create("InitializedDeclaratorList", v$25); Node v$27 = GNode.create("Declaration", null, v$15, v$26); Node v$28 = GNode.create("PrimaryIdentifier", "env"); Node v$29 = GNode.create("IndirectionExpression", v$28); Node v$30 = GNode.create("IndirectComponentSelection", v$29, "SetBooleanField"); Node v$31 = GNode.create("PrimaryIdentifier", "env"); Node v$32 = GNode.create("PrimaryIdentifier", "jEnv"); Node v$33 = GNode.create("PrimaryIdentifier", "fidAbrupt"); Node v$34 = GNode.create("IntegerConstant", "1"); Node v$35 = GNode.create("ExpressionList", v$31, v$32, v$33, v$34); Node v$36 = GNode.create("FunctionCall", v$30, v$35); Node v$37 = GNode.create("ExpressionStatement", v$36); Node v$38 = GNode.create("CompoundStatement", v$13, v$27, v$37, abruptFlowJump, null); return v$38; } /** * Create a compound statement. * * @param jaField The jaField. * @param init The init. * @param releaseAbrupt The releaseAbrupt. * @param caDecl The caDecl. * @param caField The caField. * @param getRegion The getRegion. * @param body The body. * @param label The label. * @param setRegion The setRegion. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node withPrimitiveArray(String jaField, Node init, String releaseAbrupt, Node caDecl, String caField, String getRegion, Node body, String label, String setRegion, Node abruptFlowCheck) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, jaField); Node v$3 = GNode.create("AssignmentExpression", v$2, "=", init); Node v$4 = GNode.create("ExpressionStatement", v$3); Node v$5 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$6 = GNode.create("IndirectComponentSelection", v$5, releaseAbrupt); Node v$7 = GNode.create("IntegerConstant", "0"); Node v$8 = GNode.create("AssignmentExpression", v$6, "=", v$7); Node v$9 = GNode.create("ExpressionStatement", v$8); Node v$10 = GNode.create("TypedefName", "jint"); Node v$11 = GNode.create("DeclarationSpecifiers", v$10); Node v$12 = GNode.create("SimpleDeclarator", "length"); Node v$13 = GNode.create("PrimaryIdentifier", "env"); Node v$14 = GNode.create("IndirectionExpression", v$13); Node v$15 = GNode.create("IndirectComponentSelection", v$14, "GetArrayLength"); Node v$16 = GNode.create("PrimaryIdentifier", "env"); Node v$17 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$18 = GNode.create("IndirectComponentSelection", v$17, jaField); Node v$19 = GNode.create("ExpressionList", v$16, v$18); Node v$20 = GNode.create("FunctionCall", v$15, v$19); Node v$21 = GNode.create("InitializedDeclarator", null, v$12, null, null, v$20); Node v$22 = GNode.create("InitializedDeclaratorList", v$21); Node v$23 = GNode.create("Declaration", null, v$11, v$22); Node v$24 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$25 = GNode.create("IndirectComponentSelection", v$24, caField); Node v$26 = GNode.create("PrimaryIdentifier", "ca"); Node v$27 = GNode.create("AssignmentExpression", v$25, "=", v$26); Node v$28 = GNode.create("ExpressionStatement", v$27); Node v$29 = GNode.create("PrimaryIdentifier", "env"); Node v$30 = GNode.create("IndirectionExpression", v$29); Node v$31 = GNode.create("IndirectComponentSelection", v$30, getRegion); Node v$32 = GNode.create("PrimaryIdentifier", "env"); Node v$33 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$34 = GNode.create("IndirectComponentSelection", v$33, jaField); Node v$35 = GNode.create("IntegerConstant", "0"); Node v$36 = GNode.create("PrimaryIdentifier", "length"); Node v$37 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$38 = GNode.create("IndirectComponentSelection", v$37, caField); Node v$39 = GNode.create("ExpressionList", v$32, v$34, v$35, v$36, v$38); Node v$40 = GNode.create("FunctionCall", v$31, v$39); Node v$41 = GNode.create("ExpressionStatement", v$40); Node v$42 = GNode.create("PrimaryIdentifier", label); Node v$43 = GNode.create("GotoStatement", null, v$42); Node v$44 = GNode.create("NamedLabel", label, null); Node v$45 = GNode.create("IntegerConstant", "2"); Node v$46 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$47 = GNode.create("IndirectComponentSelection", v$46, releaseAbrupt); Node v$48 = GNode.create("EqualityExpression", v$45, "!=", v$47); Node v$49 = GNode.create("PrimaryIdentifier", "env"); Node v$50 = GNode.create("IndirectionExpression", v$49); Node v$51 = GNode.create("IndirectComponentSelection", v$50, setRegion); Node v$52 = GNode.create("PrimaryIdentifier", "env"); Node v$53 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$54 = GNode.create("IndirectComponentSelection", v$53, jaField); Node v$55 = GNode.create("IntegerConstant", "0"); Node v$56 = GNode.create("PrimaryIdentifier", "length"); Node v$57 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$58 = GNode.create("IndirectComponentSelection", v$57, caField); Node v$59 = GNode.create("ExpressionList", v$52, v$54, v$55, v$56, v$58); Node v$60 = GNode.create("FunctionCall", v$51, v$59); Node v$61 = GNode.create("ExpressionStatement", v$60); Node v$62 = GNode.create("IfStatement", v$48, v$61); Node v$63 = GNode.create("LabeledStatement", v$44, v$62); Node v$64 = GNode.create("CompoundStatement", v$23, caDecl, v$28, v$41, body, v$43, v$63, null); Node v$65 = GNode.create("CompoundStatement", v$4, v$9, v$64, abruptFlowCheck, null); return v$65; } /** * Create a compound statement. * * @param jaField The jaField. * @param init The init. * @param releaseAbrupt The releaseAbrupt. * @param caField The caField. * @param body The body. * @param label The label. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node withReferenceArray(String jaField, Node init, String releaseAbrupt, String caField, Node body, String label, Node abruptFlowCheck) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, jaField); Node v$3 = GNode.create("AssignmentExpression", v$2, "=", init); Node v$4 = GNode.create("ExpressionStatement", v$3); Node v$5 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$6 = GNode.create("IndirectComponentSelection", v$5, releaseAbrupt); Node v$7 = GNode.create("IntegerConstant", "0"); Node v$8 = GNode.create("AssignmentExpression", v$6, "=", v$7); Node v$9 = GNode.create("ExpressionStatement", v$8); Node v$10 = GNode.create("TypedefName", "jsize"); Node v$11 = GNode.create("DeclarationSpecifiers", v$10); Node v$12 = GNode.create("SimpleDeclarator", "i"); Node v$13 = GNode.create("InitializedDeclarator", null, v$12, null, null, null); Node v$14 = GNode.create("InitializedDeclaratorList", v$13); Node v$15 = GNode.create("Declaration", null, v$11, v$14); Node v$16 = GNode.create("TypedefName", "jint"); Node v$17 = GNode.create("DeclarationSpecifiers", v$16); Node v$18 = GNode.create("SimpleDeclarator", "length"); Node v$19 = GNode.create("PrimaryIdentifier", "env"); Node v$20 = GNode.create("IndirectionExpression", v$19); Node v$21 = GNode.create("IndirectComponentSelection", v$20, "GetArrayLength"); Node v$22 = GNode.create("PrimaryIdentifier", "env"); Node v$23 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$24 = GNode.create("IndirectComponentSelection", v$23, jaField); Node v$25 = GNode.create("ExpressionList", v$22, v$24); Node v$26 = GNode.create("FunctionCall", v$21, v$25); Node v$27 = GNode.create("InitializedDeclarator", null, v$18, null, null, v$26); Node v$28 = GNode.create("InitializedDeclaratorList", v$27); Node v$29 = GNode.create("Declaration", null, v$17, v$28); Node v$30 = GNode.create("TypedefName", "jobject"); Node v$31 = GNode.create("DeclarationSpecifiers", v$30); Node v$32 = GNode.create("SimpleDeclarator", "ca"); Node v$33 = GNode.create("ArrayQualifierList", false); Node v$34 = GNode.create("PrimaryIdentifier", "length"); Node v$35 = GNode.create("ArrayDeclarator", v$32, v$33, v$34); Node v$36 = GNode.create("InitializedDeclarator", null, v$35, null, null, null); Node v$37 = GNode.create("InitializedDeclaratorList", v$36); Node v$38 = GNode.create("Declaration", null, v$31, v$37); Node v$39 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$40 = GNode.create("IndirectComponentSelection", v$39, caField); Node v$41 = GNode.create("PrimaryIdentifier", "ca"); Node v$42 = GNode.create("AssignmentExpression", v$40, "=", v$41); Node v$43 = GNode.create("ExpressionStatement", v$42); Node v$44 = GNode.create("PrimaryIdentifier", "i"); Node v$45 = GNode.create("IntegerConstant", "0"); Node v$46 = GNode.create("AssignmentExpression", v$44, "=", v$45); Node v$47 = GNode.create("PrimaryIdentifier", "i"); Node v$48 = GNode.create("PrimaryIdentifier", "length"); Node v$49 = GNode.create("RelationalExpression", v$47, "<", v$48); Node v$50 = GNode.create("PrimaryIdentifier", "i"); Node v$51 = GNode.create("PostincrementExpression", v$50); Node v$52 = GNode.create("PrimaryIdentifier", "ca"); Node v$53 = GNode.create("PrimaryIdentifier", "i"); Node v$54 = GNode.create("SubscriptExpression", v$52, v$53); Node v$55 = GNode.create("PrimaryIdentifier", "env"); Node v$56 = GNode.create("IndirectionExpression", v$55); Node v$57 = GNode.create("IndirectComponentSelection", v$56, "GetObjectArrayElement"); Node v$58 = GNode.create("PrimaryIdentifier", "env"); Node v$59 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$60 = GNode.create("IndirectComponentSelection", v$59, jaField); Node v$61 = GNode.create("PrimaryIdentifier", "i"); Node v$62 = GNode.create("ExpressionList", v$58, v$60, v$61); Node v$63 = GNode.create("FunctionCall", v$57, v$62); Node v$64 = GNode.create("AssignmentExpression", v$54, "=", v$63); Node v$65 = GNode.create("ExpressionStatement", v$64); Node v$66 = GNode.create("ForStatement", v$46, v$49, v$51, v$65); Node v$67 = GNode.create("PrimaryIdentifier", label); Node v$68 = GNode.create("GotoStatement", null, v$67); Node v$69 = GNode.create("NamedLabel", label, null); Node v$70 = GNode.create("IntegerConstant", "2"); Node v$71 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$72 = GNode.create("IndirectComponentSelection", v$71, releaseAbrupt); Node v$73 = GNode.create("EqualityExpression", v$70, "!=", v$72); Node v$74 = GNode.create("PrimaryIdentifier", "i"); Node v$75 = GNode.create("IntegerConstant", "0"); Node v$76 = GNode.create("AssignmentExpression", v$74, "=", v$75); Node v$77 = GNode.create("PrimaryIdentifier", "i"); Node v$78 = GNode.create("PrimaryIdentifier", "length"); Node v$79 = GNode.create("RelationalExpression", v$77, "<", v$78); Node v$80 = GNode.create("PrimaryIdentifier", "i"); Node v$81 = GNode.create("PostincrementExpression", v$80); Node v$82 = GNode.create("PrimaryIdentifier", "env"); Node v$83 = GNode.create("IndirectionExpression", v$82); Node v$84 = GNode.create("IndirectComponentSelection", v$83, "SetObjectArrayElement"); Node v$85 = GNode.create("PrimaryIdentifier", "env"); Node v$86 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$87 = GNode.create("IndirectComponentSelection", v$86, jaField); Node v$88 = GNode.create("PrimaryIdentifier", "i"); Node v$89 = GNode.create("PrimaryIdentifier", "ca"); Node v$90 = GNode.create("PrimaryIdentifier", "i"); Node v$91 = GNode.create("SubscriptExpression", v$89, v$90); Node v$92 = GNode.create("ExpressionList", v$85, v$87, v$88, v$91); Node v$93 = GNode.create("FunctionCall", v$84, v$92); Node v$94 = GNode.create("ExpressionStatement", v$93); Node v$95 = GNode.create("PrimaryIdentifier", "env"); Node v$96 = GNode.create("IndirectionExpression", v$95); Node v$97 = GNode.create("IndirectComponentSelection", v$96, "ExceptionCheck"); Node v$98 = GNode.create("PrimaryIdentifier", "env"); Node v$99 = GNode.create("ExpressionList", v$98); Node v$100 = GNode.create("FunctionCall", v$97, v$99); Node v$101 = GNode.create("BreakStatement", false); Node v$102 = GNode.create("IfStatement", v$100, v$101); Node v$103 = GNode.create("CompoundStatement", v$94, v$102, null); Node v$104 = GNode.create("ForStatement", v$76, v$79, v$81, v$103); Node v$105 = GNode.create("IfStatement", v$73, v$104); Node v$106 = GNode.create("LabeledStatement", v$69, v$105); Node v$107 = GNode.create("CompoundStatement", 9). add(v$15).add(v$29).add(v$38).add(v$43).add(v$66).add(body).add(v$68). add(v$106).add(null); Node v$108 = GNode.create("CompoundStatement", v$4, v$9, v$107, abruptFlowCheck, null); return v$108; } /** * Create a compound statement. * * @param jsField The jsField. * @param init The init. * @param releaseAbrupt The releaseAbrupt. * @param csField The csField. * @param body The body. * @param label The label. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node withString(String jsField, Node init, String releaseAbrupt, String csField, Node body, String label, Node abruptFlowCheck) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, jsField); Node v$3 = GNode.create("AssignmentExpression", v$2, "=", init); Node v$4 = GNode.create("ExpressionStatement", v$3); Node v$5 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$6 = GNode.create("IndirectComponentSelection", v$5, releaseAbrupt); Node v$7 = GNode.create("IntegerConstant", "0"); Node v$8 = GNode.create("AssignmentExpression", v$6, "=", v$7); Node v$9 = GNode.create("ExpressionStatement", v$8); Node v$10 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$11 = GNode.create("IndirectComponentSelection", v$10, csField); Node v$12 = GNode.create("TypedefName", "jchar"); Node v$13 = GNode.create("SpecifierQualifierList", v$12); Node v$14 = GNode.create("TypeQualifierList", false); Node v$15 = GNode.create("Pointer", v$14, null); Node v$16 = GNode.create("AbstractDeclarator", v$15, null); Node v$17 = GNode.create("TypeName", v$13, v$16); Node v$18 = GNode.create("PrimaryIdentifier", "env"); Node v$19 = GNode.create("IndirectionExpression", v$18); Node v$20 = GNode.create("IndirectComponentSelection", v$19, "GetStringChars"); Node v$21 = GNode.create("PrimaryIdentifier", "env"); Node v$22 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$23 = GNode.create("IndirectComponentSelection", v$22, jsField); Node v$24 = GNode.create("IntegerConstant", "0"); Node v$25 = GNode.create("ExpressionList", v$21, v$23, v$24); Node v$26 = GNode.create("FunctionCall", v$20, v$25); Node v$27 = GNode.create("CastExpression", v$17, v$26); Node v$28 = GNode.create("AssignmentExpression", v$11, "=", v$27); Node v$29 = GNode.create("ExpressionStatement", v$28); Node v$30 = GNode.create("PrimaryIdentifier", label); Node v$31 = GNode.create("GotoStatement", null, v$30); Node v$32 = GNode.create("NamedLabel", label, null); Node v$33 = GNode.create("PrimaryIdentifier", "env"); Node v$34 = GNode.create("IndirectionExpression", v$33); Node v$35 = GNode.create("IndirectComponentSelection", v$34, "ReleaseStringChars"); Node v$36 = GNode.create("PrimaryIdentifier", "env"); Node v$37 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$38 = GNode.create("IndirectComponentSelection", v$37, jsField); Node v$39 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$40 = GNode.create("IndirectComponentSelection", v$39, csField); Node v$41 = GNode.create("ExpressionList", v$36, v$38, v$40); Node v$42 = GNode.create("FunctionCall", v$35, v$41); Node v$43 = GNode.create("ExpressionStatement", v$42); Node v$44 = GNode.create("LabeledStatement", v$32, v$43); Node v$45 = GNode.create("CompoundStatement", v$4, v$9, v$29, body, v$31, v$44, abruptFlowCheck, null); return v$45; } /** * Create a compound statement. * * @param jsField The jsField. * @param init The init. * @param releaseAbrupt The releaseAbrupt. * @param csField The csField. * @param body The body. * @param label The label. * @param abruptFlowCheck The abruptFlowCheck. * @return The generic node. */ public Node withStringUTF(String jsField, Node init, String releaseAbrupt, String csField, Node body, String label, Node abruptFlowCheck) { Node v$1 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$2 = GNode.create("IndirectComponentSelection", v$1, jsField); Node v$3 = GNode.create("AssignmentExpression", v$2, "=", init); Node v$4 = GNode.create("ExpressionStatement", v$3); Node v$5 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$6 = GNode.create("IndirectComponentSelection", v$5, releaseAbrupt); Node v$7 = GNode.create("IntegerConstant", "0"); Node v$8 = GNode.create("AssignmentExpression", v$6, "=", v$7); Node v$9 = GNode.create("ExpressionStatement", v$8); Node v$10 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$11 = GNode.create("IndirectComponentSelection", v$10, csField); Node v$12 = GNode.create("TypedefName", "jbyte"); Node v$13 = GNode.create("SpecifierQualifierList", v$12); Node v$14 = GNode.create("TypeQualifierList", false); Node v$15 = GNode.create("Pointer", v$14, null); Node v$16 = GNode.create("AbstractDeclarator", v$15, null); Node v$17 = GNode.create("TypeName", v$13, v$16); Node v$18 = GNode.create("PrimaryIdentifier", "env"); Node v$19 = GNode.create("IndirectionExpression", v$18); Node v$20 = GNode.create("IndirectComponentSelection", v$19, "GetStringUTFChars"); Node v$21 = GNode.create("PrimaryIdentifier", "env"); Node v$22 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$23 = GNode.create("IndirectComponentSelection", v$22, jsField); Node v$24 = GNode.create("IntegerConstant", "0"); Node v$25 = GNode.create("ExpressionList", v$21, v$23, v$24); Node v$26 = GNode.create("FunctionCall", v$20, v$25); Node v$27 = GNode.create("CastExpression", v$17, v$26); Node v$28 = GNode.create("AssignmentExpression", v$11, "=", v$27); Node v$29 = GNode.create("ExpressionStatement", v$28); Node v$30 = GNode.create("NamedLabel", label, null); Node v$31 = GNode.create("PrimaryIdentifier", "env"); Node v$32 = GNode.create("IndirectionExpression", v$31); Node v$33 = GNode.create("IndirectComponentSelection", v$32, "ReleaseStringUTFChars"); Node v$34 = GNode.create("PrimaryIdentifier", "env"); Node v$35 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$36 = GNode.create("IndirectComponentSelection", v$35, jsField); Node v$37 = GNode.create("Char", false); Node v$38 = GNode.create("SpecifierQualifierList", v$37); Node v$39 = GNode.create("TypeQualifierList", false); Node v$40 = GNode.create("Pointer", v$39, null); Node v$41 = GNode.create("AbstractDeclarator", v$40, null); Node v$42 = GNode.create("TypeName", v$38, v$41); Node v$43 = GNode.create("PrimaryIdentifier", "pcEnv"); Node v$44 = GNode.create("IndirectComponentSelection", v$43, csField); Node v$45 = GNode.create("CastExpression", v$42, v$44); Node v$46 = GNode.create("ExpressionList", v$34, v$36, v$45); Node v$47 = GNode.create("FunctionCall", v$33, v$46); Node v$48 = GNode.create("ExpressionStatement", v$47); Node v$49 = GNode.create("LabeledStatement", v$30, v$48); Node v$50 = GNode.create("CompoundStatement", v$4, v$9, v$29, body, v$49, abruptFlowCheck, null); return v$50; } }
8c79db1bb22cea287166ad90b014468b2f022a7b
2a85e0ba9cfd4b92f21c0cda99f1fe19f8e75236
/P07_Kafka_Streams/kstreams/src/main/java/ee/ut/cs/dsg/dsg/exercise1/Exercise1Streams.java
95e563ffbabf552f41251760ff6c4c3676bd9e44
[]
no_license
enliktjioe/dataeng2020
d334d4cac9b63e8f630a68c377701c7f0b5a1cfa
5c033669225b2ad6f025301c1d732b071c86afae
refs/heads/master
2023-02-20T13:46:45.040120
2021-01-21T21:54:30
2021-01-21T21:54:30
297,154,548
0
0
null
null
null
null
UTF-8
Java
false
false
2,323
java
package ee.ut.cs.dsg.dsg.exercise1; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.kstream.*; import java.util.Arrays; import java.util.Properties; import java.util.UUID; import java.util.regex.Pattern; public class Exercise1Streams { final static Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); public static String INPUT_TOPIC = "paragraphs"; public static String OUTPUT_TOPIC = "wordcount-stream-out"; ; public static void main(String[] args) { StreamsBuilder builder = new StreamsBuilder(); Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-stream" + UUID.randomUUID()); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); KStream<String, String> words = builder.stream(INPUT_TOPIC, Consumed.with(Serdes.String(), Serdes.String())); KTable<String, Long> table = words // .mapValues(value -> value.toLowerCase() // .replace(",", " ") // .replace(";", " ") // .replace(".", " ") // .replace("!", " ") // .replace("\"", " ") // .replace("?", " ")) .flatMapValues(value -> Arrays.asList(pattern.split(value))) .groupBy((title, word) -> word).count(); KStream<String, Long> wordcounts = table.toStream(); wordcounts.to(OUTPUT_TOPIC, Produced.with(Serdes.String(), Serdes.Long())); wordcounts.print(Printed.toSysOut()); Topology topology = builder.build(); System.out.println(topology.describe()); KafkaStreams ks = new KafkaStreams(topology, props); ks.start(); } }
3c4cc05ada61acaae5a4e947161a696a28841eb4
24d1a308018170eb761118e932c604cd8213dca8
/src/Others/Udemy/DynamicProgramming/CuttingRod.java
37b4c07b88f1456a2a681a5f4ba2cb1b24b655f3
[]
no_license
Tejas1009/interviewbit
3388346c7373d80a3eaeb9faff990825661ea077
dcc46f9628458d0d50af8e962cae53d9d0524608
refs/heads/master
2023-07-18T02:17:06.531039
2021-09-07T10:28:15
2021-09-07T10:28:15
369,851,178
0
0
null
null
null
null
UTF-8
Java
false
false
1,219
java
package Others.Udemy.DynamicProgramming; /* Rod cutting Problem: Find max profit. */ public class CuttingRod { public static int maxProfit_Recur(int prices[], int n) { if (n <= 0) { return 0; } int res = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int cut = i + 1; int curr_ans = prices[i] + maxProfit_Recur(prices, n - cut); res = Math.max(res, curr_ans); } return res; } public static int maxProfit_DP(int prices[], int n) { int dp[] = new int[n + 1]; dp[0] = 0; for (int len = 1; len <= n; len++) { int res = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { int cut = i + 1; int curr_ans = prices[i] + dp[len - cut]; res = Math.max(res, curr_ans); } dp[len] = res; } return dp[n]; } public static void main(String[] args) { int prices[] = {1, 5, 8, 9, 10, 17, 17, 20}; System.out.println(maxProfit_Recur(prices, 8)); System.out.println("---------------------------"); System.out.println(maxProfit_DP(prices, 8)); } }
b0975a58e5bf3c99f6d5dc6c877b3339cb0c5565
dd80a584130ef1a0333429ba76c1cee0eb40df73
/sdk/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileReader.java
76b32b099c998e439c85b7b1874ed2dcaa62b178
[ "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
Java
false
false
2,335
java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.gltrace; import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage; import com.google.protobuf.InvalidProtocolBufferException; import java.io.EOFException; import java.io.IOException; import java.io.RandomAccessFile; public class TraceFileReader { /** Maximum size for a protocol buffer message. * The message size is dominated by the size of the compressed framebuffer. * Currently, we assume that the maximum is for a 1080p display. Since the buffers compress * well, we should probably never get close to this. */ private static final int MAX_PROTOBUF_SIZE = 1920 * 1080 * 100; /** * Obtain the next protobuf message in this file. * @param file file to read from * @param offset offset to start reading from * @return protobuf message at given offset * @throws IOException in case of file I/O errors * @throws InvalidProtocolBufferException if protobuf is not well formed */ public GLMessage getMessageAtOffset(RandomAccessFile file, long offset) throws IOException { int len; byte[] b; try { if (offset != -1) { file.seek(offset); } len = file.readInt(); if (len > MAX_PROTOBUF_SIZE) { String msg = String.format( "Unexpectedly large (%d bytes) protocol buffer message encountered.", len); throw new InvalidProtocolBufferException(msg); } b = new byte[len]; file.readFully(b); } catch (EOFException e) { return null; } return GLMessage.parseFrom(b); } }
3c304680dc67003cef2f5808bea6349b2cc7aa89
3a353a78cbeb733eff29a3da471ad0a15b3e65da
/input/javasrc/com/alvazan/orm/impl/meta/RowToPersist.java
9d6377b5bb6d04398bf48e788cfc0989131eee60
[]
no_license
shanling2004/nosqlORM
0f6a9c1e6a59ccf9c653929000991244f0f17a65
5559c255f0bc16e6fdc69572c5d9b8b46a7990bc
refs/heads/master
2021-01-16T18:02:09.777187
2012-05-31T15:03:17
2012-05-31T15:03:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
499
java
package com.alvazan.orm.impl.meta; import java.util.ArrayList; import java.util.List; import com.alvazan.orm.layer3.spi.db.Column; public class RowToPersist { private byte[] key; private List<Column> columns = new ArrayList<Column>(); public byte[] getKey() { return key; } public void setKey(byte[] key) { this.key = key; } public List<Column> getColumns() { return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } }
2df3e526aade9bca9776bad2b05563436c15e0ef
90b7ee6ad7c2b044ef084790d39709be8bc76cc4
/TIJ4/05init/src/top/woilanlan/Rock.java
0d58ba7f3cc9f1948ac922c49fe6d75d7f55a903
[ "MIT" ]
permissive
woilanlan/java-example
b992dee9bbabf4f844c25f755e7c6dfa145277ec
a24c11b5a330525be15072f02621664a388c0bcb
refs/heads/master
2022-12-29T13:34:28.258384
2020-06-07T04:00:38
2020-06-07T04:00:38
258,099,420
0
0
MIT
2020-10-13T22:36:44
2020-04-23T05:03:11
Java
UTF-8
Java
false
false
392
java
package top.woilanlan; /** * Rock */ public class Rock { Rock(){ System.out.println("Rock "); } Rock(int i){ System.out.println("Rock "+i); } public void show() { for (int i = 0; i < 10; i++) { new Rock(); } } public void show2() { for (int i = 0; i < 10; i++) { new Rock(i); } } }
ac3451ba45a6b2b476f70f1f3e792fb8d356d007
d3a8feb99fea0973541f31dd391cd0c74586f38c
/AZ3-Spring JDBC-n-Trans/src/main/java/com/infosys/domain/Author.java
719093594baa173c51be63aaf2ba0b87a482dd6f
[]
no_license
yogi3345/SpringTrainingLex
28889e5f94adc88fb42273a29a6f7b8e07b32a2d
942194a178c9782d40aa50982edf97e2546bb0bc
refs/heads/master
2022-05-03T16:04:39.529387
2022-04-01T03:07:31
2022-04-01T03:07:31
216,357,232
0
0
null
null
null
null
UTF-8
Java
false
false
723
java
package com.infosys.domain; public class Author { private String firstName; private String lastName; private int authorId; public int getAuthorId() { return authorId; } public void setAuthorId(int authorId) { this.authorId = authorId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Author(String firstName, String lastName, int authorId) { super(); this.firstName = firstName; this.lastName = lastName; this.authorId = authorId; } }
[ "Yogesh@Predator" ]
Yogesh@Predator
29df13ab1b506a8de90948eacaa8c63709a70f3c
ca0fe968873399950eea0aa94bd8dc3e95124ca1
/taotao-manager/taotao-manager-pojo/src/main/java/com/taotao/pojo/TbUser.java
9d821ce532af6c25f658fefcadff82632b758635
[]
no_license
q547263153/BookShop
0c36e3335b8d92bee6e27711c51f0233c70657e3
6d8ecff08421d16bd0185698cfd7ec37a706ebf4
refs/heads/master
2022-12-23T18:40:54.005266
2020-03-14T03:32:15
2020-03-14T03:32:15
240,046,286
0
0
null
2022-12-16T07:16:48
2020-02-12T15:27:00
JavaScript
UTF-8
Java
false
false
1,656
java
package com.taotao.pojo; import java.io.Serializable; import java.util.Date; public class TbUser implements Serializable { private Long id; private String username; private String password; private String phone; private String email; private Date created; private Date updated; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } @Override public String toString() { return "TbUser [id=" + id + ", username=" + username + ", password=" + password + ", phone=" + phone + ", email=" + email + ", created=" + created + ", updated=" + updated + "]"; } }
1cea4899a4d54bd5583c0e0115024497a739927d
f200e916a2ca9fa4a01c40a588fc965a7337f735
/src/main/java/ru/alvisid/pacs/service/impl/EditServiceImpl.java
3cd20efbe5778f7ad79844952b8948edd53ebe65
[]
no_license
EugeniyGlushkov/PACS
56091f54f69cd99fc4fdf29901c95761b063cf77
4c5738137a3720253449aac5ad62ccf84fece3fc
refs/heads/master
2020-04-02T22:04:05.316724
2019-03-13T13:47:17
2019-03-13T13:47:17
154,820,695
2
0
null
null
null
null
UTF-8
Java
false
false
2,965
java
package ru.alvisid.pacs.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import ru.alvisid.pacs.model.Edit; import ru.alvisid.pacs.repository.EditRepository; import ru.alvisid.pacs.service.AbstractService; import ru.alvisid.pacs.service.EditService; import ru.alvisid.pacs.util.exceptions.NotFoundException; import java.time.LocalDateTime; import java.util.List; import static ru.alvisid.pacs.util.ValidationUtil.checkNotFoundWithId; /** * Implementation of the {@code EditService} interface. * Extends <b>AbstractService</b> functionality. * * @author Glushkov Evgeniy * @version 1.0 * @see EditService * @see AbstractService */ @Service public class EditServiceImpl extends AbstractService<EditRepository, Edit> implements EditService { /** * Creates and saves a given edit in the data base * with inserted employee. * * @param edit the edit to create. * @param empId the employee's id to insert. * @return the created object. */ @Override public Edit create(Edit edit, int empId) { Assert.notNull(edit, currentClass.getSimpleName() + " must not be null"); return repository.save(edit, empId); } /** * Updates an existing in the data base edit * with inserted employee. * * @param edit the edit to create. * @param empId the employee's id to insert. * @throws NotFoundException if there aren't updated object in the data base. */ @Override public void update(Edit edit, int empId) throws NotFoundException { Assert.notNull(edit, currentClass.getSimpleName() + " must not be null"); checkNotFoundWithId(repository.save(edit, empId), edit.getId()); } /** * Returns all edits which are done by specific employee. * List is sorted by edit's time and edit's type. * * @param id the employee's id. * @return all edits which are done by specific employee. */ @Override public List<Edit> getAllByEmpId(int id) { return repository.getAllByEmpId(id); } /** * Returns all edits in the specified time interval. * List is sorted by edit's time, edit's type, employee's last name, first name and second name. * * @param start the start of the time interval. * @param end the end of the time interval. */ @Override public List<Edit> getAllBetween(LocalDateTime start, LocalDateTime end) { return repository.getAllBetween(start, end); } /** * Constructs new {@code EditServiceImpl} and set a specified edit's repository implementation * to the superclass's repository field. * * @param repository the specified point action's repository implementation. */ @Autowired public EditServiceImpl(EditRepository repository) { super(repository); } }
a3934854a70fc006ab38e319e551db773ef05130
a6f4bef2eaf8d3191a1d7c457e1982145ee7445f
/DeliveryPack/src/lt/vtmc/Delivery/Person.java
635eb22de4779d3cae0087fae8c8050462507905
[]
no_license
VStoncius/JP-namu-darbai
8b26a873a72614d2b2632fcc9a533843a6945911
7221a9e6106653ae9724a3c4bd406a71e0f04ac8
refs/heads/master
2020-07-30T15:31:04.703671
2019-10-21T20:00:37
2019-10-21T20:00:37
210,277,794
0
0
null
null
null
null
UTF-8
Java
false
false
535
java
package lt.vtmc.Delivery; public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public double getHungry(String name, int amount, double cost) { Deliverable pizza = new Pizza(name, amount, cost); double price = pizza.getFullPrice(); return price; } public double wantNewPhone(String name, int amount, double cost) { Deliverable pizza = new Pizza(name, amount, cost); double price = pizza.getFullPrice(); return price; } }
52a8365e901ea71bc8a9fa3e7160d4b36ad4834f
ba9592827df90a1ccfd2d85e3dc8a2e4f3f536df
/MyApplication/app/src/test/java/com/example/myapplication/ExampleUnitTest.java
8e9486ceeddb0aabf560a54c0deda9de383e092c
[]
no_license
toririggs/java-toririggs
14f53f6642768c9ede2b34573f35d7f15c2f3191
142322c705bfd69703e5a09e7fbd123fe3bea0dc
refs/heads/master
2022-06-22T03:58:11.161581
2019-12-10T05:56:20
2019-12-10T05:56:20
203,848,528
0
0
null
2022-06-21T02:10:39
2019-08-22T18:10:05
Java
UTF-8
Java
false
false
847
java
package com.example.myapplication; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ // Testing for DBHelper public class ExampleUnitTest { MainActivity ma = new MainActivity(); DBHelper db = new DBHelper(ma); @Test public void testAdd() { db.addUser("Bob", "[email protected]"); } @Test public void testUpdate() { db.updateStatus(1, "READY", 1001); } @Test public void testGetUser() { assertNotNull(db.getUser(1)); } @Test public void testGetItem() { assertNotNull(db.getItem(1)); } @Test public void testGetUsers() { assertNotNull(db.getUsers()); } }
6557e15b98dffd1b0759f965b90855e4b5fd4691
6c78cfd210815b1b5298475889783a348d74fb26
/NextGreaterElement.java
da5ddca93a6bd8aa9a5aa02c4442011fbe6acb42
[]
no_license
Recho77/Leetcode-easy
14bc8a5514b3958c1eebc2251fdc8ff88f1b0fd8
00570fa083e56de2048b5fa6068a41453ae8c042
refs/heads/master
2021-01-23T03:21:10.561542
2017-04-06T04:04:54
2017-04-06T04:04:54
86,070,377
0
0
null
null
null
null
UTF-8
Java
false
false
1,205
java
//You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. //Find all the next greater numbers for nums1's elements in the corresponding places of nums2. //The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. //If it does not exist, output -1 for this number. import java.util.*; public class Solution { public int[] nextGreaterElement(int[] findNums, int[] nums) { //define a Map to store the next number Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>(); //define an array of integers as the result int[] result = new int[findNums.length]; for(int i = 0; i < nums.length; i++){ for(int j = i+1; j < nums.length; j++){ if(nums[j] > nums[i]){ nextMap.put(nums[i], nums[j]); break; } } if(!(nextMap.containsKey(nums[i]))) nextMap.put(nums[i], -1); } for(int i = 0; i < findNums.length; i++){ result[i] = nextMap.get(findNums[i]); } return result; } }
d62fe7ba2f77190b5e54a6dc9566392d4b75cf15
c23c16ce52ece3f6494859b7a8cfe390c7f4bcde
/src/main/java/com/zhongtai/spring_redis/Main.java
0e29af919e7ccf9b738ffc73915012c7a2a8f40d
[]
no_license
yifan366/spring-redis
dde77f8bebde34f5ab6bd4e18c3cace76ad1f4c5
43e18c950eacebf5d33700ff4d9b480e6976ca1d
refs/heads/master
2021-04-26T16:19:15.778285
2016-10-12T10:04:11
2016-10-12T10:04:11
70,687,352
0
0
null
null
null
null
UTF-8
Java
false
false
855
java
package com.zhongtai.spring_redis; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.StringRedisTemplate; public class Main { public static void main(String[] args) { long starTime=System.currentTimeMillis(); ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); StringRedisTemplate st = (StringRedisTemplate) ctx.getBean("redisTemplate"); RedisConnection con = st.getConnectionFactory().getConnection(); byte[] result = con.get("ztzf".getBytes()); System.out.println(new String(result)); long endTime=System.currentTimeMillis(); long Time=endTime-starTime; System.out.println(Time); } }
2b4af9863a658e14bdd476cf62ca84d827a645ea
90b2e03cd9015d3e83275223662821525dd8508d
/src/main/java/com/yihao86/service/impl/WorksServiceImpl.java
8d1d49006e3f34e7a73c836b0e3b78d3be85af05
[]
no_license
yihao86/yihao86
6911e12963129528f1711f2aade6f8aa5775887b
d4be6c736b684aeeece9e1f7bd155ff21176eaf4
refs/heads/master
2021-06-28T13:44:48.984615
2018-09-18T00:44:42
2018-09-18T00:44:42
145,385,512
0
0
null
null
null
null
UTF-8
Java
false
false
693
java
package com.yihao86.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yihao86.dao.WorksDao; import com.yihao86.service.WorksService; @Service public class WorksServiceImpl implements WorksService { @Autowired private WorksDao wd; @Override public List<Map<String, Object>> SelectOnNew() { return wd.fandOnNew(); } @Override public List<Map<String, Object>> SelectAllById(int w_tid) { List<Map<String, Object>> tids = SelectOnNew(); for (Map<String, Object> map : tids) { } return tids; } }
59f52f95bf80df9c11cefb3d19a6e1870e9633c4
fd90e171cf8a38332660242b09676e0d50f86ae0
/src/com/hoangnhm/Util/WordType.java
7a7205268209005957280d57dd4fb1fd330d6201
[ "Apache-2.0" ]
permissive
HoangNHM/GetDb
09d21c2f820d7e5ae1f27d151730e5648aea4095
90fab37349fe304a57796c97e71761d4cd9c2265
refs/heads/master
2016-08-12T21:40:09.132017
2016-01-24T23:20:50
2016-01-24T23:20:50
50,041,944
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package com.hoangnhm.Util; /** * Created by vantuegia on 1/19/2016. */ public enum WordType { NOUN(Constant.NOUN), VERB(Constant.VERB), ADJ(Constant.ADJ); private final String type; private WordType(String type) { this.type = type; } public String getType() { return this.type; } }
21b64002c6ed2a8bebf025a6db093ee63243bc4d
522a944acfc5798d6fb70d7a032fbee39cc47343
/d6k/trunk/src/web/corsair/src/main/java/com/eventsrv/Constant.java
4b69ed90d36d81912c9f666488670ca2300fded5
[]
no_license
liuning587/D6k2.0master
50275acf1cb0793a3428e203ac7ff1e04a328a50
254de973a0fbdd3d99b651ec1414494fe2f6b80f
refs/heads/master
2020-12-30T08:21:32.993147
2018-03-30T08:20:50
2018-03-30T08:20:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
155
java
package com.eventsrv; /** * Created by ChengXi on 2016/1/11. */ public interface Constant { int TYPE_BROWSER = 0; int TYPE_EVENT_SRV = 1; }
e1e708a747b5872dfa1bfd1ebe398267228d5eba
e4842aaee43d67986aec43e308e87cba36624d5a
/src/test/java/com/projet/jhipster/web/rest/AuditResourceIT.java
fbf6eb8253f4862888c20999e1347f1ebfa0d9a4
[]
no_license
layendoye/projetJhipster
1462fb06327d2ce8880f1ad7fb9d102eb715a9a1
57aee9906be4c72d794b9837c80ba8d8af4f1b92
refs/heads/master
2022-12-23T02:04:21.516519
2019-10-14T08:43:21
2019-10-14T08:43:21
214,992,482
0
0
null
2022-12-16T05:06:11
2019-10-14T08:44:34
Java
UTF-8
Java
false
false
6,765
java
package com.projet.jhipster.web.rest; import com.projet.jhipster.ProjetApp; import io.github.jhipster.config.JHipsterProperties; import com.projet.jhipster.config.audit.AuditEventConverter; import com.projet.jhipster.domain.PersistentAuditEvent; import com.projet.jhipster.repository.PersistenceAuditEventRepository; import com.projet.jhipster.service.AuditEventService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link AuditResource} REST controller. */ @SpringBootTest(classes = ProjetApp.class) @Transactional public class AuditResourceIT { private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); private static final long SECONDS_PER_DAY = 60 * 60 * 24; @Autowired private PersistenceAuditEventRepository auditEventRepository; @Autowired private AuditEventConverter auditEventConverter; @Autowired private JHipsterProperties jhipsterProperties; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired @Qualifier("mvcConversionService") private FormattingConversionService formattingConversionService; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; private PersistentAuditEvent auditEvent; private MockMvc restAuditMockMvc; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); AuditEventService auditEventService = new AuditEventService(auditEventRepository, auditEventConverter, jhipsterProperties); AuditResource auditResource = new AuditResource(auditEventService); this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setConversionService(formattingConversionService) .setMessageConverters(jacksonMessageConverter).build(); } @BeforeEach public void initTest() { auditEventRepository.deleteAll(); auditEvent = new PersistentAuditEvent(); auditEvent.setAuditEventType(SAMPLE_TYPE); auditEvent.setPrincipal(SAMPLE_PRINCIPAL); auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); } @Test public void getAllAudits() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Get all the audits restAuditMockMvc.perform(get("/management/audits")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test public void getAudit() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); } @Test public void getAuditsByDate() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will contain the audit String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Get the audit restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test public void getNonExistingAuditsByDate() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will not contain the sample audit String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Query audits but expect no results restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(header().string("X-Total-Count", "0")); } @Test public void getNonExistingAudit() throws Exception { // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void testPersistentAuditEventEquals() throws Exception { TestUtil.equalsVerifier(PersistentAuditEvent.class); PersistentAuditEvent auditEvent1 = new PersistentAuditEvent(); auditEvent1.setId(1L); PersistentAuditEvent auditEvent2 = new PersistentAuditEvent(); auditEvent2.setId(auditEvent1.getId()); assertThat(auditEvent1).isEqualTo(auditEvent2); auditEvent2.setId(2L); assertThat(auditEvent1).isNotEqualTo(auditEvent2); auditEvent1.setId(null); assertThat(auditEvent1).isNotEqualTo(auditEvent2); } }
a9c72d2c334a817398575e5219f7176c7fadfa30
9439976175cc67fccf3966c1077844108f54d5f3
/Test/src/java/org/anhcraft/spaciouslibtest/SpaciousLibTestSpigot.java
e00c7a996178ad06246eac6663f1c65f4e5a8ee9
[ "Apache-2.0" ]
permissive
Weefle/SpaciousLib
bc1043d8392911c27a5cac2a090b56c87b9b0812
5ece8e2fa437f0f89567cdfdf042205d9c338897
refs/heads/master
2020-03-09T07:27:17.392004
2018-04-08T14:28:57
2018-04-08T14:28:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
30,694
java
package org.anhcraft.spaciouslibtest; import org.anhcraft.spaciouslib.anvil.AnvilBuilder; import org.anhcraft.spaciouslib.anvil.AnvilHandler; import org.anhcraft.spaciouslib.anvil.AnvilSlot; import org.anhcraft.spaciouslib.attribute.Attribute; import org.anhcraft.spaciouslib.attribute.AttributeModifier; import org.anhcraft.spaciouslib.bungee.BungeeManager; import org.anhcraft.spaciouslib.bungee.BungeePlayerIPResponse; import org.anhcraft.spaciouslib.command.CommandArgument; import org.anhcraft.spaciouslib.command.CommandBuilder; import org.anhcraft.spaciouslib.command.CommandRunnable; import org.anhcraft.spaciouslib.command.SubCommandBuilder; import org.anhcraft.spaciouslib.entity.EntityManager; import org.anhcraft.spaciouslib.entity.PlayerPing; import org.anhcraft.spaciouslib.events.ArmorEquipEvent; import org.anhcraft.spaciouslib.events.BungeeForwardEvent; import org.anhcraft.spaciouslib.events.NPCInteractEvent; import org.anhcraft.spaciouslib.events.PacketHandleEvent; import org.anhcraft.spaciouslib.hologram.Hologram; import org.anhcraft.spaciouslib.hologram.HologramManager; import org.anhcraft.spaciouslib.inventory.*; import org.anhcraft.spaciouslib.io.DirectoryManager; import org.anhcraft.spaciouslib.io.FileManager; import org.anhcraft.spaciouslib.mojang.CachedSkin; import org.anhcraft.spaciouslib.mojang.GameProfileManager; import org.anhcraft.spaciouslib.mojang.SkinManager; import org.anhcraft.spaciouslib.nbt.NBTManager; import org.anhcraft.spaciouslib.npc.NPC; import org.anhcraft.spaciouslib.npc.NPCManager; import org.anhcraft.spaciouslib.npc.NPCWrapper; import org.anhcraft.spaciouslib.placeholder.Placeholder; import org.anhcraft.spaciouslib.placeholder.PlaceholderManager; import org.anhcraft.spaciouslib.protocol.*; import org.anhcraft.spaciouslib.socket.ServerSocketClientHandler; import org.anhcraft.spaciouslib.socket.ServerSocketRequestHandler; import org.anhcraft.spaciouslib.socket.SocketManager; import org.anhcraft.spaciouslib.utils.CommonUtils; import org.anhcraft.spaciouslib.utils.InventoryUtils; import org.anhcraft.spaciouslib.utils.RandomUtils; import org.anhcraft.spaciouslib.utils.TimeUnit; import org.apache.commons.io.IOUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.UUID; public class SpaciousLibTestSpigot extends JavaPlugin implements Listener { private static File f = new File("plugins/SpaciousLibTest/test.txt"); private static NPCWrapper npc; private static Hologram hg; @Override public void onEnable() { try { SkinManager.get(UUID.fromString("2c8d5050-eae7-438d-88c4-c29fbcebede9"), (int) TimeUnit.WEEK.getSeconds()); } catch(Exception e) { e.printStackTrace(); } new DirectoryManager("plugins/SpaciousLibTest/").mkdirs(); try { new FileManager(f).initFile(IOUtils.toByteArray(getClass().getResourceAsStream("/test.txt"))); } catch(IOException e) { e.printStackTrace(); } try { new CommandBuilder("slt", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { for(String str : sCommand.getCommandsAsString(true)) { commandSender.sendMessage(str); } } }) .addSubCommand(new SubCommandBuilder("particle spawn", "Spawn a specific type of particle at your location", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { commandSender.sendMessage(sCommand.getCommandAsString(subCommand, true)); } }).addArgument( new CommandArgument("type", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { if(commandSender instanceof Player) { Particle.Type type = CommonUtils.getObject(strings[0].toUpperCase(), Particle.Type.values()); if(type == null) { commandSender.sendMessage("Invalid particle type!"); } else { Location location = ((Player) commandSender).getLocation(); for(int degree = 0; degree < 360; degree++) { double radians = Math.toRadians(degree); double x = Math.cos(radians) * 3; double z = Math.sin(radians) * 3; location.add(x, 0, z); Particle.create(type, location, 10).sendWorld(((Player) commandSender).getWorld()); location.subtract(x, 0, z); } } } } }, false), CommandArgument.Type.CUSTOM ).addArgument( new CommandArgument("count", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { if(commandSender instanceof Player) { Particle.Type type = CommonUtils.getObject(strings[0], Particle.Type.values()); if(type == null) { commandSender.sendMessage("Invalid particle type!"); } else { Location location = ((Player) commandSender).getLocation(); for(int degree = 0; degree < 360; degree++) { double radians = Math.toRadians(degree); double x = Math.cos(radians) * 3; double z = Math.sin(radians) * 3; location.add(x, 0, z); Particle.create(type, location, CommonUtils.toIntegerNumber(strings[1])).sendWorld(((Player) commandSender).getWorld()); location.subtract(x, 0, z); } } } } }, true), CommandArgument.Type.INTEGER_NUMBER ).hideTypeCommandString()) .addSubCommand(new SubCommandBuilder("particle list", "show all types of particle", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { StringBuilder pls = new StringBuilder(); for(Particle.Type p : Particle.Type.values()) { pls.append(p.toString()).append(" "); } commandSender.sendMessage(pls.toString()); } })) .addSubCommand( new SubCommandBuilder("playerlist set", null, new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { commandSender.sendMessage(sCommand.getCommandAsString(subCommand, true)); } }) .addArgument("header", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { commandSender.sendMessage(sCommand.getCommandAsString(subCommand, true)); } }, CommandArgument.Type.CUSTOM, false) .addArgument("footer", new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { PlayerList.create(strings[0], strings[1]).sendAll(); } }, CommandArgument.Type.CUSTOM, false) ) .addSubCommand(new SubCommandBuilder("playerlist remove", null, new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { PlayerList.remove().sendAll(); } })) .addSubCommand(new SubCommandBuilder("skin", null, new CommandRunnable() { @Override public void run(CommandBuilder sCommand, SubCommandBuilder subCommand, CommandSender commandSender, String[] strings, String s) { commandSender.sendMessage(sCommand.getCommandAsString(subCommand, true)); } }).addArgument("uuid", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { try { CachedSkin cs = SkinManager.get(UUID.fromString(value)); if(sender instanceof Player) { Player player = (Player) sender; SkinManager.changeSkin(player, cs.getSkin()); } } catch(Exception e) { e.printStackTrace(); } } }, CommandArgument.Type.UUID, false)) .addSubCommand(new SubCommandBuilder("camera", "View as a random nearby entity", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] strings, String s) { if(sender instanceof Player) { Entity e = RandomUtils.pickRandom(((Player) sender).getNearbyEntities(5, 5, 5)); Camera.create(e).sendPlayer((Player) sender); } } })) .addSubCommand(new SubCommandBuilder("camera reset", "Reset your view to normal", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] strings, String s) { if(sender instanceof Player) { Camera.create((Player) sender).sendPlayer((Player) sender); } } })) .addSubCommand(new SubCommandBuilder("bungee tp", "Teleport you or a specific player to a server in Bungee network", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { sender.sendMessage(cmd.getCommandAsString(subcmd, true)); } }).addArgument("server", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { BungeeManager.connect((Player) sender, value); } } }, CommandArgument.Type.CUSTOM, false) .addArgument("player", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { BungeeManager.connect(value, args[0]); } } }, CommandArgument.Type.ONLINE_PLAYER, true) ) .addSubCommand(new SubCommandBuilder("bungee ip", "Get your real IP", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { BungeeManager.getIP((Player) sender, new BungeePlayerIPResponse() { @Override public void result(String ip, int port) { sender.sendMessage(ip + ":" + port); } }); } } })) .buildExecutor(this) .addSubCommand(new SubCommandBuilder("bungee data", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { sender.sendMessage("sent successfully!"); ByteArrayOutputStream bytedata = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(bytedata); try { data.writeUTF(sender.getName()); } catch(IOException e) { e.printStackTrace(); } BungeeManager.forwardData("slt", bytedata.toByteArray()); } })) .addSubCommand(new SubCommandBuilder("test", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { Player p = (Player) sender; p.getInventory().addItem( new BookManager("&aGuide", 1) .setAuthor("anhcraft") .setTitle("GUIDE") .setBookGeneration(BookManager.BookGeneration.ORIGINAL) .addPage(PlaceholderManager.replace( "Name: {player_name}\n" + "Level: {player_level}\n" + "Exp: {player_exp}\n" + "Ping: {player_ping}\n" + "Health: {player_health}/{player_max_health}", p)) .addPage("Second page") .addPage("Third page") .setUnbreakable(true) .addAttributeModifier( Attribute.Type.GENERIC_MOVEMENT_SPEED, new AttributeModifier( "test", 0.05, AttributeModifier.Operation.ADD ), EquipSlot.MAINHAND) .addLore("This is the guide book of this server!") .addEnchant(Enchantment.DAMAGE_ALL, 1) .addFlag(ItemFlag.HIDE_ENCHANTS) .getItem()); p.updateInventory(); new EntityManager(p).setAttribute( new Attribute(Attribute.Type.GENERIC_ARMOR) .addModifier(new AttributeModifier("1", 3, AttributeModifier.Operation.ADD))); new AnvilBuilder(p, new AnvilHandler() { @Override public void result(Player player, String input, ItemStack item, AnvilSlot slot) { p.sendMessage(input); p.closeInventory(); } }).setItem(AnvilSlot.INPUT_LEFT, new ItemManager("test", Material.DIAMOND, 1).getItem()).open(); ShapedRecipe r = new ShapedRecipe(new ItemManager("test111", Material.DIAMOND_SWORD, 1).setUnbreakable(true).addEnchant(Enchantment.DAMAGE_ALL, 5).addLore("tesssssss").addAttributeModifier(Attribute.Type.GENERIC_MAX_HEALTH, new AttributeModifier("1", 5, AttributeModifier.Operation.ADD), EquipSlot.MAINHAND).addAttributeModifier(Attribute.Type.GENERIC_ATTACK_SPEED, new AttributeModifier("2", 10, AttributeModifier.Operation.ADD), EquipSlot.MAINHAND).addAttributeModifier(Attribute.Type.GENERIC_ATTACK_DAMAGE, new AttributeModifier("3", 20, AttributeModifier.Operation.ADD), EquipSlot.MAINHAND).getItem()); r.shape("aaa", "aaa", "aaa"); r.setIngredient('a', Material.DIAMOND); RecipeManager.register(r); ActionBar.create("test").sendAll(); Animation.create(p, Animation.Type.SWING_MAIN_HAND).sendPlayer(p); BlockBreakAnimation.create(0, p.getLocation().getBlock().getRelative(BlockFace.DOWN), 5).sendWorld(p.getWorld()); Particle.create(Particle.Type.BARRIER, p.getLocation(), 5).sendWorld(p.getWorld()); PlayerList.create("aaa", "bbb").sendAll(); Title.create("wwwwwwwww", Title.Type.TITLE).sendPlayer(p); Camera.create(p).sendPlayer(p); } } })) .addSubCommand(new SubCommandBuilder("npc spawn", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player && npc == null) { Player p = (Player) sender; try { npc = NPCManager.register("test", new NPC( new GameProfileManager("test") .setSkin(SkinManager.get(UUID.fromString("2c8d5050-eae7-438d-88c4-c29fbcebede9")).getSkin()).getGameProfile(), p.getLocation(), NPC.Addition.INTERACT_HANDLER, NPC.Addition.NEARBY_RENDER).setNearbyRadius(20)); } catch(Exception e) { e.printStackTrace(); } } } })) .addSubCommand(new SubCommandBuilder("npc tphere", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player && npc != null) { Player p = (Player) sender; npc.teleport(p.getLocation()); } } })) .addSubCommand(new SubCommandBuilder("npc remove", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player && npc != null) { NPCManager.unregister("test"); npc = null; } } })) .addSubCommand(new SubCommandBuilder("npc rename", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { sender.sendMessage(cmd.getCommandAsString(subcmd, true)); } }).addArgument("name", new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player && npc != null) { npc.setName(value); } } }, CommandArgument.Type.CUSTOM, false)) .addSubCommand(new SubCommandBuilder("hg add", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { Player player = (Player) sender; hg = new Hologram("test", player.getLocation()); hg.addLine("test 1"); hg.addLine("test 2"); hg.addLine("test 3"); hg.addViewer(player); HologramManager.register(hg); } } })) .addSubCommand(new SubCommandBuilder("hg remove", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { HologramManager.unregister(hg); } } })) .addSubCommand(new SubCommandBuilder("json", null, new CommandRunnable() { @Override public void run(CommandBuilder cmd, SubCommandBuilder subcmd, CommandSender sender, String[] args, String value) { if(sender instanceof Player) { Player player = (Player) sender; try { new FileManager(f).writeIfExist(NBTManager.fromEntity(player).toJSON().getBytes(StandardCharsets.UTF_8)); } catch(IOException e) { e.printStackTrace(); } } } })) .buildExecutor(this) .clone("sl").buildExecutor(this) .clone("spaciouslib").buildExecutor(this); } catch(Exception e) { e.printStackTrace(); } getServer().getPluginManager().registerEvents(this, this); System.out.println("Starting socket server..."); SocketManager.registerServer(25568, new ServerSocketRequestHandler() { @Override public void request(ServerSocketClientHandler client, String data) { System.out.println("Client >> " + data); } }); for(Placeholder placeholder : PlaceholderManager.getPlaceholders()){ System.out.println(placeholder.getPlaceholder()); } new BukkitRunnable() { @Override public void run() { for(Player player : Bukkit.getServer().getOnlinePlayers()){ ActionBar.create(Integer.toString(PlayerPing.get(player))+" ms", 60, 80, 60).sendPlayer(player); } } }.runTaskTimerAsynchronously(this, 40, 40); } @EventHandler public void npc(NPCInteractEvent event){ if(event.getNPC().equals(npc.getNPC())){ InventoryManager inv = new InventoryManager(npc.getNPC().getGameProfile().getName(), 54); int i = 0; while(i < 54){ inv.set(i, new ItemManager("", RandomUtils.pickRandom(InventoryUtils.getArmors()), 1).getItem(), new InteractItemRunnable() { @Override public void run(Player player, ItemStack item, ClickType action, int slot) { } }); i++; } inv.open(event.getPlayer()); } } @EventHandler public void ev(PacketHandleEvent ev) { if(ev.getType().equals(PacketHandleEvent.Type.SERVER_BOUND)) { if(ev.getPacket().getClass().getSimpleName().equals("PacketPlayInChat")) { if(ev.getPacketValue("a").toString().equalsIgnoreCase("savemydata")) { ev.setCancelled(true); FileConfiguration fc = YamlConfiguration.loadConfiguration(f); NBTManager.fromEntity(ev.getPlayer()).toConfigurationSection(fc); try { fc.save(f); } catch(IOException e) { e.printStackTrace(); } } if(ev.getPacketValue("a").toString().equalsIgnoreCase("applymydata")) { ev.setCancelled(true); FileConfiguration fc = YamlConfiguration.loadConfiguration(f); NBTManager.fromConfigurationSection(fc).toEntity(ev.getPlayer()); } } } } @EventHandler public void forward(BungeeForwardEvent ev) { if(ev.getChannel().equals("slt")) { try { Bukkit.getServer().broadcastMessage("Forward from: " + ev.getData().readUTF()); } catch(IOException e) { e.printStackTrace(); } } } @EventHandler public void equip(ArmorEquipEvent event){ if(!InventoryUtils.isNull(event.getNewArmor())){ if(event.getNewArmor().getType().equals(Material.DIAMOND_HELMET)){ event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 100000, 1)); } } } @Override public void onDisable() { } }
60bed73065142282d046c1d100e567f11263651f
e69be2fd26b49c0f949f2b90220c9985895e1a57
/src/main/java/com/unitedlearningacademy/TutorialPlugin/PlayerCooldownManager.java
7dd012c0c70d57e837738a240630153dea2af92f
[]
no_license
RobbieGM/ULATutorialPlugin
2dc9c8fd2c8b58adafe9581722968d9b626e458f
80c366d028a1890c68386af0d8548e04905a29cb
refs/heads/master
2022-12-08T15:19:20.756819
2020-09-02T19:35:20
2020-09-02T19:35:20
282,097,744
0
0
null
null
null
null
UTF-8
Java
false
false
3,355
java
package com.unitedlearningacademy.TutorialPlugin; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class PlayerCooldownManager { public static class Cooldown { long startDatetime; long endDatetime; public Cooldown(long start, long end) { this.startDatetime = start; this.endDatetime = end; } public Cooldown(long time) { long now = new Date().getTime(); startDatetime = now; endDatetime = now + time; } public long duration() { return endDatetime - startDatetime; } public static Cooldown none() { return new Cooldown(0, 0); } public static Cooldown longest(Cooldown... cooldowns) { return Arrays.asList(cooldowns).stream().max(Comparator.comparing(c -> c.endDatetime)).get(); } } Map<ItemCooldownKey, Cooldown> itemSpecificCooldowns; Map<UUID, Cooldown> playerCooldowns; Map<UUID, CooldownBossBar> bossBars; public JavaPlugin plugin; public PlayerCooldownManager(JavaPlugin plugin) { itemSpecificCooldowns = new HashMap<>(); playerCooldowns = new HashMap<>(); bossBars = new HashMap<>(); this.plugin = plugin; } CooldownBossBar getBossBar(Player player) { CooldownBossBar bb; if (!bossBars.containsKey(player.getUniqueId())) { bb = new CooldownBossBar(this, player); bossBars.put(player.getUniqueId(), bb); } else { bb = bossBars.get(player.getUniqueId()); } return bb; } public void useItem(Player player, UseableItem item) { setPlayerCooldown(player, item.getPlayerCooldown()); itemSpecificCooldowns.put(new ItemCooldownKey(player, item), new Cooldown(item.getItemCooldown())); getBossBar(player).useItem(item); } public void setPlayerCooldown(Player player, long cooldown) { setPlayerCooldown(player, cooldown, false); } public void setPlayerCooldown(Player player, long cooldown, boolean force) { Cooldown newCooldown = new Cooldown(cooldown); if (newCooldown.endDatetime > getCooldown(player).endDatetime || force) { playerCooldowns.put(player.getUniqueId(), new Cooldown(cooldown)); } } /** * Gets a player's {@link Cooldown}. * @param player The player to query the cooldown of * @return The Cooldown object */ public Cooldown getCooldown(Player player) { UUID uuid = player.getUniqueId(); return playerCooldowns.containsKey(uuid) ? playerCooldowns.get(uuid) : Cooldown.none(); } /** * Gets a player's cooldown for an item, taking into account both player and item cooldowns. * @param player The player to query the cooldown of * @param item The item to query the item-specific cooldown of * @return The {@link Cooldown} with the greater {@link Cooldown#endDatetime} */ public Cooldown getCooldown(Player player, UseableItem item) { ItemCooldownKey key = item != null && player != null ? new ItemCooldownKey(player, item) : null; Cooldown itemCooldown = key != null && itemSpecificCooldowns.containsKey(key) ? itemSpecificCooldowns.get(key) : Cooldown.none(); return Cooldown.longest(itemCooldown, getCooldown(player)); } public boolean playerMayUseItem(Player player, UseableItem item) { long now = new Date().getTime(); return now > getCooldown(player, item).endDatetime; } }
9eec4378cd991ca5bf17154110824202204ff420
b09f518c08e930460e08309dc5f6dd5b1e6ff6de
/1086-synchronized/src/main/java/com/tuyrk/unit03/SynchronizedObjectCodeBlock2.java
e920cbd86706a067b99355689d11c469538a27b6
[]
no_license
tuyrk/learn-imooc
087c185d9fa50b39f73b29b44bc281f03f5e5ccf
99040f6fca437ecf36eaaaf21447a92c5f2eb0ec
refs/heads/master
2022-11-04T12:36:15.671227
2020-11-22T12:07:03
2020-11-22T12:07:03
219,886,876
1
1
null
2022-10-05T19:37:44
2019-11-06T01:38:53
Java
UTF-8
Java
false
false
1,451
java
package com.tuyrk.unit03; /** * 对象锁示例1,代码块形式 */ public class SynchronizedObjectCodeBlock2 implements Runnable { private static SynchronizedObjectCodeBlock2 instance = new SynchronizedObjectCodeBlock2(); private Object lock1 = new Object(); private Object lock2 = new Object(); public static void main(String[] args) { Thread t1 = new Thread(instance); Thread t2 = new Thread(instance); t1.start(); t2.start(); while (t1.isAlive() || t2.isAlive()) { } System.out.println("finished"); } @Override public void run() { synchronized (lock1) { System.out.println("我是对象锁的代码块形式-lock1。我叫" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ",lock1-运行结束。"); } synchronized (lock2) { System.out.println("我是对象锁的代码块形式-lock2。我叫" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ",lock2-运行结束。"); } } }
c40706afe997ea647dcd81a0df2c4b4f2f87fcc7
4d97a8ec832633b154a03049d17f8b58233cbc5d
/Math/81/Math/evosuite-branch/5/org/apache/commons/math/linear/EigenDecompositionImplEvoSuite_branch_Test.java
c1b4450441350a86afaa5a7b94864d4e98ca3a55
[]
no_license
4open-science/evosuite-defects4j
be2d172a5ce11e0de5f1272a8d00d2e1a2e5f756
ca7d316883a38177c9066e0290e6dcaa8b5ebd77
refs/heads/master
2021-06-16T18:43:29.227993
2017-06-07T10:37:26
2017-06-07T10:37:26
93,623,570
2
1
null
null
null
null
UTF-8
Java
false
false
58,666
java
/* * This file was automatically generated by EvoSuite * Thu Dec 11 20:10:36 GMT 2014 */ package org.apache.commons.math.linear; import static org.junit.Assert.*; import org.junit.Test; import org.apache.commons.math.linear.Array2DRowRealMatrix; import org.apache.commons.math.linear.ArrayRealVector; import org.apache.commons.math.linear.DecompositionSolver; import org.apache.commons.math.linear.EigenDecompositionImpl; import org.apache.commons.math.linear.InvalidMatrixException; import org.apache.commons.math.linear.OpenMapRealMatrix; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealVector; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.EvoSuiteFile; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, resetStaticState = true) public class EigenDecompositionImplEvoSuite_branch_Test extends EigenDecompositionImplEvoSuite_branch_Test_scaffolding { @Test public void test00() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = double0; double double1 = 1240.172195104401; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray0[0] = double1; doubleArray1[3] = double0; doubleArray1[4] = double0; doubleArray1[5] = double0; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1240.172195104401, 1240.172195104401, (-1.0), (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {1240.172195104401, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(6.902270600355946E26, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getV(); assertArrayEquals(new double[] {1240.172195104401, 1240.172195104401, (-1.0), (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {1240.172195104401, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(6.902270600355946E26, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test01() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double1 = 1240.1721951044; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray1[2] = double1; doubleArray1[3] = double0; doubleArray1[4] = double0; doubleArray1[5] = double0; double double2 = (-639.4404141452073); doubleArray0[5] = double2; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, (-639.4404141452073), 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {1240.1721951044, 1240.1721951044, 1240.1721951044, (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(2.3645438025403433E12, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test02() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double1 = 1240.1721951044; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray1[2] = double1; doubleArray1[3] = double0; doubleArray1[4] = double0; doubleArray1[5] = double0; double double2 = (-639.4404141452073); doubleArray0[5] = double2; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1240.1721951044, 1240.1721951044, 1240.1721951044, (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, (-639.4404141452073), 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(2.365527279184785E12, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test03() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = double0; double double1 = 1239.4; doubleArray1[1] = double1; doubleArray1[3] = double0; doubleArray1[4] = double0; doubleArray1[5] = double0; double double2 = (-639.4404141452073); doubleArray1[2] = double2; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 1239.4, (-639.4404141452073), (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test04() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[1] = double0; doubleArray1[2] = double0; doubleArray1[3] = double0; double double1 = (-3009.817707219683); doubleArray1[4] = double1; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[2]); assertArrayEquals(new double[] {0.0, (-1.0), (-1.0), (-1.0), (-3009.817707219683), 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test05() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = doubleArray0[0]; double double1 = 1316.6698110017353; doubleArray1[3] = doubleArray1[2]; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray0[0] = double1; doubleArray1[4] = double0; doubleArray1[5] = double0; double double2 = (-647.3134674392506); doubleArray0[5] = double2; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1316.6698110017353, 1316.6698110017353, (-1.0), (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {1316.6698110017353, 0.0, 0.0, 0.0, 0.0, (-647.3134674392506), 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(1.4775622483077373E12, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test06() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = doubleArray0[0]; doubleArray1[3] = doubleArray1[2]; doubleArray1[0] = doubleArray1[3]; doubleArray1[1] = double0; double double1 = (-279.49881691); doubleArray1[2] = double1; doubleArray1[3] = double1; doubleArray1[4] = doubleArray1[2]; doubleArray1[5] = double0; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {(-1.0), (-1.0), (-279.49881691), (-279.49881691), (-279.49881691), (-1.0), (-279.49881691)}, doubleArray1, 0.01); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals((-2.7475985117843296E19), eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test07() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = doubleArray0[0]; double double1 = 1316.6698110017353; doubleArray1[3] = doubleArray1[2]; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray1[4] = double0; doubleArray1[5] = double0; double double2 = (-647.3134674392506); doubleArray0[5] = double2; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, (-647.3134674392506), 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {1316.6698110017353, 1316.6698110017353, (-1.0), (-1.0), (-1.0), (-1.0), (-1.0)}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals((-1.1204615599487748E9), eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test08() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double1 = 1240.172195104401; doubleArray1[1] = double1; double double2 = (-279.0); doubleArray1[2] = double2; doubleArray1[3] = double2; doubleArray1[4] = double1; doubleArray1[5] = double0; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 1240.172195104401, (-279.0), (-279.0), 1240.172195104401, (-1.0), (-279.0)}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test09() throws Throwable { double[] doubleArray0 = new double[6]; double double0 = 849.4371651739608; doubleArray0[0] = double0; double double1 = 1.0; doubleArray0[3] = double1; double double2 = 0.0; doubleArray0[1] = double1; doubleArray0[2] = doubleArray0[0]; double double3 = 0.5; doubleArray0[0] = double2; double double4 = 1.7272275883635901; doubleArray0[5] = double4; double[] doubleArray1 = new double[5]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[0] = double1; doubleArray1[1] = double3; doubleArray1[2] = double4; doubleArray1[3] = double3; doubleArray1[4] = double4; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[0]); assertArrayEquals(new double[] {1.0, 0.5, 1.7272275883635901, 0.5, 1.7272275883635901}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 1.0, 849.4371651739608, 1.0, 0.0, 1.7272275883635901}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(2892.031414375631, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test10() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double1 = 1240.1721951044; doubleArray1[0] = double1; doubleArray1[1] = double0; doubleArray1[5] = double1; doubleArray1[2] = double1; doubleArray1[3] = double0; doubleArray1[4] = double0; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1240.1721951044, (-1.0), 1240.1721951044, (-1.0), (-1.0), 1240.1721951044, (-1.0)}, doubleArray1, 0.01); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(2.365527278734591E12, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test11() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = double0; double double1 = 1240.172195104401; doubleArray1[3] = doubleArray1[2]; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray0[0] = double1; doubleArray1[4] = double0; doubleArray1[5] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1240.172195104401, 1240.172195104401, (-1.0), (-1.0), (-1.0), (-1.0), 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {1240.172195104401, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test12() throws Throwable { double[] doubleArray0 = new double[10]; double double0 = 0.5; double double1 = (-934.58734); doubleArray0[2] = double1; double double2 = 3162.9987232564677; doubleArray0[5] = double2; double double3 = 1.0E-11; double[] doubleArray1 = new double[9]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[1] = doubleArray0[2]; doubleArray1[5] = double0; doubleArray1[0] = double2; doubleArray1[2] = double1; doubleArray1[3] = double3; doubleArray1[4] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[2]); assertArrayEquals(new double[] {0.0, 0.0, (-934.58734), 0.0, 0.0, 3162.9987232564677, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {3162.9987232564677, (-934.58734), (-934.58734), 1.0E-11, 0.5, 0.5, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test13() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double1 = 1240.172195104401; doubleArray1[4] = double0; doubleArray1[0] = double0; double double2 = 1.0E-11; doubleArray1[1] = double2; doubleArray1[2] = double0; doubleArray1[3] = double1; doubleArray1[5] = double0; doubleArray1[6] = doubleArray1[3]; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {(-1.0), 1.0E-11, (-1.0), 1240.172195104401, (-1.0), (-1.0), 1240.172195104401}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals((-1.3614666245257476E7), eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test14() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = 2.2250738585072014E-308; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = double0; doubleArray1[1] = double0; doubleArray1[3] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 2.2250738585072014E-308, 2.2250738585072014E-308, 2.2250738585072014E-308, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test15() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = doubleArray0[0]; double double1 = 1316.6698110017353; doubleArray1[3] = doubleArray1[2]; doubleArray1[0] = double1; doubleArray1[1] = double1; doubleArray1[4] = double0; doubleArray1[5] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {1316.6698110017353, 1316.6698110017353, (-1.0), (-1.0), (-1.0), (-1.0), 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test16() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[0] = double0; double double1 = 1.0E-11; doubleArray1[1] = double1; doubleArray1[2] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {(-1.0), 1.0E-11, (-1.0), 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(Double.NaN, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test17() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[0] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[2] = double0; doubleArray1[4] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, (-1.0), 0.0, (-1.0), 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getD(); assertArrayEquals(new double[] {0.0, 0.0, (-1.0), 0.0, (-1.0), 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); EigenDecompositionImpl eigenDecompositionImpl1 = null; try { eigenDecompositionImpl1 = new EigenDecompositionImpl((RealMatrix) array2DRowRealMatrix0, doubleArray1[2]); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // cannot solve degree 3 equation // } } @Test public void test18() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); doubleArray0[4] = double0; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[1] = double0; doubleArray1[3] = double0; doubleArray1[4] = double0; double double1 = (-3009.817707219683); doubleArray1[5] = double1; doubleArray1[6] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, (-1.0), 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, (-1.0), 0.0, (-1.0), (-1.0), (-3009.817707219683), (-1.0)}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getD(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, (-1.0), 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, (-1.0), 0.0, (-1.0), (-1.0), (-3009.817707219683), (-1.0)}, doubleArray1, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl1 = new EigenDecompositionImpl((RealMatrix) array2DRowRealMatrix0, doubleArray0[4]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, (-1.0), 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, (-1.0), 0.0, (-1.0), (-1.0), (-3009.817707219683), (-1.0)}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl1); assertEquals(-0.0, eigenDecompositionImpl1.getDeterminant(), 0.01D); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertFalse(eigenDecompositionImpl1.equals((Object)eigenDecompositionImpl0)); assertFalse(eigenDecompositionImpl0.equals((Object)eigenDecompositionImpl1)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(eigenDecompositionImpl1, eigenDecompositionImpl0); assertNotSame(eigenDecompositionImpl0, eigenDecompositionImpl1); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test19() throws Throwable { double[] doubleArray0 = new double[2]; double[] doubleArray1 = new double[3]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double0 = 0.0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray1, doubleArray0, double0); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); DecompositionSolver decompositionSolver0 = eigenDecompositionImpl0.getSolver(); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0}, doubleArray0, 0.01); assertNotNull(decompositionSolver0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(false, decompositionSolver0.isNonSingular()); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); DecompositionSolver decompositionSolver1 = eigenDecompositionImpl0.getSolver(); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0}, doubleArray0, 0.01); assertNotNull(decompositionSolver1); assertEquals(false, decompositionSolver1.isNonSingular()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(decompositionSolver1.equals((Object)decompositionSolver0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(decompositionSolver1, decompositionSolver0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test20() throws Throwable { double[] doubleArray0 = new double[7]; int int0 = 3; OpenMapRealMatrix openMapRealMatrix0 = new OpenMapRealMatrix(int0, int0); assertNotNull(openMapRealMatrix0); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl((RealMatrix) openMapRealMatrix0, doubleArray0[4]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); double double0 = eigenDecompositionImpl0.getDeterminant(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertEquals(0.0, double0, 0.01D); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); } @Test public void test21() throws Throwable { double[] doubleArray0 = new double[7]; int int0 = 3; OpenMapRealMatrix openMapRealMatrix0 = new OpenMapRealMatrix(int0, int0); assertNotNull(openMapRealMatrix0); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl((RealMatrix) openMapRealMatrix0, doubleArray0[4]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getVT(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(true, openMapRealMatrix0.isSquare()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(3, array2DRowRealMatrix0.getRowDimension()); assertEquals(3, array2DRowRealMatrix0.getColumnDimension()); assertEquals(true, array2DRowRealMatrix0.isSquare()); try { RealVector realVector0 = eigenDecompositionImpl0.getEigenvector(int0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 3 // } } @Test public void test22() throws Throwable { double[] doubleArray0 = new double[6]; double[] doubleArray1 = new double[5]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[0]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); int int0 = 0; ArrayRealVector arrayRealVector0 = (ArrayRealVector)eigenDecompositionImpl0.getEigenvector(int0); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(arrayRealVector0); assertEquals(false, arrayRealVector0.isInfinite()); assertEquals(6, arrayRealVector0.getDimension()); assertEquals(Double.NaN, arrayRealVector0.getLInfNorm(), 0.01D); assertEquals(Double.NaN, arrayRealVector0.getNorm(), 0.01D); assertEquals(true, arrayRealVector0.isNaN()); assertEquals(Double.NaN, arrayRealVector0.getL1Norm(), 0.01D); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getVT(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(6, array2DRowRealMatrix0.getRowDimension()); assertEquals(6, array2DRowRealMatrix0.getColumnDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test23() throws Throwable { double[] doubleArray0 = new double[6]; double[] doubleArray1 = new double[5]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[0]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getVT(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(6, array2DRowRealMatrix0.getColumnDimension()); assertEquals(6, array2DRowRealMatrix0.getRowDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); Array2DRowRealMatrix array2DRowRealMatrix1 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getVT(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(array2DRowRealMatrix1); assertEquals(6, array2DRowRealMatrix1.getColumnDimension()); assertEquals(true, array2DRowRealMatrix1.isSquare()); assertEquals(6, array2DRowRealMatrix1.getRowDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertSame(array2DRowRealMatrix1, array2DRowRealMatrix0); assertNotSame(doubleArray1, doubleArray0); } @Test public void test24() throws Throwable { double[] doubleArray0 = new double[6]; double[] doubleArray1 = new double[5]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[0]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getD(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(6, array2DRowRealMatrix0.getRowDimension()); assertEquals(6, array2DRowRealMatrix0.getColumnDimension()); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); Array2DRowRealMatrix array2DRowRealMatrix1 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getD(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(array2DRowRealMatrix1); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(6, array2DRowRealMatrix1.getRowDimension()); assertEquals(6, array2DRowRealMatrix1.getColumnDimension()); assertEquals(true, array2DRowRealMatrix1.isSquare()); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertSame(array2DRowRealMatrix1, array2DRowRealMatrix0); assertNotSame(doubleArray1, doubleArray0); } @Test public void test25() throws Throwable { double[] doubleArray0 = new double[6]; double double0 = 849.4371651739608; double[] doubleArray1 = new double[5]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, double0); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); int int0 = 0; ArrayRealVector arrayRealVector0 = (ArrayRealVector)eigenDecompositionImpl0.getEigenvector(int0); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(arrayRealVector0); assertEquals(true, arrayRealVector0.isNaN()); assertEquals(Double.NaN, arrayRealVector0.getLInfNorm(), 0.01D); assertEquals(false, arrayRealVector0.isInfinite()); assertEquals(6, arrayRealVector0.getDimension()); assertEquals(Double.NaN, arrayRealVector0.getL1Norm(), 0.01D); assertEquals(Double.NaN, arrayRealVector0.getNorm(), 0.01D); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getV(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(6, array2DRowRealMatrix0.getColumnDimension()); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(6, array2DRowRealMatrix0.getRowDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test26() throws Throwable { double[] doubleArray0 = new double[8]; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getV(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix1 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getV(); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix1); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertEquals(8, array2DRowRealMatrix1.getRowDimension()); assertEquals(true, array2DRowRealMatrix1.isSquare()); assertEquals(8, array2DRowRealMatrix1.getColumnDimension()); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertSame(array2DRowRealMatrix1, array2DRowRealMatrix0); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test27() throws Throwable { double[] doubleArray0 = new double[8]; double double0 = (-1.0); double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); doubleArray1[0] = double0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); Array2DRowRealMatrix array2DRowRealMatrix0 = (Array2DRowRealMatrix)eigenDecompositionImpl0.getV(); assertArrayEquals(new double[] {(-1.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(array2DRowRealMatrix0); assertEquals(8, array2DRowRealMatrix0.getRowDimension()); assertEquals(true, array2DRowRealMatrix0.isSquare()); assertEquals(8, array2DRowRealMatrix0.getColumnDimension()); assertEquals(-0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); EigenDecompositionImpl eigenDecompositionImpl1 = null; try { eigenDecompositionImpl1 = new EigenDecompositionImpl((RealMatrix) array2DRowRealMatrix0, doubleArray0[5]); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // eigen decomposition of assymetric matrices not supported yet // } } @Test public void test28() throws Throwable { double[] doubleArray0 = new double[10]; double[] doubleArray1 = new double[9]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray0[1]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); int int0 = 0; double double0 = eigenDecompositionImpl0.getRealEigenvalue(int0); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertEquals(0.0, double0, 0.01D); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test29() throws Throwable { double[] doubleArray0 = new double[7]; int int0 = 3; OpenMapRealMatrix openMapRealMatrix0 = new OpenMapRealMatrix(int0, int0); assertNotNull(openMapRealMatrix0); assertEquals(true, openMapRealMatrix0.isSquare()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl((RealMatrix) openMapRealMatrix0, doubleArray0[4]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(true, openMapRealMatrix0.isSquare()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); double[] doubleArray1 = eigenDecompositionImpl0.getRealEigenvalues(); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertNotNull(doubleArray1); assertEquals(true, openMapRealMatrix0.isSquare()); assertEquals(3, openMapRealMatrix0.getRowDimension()); assertEquals(3, openMapRealMatrix0.getColumnDimension()); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); } @Test public void test30() throws Throwable { double[] doubleArray0 = new double[8]; double[] doubleArray1 = new double[7]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray0, doubleArray1, doubleArray1[3]); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); int int0 = 0; double double0 = eigenDecompositionImpl0.getImagEigenvalue(int0); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, doubleArray1, 0.01); assertEquals(0.0, double0, 0.01D); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray1, doubleArray0); } @Test public void test31() throws Throwable { double[] doubleArray0 = new double[2]; double[] doubleArray1 = new double[3]; assertFalse(doubleArray1.equals((Object)doubleArray0)); assertNotSame(doubleArray1, doubleArray0); double double0 = 0.0; EigenDecompositionImpl eigenDecompositionImpl0 = new EigenDecompositionImpl(doubleArray1, doubleArray0, double0); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0}, doubleArray0, 0.01); assertNotNull(eigenDecompositionImpl0); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray0, doubleArray1); double[] doubleArray2 = eigenDecompositionImpl0.getImagEigenvalues(); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray1, 0.01); assertArrayEquals(new double[] {0.0, 0.0}, doubleArray0, 0.01); assertArrayEquals(new double[] {0.0, 0.0, 0.0}, doubleArray2, 0.01); assertNotNull(doubleArray2); assertEquals(0.0, eigenDecompositionImpl0.getDeterminant(), 0.01D); assertFalse(doubleArray1.equals((Object)doubleArray0)); assertFalse(doubleArray1.equals((Object)doubleArray2)); assertFalse(doubleArray0.equals((Object)doubleArray2)); assertFalse(doubleArray0.equals((Object)doubleArray1)); assertFalse(doubleArray2.equals((Object)doubleArray0)); assertFalse(doubleArray2.equals((Object)doubleArray1)); assertNotSame(doubleArray1, doubleArray0); assertNotSame(doubleArray1, doubleArray2); assertNotSame(doubleArray0, doubleArray2); assertNotSame(doubleArray0, doubleArray1); assertNotSame(doubleArray2, doubleArray0); assertNotSame(doubleArray2, doubleArray1); } }
b1f6801c4649a65a48893b2debbab40e8b74f41a
5afdc998aa45d5ba7201ac41e958a349e6aef485
/app/src/main/java/com/furiouskitten/amiel/solidarity/Activities/UbcvThreeChaptersActivity.java
120489a0e16fbd25bb94de150f34065fdb7af4fd
[]
no_license
Awiello/Solidarity
e563deaf4f034efa70d53e910c42fa2150f760e0
b67d01c56b90042e5e2a466126557ada8ba09321
refs/heads/master
2020-06-30T15:10:28.114903
2019-08-06T14:30:24
2019-08-06T14:30:24
200,867,133
0
0
null
null
null
null
UTF-8
Java
false
false
6,985
java
package com.furiouskitten.amiel.solidarity.Activities; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.widget.CardView; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.blogspot.atifsoftwares.animatoolib.Animatoo; import com.furiouskitten.amiel.solidarity.Adapters.UbcvThreeAdapters; import com.furiouskitten.amiel.solidarity.Adapters.UbcvTwoAdapters; import com.furiouskitten.amiel.solidarity.Authentication.LoginActivity; import com.furiouskitten.amiel.solidarity.DictionaryMainActivity; import com.furiouskitten.amiel.solidarity.Models.UbcvOneChaptersModel; import com.furiouskitten.amiel.solidarity.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; public class UbcvThreeChaptersActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { //Firebase FirebaseAuth mAuth; FirebaseUser currentUser; List<UbcvOneChaptersModel> mUbcvOneModels; Animation fadeInAnim; CardView bigTextBgCardView; TextView bigText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ubcv_three_chapters); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("UBCV 103 Chapters"); mAuth = FirebaseAuth.getInstance(); currentUser = mAuth.getCurrentUser(); fadeInAnim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.button_animation_two); //textxs bigTextBgCardView = findViewById(R.id.chapterBigTextBg); bigText = findViewById(R.id.chapterBigText); //Start RecyclerView mUbcvOneModels = new ArrayList<>(); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.loveofwisdom, "Introduction To Love of Wisdom")); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.wisdom, "Chapter 2: Definition of Wisdom")); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.learning, "Chapter 3: Principles of Learning and Thinking")); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.asdasdasasdsadaww, "Chapter 4: The Library")); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.studyhabits, "Chapter 5: Study Habits")); mUbcvOneModels.add(new UbcvOneChaptersModel(R.drawable.lifelonglearning, "Chapter 6: Lifelong Learning")); RecyclerView myUbcvRecyclerView = findViewById(R.id.ubcvOneRecyclerView); UbcvThreeAdapters myUbcvOneAdapter = new UbcvThreeAdapters(this, mUbcvOneModels); myUbcvRecyclerView.setLayoutManager(new GridLayoutManager(this, 1)); myUbcvRecyclerView.setAdapter(myUbcvOneAdapter); bigTextBgCardView.startAnimation(fadeInAnim); bigText.startAnimation(fadeInAnim); myUbcvRecyclerView.startAnimation(fadeInAnim); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); updateNavHeader(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.ubcv_three_chapters, menu); 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { startActivity(new Intent(this, BookHomeActivity.class)); Animatoo.animateFade(this); finish(); } else if (id == R.id.nav_gallery){ startActivity(new Intent(this, DictionaryMainActivity.class)); Animatoo.animateFade(this); finish(); } else if (id == R.id.nav_send) { FirebaseAuth.getInstance().signOut(); Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class); startActivity(loginActivity); finish(); } else if (id == R.id.nav_main){ startActivity(new Intent(this, MainMenuActivity.class)); Animatoo.animateFade(this); finish(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void updateNavHeader(){ NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); View headerView = navigationView.getHeaderView(0); TextView navUserMail = headerView.findViewById(R.id.bookMenuDrawerEmail); ImageView navUserPhoto = headerView.findViewById(R.id.bookMenuDrawerImageView); navUserMail.setText(currentUser.getEmail()); String photo = String.valueOf(currentUser.getPhotoUrl()); Picasso.get().load(photo).into(navUserPhoto); } }
c0b7156b44b21129d753cb634d3309be3ae6b542
2eee2ee1add568484d410aa301b64395c6066e8c
/app/src/main/java/com/example/minglishmantra_beta/Fragment/BlankFragment.java
c2239006f445de933aadc34b29086df15cc236a8
[]
no_license
git1998/MyTuation-App
1351be43a1775d03ac51e9d78907af024a81de6a
f41a46db8da8749d403c5179d8a94ca1c460d62a
refs/heads/main
2023-01-31T13:44:56.015054
2020-12-16T11:58:45
2020-12-16T11:58:45
321,900,104
0
0
null
null
null
null
UTF-8
Java
false
false
729
java
package com.example.minglishmantra_beta.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.minglishmantra_beta.R; public class BlankFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.blank_fragment, container, false); getActivity().finish(); return view; } }
ad9387b0d7fd33c1e7f55fddd10b1807500c161c
638a4cad6a796ca0687957f9b504e54467f4c5c2
/ch04/src/woontaek/P3.java
d86fe12f3d3f64911b5abdcbd5bcf7f42a4ced98
[]
no_license
ohwoonteak/work_java
b8bb920762856ad28b6829938f63a137b9204d7c
e5040a71bda51bb7d9aa837da59567efdc10ca8a
refs/heads/master
2021-09-03T03:44:00.395220
2018-01-05T08:42:21
2018-01-05T08:42:21
115,475,088
0
0
null
null
null
null
UTF-8
Java
false
false
266
java
package woontaek; public class P3 { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 2; j <= 9; j++) { System.out.printf("%d * %d = %d \t", j, i, i * j); } System.out.println(); } } }
[ "KOITT@KOITT-PC02" ]
KOITT@KOITT-PC02
6891859fc3b676a907ce7a3ce359ee9799cc2c32
d8ee5c4f309efbdeb192f728ef30d1cc217d5883
/flume-ng-core/src/main/java/org/apache/flume/lifecycle/LifecycleSupervisor.java
bf16eafc53b0e19f43cacb3102e0e93c6e784621
[ "Apache-2.0", "LicenseRef-scancode-protobuf", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "BSD-2-Clause" ]
permissive
lizu18xz/flume-release-1.7.0
2d52b6fd85434cba113943212fb72eb12c5c2ee1
5844b7e740558c05ce8600ae84b53734fbe56564
refs/heads/master
2020-04-22T00:24:08.260288
2019-03-28T12:07:55
2019-03-28T12:07:55
169,978,496
0
0
null
null
null
null
UTF-8
Java
false
false
12,976
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.flume.lifecycle; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.flume.FlumeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; public class LifecycleSupervisor implements LifecycleAware { private static final Logger logger = LoggerFactory.getLogger(LifecycleSupervisor.class); private Map<LifecycleAware, Supervisoree> supervisedProcesses; private Map<LifecycleAware, ScheduledFuture<?>> monitorFutures; private ScheduledThreadPoolExecutor monitorService; private LifecycleState lifecycleState; private Purger purger; private boolean needToPurge; public LifecycleSupervisor() { lifecycleState = LifecycleState.IDLE; supervisedProcesses = new HashMap<LifecycleAware, Supervisoree>(); monitorFutures = new HashMap<LifecycleAware, ScheduledFuture<?>>(); monitorService = new ScheduledThreadPoolExecutor(10, new ThreadFactoryBuilder().setNameFormat( "lifecycleSupervisor-" + Thread.currentThread().getId() + "-%d") .build()); monitorService.setMaximumPoolSize(20); monitorService.setKeepAliveTime(30, TimeUnit.SECONDS); purger = new Purger(); needToPurge = false; } @Override public synchronized void start() { logger.info("Starting lifecycle supervisor {}", Thread.currentThread() .getId()); monitorService.scheduleWithFixedDelay(purger, 2, 2, TimeUnit.HOURS); lifecycleState = LifecycleState.START; logger.debug("Lifecycle supervisor started"); } @Override public synchronized void stop() { logger.info("Stopping lifecycle supervisor {}", Thread.currentThread() .getId()); if (monitorService != null) { monitorService.shutdown(); try { monitorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error("Interrupted while waiting for monitor service to stop"); } if (!monitorService.isTerminated()) { monitorService.shutdownNow(); try { while (!monitorService.isTerminated()) { monitorService.awaitTermination(10, TimeUnit.SECONDS); } } catch (InterruptedException e) { logger.error("Interrupted while waiting for monitor service to stop"); } } } for (final Entry<LifecycleAware, Supervisoree> entry : supervisedProcesses.entrySet()) { if (entry.getKey().getLifecycleState().equals(LifecycleState.START)) { entry.getValue().status.desiredState = LifecycleState.STOP; entry.getKey().stop(); } } /* If we've failed, preserve the error state. */ if (lifecycleState.equals(LifecycleState.START)) { lifecycleState = LifecycleState.STOP; } supervisedProcesses.clear(); monitorFutures.clear(); logger.debug("Lifecycle supervisor stopped"); } public synchronized void fail() { lifecycleState = LifecycleState.ERROR; } public synchronized void supervise(LifecycleAware lifecycleAware, SupervisorPolicy policy, LifecycleState desiredState) { if (this.monitorService.isShutdown() || this.monitorService.isTerminated() || this.monitorService.isTerminating()) { throw new FlumeException("Supervise called on " + lifecycleAware + " " + "after shutdown has been initiated. " + lifecycleAware + " will not" + " be started"); } Preconditions.checkState(!supervisedProcesses.containsKey(lifecycleAware), "Refusing to supervise " + lifecycleAware + " more than once"); if (logger.isDebugEnabled()) { logger.debug("Supervising service:{} policy:{} desiredState:{}", new Object[] { lifecycleAware, policy, desiredState }); } Supervisoree process = new Supervisoree(); process.status = new Status(); process.policy = policy; process.status.desiredState = desiredState; process.status.error = false; MonitorRunnable monitorRunnable = new MonitorRunnable(); monitorRunnable.lifecycleAware = lifecycleAware; monitorRunnable.supervisoree = process; monitorRunnable.monitorService = monitorService; supervisedProcesses.put(lifecycleAware, process); ScheduledFuture<?> future = monitorService.scheduleWithFixedDelay( monitorRunnable, 0, 3, TimeUnit.SECONDS); monitorFutures.put(lifecycleAware, future); } public synchronized void unsupervise(LifecycleAware lifecycleAware) { Preconditions.checkState(supervisedProcesses.containsKey(lifecycleAware), "Unaware of " + lifecycleAware + " - can not unsupervise"); logger.debug("Unsupervising service:{}", lifecycleAware); synchronized (lifecycleAware) { Supervisoree supervisoree = supervisedProcesses.get(lifecycleAware); supervisoree.status.discard = true; this.setDesiredState(lifecycleAware, LifecycleState.STOP); logger.info("Stopping component: {}", lifecycleAware); lifecycleAware.stop(); } supervisedProcesses.remove(lifecycleAware); //We need to do this because a reconfiguration simply unsupervises old //components and supervises new ones. monitorFutures.get(lifecycleAware).cancel(false); //purges are expensive, so it is done only once every 2 hours. needToPurge = true; monitorFutures.remove(lifecycleAware); } public synchronized void setDesiredState(LifecycleAware lifecycleAware, LifecycleState desiredState) { Preconditions.checkState(supervisedProcesses.containsKey(lifecycleAware), "Unaware of " + lifecycleAware + " - can not set desired state to " + desiredState); logger.debug("Setting desiredState:{} on service:{}", desiredState, lifecycleAware); Supervisoree supervisoree = supervisedProcesses.get(lifecycleAware); supervisoree.status.desiredState = desiredState; } @Override public synchronized LifecycleState getLifecycleState() { return lifecycleState; } public synchronized boolean isComponentInErrorState(LifecycleAware component) { return supervisedProcesses.get(component).status.error; } public static class MonitorRunnable implements Runnable { public ScheduledExecutorService monitorService; public LifecycleAware lifecycleAware; public Supervisoree supervisoree; @Override public void run() { logger.debug("checking process:{} supervisoree:{}", lifecycleAware, supervisoree); long now = System.currentTimeMillis(); try { if (supervisoree.status.firstSeen == null) { logger.debug("first time seeing {}", lifecycleAware); supervisoree.status.firstSeen = now; } supervisoree.status.lastSeen = now; synchronized (lifecycleAware) { if (supervisoree.status.discard) { // Unsupervise has already been called on this. logger.info("Component has already been stopped {}", lifecycleAware); return; } else if (supervisoree.status.error) { logger.info("Component {} is in error state, and Flume will not" + "attempt to change its state", lifecycleAware); return; } supervisoree.status.lastSeenState = lifecycleAware.getLifecycleState(); if (!lifecycleAware.getLifecycleState().equals( supervisoree.status.desiredState)) { logger.debug("Want to transition {} from {} to {} (failures:{})", new Object[] { lifecycleAware, supervisoree.status.lastSeenState, supervisoree.status.desiredState, supervisoree.status.failures }); switch (supervisoree.status.desiredState) { case START: try { logger.info("启动组件start...... : "+lifecycleAware.getClass().getSimpleName()); lifecycleAware.start(); } catch (Throwable e) { logger.error("Unable to start " + lifecycleAware + " - Exception follows.", e); if (e instanceof Error) { // This component can never recover, shut it down. supervisoree.status.desiredState = LifecycleState.STOP; try { lifecycleAware.stop(); logger.warn("Component {} stopped, since it could not be" + "successfully started due to missing dependencies", lifecycleAware); } catch (Throwable e1) { logger.error("Unsuccessful attempt to " + "shutdown component: {} due to missing dependencies." + " Please shutdown the agent" + "or disable this component, or the agent will be" + "in an undefined state.", e1); supervisoree.status.error = true; if (e1 instanceof Error) { throw (Error) e1; } // Set the state to stop, so that the conf poller can // proceed. } } supervisoree.status.failures++; } break; case STOP: try { lifecycleAware.stop(); } catch (Throwable e) { logger.error("Unable to stop " + lifecycleAware + " - Exception follows.", e); if (e instanceof Error) { throw (Error) e; } supervisoree.status.failures++; } break; default: logger.warn("I refuse to acknowledge {} as a desired state", supervisoree.status.desiredState); } if (!supervisoree.policy.isValid(lifecycleAware, supervisoree.status)) { logger.error( "Policy {} of {} has been violated - supervisor should exit!", supervisoree.policy, lifecycleAware); } } } } catch (Throwable t) { logger.error("Unexpected error", t); } logger.debug("Status check complete"); } } private class Purger implements Runnable { @Override public void run() { if (needToPurge) { monitorService.purge(); needToPurge = false; } } } public static class Status { public Long firstSeen; public Long lastSeen; public LifecycleState lastSeenState; public LifecycleState desiredState; public int failures; public boolean discard; public volatile boolean error; @Override public String toString() { return "{ lastSeen:" + lastSeen + " lastSeenState:" + lastSeenState + " desiredState:" + desiredState + " firstSeen:" + firstSeen + " failures:" + failures + " discard:" + discard + " error:" + error + " }"; } } public abstract static class SupervisorPolicy { abstract boolean isValid(LifecycleAware object, Status status); public static class AlwaysRestartPolicy extends SupervisorPolicy { @Override boolean isValid(LifecycleAware object, Status status) { return true; } } public static class OnceOnlyPolicy extends SupervisorPolicy { @Override boolean isValid(LifecycleAware object, Status status) { return status.failures == 0; } } } private static class Supervisoree { public SupervisorPolicy policy; public Status status; @Override public String toString() { return "{ status:" + status + " policy:" + policy + " }"; } } }
54d1519f761b03f628324fbef7c17461d50054a9
64f461a3afac0fc99594b9cc6c5b83c08c323269
/src/main/Main.java
4e768be11306aa23662abca591da29be26c83b99
[]
no_license
andresgabrielrc/M1SistemaClientes
de08d3622deab833ec9826c94abef892ef87eb01
c9b82afcd988a95379be0be1c294257a91818b94
refs/heads/main
2023-07-11T02:55:42.342065
2021-08-10T22:19:17
2021-08-10T22:19:17
394,790,960
0
0
null
null
null
null
UTF-8
Java
false
false
138
java
package main; public class Main { public static void main(String[] args) { Menu m = new Menu(); m.iniMenu(); } }
8a8c2cce173270a4977ee0ea33c3b4456609b14b
1ac29410cf0390609fa9fcaa56e4ec170d7913ba
/app/src/main/java/com/example/shika/message/ui/Sign_Up.java
02b24681af48a3d03fea55a980f8834e9cb0de80
[ "Unlicense" ]
permissive
ahmedmshaker/MessageApp
04fe0c18f7f387b675e996cc32a8df602f8ae16f
a994e10182a6e1f4fb6d52437cd0994b9ccd23ea
refs/heads/master
2022-01-15T12:19:14.638113
2015-09-20T14:17:29
2015-09-20T14:17:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,374
java
package com.example.shika.message.ui; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.example.shika.message.R; public class Sign_Up extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign__up); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new signUpFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_sign__up, menu); 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
f65db80d0744af0547d6f4fbe2dd4b8081bc0680
7fa9c6b0fa1d0726ae1cda0199716c811a1ea01b
/Crawler/data/Token.java
d6c54bde34690cffbabee9dcdfea1eeeeb15b805
[]
no_license
NayrozD/DD2476-Project
b0ca75799793d8ced8d4d3ba3c43c79bb84a72c0
94dfb3c0a470527b069e2e0fd9ee375787ee5532
refs/heads/master
2023-03-18T04:04:59.111664
2021-03-10T15:03:07
2021-03-10T15:03:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
437
java
14 https://raw.githubusercontent.com/mjtb49/LattiCG/master/src/randomreverser/reversal/asm/Token.java package randomreverser.reversal.asm; public class Token { private final String text; private final int line; public Token(String text, int line) { this.text = text; this.line = line; } public String getText() { return text; } public int getLine() { return line; } }
5335cdea7bc412b5cc389dfe05521865875c719b
6ec42de9ea1aa86a41941207444650ca305a8c88
/lesson2/RelativeLayout/app/src/androidTest/java/edu/sirius/examples/android/relativelayout/ExampleInstrumentedTest.java
069508d26ec2ad9269ed389edad2dd33e0747eb1
[]
no_license
skvarovski/sirius_android
88cf19cc8eb2d6beb957f60a4884993d59697f41
00e9cb24ac520848b6de0b90cb6b7b55d1999a1e
refs/heads/master
2020-05-15T04:09:14.937859
2019-01-09T04:05:31
2019-01-09T04:05:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package edu.sirius.examples.android.relativelayout; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("edu.sirius.examples.android.relativelayout", appContext.getPackageName()); } }
5cec364e7d1f0f407f153faa741887e7a7129776
1edb528ff62988fe9f58f4ecdca9089ebe36155d
/app/src/main/java/com/example/mainactivity/dashActivity.java
6873650671bdc807d018b0263eb856e4640e0917
[]
no_license
Mayur2311/News
7d8d937bd14b4fb4a676af91f59442a03c672876
f868042586b822520cdb96dd145fbf70e1f47eac
refs/heads/master
2023-05-04T05:49:10.112474
2021-05-23T19:45:10
2021-05-23T19:45:10
368,980,988
0
0
null
null
null
null
UTF-8
Java
false
false
2,927
java
package com.example.mainactivity; import androidx.annotation.NonNull; 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.navigation.NavController; import androidx.navigation.Navigation; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.widget.Toast; import com.example.mainactivity.utils.NetworkCheck; import com.google.android.material.navigation.NavigationView; import com.google.firebase.auth.FirebaseAuth; public class dashActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { Toolbar toolbar; DrawerLayout drawerLayout; NavController navController; NavigationView navigationView; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash); firebaseAuth = FirebaseAuth.getInstance(); setupNavigation(); NetworkCheck networkCheck = new NetworkCheck(); if(!networkCheck.checkNetwork(this)) { Toast.makeText(getApplicationContext(), "No Internet", Toast.LENGTH_SHORT).show(); } } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { item.setCheckable(true); drawerLayout.closeDrawers(); int id =item.getItemId(); if (id == R.id.dashboard) { navController.navigate(R.id.dashboardFragment); }else if (id == R.id.logout) { firebaseAuth.signOut(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } return true; } public void setupNavigation() { toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); drawerLayout = findViewById(R.id.drawerDashLayout); navigationView = findViewById(R.id.navigationView); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); drawerLayout.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); navController = Navigation.findNavController(this, R.id.host_fragment); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); }else { super.onBackPressed(); } } }
fac74bece193a2ee757aa3a98b0c0c78c8efc160
73538e66350d577bcd02ece3b7d17e699fe85ec5
/src/main/java/guru/springframework/controllers/IndexController.java
a6e203ea2f4ceda2213a4aa4bf2b604334f0e4cd
[]
no_license
davidwightman/spring5-recipe-app
ed6e8e7009a5b78b416297490f4fc9fb271b88c9
305fba19ccc2396b7161452aa651c0a57a4ce3a7
refs/heads/master
2022-11-28T04:38:01.898646
2020-08-09T19:39:34
2020-08-09T19:39:34
277,807,567
0
0
null
2020-07-07T12:16:04
2020-07-07T12:16:04
null
UTF-8
Java
false
false
715
java
package guru.springframework.controllers; import guru.springframework.services.RecipeService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Slf4j @Controller public class IndexController { private final RecipeService recipeService; public IndexController(RecipeService recipeService) { this.recipeService = recipeService; } @RequestMapping({"", "/", "/index"}) public String getIndexPage(Model model) { log.debug("getting index page"); model.addAttribute("recipes", recipeService.getRecipes()); return "index"; } }
84023f5e9659a29f40e0c2326e3aee58588b7562
cd6815de58c0e324c327a055a34cd80706bb88c9
/spring-demo/src/main/java/cn/liuhp/anno/post/CustomBeanFactoryPostProcessor.java
9cd0624ebc6f8035e20e9f7b76585a037870d6c6
[]
no_license
Liuhp534/server-manager-central
4354f2d07ae575693a08ba24817b79f827afe263
60f8bfc9d35a9de1bd69996dde502130bf73b265
refs/heads/master
2022-12-21T22:49:00.731851
2022-04-29T13:05:09
2022-04-29T13:05:09
187,558,173
1
0
null
2022-12-16T10:37:30
2019-05-20T02:58:27
Java
UTF-8
Java
false
false
802
java
package cn.liuhp.anno.post; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.stereotype.Component; /** * @description: beanfactory后置处理器 * @author: liuhp534 * @create: 2020-02-07 14:23 */ @Component public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("进入自定义beanFactoryPostProcessor"); int beanCount = beanFactory.getBeanDefinitionCount(); System.out.println("beanCount = " + beanCount); } }
37b18b516ee1cce92cf6116daee3a1df3a5d7a83
111209d369157dbcca1d01056623c27f3cecc9d7
/CohesiveAppServer/CohesiveBackend/CohesiveBusiness-ejb/src/java/com/ibd/cohesive/app/business/teacher/summary/teacherleavemanagement/TeacherLeaveManagementBO.java
a0e42b938241bf67dca2fe4dc63de1aa0ff75653
[]
no_license
IBD-Technologies/NewGenEducationApp
d3c1768316c091ade0bda050fdfc1dfe66aa5070
7e27094a635782ebd8c0a940b614485c52fe63d3
refs/heads/master
2021-05-19T11:30:04.032333
2020-06-12T17:35:22
2020-06-12T17:35:22
251,661,845
0
0
null
null
null
null
UTF-8
Java
false
false
798
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ibd.cohesive.app.business.teacher.summary.teacherleavemanagement; /** * * @author DELL */ public class TeacherLeaveManagementBO { TeacherLeaveManagementFilter filter; TeacherLeaveManagementResult result[]; public TeacherLeaveManagementFilter getFilter() { return filter; } public void setFilter(TeacherLeaveManagementFilter filter) { this.filter = filter; } public TeacherLeaveManagementResult[] getResult() { return result; } public void setResult(TeacherLeaveManagementResult[] result) { this.result = result; } }
73e18559d02d36e2cd48cba8e0bb841ec89edbcd
a8127e945b4c719037866e1ec2eb42cd238687e1
/clinic.java
9cc0649b18ba462ae018e407a9c0bef2dec78f64
[]
no_license
darrinmwiley/Kattis-Solutions
efd638ad286582968dbad6cd7463783e8cf4ae1d
4ef7402e7e667a12400d2167c1a9a585b173fbe8
refs/heads/master
2021-07-31T20:51:48.617983
2021-07-29T22:41:20
2021-07-29T22:41:20
80,001,676
1
0
null
null
null
null
UTF-8
Java
false
false
3,854
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; public class clinic { StringTokenizer st; BufferedReader file; ArrayList<patient> list = new ArrayList<patient>(); HashSet<String> dead = new HashSet<String>(); PrintWriter pout; long T = 0; PriorityQueue<patient> que; public static void main(String[] args) throws Exception { new clinic().run(); } public void run() throws Exception { Comparator<patient> comp = new Comparator<patient>() { @Override public int compare(patient arg0, patient arg1) { return arg0.compare(arg1, T); } }; que = new PriorityQueue<patient>(comp); file = new BufferedReader(new InputStreamReader(System.in)); pout = new PrintWriter(System.out); int Q = nextInt(); long K = nextInt(); try { for(int i = 0;i<Q;i++) { int next = nextInt(); if(next == 1) { try { T = nextLong(); addPatient(new patient(T, next(), nextLong(), K)); }catch(Exception ex) {} } if(next == 2) { try { T = nextLong(); treatPatient(T); }catch(Exception ex){} } if(next == 3) { T = nextLong(); try { kill(next()); }catch(Exception ex) {} } } pout.flush(); }catch(Exception ex) {while(true) {}} } public void addPatient(patient p) { que.add(p); } public void treatPatient(long T) { while(true) { if(que.isEmpty()) { pout.println("doctor takes a break"); return; } patient first = que.poll(); if(!dead.contains(first.name)) { pout.println(first.name); return; } } } public void kill(String name) { dead.add(name); } /* 4 3 3 3 1 1 2 1 2 3 1 3 4 5 2 3 4 */ private class patient{ long S; long ArrivalTime; String name; long K; public patient(long A,String name, long S, long K) { this.S = S; this.ArrivalTime = A; this.name = name; this.K = K; } public long getPriority(long T) { return S + K*(T - ArrivalTime); } public int compare(patient p, long T) { int comp = Long.compare(p.getPriority(T), getPriority(T)); if(comp == 0) { return name.compareTo(p.name); } return comp; } public String toString() { return S+" "+name+" "+ArrivalTime; } } public void newst() { try { st = new StringTokenizer(file.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String readLine() throws IOException { return file.readLine(); } public String next() { if(st == null || !st.hasMoreTokens()) newst(); return st.nextToken(); } public int nextInt() { if(st == null || !st.hasMoreTokens()) newst(); return Integer.parseInt(st.nextToken()); } public long nextLong() { if(st == null || !st.hasMoreTokens()) newst(); return Long.parseLong(st.nextToken()); } }
8f3febe1ef5db1f6b140d8e907d04792b2be84e8
21e16c35caac040b51d77c22823f51616da5fcc4
/app/src/main/java/com/example/brainbeats/basicbb/HeadsetService.java
ec7f499a40bfc368c552d567c4988c9ce277076d
[]
no_license
BrainBeats/BasicBB
16c45846a3cc2d9a4e46d88e3e7a67165186c817
13130db944adbf0b402b56a40f4ae8c1ed420a9c
refs/heads/master
2021-01-09T20:26:43.239906
2016-06-16T07:57:37
2016-06-16T07:57:37
60,679,491
0
0
null
2016-06-09T08:12:05
2016-06-08T07:55:01
Java
UTF-8
Java
false
false
7,325
java
package com.example.brainbeats.basicbb; /** * Created by tdeframond on 31/05/16. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import com.emotiv.insight.IEdk; import com.emotiv.insight.IEdkErrorCode; import com.emotiv.insight.IEdk.IEE_DataChannel_t; import com.emotiv.insight.IEdk.IEE_Event_t; public class HeadsetService extends Activity { private static final int REQUEST_ENABLE_BT = 1; private BluetoothAdapter mBluetoothAdapter; private boolean lock = false; private boolean isEnablGetData = false; private boolean isEnableWriteFile = false; int userId; private BufferedWriter motion_writer; Button Start_button,Stop_button; IEE_DataChannel_t[] Channel_list = {IEE_DataChannel_t.IED_AF3, IEE_DataChannel_t.IED_T7,IEE_DataChannel_t.IED_Pz, IEE_DataChannel_t.IED_T8,IEE_DataChannel_t.IED_AF4}; String[] Name_Channel = {"AF3","T7","Pz","T8","AF4"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.headset_layout); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); if (!mBluetoothAdapter.isEnabled()) { if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } Start_button = (Button)findViewById(R.id.startbutton); Stop_button = (Button)findViewById(R.id.stopbutton); Start_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Log.e("FFTSample","Start Write File"); setDataFile(); isEnableWriteFile = true; } }); Stop_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Log.e("FFTSample","Stop Write File"); StopWriteFile(); isEnableWriteFile = false; } }); //Connect to emoEngine IEdk.IEE_EngineConnect(this,""); Thread processingThread=new Thread() { @Override public void run() { // TODO Auto-generated method stub super.run(); while(true) { try { handler.sendEmptyMessage(0); handler.sendEmptyMessage(1); if(isEnablGetData && isEnableWriteFile)handler.sendEmptyMessage(2); Thread.sleep(100); } catch (Exception ex) { ex.printStackTrace(); } } } }; processingThread.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: int state = IEdk.IEE_EngineGetNextEvent(); if (state == IEdkErrorCode.EDK_OK.ToInt()) { int eventType = IEdk.IEE_EmoEngineEventGetType(); userId = IEdk.IEE_EmoEngineEventGetUserId(); if(eventType == IEE_Event_t.IEE_UserAdded.ToInt()){ Log.e("SDK","User added"); IEdk.IEE_FFTSetWindowingType(userId, IEdk.IEE_WindowsType_t.IEE_BLACKMAN); isEnablGetData = true; } if(eventType == IEE_Event_t.IEE_UserRemoved.ToInt()){ Log.e("SDK","User removed"); isEnablGetData = false; } } break; case 1: int number = IEdk.IEE_GetInsightDeviceCount(); if(number != 0) { if(!lock){ lock = true; IEdk.IEE_ConnectInsightDevice(0); } } else lock = false; break; case 2: for(int i=0; i < Channel_list.length; i++) { double[] data = IEdk.IEE_GetAverageBandPowers(Channel_list[i]); if(data.length == 5){ try { motion_writer.write(Name_Channel[i] + ","); for(int j=0; j < data.length;j++) addData(data[j]); motion_writer.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } break; } } }; private void setDataFile() { try { String eeg_header = "Channel , Theta ,Alpha ,Low beta ,High beta , Gamma "; File root = Environment.getExternalStorageDirectory(); String file_path = root.getAbsolutePath()+ "/FFTSample/"; File folder=new File(file_path); if(!folder.exists()) { folder.mkdirs(); } motion_writer = new BufferedWriter(new FileWriter(file_path+"bandpowerValue.csv")); motion_writer.write(eeg_header); motion_writer.newLine(); } catch (Exception e) { Log.e("","Exception"+ e.getMessage()); } } private void StopWriteFile(){ try { motion_writer.flush(); motion_writer.close(); } catch (Exception e) { // TODO: handle exception } } /** * public void addEEGData(Double[][] eegs) Add EEG Data for write int the * EEG File * * * - double array of eeg data */ public void addData(double data) { if (motion_writer == null) { return; } String input = ""; input += (String.valueOf(data) + ","); try { motion_writer.write(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
cd5dcd6bc990276093795c3f966c41d367229b88
cb5c644324b964a811591825f2da1031a28b974a
/app/src/main/java/com/gwkj/qixiubaodian/obd/Utils/LoadFileModel.java
cc5e78c8a82cf67f7f0501156dce8ffdae9ac9cf
[]
no_license
carrotbo/GOBD
d804c5e939788d82943dea2d265a469c0ee34507
f66301243b866883dd776d7432beee2985d8b2ca
refs/heads/master
2020-05-30T21:15:59.706096
2019-06-04T07:31:05
2019-06-04T07:31:05
189,968,578
1
0
null
null
null
null
UTF-8
Java
false
false
821
java
package com.gwkj.qixiubaodian.obd.Utils; import android.text.TextUtils; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by 12457 on 2017/8/21. */ public class LoadFileModel { public static void loadPdfFile(String url, Callback<ResponseBody> callback) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://www.baidu.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); LoadFileApi mLoadFileApi = retrofit.create(LoadFileApi.class); if (!TextUtils.isEmpty(url)) { Call<ResponseBody> call = mLoadFileApi.loadPdfFile(url); call.enqueue(callback); } } }
a737ade27bcb9f8609bf9b6542ac64c83da573c4
bd11306a566da4fe60508619165e78ffdff8899b
/src/com/SwingDome/OuterClassEvent.java
cb9c272701db5eac78d62ddc3701965b9ce356df
[]
no_license
Andchenn/J_item
8ff0895a7dcd3ed8fd97ef8da8142963cc8b94d8
bf467479d1632615fc1fba6634e1ec232264519b
refs/heads/master
2020-03-17T03:05:26.929679
2018-05-13T08:40:52
2018-05-13T08:40:52
133,219,613
0
0
null
null
null
null
UTF-8
Java
false
false
1,109
java
package com.SwingDome; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /* * 外部类作为事件监听器 * */ public class OuterClassEvent extends JFrame implements ActionListener { JButton btn; public OuterClassEvent() { super("java监听事件"); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); btn = new JButton("点击"); btn.addActionListener(new OuterClass(this)); getContentPane().add(btn); setBounds(200, 200, 300, 160); setVisible(true); } public static void main(String[] args) { new OuterClassEvent(); } @Override public void actionPerformed(ActionEvent e) { Container c =getContentPane(); c.setBackground(Color.blue); } } /*外部类×××××××××××××××××××××××*/ class OuterClass implements ActionListener { OuterClassEvent oce; public OuterClass(OuterClassEvent oce) { this.oce = oce; } @Override public void actionPerformed(ActionEvent e) { Container c = new Container(); c.setBackground(Color.blue); } }
32bb2992bacab81feab7282f3361868e53ee75fc
19332dd9a8388944baa7ddbe8f0b397b7f1b1b46
/src/main/java/com/Nepian/LoginManager/Listener/PlayerDataLoad/LocationLoading.java
1b187248ef6b65ac54b7195486bb3273d17c3d3f
[]
no_license
Nepian/LoginManager
f78dc34f2b31b33e4965d9379148063ce3fac23d
8ea30e13746396f29d36fff608b78e7bdc269bfa
refs/heads/master
2021-01-10T15:52:40.530723
2015-11-15T11:34:36
2015-11-15T11:34:36
45,664,733
0
0
null
null
null
null
UTF-8
Java
false
false
955
java
package com.Nepian.LoginManager.Listener.PlayerDataLoad; import static com.Nepian.LoginManager.Configuration.Properties.*; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import com.Nepian.LoginManager.Configuration.Config; import com.Nepian.LoginManager.Events.PlayerDataLoadEvent; import com.Nepian.LoginManager.PlayerData.PlayerData; public class LocationLoading implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public static void onPlayerDataLoad(PlayerDataLoadEvent event) { if (!Config.PLAYERDATA__LOAD__LOCATION.getBoolean()) { return; } Player player = event.getPlayer(); PlayerData data = event.getPlayerData(); if (!data.hasData(PATH_LOCATION)) { data.setData(PATH_LOCATION, player.getLocation()); } else { player.teleport((Location) data.get(PATH_LOCATION)); } } }