blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52b73dd0cff0f98a1cd913214a36b561736910ff | 38d351508ff44be847656c5186168168fac4a5c6 | /src/test/java/org/hibernate/ogm/HikeQueryTest.java | 23d910515b1b73f7b70f47dbd4aae39e2a0a6392 | [
"Apache-2.0"
] | permissive | SergeyPoletaev/hibernate-ogm-gradle | 1e521eccee04e8a9ad3eff7edaf8666bcab1da31 | a726edc142c47fd4f05a45d11b847fe9bcbdc1d6 | refs/heads/master | 2021-05-17T16:07:23.435162 | 2020-03-29T06:19:36 | 2020-03-29T06:19:36 | 250,862,669 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,949 | java |
/*
package org.hibernate.ogm;
import static org.fest.assertions.Assertions.assertThat;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.lucene.search.Query;
import mainpack.Hike;
import mainpack.HikeSection;
import mainpack.Person;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.DatabaseRetrievalMethod;
import org.hibernate.search.query.ObjectLookupMethod;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HikeQueryTest {
private static EntityManagerFactory entityManagerFactory;
@BeforeClass
public static void setUpEntityManagerFactory() {
entityManagerFactory = Persistence.createEntityManagerFactory( "hikePu" );
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
// create a Person
Person bob = new Person( "Bob", "McRobb" );
// and two hikes
Hike cornwall = new Hike(
"Visiting Land's End", new Date(), new BigDecimal( "5.5" ),
new HikeSection( "Penzance", "Mousehole" ),
new HikeSection( "Mousehole", "St. Levan" ),
new HikeSection( "St. Levan", "Land's End" )
);
Hike isleOfWight = new Hike(
"Exploring Carisbrooke Castle", new Date(), new BigDecimal( "7.5" ),
new HikeSection( "Freshwater", "Calbourne" ),
new HikeSection( "Calbourne", "Carisbrooke Castle" )
);
// let Bob organize the two hikes
cornwall.setOrganizer( bob );
bob.getOrganizedHikes().add( cornwall );
isleOfWight.setOrganizer( bob );
bob.getOrganizedHikes().add( isleOfWight );
// persist organizer (will be cascaded to hikes)
entityManager.persist( bob );
entityManager.getTransaction().commit();
// get a new EM to make sure data is actually retrieved from the store and not Hibernate’s internal cache
entityManager.close();
}
@AfterClass
public static void closeEntityManagerFactory() {
entityManagerFactory.close();
}
@Test
public void canSearchUsingJPQLQuery() {
// Get a new entityManager
EntityManager entityManager = entityManagerFactory.createEntityManager();
// Start transaction
entityManager.getTransaction().begin();
// Find all the available hikes ordered by difficulty
List<Hike> hikes = entityManager.createQuery( "SELECT h FROM Hike h ORDER BY h.difficulty ASC" , Hike.class ).getResultList();
assertThat( hikes.size() ).isEqualTo( 2 );
assertThat( hikes ).onProperty( "description" ).containsExactly( "Visiting Land's End", "Exploring Carisbrooke Castle" );
entityManager.getTransaction().commit();
entityManager.close();
}
@Test
public void canSearchUsingNativeQuery() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
// Search for the hikes with a section that start from "Penzace" in MongoDB
List<Hike> hikes = entityManager
.createNativeQuery( "{ $query : { sections : { $elemMatch : { start: 'Penzance' } } } }", Hike.class )
.getResultList();
// Search for the hikes with a section that start from "Penzace" in Neo4j
// List<Hike> hikes = entityManager
// .createNativeQuery( " MATCH (h:Hike) - - (:Hike_sections {start: 'Penzance'} ) RETURN h", Hike.class )
// .getResultList();
assertThat( hikes ).onProperty( "description" ).containsOnly( "Visiting Land's End" );
entityManager.getTransaction().commit();
entityManager.close();
}
@Test
public void canSearchUsingFullTextQuery() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
//Add full-text superpowers to any EntityManager:
FullTextEntityManager ftem = Search.getFullTextEntityManager(entityManager);
// Optionally use the QueryBuilder to simplify Query definition:
QueryBuilder b = ftem.getSearchFactory().buildQueryBuilder().forEntity( Hike.class ).get();
// A lucene query to look for hike to the Carisbrooke castle:
// Note that the query looks for "cariboke" instead of "Carisbrooke"
Query lq = b.keyword().onField("description").matching("carisbroke castle").createQuery();
//Transform the Lucene Query in a JPA Query:
FullTextQuery ftQuery = ftem.createFullTextQuery(lq, Hike.class);
//This is a requirement when using Hibernate OGM instead of ORM:
ftQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID );
// List matching hikes
List<Hike> hikes = ftQuery.getResultList();
assertThat( hikes ).onProperty( "description" ).containsOnly( "Exploring Carisbrooke Castle" );
entityManager.getTransaction().commit();
entityManager.close();
}
}
*/
| [
"info.elekit@yandex.ru"
] | info.elekit@yandex.ru |
506a77a590b95321dae1daf168c592f5298f51b4 | 77633f79302a01cf5ea79122bc7fd08b39908ef8 | /CrazyChatParent/parent/group/src/main/java/com/crazychat/group/aop/AspectAuth.java | d4050da414bf5fb5268b165ead9a766764be29a6 | [] | no_license | sur1-123/CrazyChat | 238f5dae0df5e71ec73fa261c4702ba11c4f5702 | 828eda8c725a6e6a936af608b8b6ed038dbd71b2 | refs/heads/master | 2022-03-21T12:19:47.167302 | 2019-05-05T05:22:34 | 2019-05-05T05:22:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 807 | java | package com.crazychat.group.aop;
import com.crazychat.common.entity.StatusCode;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class AspectAuth {
/**
* 在执行之前检查权限
*/
@Before("execution(public * com.crazychat.group.controller.GroupController.auth*(..))")
public void before(JoinPoint point) {
// 获取request
HttpServletRequest request = (HttpServletRequest) point.getArgs()[0];
// 检查角色
if (null == request.getAttribute("claims_admin")) {
throw new RuntimeException(StatusCode.ACCESSERROR.getMsg());
}
}
}
| [
"jxin48598@gmail.com"
] | jxin48598@gmail.com |
827cd27cdcec8078a45397639192807f04061277 | 06f79b553e793f57519f578ae81e697aa6da7417 | /sardine/src/main/java/com/zhongjh/sardine/model/Propstat.java | 6089d96c64bb1b9170370e6982170ef381290d1c | [] | no_license | aaatttcccc/Lib | 14c1c33790bc689a72688d6068e1614e498407bb | 18d4590eff1e41fe5b7b07324022d04308667518 | refs/heads/master | 2021-08-07T00:27:01.123735 | 2021-05-27T10:17:23 | 2021-05-27T10:17:23 | 117,764,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,348 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.4-10/27/2009 06:09 PM(mockbuild)-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.12.23 at 06:27:19 PM PST
//
package com.zhongjh.sardine.model;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import java.lang.Error;
/**
* <p>Java class for anonymous complex type.</p>
*
* <p>The following schema fragment specifies the expected content contained within this class.</p>
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{DAV:}prop"/>
* <element ref="{DAV:}status"/>
* <element ref="{DAV:}error" minOccurs="0"/>
* <element ref="{DAV:}responsedescription" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@Root
@Namespace(prefix = "D", reference = "DAV:")
public class Propstat {
@Element
protected Prop prop;
@Element
protected String status;
@Element(required = false)
protected Error error;
@Element(required = false)
protected String responsedescription;
/**
* Gets the value of the prop property.
*
* @return
* possible object is
* {@link Prop }
*
*/
public Prop getProp() {
return prop;
}
/**
* Sets the value of the prop property.
*
* @param value
* allowed object is
* {@link Prop }
*
*/
public void setProp(Prop value) {
this.prop = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
/**
* Gets the value of the error property.
*
* @return
* possible object is
* {@link Error }
*
*/
public Error getError() {
return error;
}
/**
* Sets the value of the error property.
*
* @param value
* allowed object is
* {@link Error }
*
*/
public void setError(Error value) {
this.error = value;
}
/**
* Gets the value of the responsedescription property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getResponsedescription() {
return responsedescription;
}
/**
* Sets the value of the responsedescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setResponsedescription(String value) {
this.responsedescription = value;
}
}
| [
"254191389@qq.com"
] | 254191389@qq.com |
bcf941eb472c8360a585a90d50d58f117ff18e65 | 5bc9d8f92f38967cc9ecc03000c0606dbbb38f74 | /sca4j/modules/tags/sca4j-modules-parent-pom-0.1.5/extension/binding/sca4j-binding-jms/src/main/java/org/sca4j/binding/jms/runtime/lookup/destination/DestinationStrategy.java | ca2e1469c601ad180ceec78ef041e5f454e7a961 | [] | no_license | codehaus/service-conduit | 795332fad474e12463db22c5e57ddd7cd6e2956e | 4687d4cfc16f7a863ced69ce9ca81c6db3adb6d2 | refs/heads/master | 2023-07-20T00:35:11.240347 | 2011-08-24T22:13:28 | 2011-08-24T22:13:28 | 36,342,601 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,059 | java | /**
* SCA4J
* Copyright (c) 2009 - 2099 Service Symphony Ltd
*
* Licensed to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. A copy of the license
* is included in this distrubtion or you may obtain a copy at
*
* http://www.opensource.org/licenses/apache2.0.php
*
* 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.
*
* This project contains code licensed from the Apache Software Foundation under
* the Apache License, Version 2.0 and original code from project contributors.
*
*
* Original Codehaus Header
*
* Copyright (c) 2007 - 2008 fabric3 project contributors
*
* Licensed to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. A copy of the license
* is included in this distrubtion or you may obtain a copy at
*
* http://www.opensource.org/licenses/apache2.0.php
*
* 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.
*
* This project contains code licensed from the Apache Software Foundation under
* the Apache License, Version 2.0 and original code from project contributors.
*
* Original Apache Header
*
* Copyright (c) 2005 - 2006 The Apache Software Foundation
*
* Apache Tuscany is an effort undergoing incubation at The Apache Software
* Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is
* required of all newly accepted projects until a further review indicates that
* the infrastructure, communications, and decision making process have stabilized
* in a manner consistent with other successful ASF projects. While incubation
* status is not necessarily a reflection of the completeness or stability of the
* code, it does indicate that the project has yet to be fully endorsed by the ASF.
*
* This product includes software developed by
* The Apache Software Foundation (http://www.apache.org/).
*/
/*
* 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.sca4j.binding.jms.runtime.lookup.destination;
import java.util.Hashtable;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import org.sca4j.binding.jms.common.DestinationDefinition;
/**
* Strategy for looking up destinations.
*
* @version $Revsion$ $Date: 2008-03-17 21:24:49 +0000 (Mon, 17 Mar 2008) $
*
*/
public interface DestinationStrategy {
/**
* Gets the destination based on SCA JMS binding rules.
*
* @param definition Destination definition.
* @param cf Connection factory.
* @param env JNDI environment.
* @return Lokked up or created destination.
*/
Destination getDestination(DestinationDefinition definition, ConnectionFactory cf, Hashtable<String, String> env);
}
| [
"meerajk@15bcc2b3-4398-4609-aa7c-97eea3cd106e"
] | meerajk@15bcc2b3-4398-4609-aa7c-97eea3cd106e |
3bce27a718c087ba12dcafacc867ff96920e2c9a | 8f3a0488de57d02c121d3864f5bd31da3dcf12fb | /src/by/it/basumatarau/jd02_02/Goods.java | 2b410bbb8b4bd83c7c91b6d174618befe6ee37d6 | [] | no_license | aliashkov/JD2018-08-21 | 1ec80c0ca185e62c1bdb391bcb94bb86c14c439f | aaaa6821d302d9e9e0bb83c3920afd9eb99b269a | refs/heads/master | 2020-03-27T15:30:12.710891 | 2018-11-03T09:38:02 | 2018-11-03T09:38:02 | 146,722,183 | 1 | 0 | null | 2018-08-30T08:48:36 | 2018-08-30T08:48:36 | null | UTF-8 | Java | false | false | 525 | java | package by.it.basumatarau.jd02_02;
import java.util.HashMap;
class Goods {
private static HashMap<String, Double> merchantGoods = new HashMap<>();
static {
merchantGoods.put("tomatoes", 120.0);
merchantGoods.put("cucumbers", 100.0);
merchantGoods.put("alcohol", 140.0);
merchantGoods.put("potatoes", 200.0);
merchantGoods.put("bread", 80.0);
merchantGoods.put("salt", 60.0);
}
static HashMap<String, Double> getGoods(){
return merchantGoods;
}
}
| [
"basumatarau@gmail.com"
] | basumatarau@gmail.com |
5eb8cb39b5b50791c61625e5fe277ff60b981417 | 1ce6202f20367d2fb26f61488aacc2fad57dc697 | /src/main/java/com/fedex/pdsm/excel/ComparisonOfExcelSheets.java | f4187e85be4b4e6b60d14ceadbbe0108fe6d80fd | [] | no_license | naveenkankanala9/pdsm | a082fe76c69453b96a007e872ed43e913b93ecb0 | 16e5a6fea6fc53a1e12df9a80396c68d2689e0a3 | refs/heads/master | 2021-05-10T10:23:15.939937 | 2018-01-21T23:20:37 | 2018-01-21T23:20:37 | 118,381,342 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,613 | 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.fedex.pdsm.excel;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.sun.media.sound.InvalidFormatException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author s5216
*/
@SuppressWarnings("restriction")
public class ComparisonOfExcelSheets {
public JSONArray excelToJsonForSheet(String excelSheet, String colName) throws FileNotFoundException, IOException, InvalidFormatException, JSONException {
CSVReader reader = new CSVReader(new FileReader(excelSheet));
List<String[]> records = reader.readAll();
JSONArray rows = new JSONArray();
JSONObject jRow = new JSONObject();
int columnNumber = 0;
String[] a = records.get(0);
for (int k = 0; k < a.length; k++) {
if (colName.equals(a[k])) {
columnNumber = k;
System.out.println("k: " + k);
}
}
String name = "";
for (int i = 0; i < records.size(); i++) {
String[] s = records.get(i);
JSONArray record = new JSONArray(s);
name = s[columnNumber];
jRow.put(name, record);
}
rows.put(jRow);
reader.close();
return rows;
}
public JSONArray comparingTwoSheets(JSONArray sheet1data, JSONArray sheet2data, String colName) throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject();
ArrayList<String> keysForSheet1 = new ArrayList<>();
ArrayList<String> keysForSheet2 = new ArrayList<>();
Set<String> resultSetKeys = new TreeSet<>();
for (int i = 0; i < sheet1data.length(); i++) {
json = sheet1data.getJSONObject(i);
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysForSheet1.add(key.trim().toLowerCase());
}
}
System.out.println("Sheet1 size: " + keysForSheet1.size());
for (String s1 : keysForSheet1) {
System.out.println("sheet1: " + s1);
}
for (int i = 0; i < sheet2data.length(); i++) {
json = sheet2data.getJSONObject(i);
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysForSheet2.add(key.trim().toLowerCase());
}
}
System.out.println("Sheet2 size: " + keysForSheet2.size());
for (String s2 : keysForSheet2) {
System.out.println("sheet2: " + s2);
}
for (String keys : keysForSheet1) {
System.out.println("key check: " + keys);
if (keysForSheet2.contains(keys)) {
System.out.println("testing: " + keysForSheet2.contains(keys));
resultSetKeys.add(keys);
}
}
for (String keys : keysForSheet2) {
System.out.println("key check2: " + keys);
if (keysForSheet1.contains(keys)) {
System.out.println("testing2: " + keysForSheet1.contains(keys));
resultSetKeys.add(keys);
}
}
for (int i = 0; i < keysForSheet2.size(); i++) {
String s = keysForSheet2.get(i);
System.out.println("me: " + s);
if ("name".equals(s)) {
System.out.println("hi i came........");
}
}
System.out.println("Result set: " + resultSetKeys);
JSONArray rows = new JSONArray();
for (String value : resultSetKeys) {
for (int i = 0; i < sheet1data.length(); i++) {
Iterator<String> keys = sheet1data.getJSONObject(i).keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (value.equals(key)) {
rows.put(sheet1data.getJSONObject(i).getJSONArray(value));
}
}
}
}
writeDataToNewExcelFile(rows, colName);
return rows;
}
private static void writeDataToNewExcelFile(JSONArray resultData, String colName) {
try {
// C:\workspace\pdsm\src\main\resources
FileWriter file = new FileWriter("C:\\workspace\\pdsm\\src\\main\\resources\\result.csv");
System.out.println(file + "------------------------");
CSVWriter write = new CSVWriter(file);
List<String[]> result = new ArrayList<>();
for (int i = 0; i < resultData.length(); i++) {
String[] arr = new String[resultData.length()];
for (int j = 0; j < arr.length; j++) {
arr[j] = (String) resultData.getJSONArray(i).getString(j);
}
result.add(arr);
}
write.writeAll(result);
write.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| [
"naveenkankanala9@gmail.com"
] | naveenkankanala9@gmail.com |
03e33ca3b7e9ed44414317b96cfc00ad79d02555 | c7838f44e7640a6dd7b90e1e1cd687606881d8c0 | /com.qa.MyStore/src/main/java/com/qa/MyStore/Test_Base/Test_Base.java | ee548ddbf6ab03c172f033a13927da29f13b5235 | [] | no_license | harshadbele/MyStore | d91fc06b9dfb74b27486ea9acb634c7427bf10a3 | 9addfed903c6d82cbc7bcc85b358072e48247404 | refs/heads/master | 2022-07-25T23:32:17.583747 | 2020-08-16T20:12:49 | 2020-08-16T20:12:49 | 184,771,269 | 0 | 0 | null | 2020-08-16T16:39:24 | 2019-05-03T14:39:50 | Java | UTF-8 | Java | false | false | 1,065 | java | package com.qa.MyStore.Test_Base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test_Base {
public static String src="C:\\Users\\admin\\workspace\\MyStore\\automation\\src\\main\\java\\com\\qa\\MyStore\\config\\config.properties";
public static WebDriver driver;
public static Properties prop;
//commented
public Test_Base()
{
try {
FileInputStream fis=new FileInputStream(src);
prop=new Properties();
prop.load(fis);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.getMessage();
}
}
public void intialization()
{
String browsername=prop.getProperty("browser");
if(browsername.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver","c://chromedriver.exe");
driver=new ChromeDriver();
driver.get(prop.getProperty("url"));
}
driver.manage().window().maximize();
}
}
| [
"beleharshad@gmail.com"
] | beleharshad@gmail.com |
f67155a5037813815f510c07e10761f6d47c2787 | 0e209d3b57ad3a8e7ff99789ff53723a001310b0 | /Bus.java | 7eb3a88b073d260ef88ce9ee12b9560ff7c5171d | [] | no_license | cbrown60/Java_homework | c2074ab3422f17c25dee73214c40e322796e9097 | 5fbbe83573d7b8b1b6d069abf454cedde002f18b | refs/heads/master | 2021-01-17T21:22:10.230270 | 2017-03-07T09:09:50 | 2017-03-07T09:09:50 | 84,178,464 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 646 | java | public class Bus {
private int number;
private Passenger[]persons;
public Bus(int number){
this.number = number;
this.persons = new Passenger[5];
}
public int getNumber(){
return this.number;
}
public int personsOnBus(){
int count = 0;
for (Passenger passenger : persons){
if(passenger != null){
count = count +1;
}
}
return count;
}
public void addPeople(Passenger passenger){
if(isBusFull()){
return ;
}
int index = this.personsOnBus();
persons[index] = passenger;
}
public boolean isBusFull(){
return personsOnBus() == persons.length;
}
} | [
"cbrown605@googlemail.com"
] | cbrown605@googlemail.com |
281e01a891c607f2de12f051ad17e33f6538d123 | a2203e266a4b0919fbde02e79ed63059b804052c | /JAVA/Practice_Problems/Remove_Element.java | 506e3764cdb6b9e2152ad7c77c6d8d7aa1923597 | [] | no_license | bhavnagit/Hacktoberfest2020 | e5abfc4f4d5a48720f5f6c9c61cd5967846fe6fb | 24c76f186e1998d47d1654aaa2e9470a9968292f | refs/heads/master | 2022-12-20T03:24:14.712763 | 2020-10-04T14:38:59 | 2020-10-04T14:38:59 | 300,847,284 | 1 | 0 | null | 2020-10-03T10:08:33 | 2020-10-03T09:50:59 | null | UTF-8 | Java | false | false | 533 | java | /*Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Solution: Refactor: Update solution. Use two pointers.
*/
public class Solution {
public int removeElement(int[] A, int elem) {
int N = A.length;
int idx = 0;
for (int i = 0; i < N; ++i) {
if (A[i] != elem) {
A[idx++] = A[i];
}
}
return idx;
}
} | [
"harshitaraj248@gmail.com"
] | harshitaraj248@gmail.com |
6b3dd805f242439a341c5b1dd6b17a54eb199499 | 67e9d583bc1294594d58949320eccb5a237551ae | /filter/src/main/java/com/vsimpleton/filter/LightFilter.java | 9d2e7d55cf910ffa144f7fae01a46dc9506ea3fb | [] | no_license | vSimpleton/PhotoEditor | 57199f0e9de62076c66622b2b031ddbc3b429c6b | 2e3d1f43eab583d53de36f101c281863842c313e | refs/heads/master | 2023-04-20T03:40:55.261319 | 2021-05-08T10:37:58 | 2021-05-08T10:37:58 | 364,769,103 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,242 | java | /*
* HaoRan ImageFilter Classes v0.1
* Copyright (C) 2012 Zhenjun Dai
*
* 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.
*/
package com.vsimpleton.filter;
/**
* ������
* @author daizhj
*
*/
public class LightFilter extends RadialDistortionFilter{
/**
* ��������
*/
public float Light = 150.0f;
//@Override
public Image process(Image imageIn) {
int width = imageIn.getWidth();
int halfw = width / 2;
int height = imageIn.getHeight();
int halfh = height / 2;
int R = Math.min(halfw, halfh);
//���ĵ㣬������ֵ����ǿ�����ķ���ƫ��
Point point = new Point(halfw, halfh);
int r = 0, g = 0, b = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
float length = (float)Math.sqrt(Math.pow((x -point.X), 2) + Math.pow((y -point.Y), 2));
r = imageIn.getRComponent(x, y);
g = imageIn.getGComponent(x, y);
b = imageIn.getBComponent(x, y);
//λ�ڹ�����
if(length < R) {
float pixel = Light * (1.0f - length /R);
r = r + (int)pixel;
r = Math.max(0, Math.min(r, 255));
g = g + (int)pixel;
g = Math.max(0, Math.min(g, 255));
b = b + (int)pixel;
b = Math.max(0, Math.min(b, 255));
}
imageIn.setPixelColor(x, y, r, g, b);
}
}
return imageIn;
}
} | [
"masm@luxuewen.xom"
] | masm@luxuewen.xom |
91f9b81422594b058e5bd88bca2af6d74e825135 | 9ee22cbfc54eb416dc1e569069e9dbe9d1951df0 | /src/hospital/Patient.java | a78ce8bcab7c7afbc62529aa046283e8f118870e | [] | no_license | EternalCode/HospitalApp | 6655ba731116ae75126c0a9e6f254efa52258133 | f583ac848256abf6454d0e0a76dc50f444c01127 | refs/heads/master | 2021-01-13T13:05:16.122512 | 2017-01-12T01:10:27 | 2017-01-12T01:10:27 | 78,695,060 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,860 | java | package hospital;
//import needed builtins
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* Patient class handles various patient object needs and has methods for
* patient condition manipulation
*
* @author group_0326
*
*/
public class Patient {
// define class instance variables
private String name, dob; // name and date of birth properties of a patient
// are strings
private List<String> conditions; // conditions is a list of PatientCondition
// objects
private String temp, bloodp, heartr, prescription, vitaltime, hID, arrival,
seendoctordatestime;
// temperature, bloodpressure, heartrate, symptoms, vitals recorded time are
// all recorded as strings in this phase
/**
* Patient constructor creates a patient object and assigns it's instance
* variables according to the parameters passed into the constructor
*
* @param name
* string name of patient
* @param dob
* string date of birth of patient
* @param hID
* health card number of patient
* @param arrivetime
* arrival time of patient
*/
public Patient(String name, String dob, String hID, String arrivetime,
String datestime) {
// sets properties in accordance to paramaters
this.name = name;
this.dob = dob;
this.conditions = new ArrayList<String>();
this.hID = hID;
this.arrival = arrivetime;
this.seendoctordatestime = datestime;
}
/**
* getSeenDoctorTime return a string represents the time that patient saw a
* doctor
*
* @return a string represents the time when patient saw a doctor
*/
public String getSeenDoctorTime() {
return seendoctordatestime;
}
/**
* getName is a getter for the patient's name
*
* @return string patient's name
*/
public String getName() {
return this.name;
}
/**
* getTime return a int represents the time with no ":" between it, for
* comparing later
*
* @return a int represent a time with no ":" between hour and minutes
*/
public int getTime() {
String newtype = arrival.replaceAll("[:]", "");
int time = Integer.parseInt(newtype);
return time;
}
/**
* getHealthID let outside class this method for get patient's id
*
* @return a string represents the patient's health card number
*/
public String getHealthID() {
return hID;
}
/**
* toString returns a string representation of a patient object it includes
* the name, date of birth, healthcard number and arrival time
*
* @return returns a string representation of a patient object
*/
public String toString() {
String info = name + "," + dob + "," + hID + "," + arrival + ","
+ seendoctordatestime;
return info;
}
/**
* showInfo collects all required information that patient have for
* displaying in the layout
*
* @return a string represents all information the patient have in readable
* format
*/
public String showInfo() {
String conditionstring = "";
for (int i = 0; i < conditions.size(); i++) {
switch ((i + 1) % 5) {
case 3:
conditionstring += " Blood Presure: " + conditions.get(i) + " ";
break;
case 4:
conditionstring += " Heart Rate: " + conditions.get(i) + " ";
break;
case 1:
conditionstring += "At the time "
+ conditions.get(i) + " vital signs are" + ": \n";
break;
case 2:
conditionstring += "Temperture: " + conditions.get(i) + " ";
break;
case 0:
conditionstring += " Prescription: " + conditions.get(i)
+ ". \n" + " \n";
break;
}
}
// rewrite the tostring as a readable way
String newinfo = "name: " + name + ", \n" + "Date of birth: " + dob
+ ", \n" + "Health Card Number: " + hID + ", \n"
+ "Arrival Time: " + arrival + ", \n"
+ "Time of seen a doctor: " + seendoctordatestime;
String display = newinfo + ", \n" + conditionstring;
return display;
}
/**
* make the latestcondition to be the new one and add each item by
* descreasing order to the front of String array in order to be recorded as
* correct order
*
* @param c
* a patientcondition from nurse
*/
public void addConditionByNurse(PatientCondition c) {
// add to condition list the following condition properties
conditions.add(0, c.getPrescription());
conditions.add(0, c.getHeartRate());
conditions.add(0, c.getBloodPressure());
conditions.add(0, c.getTemperature());
conditions.add(0, c.getVitalTime());
}
/**
* getAllConditionsToSave return a string of all conditions data and ready
* to be saved
*
* @return a string of all conditions data with space between them
*/
public String getAllConditionsToSave() {
// generate a string to represent all the conditions in the condition
// property of a patient
String result = "";
for (int i = 0; i < conditions.size(); i++) {
result += conditions.get(i) + " ";
}
// return the generated string
return result;
}
/**
* addConditions When get the Vitalsigns from populate in Nurse, this method
* will be called and put all collected string array into conditions list
* and record the latest data of conditions
*
* @param vitalsigns
*/
public void addConditions(String[] vitalsigns) {
for (int i = 0; i < vitalsigns.length; i++) {
conditions.add(vitalsigns[i]);
}
/*
* //creates a condition object for the patient temp = vitalsigns[0];
* bloodp = vitalsigns[1]; heartr = vitalsigns[2]; vitaltime =
* vitalsigns [3]; prescription = vitalsigns [4]; PatientCondition c =
* new PatientCondition(temp, bloodp, heartr, vitaltime, prescription);
* //defines this condition to be the latest condition
* this.addLatestCondition(c);
*/
}
/**
* conditionsEmpty will return true if the patient have no vital signs
*
* @return true if the patient have no vital signs
*/
public boolean conditionsEmpty() {
if (conditions.isEmpty()) {
return true;
} else {
return false;
}
}
/**
* getLatestCondition will collect the first 5 index value from condition
* list which is the latest condition recorded by the nurse because of the
* decreasing recorded
*
* @return the last recorded patient condition
*/
public PatientCondition getLatestCondition() {
vitaltime = conditions.get(0);
temp = conditions.get(1);
bloodp = conditions.get(2);
heartr = conditions.get(3);
prescription = conditions.get(4);
PatientCondition c = new PatientCondition(vitaltime, temp, bloodp,
heartr, prescription);
// defines this condition to be the latest condition
return c;
}
/**
* EditPrescriptionByPhysician offer the physician to edit the prescription
* from None to some prescription
*
* @param prescription
* the string represents the prescription
*/
public void EditPrescriptionByPhysician(String prescription) {
conditions.set(4, prescription);
}
/**
* getUrgency compare the double of conditions with the hospitial policy to
* caculate the points for judge the urgency level
*
* @return the int represents the urgency level
*/
public int getUrgency() {
// calculate and return the urgency of the patient, based on most recent
// condition
int urgency = 0;
if (Double.parseDouble(this.getLatestCondition().getBloodPressure()) >= 90) {
urgency += 1;
}
if ((Double.parseDouble(this.getLatestCondition().getHeartRate()) >= 100)
| (Double.parseDouble(this.getLatestCondition().getHeartRate())) <= 50) {
urgency += 1;
}
if (Double.parseDouble(this.getLatestCondition().getTemperature()) >= 39) {
urgency += 1;
}
if (this.getAge() <= 2) {
urgency += 1;
}
return urgency;
}
/**
* a help function for helping find calculate the patient's age from a
* string of date of birth
*
* @return int represents the age of the patient
*/
private int getAge() {
// we calculate age from Date of birth
// make a date object for easy date calculations
Date date = new Date();
// split string and put into a string list
List<String> dOb = new ArrayList<String>(Arrays.asList(dob.split("/")));
// calculate years passed
int year = ((date.getYear() + 1900) - (Integer.parseInt(dOb.get(2))));
int month = ((date.getMonth() + 1) - (Integer.parseInt(dOb.get(0))));
int day = ((date.getDate()) - (Integer.parseInt(dOb.get(1))));
if (day < 0 && month <= 0) {
year -= 1;
} else if (month < 0) {
year -= 1;
}
// return years passed
return year;
}
/**
* editSeenDoctorByNurse allows the nurse to change the patient's seen
* doctor status
*
* @param datestime
* the string represents the date and time that patient saw a
* doctor if it is none the patient haven't seen a doctor
*/
public void editSeenDoctorByNurse(String datestime) {
this.seendoctordatestime = datestime;
}
} | [
"dilshan.gunasekera@mail.utoronto.ca"
] | dilshan.gunasekera@mail.utoronto.ca |
bf263554884dae7ea24dcd2e83773772bfa06515 | e423ffee6c2a35f1fedfc80bd9b17ce4c93c188d | /admin-starter-springboot-master/src/main/java/com/github/adminfaces/starter/bean/FuncionarioList.java | 30a61a528fd3551faaf024680298c3df7899a7a7 | [] | no_license | JuanHermann/Tcc | 49018968ef05abe10d94f233678bbae4a3ef31b0 | 262ea19f0a5b8a7decdb9e66cb9872e051c82692 | refs/heads/master | 2021-06-11T23:51:48.149795 | 2021-05-25T17:02:42 | 2021-05-25T17:02:42 | 154,217,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,676 | java | package com.github.adminfaces.starter.bean;
import com.github.adminfaces.starter.model.Permissao;
import com.github.adminfaces.starter.model.Usuario;
import com.github.adminfaces.starter.model.UsuarioServico;
import com.github.adminfaces.starter.repository.PermissaoRepository;
import com.github.adminfaces.starter.repository.UsuarioRepository;
import com.github.adminfaces.starter.repository.UsuarioServicoRepository;
import static com.github.adminfaces.starter.util.Utils.addDetailMessage;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("view")
public class FuncionarioList extends AbastractListBean<Usuario, UsuarioRepository> {
@Autowired
private UsuarioRepository usuarioRepository;
@Autowired
private UsuarioServicoRepository usuarioServicoRepository;
@Autowired
private PermissaoRepository permissaoRepository;
private boolean role;
public FuncionarioList() {
super(Usuario.class);
}
public void buscar() {
if (getNome() != "") {
setLista(filtrarFuncionarios(
usuarioRepository.findByNomeLikeAndAtivoOrderByNome("%" + getNome() + "%", true)));
} else {
listar();
}
setNome("");
setRegistrosSelecionados(null);
}
@Override
public void listar() {
setLista(filtrarFuncionarios(usuarioRepository.findByAtivoOrderByNome(true)));
}
private List<Usuario> filtrarFuncionarios(List<Usuario> lista) {
List<Usuario> usuarios = lista;
List<Usuario> pesquisa = new ArrayList<>();
for (Usuario usuario : usuarios) {
List<Permissao> permissoes = usuario.getPermissoes();
role = false;
for (Permissao p : permissoes) {
if (p.getNome().equals("ROLE_ATENDENTE")) {
role = true;
} else if (p.getNome().equals("ROLE_FUNCIONARIO")) {
role = true;
}else if (p.getNome().equals("ROLE_ADMIN")) {
role = true;
}
}
if (role == true) {
pesquisa.add(usuario);
}
}
return pesquisa;
}
@Override
public void deletarSelecionados() {
int num = 0;
for (Usuario funcionario : getRegistrosSelecionados()) {
funcionario.setAtivo(false);
funcionario.getPermissoes().clear();
funcionario.addPermissao(permissaoRepository.findByNome("ROLE_CLIENTE"));
getRepository().save(getObjeto());
for (UsuarioServico us : usuarioServicoRepository.findByUsuarioAndAtivo(funcionario, true)) {
us.setAtivo(false);
usuarioServicoRepository.save(us);
}
num++;
}
getRegistrosSelecionados().clear();
addDetailMessage(num + " Registros deletado com sucesso!");
listar();
}
}
| [
"35999705+Ruanoid@users.noreply.github.com"
] | 35999705+Ruanoid@users.noreply.github.com |
933c5f0387ec8c7c3f11bd29fef29b55ac3fc3fb | 5137f916edc1e6e2dd56122a8ebfde925bd2b166 | /ratings-data-service/ratings-data-service/src/main/java/com/example/ratingsdataservice/models/Rating.java | 29b53321a8fd770c969c7542897bc63313c8437c | [] | no_license | ajaypy/spring | 5d15d406e54bc5e3206599f8868635b8e367703a | 613d34ef62571fd3e1298205f696689990c5c855 | refs/heads/master | 2022-11-20T14:44:49.985095 | 2020-07-14T05:11:59 | 2020-07-14T05:11:59 | 279,483,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | package com.example.ratingsdataservice.models;
public class Rating {
private String movieId;
private int rating;
public Rating(String movieId, int rating) {
this.movieId = movieId;
this.rating = rating;
}
public String getMovieId() {
return movieId;
}
public void setMovieId(String movieId) {
this.movieId = movieId;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
| [
"ajay.goel@gmail.com"
] | ajay.goel@gmail.com |
e0becdd0297336168b20f94fa8442c50a542e1be | df11da9ea164fa19f2ad7ffbbc9ddadb0698e157 | /src/main/java/com/golems_metal/entity/modernmetals/EntityTantalumGolem.java | 1342f31baa6c7565306e584fd31d5d064119f864 | [] | no_license | MinecraftModDevelopmentMods/Base-Metal-Golems | 7f254f4190d02d13faf9794c66f2c3882decb249 | 2d9914c07607064d1582652d512f4f6fb5fb2676 | refs/heads/master-1.12.2 | 2023-08-07T12:36:36.561660 | 2021-05-29T01:16:33 | 2021-05-29T01:16:33 | 67,570,928 | 4 | 2 | null | 2021-05-29T01:16:34 | 2016-09-07T04:06:17 | Java | UTF-8 | Java | false | false | 438 | java | package com.golems_metal.entity.modernmetals;
import com.golems_metal.entity.MetalGolemColorized;
import com.golems_metal.entity.MetalGolemNames;
import com.golems_metal.init.MetalGolems;
import net.minecraft.world.World;
public class EntityTantalumGolem extends MetalGolemColorized {
public EntityTantalumGolem(World world) {
super(world, 0xD8D6D7);
this.setLootTableLoc(MetalGolems.MODID, MetalGolemNames.TANTALUM_GOLEM);
}
} | [
"15920401+skyjay1@users.noreply.github.com"
] | 15920401+skyjay1@users.noreply.github.com |
0dc130fcf93daa138a3bd5707b60691c677a608a | 3a0271e61187cb35e53cb0fde9ca70c7535b7608 | /calendar/src/main/java/com/dev/bins/calendar/LayoutManager.java | c33d7aae37479b8a355e675f03f4211e1cd417cd | [
"Apache-2.0"
] | permissive | devbins/Daily | eb190f34b38d34e17fe5acec1c3c3e4ddb281f45 | a949dc22b7d4fad41e7f7970e2886ac51c54dd6c | refs/heads/master | 2021-08-22T21:02:59.012770 | 2017-12-01T08:48:25 | 2017-12-01T08:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,884 | java | package com.dev.bins.calendar;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import static com.dev.bins.calendar.CalendarAdapter.STATE_OPEN;
/**
* Created by bin on 25/10/2017.
*/
public class LayoutManager extends RecyclerView.LayoutManager {
private RecyclerView mRecyclerView;
private CalendarAdapter mAdapter;
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
final int childCount = getChildCount();
if (childCount == 0 && state.isPreLayout()) {
return;
}
int width = getWidth();
int cellHeight = width/7;
if (mAdapter.getCurrentState() == STATE_OPEN){
}else {
}
}
@Override
public boolean canScrollHorizontally() {
return true;
}
@Override
public boolean canScrollVertically() {
return false;
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
return super.scrollHorizontallyBy(dx, recycler, state);
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
mRecyclerView = view;
mAdapter = (CalendarAdapter) mRecyclerView.getAdapter();
}
@Override
public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
super.onDetachedFromWindow(view, recycler);
mRecyclerView = null;
mAdapter = null;
}
}
| [
"bin6160@126.com"
] | bin6160@126.com |
d3fcb10aa2e27a35cdccb82ee861b3a0b10887fd | 2fbd7bbde2b8bbbc54c2a481547509f97ab11110 | /Life/src/main/java/ru/nsu/fit/g14201/chirikhin/controller/ConfigurationRunnable.java | 1e1d96ce54696a78eefc0363ae5c8dbe57997feb | [] | no_license | WildWind03/Graphics | e5233dd04741565d96f7c7ac78816139896e7740 | f6a6049dbdf777cf464cfb056fd5aa9df7bbc0a4 | refs/heads/master | 2021-01-23T06:05:38.596878 | 2017-06-01T08:15:36 | 2017-06-01T08:15:36 | 102,488,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 191 | java | package ru.nsu.fit.g14201.chirikhin.controller;
import ru.nsu.fit.g14201.chirikhin.view.Configuration;
public interface ConfigurationRunnable {
void run(Configuration configuration);
}
| [
"usergreat03@gmail.com"
] | usergreat03@gmail.com |
86951dbcefca29b353b51f5bbe5a7c884341aa63 | 027ef5c2eccf7658c5351202815f8f1248ea103f | /src/main/java/com/amayadream/webchat/utils/UploadUtil.java | 3737b66e4ee7358373df5a2946e123c3e1422bdd | [] | no_license | sch111222/- | 4ad3d2b99e60b23365fb1cae3b64f203ba2adf95 | 7cce773e5091df740cdc1b968dde0195c9af29e4 | refs/heads/master | 2020-04-16T01:40:45.002816 | 2019-01-11T05:10:34 | 2019-01-11T05:10:34 | 165,182,489 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,766 | java | package com.amayadream.webchat.utils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
public class UploadUtil {
/**
* Spring MVC文件上传,返回的是经过处理的path+fileName
* @param request request
* @param folder 上传文件夹
* @param userid 用户名
* @return
*/
public String upload(HttpServletRequest request, String folder, String userid){
FileUtil fileUtil = new FileUtil();
String file_url = "";
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
String prefix = fileUtil.getFilePrefix(file);
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为"",说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName = userid + "." + prefix;
//定义上传路径,格式为 upload/Amayadream/Amayadream.jpg
String path = request.getServletContext().getRealPath("/") + folder + "/" + userid;
File localFile = new File(path, fileName);
if(!localFile.exists()){
localFile.mkdirs();
}
try {
file.transferTo(localFile);
file_url = folder + "/" + userid + "/" + fileName;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return file_url;
}
}
| [
"sch159632@163.com"
] | sch159632@163.com |
1e6c3bab1275e0157c935a3343e1f3fdbf88c27c | 960b630bca4af5cd661c24bea5d48d0e093871a3 | /2020_Spring/3_CS5334_Advanced_Internet_Information_Processing/cs5334-java/WEB-INF/classes/JdbcCheckup1.java | f124912456cdc25b79cd4259de01e82367f146eb | [] | no_license | zebointexas/courses | 33cc9b97c6d54b5914923fc5877a7ed8f461b442 | cff85f183f7a0892bced0a0cfb06d60f6e1f3836 | refs/heads/master | 2023-02-08T12:32:35.245266 | 2020-12-16T21:12:48 | 2020-12-16T21:12:48 | 239,605,780 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 983 | java |
/*
* This sample can be used to check the JDBC installation.
* Just run it and provide the connect information. It will select
* "Hello World" from the database.
*/
// You need to import the java.sql package to use JDBC
import java.sql.*;
// We import java.io to be able to read from the command line
import java.io.*;
class JdbcCheckup1
{
public static void main (String args []) throws SQLException, IOException
{
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn =
new oracle.jdbc.OracleDriver ().defaultConnection ();
// Create a statement
Statement stmt = conn.createStatement ();
// Do the SQL "Hello World" thing
ResultSet rset = stmt.executeQuery ("SELECT 'Hello World' FROM dual");
while (rset.next ())
System.out.println (rset.getString (1));
System.out.println ("Your JDBC installation is correct.");
}
}
| [
"46735920+zebointexas@users.noreply.github.com"
] | 46735920+zebointexas@users.noreply.github.com |
4c187e74f012e44a2309889a0fc4146b720832ff | 31dbba883863f85404480f6ba59b54b9ee6a0213 | /app/src/androidTest/java/moo/ruts/av/th/firebase/ExampleInstrumentedTest.java | 47ee88a0c7ff8451f2de7af94fc7d677903f31fa | [] | no_license | chadchol05/firebase | 22787b04ae88b26766c10b8672bee2318d134a35 | 90cc6e60999fe33a2997ab657d8e886a53bce0b6 | refs/heads/master | 2020-04-15T10:11:11.827486 | 2019-01-08T06:58:47 | 2019-01-08T06:58:47 | 164,584,136 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 730 | java | package moo.ruts.av.th.firebase;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("moo.ruts.av.th.firebase", appContext.getPackageName());
}
}
| [
"nokcod@gmail.com"
] | nokcod@gmail.com |
b68115ae977e5563223995ec428de9838c2d3e56 | ac875c56b92a914cd5ddacaad03bbd4a62e44067 | /Iterator/src/main/java/ua/martynenko/pattern/iterator/sample/LinkedList.java | 161f7dfcaadd9ec484a8aab0552c8278707aed7e | [] | no_license | martynenko-e/Patterns | 8ccdafcadb3c00ab35ef3f6cd53083b2bbdb8ca7 | 7731b607e3eaa146db343c106816afdac0535007 | refs/heads/master | 2021-01-10T07:16:53.089630 | 2015-10-07T14:15:12 | 2015-10-07T14:15:12 | 43,609,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,273 | java | package ua.martynenko.pattern.iterator.sample;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
/**
* Created by Martynenko Yevhen on 06.10.2015.
*/
public class LinkedList<T> implements List<T> {
private Node root;
private int modCount;
private static class Node {
private Node next;
private Object value;
}
/*
Add new root to LinkedList
1->2->3->4->5->6->7
1->
1->2->
1->2->3->
1->2->3->3.5->(4->5->6->7->....->100500)
Remove root from LinkedList
1->2->3->4->5->6->7
1->
1->2->
1->2->3->(4->)(5->6->7)
1->2->3->3->(5->6->7)
Add new object to ArrayList
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, null]
[1, 2, 3, 4, 4, 5, 6, 7]
[1, 2, 3, 3.5, 4, 5, 6, 7]
Remove object from ArrayList
[1, 2, 3, 4, 5, 6, 7, 7]
[1, 2, 3, 4, 5, 6, 7]
*/
public LinkedList() {
clear();
}
@Override
public int size() {
int size = 0;
Node node = root;
while (node != null) {
size++;
node = node.next;
}
return size;
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public boolean contains(Object o) {
Node node = root;
while (node != null) {
Object object = node.value;
if (object == null) {
if (o == null) {
return true;
}
}
if (object.equals(o)) {
return true;
}
node = node.next;
}
return false;
}
@Override
public Iterator<T> iterator() {
return new LinkedListIterator<T>();
}
@Override
public boolean add(T value) {
Node last = getLast();
last = insertAfter(last, value);
return true;
}
private Node insertAfter(Node node, T value) {
modCount++;
if (node == null) {
root = new Node();
root.value = value;
return root;
}
Node old = node.next;
node.next = new Node();
node.next.value = value;
node.next.next = old;
return node.next;
}
private Node getLast() {
if (root == null) {
return null;
}
Node node = root;
while (node.next != null) {
node = node.next;
}
return node;
}
@Override
public boolean remove(Object object) {
int index = indexOf(object);
if (index == -1) {
return false;
}
remove(index);
return true;
}
@Override
public void clear() {
root = null;
modCount++;
}
@Override
public T get(int index) {
return (T)getNode(index).value;
}
private Node getNode(int index) {
if (index < 0 || (index == 0 && root == null)) {
throw new ArrayIndexOutOfBoundsException(index);
}
int i = 0;
Node node = root;
do {
if (i == index) {
return node;
}
i++;
node = node.next;
} while (node != null);
throw new ArrayIndexOutOfBoundsException(index);
}
@Override
public T set(int index, T object) {
Node node = getNode(index);
Object old = node.value;
node.value = object;
modCount++;
return (T)old;
}
@Override
public void add(int index, T object) {
if (index == 0) {
Node old = root;
root = new Node();
root.value = object;
root.next = old;
} else {
Node prevNode = getNode(index - 1);
if (prevNode.next == null) {
prevNode.next = new Node();
prevNode.next.value = object;
} else {
insertAfter(prevNode, object);
}
}
}
@Override
public T remove(int index) {
modCount++;
if (index == 0) {
if (root == null) {
throw new ArrayIndexOutOfBoundsException(index);
}
Object old = root.value;
root = root.next;
return (T)old;
} else {
Node prevNode = getNode(index - 1);
Node node = prevNode.next;
if (node == null) {
throw new ArrayIndexOutOfBoundsException(index);
}
prevNode.next = node.next;
return (T)node.value;
}
}
@Override
public int indexOf(Object object) {
int index = 0;
Node node = root;
while (node != null) {
Object value = node.value;
if (value == null && object == null) {
return index;
}
if (value.equals(object)) {
return index;
}
index++;
node = node.next;
}
return -1;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append('[');
Node node = root;
while (node != null) {
result.append(node.value);
if (node.next != null) {
result.append(", ");
}
node = node.next;
}
result.append(']');
return result.toString();
}
private class LinkedListIterator<T> implements Iterator<T> {
private Node curr;
private Node prev;
private boolean removed;
private int expectedModCount = modCount;
public LinkedListIterator() {
this.curr = null;
this.prev = null;
this.removed = false;
}
@Override
public boolean hasNext() {
return (curr == null && prev == null && root != null)
|| (curr != null && curr.next != null);
}
@Override
public T next() {
checkForComodification();
if (!hasNext()) {
throw new NoSuchElementException();
}
removed = false;
if (curr == null && prev == null) {
curr = root;
prev = null;
return (T)curr.value;
} else {
prev = curr;
curr = curr.next;
return (T)curr.value;
}
}
@Override
public void remove() {
checkForComodification();
if (removed || curr == null) {
throw new IllegalStateException();
}
if (curr == root) {
root = curr.next;
} else if (prev != null) {
Node next = curr.next;
curr = prev;
curr.next = next;
}
prev = null;
removed = true;
modCount++;
expectedModCount = modCount;
}
private void checkForComodification() {
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
}
| [
"martynenko.evhen@gmail.com"
] | martynenko.evhen@gmail.com |
87d9dfdb9bc08b8421e9746a91c397f249d8fa87 | 582cf146893bcef5e374db9f873ca0aa1116a1f6 | /src/main/com/mi/game/module/pet/pojo/PetEntity.java | c4f30fc7d0df0b70e55ed51f43d967e076c10ba0 | [] | no_license | hexiaoweiff8/GameServer | 09e69880847d061d7416a21be297439255da50ca | 19d80004ff558c3c69cab8c3a2247f00dc4224e3 | refs/heads/master | 2021-01-17T12:50:30.448481 | 2016-06-15T03:40:48 | 2016-06-15T03:40:48 | 59,183,210 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,029 | java | package com.mi.game.module.pet.pojo;
import java.util.HashMap;
import java.util.Map;
import com.mi.core.pojo.BaseEntity;
public class PetEntity extends BaseEntity{
/**
*
*/
private static final long serialVersionUID = -1457060602128388468L;
private String playerID; // 玩家ID
private Map<Long,Pet> petMap; // 宠物集合
private Map<Integer,PetShard> shardMap; // 碎片集合
//private int maxSellNum; // 最大背包个数
private int maxFieldNum = 6; // 宠物最大栏位
@Override
public Map<String,Object> responseMap(){
Map<String,Object> data = new HashMap<String, Object>();
if(petMap!=null){
data.put("petMap", petMap.values());
}
data.put("shardMap", shardMap.values());
//data.put("maxSellNum", maxSellNum);
data.put("maxFieldNum", maxFieldNum);
return data;
}
// public int getMaxSellNum() {
// return maxSellNum;
// }
//
// public void setMaxSellNum(int maxSellNum) {
// this.maxSellNum = maxSellNum;
// }
public Map<Long, Pet> getPetMap() {
if(petMap == null)
petMap = new HashMap<Long,Pet>();
return petMap;
}
public void setPetMap(Map<Long, Pet> petMap) {
this.petMap = petMap;
}
public Map<Integer, PetShard> getShardMap() {
if(shardMap == null){
shardMap = new HashMap<Integer, PetShard>();
}
return shardMap;
}
public void setShardMap(Map<Integer, PetShard> shardMap) {
this.shardMap = shardMap;
}
public int getMaxFieldNum() {
return maxFieldNum;
}
public void setMaxFieldNum(int maxFieldNum) {
this.maxFieldNum = maxFieldNum;
}
@Override
public Object getKey() {
// TODO 自动生成的方法存根
return playerID;
}
@Override
public String getKeyName() {
// TODO 自动生成的方法存根
return "playerID";
}
@Override
public void setKey(Object key) {
// TODO 自动生成的方法存根
this.playerID = key.toString();
}
}
| [
"hexiaoweiff8@sina.com"
] | hexiaoweiff8@sina.com |
e21a64855efb117ad30966182bb68dfdcc4eb07d | 3ac97cd288a2e395b80b9ef36fcc1f5cd4467006 | /src/main/java/com/gulang/surd/base/BaseService.java | 9f3f66bb56a465ef89db4d697f425f547e693e01 | [] | no_license | qinyunsurd/surd | 3af737b75136e0b9bc9cc339494ac5ddad442083 | 942082e192d4c705624132962ed163c8e55f17ae | refs/heads/master | 2021-01-15T08:52:56.064010 | 2017-08-09T13:29:31 | 2017-08-09T13:29:31 | 99,571,108 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 803 | java | package com.gulang.surd.base;
import java.util.List;
/**
* @author : gulang
* Create Date : 2017/8/9
* Company : Garden Plus
* Description :
*/
public interface BaseService<K,V> {
/**
* 通过一个实体对象,多条件进行查询
* @param v Entity
* @return Object
*/
V getObjectByEntity(V v);
/**
* 添加一个对象
* @param v 要保存的对象
* @return 影响行数
*/
int saveObject(V v);
/**
* 批量插入对象
* @param vs 插入的集合
* @return 影响行数
*/
int insertBatch(List<V> vs);
/**
* 根据主键进行删除
* @param k
* @return
*/
int removeObject(K k);
/**
* 更新
* @param v
* @return
*/
int updateObject(V v);
}
| [
"heyinbao@ac.cc"
] | heyinbao@ac.cc |
e56cf9caf255ee7fe3e47547e4b430f7ea0535e7 | 6af06fcc882223b6a9c814b5ac9fe53e06e535c2 | /src/com/epam/springtasks/firsttask/Second.java | e2466da4b6203d144f5bba347f84e5323f3de252 | [] | no_license | BuHT1/Spring-tasks | 86a4cddbb0d93008586bb6cd0fc9223d479dad01 | 2c35d5fb6e5f8228acd2ee1abf4511300254dd43 | refs/heads/master | 2020-12-29T09:12:59.949507 | 2020-02-19T10:51:23 | 2020-02-19T10:51:23 | 238,551,745 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 385 | java | package com.epam.springtasks.firsttask;
import org.springframework.beans.factory.annotation.Autowired;
public class Second {
@Autowired
Third thirdBean;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Second{");
sb.append("thirdBean=").append(thirdBean);
sb.append('}');
return sb.toString();
}
}
| [
"thisisbuht@gmail.com"
] | thisisbuht@gmail.com |
973c5b2d3eeae382cfca34cae4ef6dada0bf5c1a | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_3/src/b/f/j/f/Calc_1_3_15954.java | 2a1235319c723b35245e6865463c9f838d8825b7 | [] | no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 134 | java | package b.f.j.f;
public class Calc_1_3_15954 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"christian.halstrick@sap.com"
] | christian.halstrick@sap.com |
fa638ad4699c0b7360c14501de1000e5e58fe3d3 | 71b912e47ad8e73a651c79670a8a9377eaff2110 | /lac3/lac3-core/src/main/java/com/linkallcloud/core/lang/util/LinkedCharArray.java | 5e4c8efdb4a6dac7d98557bf8d0ea4bee8896640 | [] | no_license | jasonzhoumj/lac3 | 5f47cc227e631fd1be201e005ab9f3bbac5431bf | fba08c10693f5745914d446222718cfacec3def9 | refs/heads/master | 2021-03-28T12:55:26.875522 | 2020-03-11T01:28:52 | 2020-03-11T01:28:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,608 | java | package com.linkallcloud.core.lang.util;
import java.util.ArrayList;
import com.linkallcloud.core.lang.Lang;
import com.linkallcloud.core.lang.Strings;
public class LinkedCharArray {
public LinkedCharArray() {
this(256);
}
public LinkedCharArray(int size) {
if (size <= 0)
Lang.makeThrow("width must >0!");
this.width = size;
cache = new ArrayList<char[]>();
}
public LinkedCharArray(String s) {
this(s.length());
char[] cs = s.toCharArray();
cache.add(cs);
cursor = cs.length;
}
private int offset;
private int cursor;
private int width;
private ArrayList<char[]> cache;
public LinkedCharArray push(int e) {
return push((char) e);
}
public LinkedCharArray push(char e) {
char[] array;
int row = cursor / width;
int i = cursor % width;
if (cache.size() == 0 || (cursor != offset && i == 0)) {
array = new char[width];
cache.add(array);
} else {
array = cache.get(row);
}
array[i] = e;
cursor++;
return this;
}
public LinkedCharArray push(String s) {
char[] cs = s.toCharArray();
for (char c : cs)
push(c);
return this;
}
public char popFirst() {
return innerGet(offset++);
}
public LinkedCharArray popFirst(int num) {
for (int i = 0; i < num; i++)
popFirst();
return this;
}
public char popLast() {
return innerGet(--cursor);
}
public LinkedCharArray popLast(int num) {
for (int i = 0; i < num; i++)
popLast();
return this;
}
public char first() {
if (size() == 0)
return (char) 0;
return innerGet(offset);
}
public char last() {
if (size() == 0)
return (char) 0;
return innerGet(cursor - 1);
}
public LinkedCharArray set(int index, char e) {
checkBound(index);
index += offset;
char[] array = cache.get(index / width);
array[index % width] = e;
return this;
}
private void checkBound(int index) {
if (index >= size() || index < 0)
throw new IndexOutOfBoundsException("Index: "
+ index
+ ", Size: "
+ size());
}
public LinkedCharArray clear() {
cache.clear();
cursor = 0;
offset = 0;
return this;
}
private char innerGet(int index) {
char[] array = cache.get(index / width);
return array[index % width];
}
public char get(int index) {
checkBound(index);
return innerGet(index + offset);
}
public boolean isEmpty() {
return 0 == cursor - offset;
}
public int size() {
return cursor - offset;
}
public boolean startsWith(String s) {
if (null == s)
return false;
if (s.length() > this.size())
return false;
return startsWith(s.toCharArray());
}
public boolean startsWith(char[] cs) {
if (null == cs)
return false;
for (int i = 0; i < cs.length; i++)
if (cs[i] != get(i))
return false;
return true;
}
public boolean endsWith(String s) {
if (null == s)
return false;
if (s.length() > this.size())
return false;
return endsWith(s.toCharArray());
}
public boolean endsWith(char[] cs) {
if (null == cs)
return false;
if (size() < cs.length)
return false;
int of = size() - cs.length;
for (int i = 0; i < cs.length; i++)
if (cs[i] != get(of + i))
return false;
return true;
}
public int[] toIntArray() {
int[] re = new int[size()];
for (int i = 0; i < re.length; i++)
re[i] = this.get(i);
return re;
}
public char[] toArray() {
char[] re = new char[size()];
for (int i = 0; i < re.length; i++)
re[i] = (char) this.get(i);
return re;
}
public String toString() {
return new String(toArray());
}
public String toTrimmed() {
return Strings.trim(toString());
}
public String popAll() {
String re = new String(toArray());
clear();
return re;
}
}
| [
"838485220@qq.com"
] | 838485220@qq.com |
20ff718e1424e9a37074316bde349f4b8c397b4b | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/16/16_427a8cbc3dbe247089d27edc15961d7f2dff9d85/User/16_427a8cbc3dbe247089d27edc15961d7f2dff9d85_User_t.java | a228eaca9a284cdfd251ccc61d2cab5dfb5be526 | [] | 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 | 1,759 | java | /*
personal-genome-client Java client for the 23andMe Personal Genome API.
Copyright (c) 2012 held jointly by the individual authors.
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 3 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; with out 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
> http://www.fsf.org/licensing/licenses/lgpl.html
> http://www.opensource.org/licenses/lgpl-license.php
*/
package com.github.heuermh.personalgenome.client;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import javax.annotation.concurrent.Immutable;
import com.google.common.collect.ImmutableList;
/**
* User.
*/
@Immutable
public final class User {
private final String id;
private final List<Profile> profiles;
public User(final String id, final List<Profile> profiles) {
checkNotNull(id);
checkNotNull(profiles);
this.id = id;
this.profiles = ImmutableList.copyOf(profiles);
}
public String getId() {
return id;
}
public List<Profile> getProfiles() {
return profiles;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
f6dc11b599acfb293dda433578144a5e90610f68 | 99b65febae999c485c30f497106ff7c83916d85f | /app/src/main/java/com/kemizhibo/kemizhibo/other/custom/CustomIndicator.java | f7517812c4139ea575313c296f3838122d5d6a50 | [] | no_license | kemizhibo/KeMiZhiBoK730 | 5d1b9f58aa34f8696e7dfa984b347e6515524ee6 | b934c3da355f3d74f702a14fe54c832340720caf | refs/heads/master | 2020-03-25T01:22:46.683123 | 2018-09-20T10:09:11 | 2018-09-20T10:09:11 | 143,234,432 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,055 | java | package com.kemizhibo.kemizhibo.other.custom;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kemizhibo.kemizhibo.R;
/**
* Created by Administrator on 2018/7/30.
*/
public class CustomIndicator extends HorizontalScrollView{
private static final int COLOR_INDICATOR_COLOR = Color.BLACK;
private Context context;
private String[] titles;
private int count;
private Paint mPaint;
private float mTranslationX;
private float lineheight = 0.0f;
private OnIndicatorClickListener listener;
private int selectIndex = -1;
public CustomIndicator(Context context) {
this(context, null);
}
public CustomIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context){
this.context = context;
mPaint = new Paint();
mPaint.setColor(COLOR_INDICATOR_COLOR);
mPaint.setStrokeWidth(lineheight);//底部指示线的宽度
setHorizontalScrollBarEnabled(false);
}
public void setTitles(String[] titles){
this.titles = titles;
count = titles.length;
generateTitleView();
}
public void setSelectIndex(int selectI){
selectIndex = selectI;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void dispatchDraw(Canvas canvas)
{
super.dispatchDraw(canvas);
canvas.save();
canvas.translate(mTranslationX, getHeight() - lineheight);
//canvas.drawLine(0, 0, tabWidth, 0, mPaint);//(startX, startY, stopX, stopY, paint)
canvas.restore();
}
private void generateTitleView()
{
if (getChildCount() > 0)
this.removeAllViews();
count = titles.length;
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
for (int i = 0; i < count; i++)
{
TextView tv = new TextView(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT);
tv.setPadding(50, 0, 25, 0);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setTextColor(selectIndex == i ? getResources().getColor(R.color.filter_text_select) : getResources().getColor(R.color.filter_text_normal));
tv.setText(titles[i]);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);//字体大小
tv.setLayoutParams(lp);
final int finalI = i;
tv.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
selectIndex = finalI;
generateTitleView();
if(listener != null){
listener.onIndicatorClick(finalI);
}
}
});
linearLayout.addView(tv);
}
addView(linearLayout);
}
public void setOnIndicatorClickListener(OnIndicatorClickListener listener){
this.listener = listener;
}
public interface OnIndicatorClickListener{
void onIndicatorClick(int position);
}
}
| [
"17642147191@sina.com"
] | 17642147191@sina.com |
b48cf7e11f6256511f4f6569c2c564359ee09085 | a87b7251a56e2b295e68f3545e0b32f89205ccd4 | /omgt-domain/src/main/java/com/hsbcpb/omgt/domain/model/spools/package-info.java | 2408bfface98e4e515dd3b39920133ed6d8bdbc9 | [] | no_license | fabien7474/omgt | 564c364fcd00e8830f57fea0c3e6e76677d1db54 | 1ab35be390bafc3e9edcc877b31b5b54b7a599b5 | refs/heads/master | 2020-05-17T03:50:09.881639 | 2015-02-26T23:38:09 | 2015-02-26T23:38:09 | 31,394,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 113 | java | /**
* Gathers aggregates, entities, VO, FK related to spools
*/
package com.hsbcpb.omgt.domain.model.spools; | [
"fabien7474@users.noreply.github.com"
] | fabien7474@users.noreply.github.com |
2c6135b96efed8d9bc8b3f7c15aafc5c0d3e4e00 | 80948614e09540292dd265cb33ebe721ac96c5fc | /week9-week9_22.FileAnalysis/src/file/Analysis.java | 4039bb9de3780f17521abeb93aa419ab413609b8 | [] | no_license | dnatalimaldonador/OOP_Part2 | 8b20701a5b4345b351af2a49d8d4c98a5caed2cc | aafbdf36ff8b78f8514ada6429e8157d1aae07fa | refs/heads/master | 2021-01-13T08:25:31.442280 | 2015-05-16T05:59:42 | 2015-05-16T05:59:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,038 | java | package file;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/*
* 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.
*/
/**
*
* @author wenhaowu
*/
public class Analysis {
private File f1;
public Analysis(File file){
this.f1 = file;
}
public int lines() throws FileNotFoundException{
Scanner sc = new Scanner(this.f1);
int count = 0;
while(sc.hasNextLine()){
sc.nextLine();
//System.out.println("here");
count ++;
}
return count;
}
public int characters() throws FileNotFoundException{
Scanner sc = new Scanner(this.f1);
int count=0;
while(sc.hasNextLine()){
int len = sc.nextLine().length();
count += len+1;
}
return count;
}
}
| [
"wenhao293h@gmail.com"
] | wenhao293h@gmail.com |
b5e80e3fae8252f380fa7c4f157118919eb0d8ab | 14e58d824f81de111d9294b1100de9bc867a5822 | /library/src/main/java/com/pengrad/telegrambot/passport/EncryptedPassportElement.java | a541945d8ac976814d0487ea40093d72c00a41b8 | [
"Apache-2.0"
] | permissive | joaosouz91/java-telegram-bot-api | 29c649a6f0d64ad6002ae8b89260fa6688bddbf4 | 04fbbbb2255ec1e37753f8f448fa5cfd2c7f6a6a | refs/heads/master | 2020-03-26T04:30:14.400326 | 2018-08-08T08:15:57 | 2018-08-08T08:15:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,164 | java | package com.pengrad.telegrambot.passport;
import com.google.gson.Gson;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.File;
import com.pengrad.telegrambot.passport.decrypt.Decrypt;
import com.pengrad.telegrambot.request.GetFile;
import java.io.Serializable;
import java.util.Arrays;
/**
* Stas Parshin
* 30 July 2018
*/
public class EncryptedPassportElement implements Serializable {
private final static long serialVersionUID = 0L;
public enum Type {
personal_details, passport, driver_license, identity_card, internal_passport, address, utility_bill,
bank_statement, rental_agreement, passport_registration, temporary_registration, phone_number, email
}
private Type type;
private String data;
private String phone_number;
private String email;
private PassportFile[] files;
private PassportFile front_side;
private PassportFile reverse_side;
private PassportFile selfie;
public DecryptedData decryptData(Credentials credentials) throws Exception {
Class<? extends DecryptedData> clazz = dataClass();
if (clazz == null || data == null) return null;
SecureValue secureValue = credentials.secureData().ofType(type);
DataCredentials dataCredentials = secureValue.data();
String dataStr = Decrypt.decryptData(data, dataCredentials.dataHash(), dataCredentials.secret());
return new Gson().fromJson(dataStr, clazz);
}
public byte[] decryptFile(PassportFile passportFile, FileCredentials fileCredentials, TelegramBot bot) throws Exception {
File file = bot.execute(new GetFile(passportFile.fileId())).file();
byte[] fileData = bot.getFileContent(file);
return decryptFile(fileData, fileCredentials);
}
public byte[] decryptFile(PassportFile passportFile, Credentials credentials, TelegramBot bot) throws Exception {
FileCredentials fileCredentials = findFileCredentials(passportFile, credentials);
if (fileCredentials == null) {
throw new IllegalArgumentException("Don't have file credentials for " + passportFile);
}
return decryptFile(passportFile, fileCredentials, bot);
}
public byte[] decryptFile(byte[] fileData, FileCredentials fileCredentials) throws Exception {
return Decrypt.decryptFile(fileData, fileCredentials.fileHash(), fileCredentials.secret());
}
private FileCredentials findFileCredentials(PassportFile passportFile, Credentials credentials) {
SecureValue secureValue = credentials.secureData().ofType(type);
if (passportFile.equals(front_side)) return secureValue.frontSide();
if (passportFile.equals(reverse_side)) return secureValue.reverseSide();
if (passportFile.equals(selfie)) return secureValue.selfie();
for (int i = 0; i < files.length; i++) {
if (passportFile.equals(files[i])) return secureValue.files()[i];
}
return null;
}
private Class<? extends DecryptedData> dataClass() {
if (Type.personal_details == type) return PersonalDetails.class;
if (Type.passport == type) return IdDocumentData.class;
if (Type.internal_passport == type) return IdDocumentData.class;
if (Type.driver_license == type) return IdDocumentData.class;
if (Type.identity_card == type) return IdDocumentData.class;
if (Type.address == type) return ResidentialAddress.class;
return null;
}
public Type type() {
return type;
}
public String data() {
return data;
}
public String phoneNumber() {
return phone_number;
}
public String email() {
return email;
}
public PassportFile[] files() {
return files;
}
public PassportFile frontSide() {
return front_side;
}
public PassportFile reverseSide() {
return reverse_side;
}
public PassportFile selfie() {
return selfie;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EncryptedPassportElement that = (EncryptedPassportElement) o;
if (type != that.type) return false;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
if (phone_number != null ? !phone_number.equals(that.phone_number) : that.phone_number != null) return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(files, that.files)) return false;
if (front_side != null ? !front_side.equals(that.front_side) : that.front_side != null) return false;
if (reverse_side != null ? !reverse_side.equals(that.reverse_side) : that.reverse_side != null) return false;
return selfie != null ? selfie.equals(that.selfie) : that.selfie == null;
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + (data != null ? data.hashCode() : 0);
result = 31 * result + (phone_number != null ? phone_number.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + Arrays.hashCode(files);
result = 31 * result + (front_side != null ? front_side.hashCode() : 0);
result = 31 * result + (reverse_side != null ? reverse_side.hashCode() : 0);
result = 31 * result + (selfie != null ? selfie.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "EncryptedPassportElement{" +
"type=" + type +
", data='" + data + '\'' +
", phone_number='" + phone_number + '\'' +
", email='" + email + '\'' +
", files=" + Arrays.toString(files) +
", front_side=" + front_side +
", reverse_side=" + reverse_side +
", selfie=" + selfie +
'}';
}
}
| [
"noreply@github.com"
] | noreply@github.com |
45d84a972b396c755e24dcb017a68a9eb1b9eab9 | b0607996d57abfd6d4f057cd65772a14a03ee938 | /cache2k-jcache-tests/src/test/java/org/cache2k/jcache/tests/AdditionalAsyncCacheListenerTest.java | 49b6e25b9793de124514c2d3b370e740d7eeb463 | [
"Apache-2.0"
] | permissive | cache2k/cache2k | 447328703ca7e4a77487a8063881e33998c29669 | 0eaa156bdecd617b2aa4c745d0f8844a32609697 | refs/heads/master | 2023-08-01T03:36:51.443163 | 2022-11-01T08:25:04 | 2022-11-01T08:25:04 | 15,289,581 | 684 | 88 | Apache-2.0 | 2023-04-17T17:40:48 | 2013-12-18T17:25:04 | Java | UTF-8 | Java | false | false | 6,054 | java | package org.cache2k.jcache.tests;
/*
* #%L
* cache2k JCache tests
* %%
* Copyright (C) 2000 - 2022 headissue GmbH, Munich
* %%
* 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.
* #L%
*/
import org.jsr107.tck.event.CacheEntryListenerClient;
import org.jsr107.tck.event.CacheEntryListenerServer;
import org.jsr107.tck.testutil.CacheTestSupport;
import org.jsr107.tck.testutil.ExcludeListExcluder;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryExpiredListener;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryRemovedListener;
import javax.cache.event.CacheEntryUpdatedListener;
import javax.cache.event.EventType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
/**
* Test async cache listeners.
*
* @author Jens Wilke
*/
public class AdditionalAsyncCacheListenerTest extends CacheTestSupport<Integer, String> {
@Rule
public MethodRule rule = new ExcludeListExcluder(this.getClass());
private CacheEntryListenerServer cacheEntryListenerServer;
private RecordingListener<Integer, String> listener;
@Override
protected MutableConfiguration<Integer, String> newMutableConfiguration() {
return new MutableConfiguration<Integer, String>().setTypes(Integer.class, String.class);
}
@Override
protected MutableConfiguration<Integer, String> extraSetup(MutableConfiguration<Integer, String> cfg) {
// cfg.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, 5)));
cacheEntryListenerServer = new CacheEntryListenerServer<>(10011, Integer.class, String.class);
try {
cacheEntryListenerServer.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
listener = new RecordingListener<>();
cacheEntryListenerServer.addCacheEventListener(listener);
CacheEntryListenerClient<Integer, String> clientListener =
new CacheEntryListenerClient<>(cacheEntryListenerServer.getInetAddress(), cacheEntryListenerServer.getPort());
boolean _isSynchronous = false;
listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(
FactoryBuilder.factoryOf(clientListener), null, true, _isSynchronous);
return cfg.addCacheEntryListenerConfiguration(listenerConfiguration);
}
/**
* Test whether async events arrive and are in correct order. Also test with negative key.
*/
@Test
public void testInOrder() throws Exception {
int KEY = -123;
cache.put(KEY, "hello");
cache.put(KEY, "mike");
cache.remove(KEY);
listener.await(3, 60 * 1000);
assertEquals(
Arrays.asList(EventType.CREATED, EventType.UPDATED, EventType.REMOVED),
listener.extractLogForKey(KEY));
}
public static class RecordingListener<K, V> implements CacheEntryCreatedListener<K, V>,
CacheEntryUpdatedListener<K, V>, CacheEntryExpiredListener<K, V>,
CacheEntryRemovedListener<K, V> {
List<RecordedEvent<K>> log = Collections.synchronizedList(new ArrayList<RecordedEvent<K>>());
@Override
public void onCreated(final Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException {
record(EventType.CREATED, events);
}
@Override
public void onExpired(final Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException {
record(EventType.EXPIRED, events);
}
@Override
public void onRemoved(final Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException {
record(EventType.REMOVED, events);
}
@Override
public void onUpdated(final Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException {
record(EventType.UPDATED, events);
}
public List<EventType> extractLogForKey(K key) {
List<EventType> l = new ArrayList<>();
for (RecordedEvent<K> e : log) {
if (e.key.equals(key)) {
l.add(e.type);
}
}
return l;
}
public void await(int _eventCount, long _timeoutMillis) throws TimeoutException {
long t0 = System.currentTimeMillis();
while (_eventCount != log.size()) {
long t = System.currentTimeMillis();
if (t - t0 >= _timeoutMillis) {
throw new TimeoutException();
}
synchronized (log) {
try {
log.wait(_timeoutMillis - (t - t0));
} catch (InterruptedException ex) {}
}
}
}
public void record(final EventType _expectedType, final Iterable<CacheEntryEvent<? extends K, ? extends V>> events) {
for (CacheEntryEvent e0 : events) {
CacheEntryEvent<K, V> e = e0;
assertEquals(_expectedType, e.getEventType());
log.add(new RecordedEvent<K>(e.getEventType(), e.getKey()));
}
synchronized (log) {
log.notifyAll();
}
}
}
static class RecordedEvent<K> {
EventType type;
K key;
public RecordedEvent(final EventType _type, final K _key) {
type = _type;
key = _key;
}
}
}
| [
"jw_github@headissue.com"
] | jw_github@headissue.com |
1133bb74c72272fb4bb4d64b9bb1a411eb83f9f8 | fc87b2edf0f2c6b3112c7b5edec38a840c6f888f | /Week5/src/BlackSmith.java | 4b4eccbd9447b6000be4517c16f5574dff6801e7 | [] | no_license | abezhani1/DistributedJava | c0e61e8b51669d8099b1c5e5e1934c80747941b1 | e3f2909b3fae3a083e1f33733c4429ddf91b180c | refs/heads/master | 2020-03-27T09:48:12.246650 | 2018-11-15T03:00:54 | 2018-11-15T03:00:54 | 146,373,766 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,769 | java | import java.util.*;
public class BlackSmith
{
public List getWtypes(String weapon)
{
List wtypes = new ArrayList();
if (weapon.equals("Swords"))
{
wtypes.add(new Weapon("Straight Sword",350,
"Regular straight sword. For those who have affinity of European blades."));
wtypes.add(new Weapon("Katana", 400,
"Authentic Eastern steel."));
wtypes.add(new Weapon("Scimitar", 360,
"Classic curved blade. Shout out to all the Drizzt fans!"));
}
else if (weapon.equals("Axes"))
{
wtypes.add(new Weapon("Battle Axe", 350,
"Standard battle axe, For those who want to be a viking war-lord."));
wtypes.add(new Weapon("Hand Axe", 200,
"Light chopping axe. Carry it with you on the go!"));
wtypes.add(new Weapon("War Axe", 360,
"An axe with two edges, because one edge is never enough."));
}
else
{
wtypes.add(new Weapon("Javelin", 200,
"A throwing spear. When you're tired or don't have time to let the " +
"enemy come to you."));
wtypes.add(new Weapon("Trident", 360,
"A three pronged spear. Neptune and/or Poseidon would be proud."));
wtypes.add(new Weapon("Long Spear", 350,
"Standard long spear. Designed to keep enemies at bay. Can be combined " +
"with a shield."));
}
return wtypes;
}
} | [
"abezhani@my.wctc.edu"
] | abezhani@my.wctc.edu |
888c26baaa55b4540a52358b489795c769cd4a04 | c0f1f3f6772faec824631c101585f6be7747643b | /enterprise/saidemo2_enterprise/app/src/main/java/com/example/dy/sai_demo2/Register2Activity.java | 9d4eeddea2282ed8939a8fac982ecf21ea645c8c | [] | no_license | 068089dy/Sai-plus | 2b93af6c62c58ea183ab65f39a07d49723497900 | cedd6a59226c082700ccbd91d39e80d8cf85a445 | refs/heads/master | 2020-03-27T19:34:52.979974 | 2018-09-01T13:13:35 | 2018-09-01T13:13:35 | 146,998,571 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,147 | java | package com.example.dy.sai_demo2;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class Register2Activity extends AppCompatActivity {
EditText edit_legal_name;
EditText edit_legal_IDcard;
//EditText edit_IDcard_image;
ImageView edit_IDcard_image;
String IDcard_image_path = "";
EditText edit_email;
EditText edit_tel;
EditText edit_code;
EditText edit_password;
Button submit_btn;
String enterprise_name;
String num;
String postcode;
String location;
static Register2Activity me;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
me = this;
//沉浸式,从郭霖那炒的,我也懒得去看。
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
initview();
// submit_btn = (Button) findViewById(R.id.submit_btn);
// submit_btn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent intent = new Intent(Register2Activity.this, Register3Activity.class);
//
// Log.d("start3","start3" );
// startActivity(intent);
// Log.d("start3","open3" );
// finish();
//
// }
// });
}
private void initview(){
enterprise_name = getIntent().getStringExtra("enterprise_name");
num = getIntent().getStringExtra("num");
postcode = getIntent().getStringExtra("postcode");
location = getIntent().getStringExtra("location");
edit_IDcard_image = (ImageView) findViewById(R.id.IDcard_image);
edit_IDcard_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//调用相册
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
});
edit_legal_IDcard = (EditText) findViewById(R.id.legal_IDcard);
edit_legal_name = (EditText) findViewById(R.id.legal_name);
edit_email = (EditText) findViewById(R.id.email);
edit_tel = (EditText) findViewById(R.id.tel);
edit_code = (EditText) findViewById(R.id.code);
edit_password = (EditText) findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit_btn);
submit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(IDcard_image_path.equals("") ||
edit_legal_IDcard.getText().toString().equals("") ||
edit_legal_name.getText().toString().equals("") ||
edit_password.getText().toString().equals("") ||
edit_email.getText().toString().equals("") ||
edit_tel.getText().toString().equals("") ||
edit_code.getText().toString().equals("")) {
Toast.makeText(Register2Activity.this,"请检查信息是否输入完整",Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(Register2Activity.this, Register3Activity.class);
intent.putExtra("IDcard_image", IDcard_image_path);
intent.putExtra("legal_IDcard", edit_legal_IDcard.getText().toString());
intent.putExtra("legal_name", edit_legal_name.getText().toString());
intent.putExtra("password", edit_password.getText().toString());
intent.putExtra("email", edit_email.getText().toString());
intent.putExtra("tel", edit_tel.getText().toString());
intent.putExtra("code", edit_code.getText().toString());
intent.putExtra("location", location);
intent.putExtra("enterprise_name", enterprise_name);
intent.putExtra("num", num);
intent.putExtra("postcode", postcode);
Log.d("start3","start3" );
startActivity(intent);
Log.d("start3","open3" );
finish();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//获取图片路径
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
Log.d("image_path",imagePath);
//showImage(imagePath);
Bitmap bm = BitmapFactory.decodeFile(imagePath);
edit_IDcard_image.setImageBitmap(bm);
IDcard_image_path = imagePath;
c.close();
}
}
}
| [
"068089dy@gmail.com"
] | 068089dy@gmail.com |
7ef1da50810057550dc312eb9c75ed91143c769c | e50b4cd6645bb9e04d400a67913de23aaafeb44f | /src/main/java/self_preparation/java_features/o_object_methods/Example.java | 57e4d1f67c97a1f6ec0956a466d401187d3079a6 | [] | no_license | vitalii-marchenko/algorithms-and-data-structures-java | c287bfa42a77dbf00231315cc01ec31d7c05894a | 9b5780a1b560cf0c1967b8dfbe244b3cb1c49865 | refs/heads/master | 2022-09-12T21:27:22.161770 | 2022-08-30T15:07:24 | 2022-08-30T15:07:24 | 130,473,364 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 893 | java | package self_preparation.java_features.o_object_methods;
public class Example {
static class Point implements Cloneable {
int x;
int y;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
static class Point2 {
int x;
int y;
public Object clone() {
Point point = new Point();
point.x = this.x;
point.y = this.y;
return point;
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
Integer int1 = new Integer(2);
Integer int2 = int1;
System.out.println(i1 == i2);
System.out.println(int1 == int2);
Point p = new Point();
Object clone = p.clone();
}
}
| [
"ext-vitaliy.marchenko@here.com"
] | ext-vitaliy.marchenko@here.com |
9929e29fc3de405ccb673162e6e8bcef82492fc6 | 8a74c3a7b04b3b839ed4f4365894c780005e56ef | /game-server/src/main/java/net/dodian/old/engine/task/impl/NPCRespawnTask.java | d33ffa08a922ae029209b3ec14e97593261c59cf | [] | no_license | testzemi/Dodian | a7c6b7fc74a368cc07daad98d2153c38b5a3c77c | af08374d773dfa0415e09c303e4369dbdc7fa76e | refs/heads/master | 2022-05-28T11:30:41.036839 | 2020-05-02T20:14:59 | 2020-05-02T20:14:59 | 260,778,250 | 0 | 0 | null | 2020-05-02T21:28:55 | 2020-05-02T21:28:55 | null | UTF-8 | Java | false | false | 1,140 | java | package net.dodian.old.engine.task.impl;
import net.dodian.managers.DefinitionsManager;
import net.dodian.old.engine.task.Task;
import net.dodian.old.world.World;
import net.dodian.old.world.entity.impl.npc.NPC;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
/**
* A {@link Task} implementation which handles the respawn
* of an npc.
*
* @author Professor Oak
*/
public class NPCRespawnTask extends Task implements BeanFactoryAware {
private DefinitionsManager definitionsManager;
public NPCRespawnTask(NPC npc, int respawn) {
super(respawn);
this.npc = npc;
}
private final NPC npc;
@Override
public void execute() {
//Create a new npc with fresh stats..
NPC npc_ = new NPC(npc.getId(), npc.getSpawnPosition(), definitionsManager);
//Register the npc
World.getNpcAddQueue().add(npc_);
//Stop the task
stop();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.definitionsManager = beanFactory.getBean(DefinitionsManager.class);
}
}
| [
"nozemi95@gmail.com"
] | nozemi95@gmail.com |
9903485016f4ba640dbd1e9a9966398a69a591d4 | 6baa09045c69b0231c35c22b06cdf69a8ce227d6 | /modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201603/cm/AdGroupBidModifier.java | 19103695216002b140afaa219057ccfe5563222f | [
"Apache-2.0"
] | permissive | remotejob/googleads-java-lib | f603b47117522104f7df2a72d2c96ae8c1ea011d | a330df0799de8d8de0dcdddf4c317d6b0cd2fe10 | refs/heads/master | 2020-12-11T01:36:29.506854 | 2016-07-28T22:13:24 | 2016-07-28T22:13:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,974 | java |
package com.google.api.ads.adwords.jaxws.v201603.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents an adgroup level bid modifier override for campaign level criterion
* bid modifier values.
*
*
* <p>Java class for AdGroupBidModifier complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AdGroupBidModifier">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="campaignId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="adGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="criterion" type="{https://adwords.google.com/api/adwords/cm/v201603}Criterion" minOccurs="0"/>
* <element name="bidModifier" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="baseAdGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="bidModifierSource" type="{https://adwords.google.com/api/adwords/cm/v201603}BidModifierSource" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AdGroupBidModifier", propOrder = {
"campaignId",
"adGroupId",
"criterion",
"bidModifier",
"baseAdGroupId",
"bidModifierSource"
})
public class AdGroupBidModifier {
protected Long campaignId;
protected Long adGroupId;
protected Criterion criterion;
protected Double bidModifier;
protected Long baseAdGroupId;
@XmlSchemaType(name = "string")
protected BidModifierSource bidModifierSource;
/**
* Gets the value of the campaignId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getCampaignId() {
return campaignId;
}
/**
* Sets the value of the campaignId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setCampaignId(Long value) {
this.campaignId = value;
}
/**
* Gets the value of the adGroupId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getAdGroupId() {
return adGroupId;
}
/**
* Sets the value of the adGroupId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setAdGroupId(Long value) {
this.adGroupId = value;
}
/**
* Gets the value of the criterion property.
*
* @return
* possible object is
* {@link Criterion }
*
*/
public Criterion getCriterion() {
return criterion;
}
/**
* Sets the value of the criterion property.
*
* @param value
* allowed object is
* {@link Criterion }
*
*/
public void setCriterion(Criterion value) {
this.criterion = value;
}
/**
* Gets the value of the bidModifier property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getBidModifier() {
return bidModifier;
}
/**
* Sets the value of the bidModifier property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setBidModifier(Double value) {
this.bidModifier = value;
}
/**
* Gets the value of the baseAdGroupId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getBaseAdGroupId() {
return baseAdGroupId;
}
/**
* Sets the value of the baseAdGroupId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setBaseAdGroupId(Long value) {
this.baseAdGroupId = value;
}
/**
* Gets the value of the bidModifierSource property.
*
* @return
* possible object is
* {@link BidModifierSource }
*
*/
public BidModifierSource getBidModifierSource() {
return bidModifierSource;
}
/**
* Sets the value of the bidModifierSource property.
*
* @param value
* allowed object is
* {@link BidModifierSource }
*
*/
public void setBidModifierSource(BidModifierSource value) {
this.bidModifierSource = value;
}
}
| [
"jradcliff@users.noreply.github.com"
] | jradcliff@users.noreply.github.com |
d5c4f1ab861f2d1ed8b9bbfed94ccf883d8703d3 | a91dfc9e0b66bf9a8b151f1317dc9ab0fcbb03fd | /tags/release-2-0/tools/java/org/unicode/cldr/icu/LDML2ICUConverter.java | 6c1968b3cc2515563c372b2dd4f1eb7fd85f6cd8 | [] | no_license | svn2github/CLDR | 8c28c7d33419b2cf82fa68658c2df400819548c6 | d41ba4ae267526a2bd1dd6ba21259e4dc1afcfa4 | refs/heads/master | 2020-03-10T16:23:08.329258 | 2019-01-17T18:03:40 | 2019-01-17T18:03:40 | 129,472,269 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 218,310 | java | /*
******************************************************************************
* Copyright (C) 2004-2011 International Business Machines Corporation and *
* others. All Rights Reserved. *
******************************************************************************
*/
package org.unicode.cldr.icu;
import static org.unicode.cldr.icu.ICUID.ICU_BOUNDARIES;
import static org.unicode.cldr.icu.ICUID.ICU_BRKITR_DATA;
import static org.unicode.cldr.icu.ICUID.ICU_DEPENDENCY;
import static org.unicode.cldr.icu.ICUID.ICU_DEPENDS;
import static org.unicode.cldr.icu.ICUID.ICU_DICTIONARIES;
import static org.unicode.cldr.icu.ICUID.ICU_DICTIONARY;
import static org.unicode.cldr.icu.ICUID.ICU_GRAPHEME;
import static org.unicode.cldr.icu.ICUID.ICU_LINE;
import static org.unicode.cldr.icu.ICUID.ICU_SENTENCE;
import static org.unicode.cldr.icu.ICUID.ICU_TITLE;
import static org.unicode.cldr.icu.ICUID.ICU_UCARULES;
import static org.unicode.cldr.icu.ICUID.ICU_UCA_RULES;
import static org.unicode.cldr.icu.ICUID.ICU_WORD;
import static org.unicode.cldr.icu.ICUID.ICU_XGC;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.xml.transform.TransformerException;
import org.unicode.cldr.ant.CLDRConverterTool;
import org.unicode.cldr.icu.ICUResourceWriter.Resource;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceAlias;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceArray;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceInt;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceIntVector;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceProcess;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceString;
import org.unicode.cldr.icu.ICUResourceWriter.ResourceTable;
import org.unicode.cldr.util.CLDRFile;
import org.unicode.cldr.util.CLDRFile.Factory;
import org.unicode.cldr.util.LDMLUtilities;
import org.unicode.cldr.util.SupplementalDataInfo;
import org.unicode.cldr.util.XPathParts;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ibm.icu.dev.test.util.ElapsedTimer;
import com.ibm.icu.dev.tool.UOption;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.text.UCharacterIterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
/**
* Converts from LDML files (from the CLDR project) into ICU text or binary format.
*
* @author Ram Viswanadha
* @author Brian Rower - Added Binary file root and fixed memory leak - June 2008
*/
public class LDML2ICUConverter extends CLDRConverterTool {
/**
* These must be kept in sync with getOptions().
*/
private static final int HELP1 = 0;
private static final int HELP2 = 1;
private static final int SOURCEDIR = 2;
private static final int DESTDIR = 3;
private static final int SPECIALSDIR = 4;
private static final int WRITE_DEPRECATED = 5;
private static final int WRITE_DRAFT = 6;
private static final int SUPPLEMENTALDIR = 7;
private static final int SUPPLEMENTALONLY = 8;
private static final int METADATA_ONLY = 9;
private static final int METAZONES_ONLY = 10;
private static final int LIKELYSUBTAGS_ONLY = 11;
private static final int PLURALS_ONLY = 12;
private static final int NUMBERS_ONLY = 13;
private static final int WRITE_BINARY = 14;
private static final int VERBOSE = 15;
private static final int ASCII_NUMBERS = 16;
private static final int WINDOWSZONES_ONLY = 17;
private static final int BCP47_KEY_TYPE = 18;
private static final UOption[] options = new UOption[] {
UOption.HELP_H(),
UOption.HELP_QUESTION_MARK(),
UOption.SOURCEDIR(),
UOption.DESTDIR(),
UOption.create("specialsdir", 'p', UOption.REQUIRES_ARG),
UOption.create("write-deprecated", 'w', UOption.REQUIRES_ARG),
UOption.create("write-draft", 'f', UOption.NO_ARG),
UOption.create("supplementaldir", 'm', UOption.REQUIRES_ARG),
UOption.create("supplemental-only", 'l', UOption.NO_ARG),
UOption.create("metadata-only", 'q', UOption.NO_ARG),
UOption.create("metazones-only", 'z', UOption.NO_ARG),
UOption.create("likely-only", 't', UOption.NO_ARG),
UOption.create("plurals-only", 'r', UOption.NO_ARG),
UOption.create("numbers-only", 'n', UOption.NO_ARG),
UOption.create("write-binary", 'b', UOption.NO_ARG),
UOption.VERBOSE(),
UOption.create("ascii-numbers", 'a', UOption.NO_ARG),
UOption.create("windowszones-only", 'i', UOption.NO_ARG),
UOption.create("bcp47-keytype", 'k', UOption.REQUIRES_ARG),
};
private String sourceDir;
private String destDir;
private String specialsDir;
private String supplementalDir;
private boolean writeDraft;
private boolean writeBinary;
private boolean asciiNumbers;
private int startOfRange; // First character of a potential range.
private int lastOfRange; // The (so far) last character of a potential range.
private String lastStrengthSymbol = "";
/**
* Add comments on the item to indicate where fallbacks came from. Good for information, bad for diffs.
*/
private static final boolean verboseFallbackComments = false;
private Document supplementalDoc;
private SupplementalDataInfo supplementalDataInfo;
private static final boolean DEBUG = false;
// TODO: hard-coded file names for now
private static final String supplementalDataFile = "supplementalData.xml";
private static final String supplementalMetadataFile = "supplementalMetadata.xml";
private static final String metaZonesFile = "metaZones.xml";
private static final String likelySubtagsFile = "likelySubtags.xml";
private static final String pluralsFile = "plurals.xml";
private static final String numberingSystemsFile = "numberingSystems.xml";
private static final String windowsZonesFile = "windowsZones.xml";
private List<String> _xpathList = new ArrayList<String>();
private ICULog log;
private ICUWriter writer;
private CLDRFile.Factory cldrFactory;
private CLDRFile.Factory specialsFactory;
private final LDMLServices serviceAdapter = new LDMLServices() {
public Factory cldrFactory() {
return LDML2ICUConverter.this.cldrFactory;
}
public CLDRFile getSpecialsFile(String locale) {
return LDML2ICUConverter.this.getSpecialsFile(locale);
}
public boolean xpathListContains(String xpath) {
return LDML2ICUConverter.this.xpathListContains(xpath);
}
public boolean isDraftStatusOverridable(String locName) {
return LDML2ICUConverter.this.isDraftStatusOverridable(locName);
}
public Resource parseBundle(CLDRFile file) {
return LDML2ICUConverter.this.parseBundle(file);
}
public SupplementalDataInfo getSupplementalDataInfo() {
return LDML2ICUConverter.this.supplementalDataInfo;
}
};
private Resource parseBundle(CLDRFile file) {
LDML2ICUInputLocale fakeLocale = new LDML2ICUInputLocale(file, serviceAdapter);
return parseBundle(fakeLocale);
}
public static void main(String[] args) {
LDML2ICUConverter cnv = new LDML2ICUConverter();
cnv.processArgs(args);
}
private void usage() {
System.out.println(
"\nUsage: LDML2ICUConverter [OPTIONS] [FILES]\nLDML2ICUConverter [OPTIONS] " +
"-w [DIRECTORY]\n" +
"This program is used to convert LDML files to ICU ResourceBundle TXT files.\n" +
"Please refer to the following options. Options are not case sensitive.\n" +
"Options:\n" +
"-s or --sourcedir source directory for files followed by path, " +
"default is current directory.\n" +
"-d or --destdir destination directory, followed by the path, "+
"default is current directory.\n" +
"-p or --specialsdir source directory for files containing special data " +
"followed by the path. None if not specified\n" +
"-f or --write-draft write data for LDML nodes marked draft.\n" +
"-m or --suplementaldir source directory for finding the supplemental data.\n" +
"-l or --supplemental-only read " + supplementalDataFile + " file from the given " +
"directory and write appropriate files to destination " +
"directory\n" +
"-q or --metadata-only read " + supplementalMetadataFile + " file from the given " +
"directory and write appropriate files to destination " +
"directory\n" +
"-t or --likely-only read " + likelySubtagsFile + " file from the given directory " +
"and write appropriate files to destination directory\n" +
"-r or --plurals-only read " + pluralsFile + " file from the given directory and " +
"write appropriate files to destination directory\n" +
"-z or --metazones-only read " + metaZonesFile + " file from the given directory " +
"and write appropriate files to destination directory\n" +
"-i or --windowszones-only read " + windowsZonesFile + " file from the given directory " +
"and write appropriate files to destination directory\n" +
"-n or --numbers-only read " + numberingSystemsFile + " file from the given " +
"directory and write appropriate files to destination " +
"directory\n" +
"-w [dir] or --write-deprecated [dir] write data for deprecated locales. 'dir' is a " +
"directory of source xml files.\n" +
"-b or --write-binary write data in binary (.res) files rather than .txt\n" +
"-h or -? or --help this usage text.\n" +
"-v or --verbose print out verbose output.\n" +
"-a or --ascii-numbers do ASCII-only numbers.\n" +
"-k [dir] or --bcp47-keytype [dir] write data for bcp47 key/type data. 'dir' is a " +
"directory of bcp47 key/type data xml files.\n" +
"example: org.unicode.cldr.icu.LDML2ICUConverter -s xxx -d yyy en.xml");
System.exit(-1);
}
/**
* First method called from the main method. Will check all the args and direct us from there. If not doing anything
* special, just taking in XML files and writing TXT or Binary files, then will call processFile()
*/
@Override
public void processArgs(String[] args) {
int remainingArgc = 0;
// Reset options (they're static).
for (int i = 0; i < options.length; i++) {
options[i].doesOccur = false;
}
try {
remainingArgc = UOption.parseArgs(args, options);
} catch (Exception e) {
// log is not set up yet, so do this manually
System.out.println("ERROR: parsing args '" + e.getMessage() + "'");
e.printStackTrace();
usage();
}
if (args.length == 0 || options[HELP1].doesOccur || options[HELP2].doesOccur) {
usage();
}
if (options[SOURCEDIR].doesOccur) {
sourceDir = options[SOURCEDIR].value;
}
if (options[DESTDIR].doesOccur) {
destDir = options[DESTDIR].value;
} else {
destDir = ".";
}
if (options[SPECIALSDIR].doesOccur) {
specialsDir = options[SPECIALSDIR].value;
}
if (options[SUPPLEMENTALDIR].doesOccur) {
supplementalDir = options[SUPPLEMENTALDIR].value;
}
if (options[WRITE_DRAFT].doesOccur) {
writeDraft = true;
}
if (options[WRITE_BINARY].doesOccur) {
writeBinary = true;
}
if (options[ASCII_NUMBERS].doesOccur) {
asciiNumbers = true;
}
// Set up logging so we can use it here on out
ICULog.Level level = DEBUG ? ICULog.Level.DEBUG : options[VERBOSE].doesOccur ? ICULog.Level.INFO : ICULog.Level.LOG;
log = new ICULogImpl(level);
// Set up resource splitting, if we have it
ResourceSplitter splitter = null;
if (splitInfos != null) {
splitter = new ResourceSplitter(log, destDir + "/..", splitInfos);
}
// Set up writer
writer = new ICUWriter(destDir, log, splitter);
if (options[WRITE_DEPRECATED].doesOccur) {
if (remainingArgc > 0) {
log.error("-w takes one argument, the directory, and no other XML files.\n");
usage();
return; // NOTREACHED
}
String depDirName = options[WRITE_DEPRECATED].value;
File depDir = new File(depDirName);
if (!depDir.isDirectory()) {
log.error(depDirName + " isn't a directory.");
usage();
return; // NOTREACHED
}
// parse for draft status?
File dstDir = new File(destDir);
boolean parseDraft = !writeDraft;
boolean parseSubLocale = sourceDir.indexOf("collation") > -1;
Set<String> validLocales = getIncludedLocales();
new DeprecatedConverter(log, serviceAdapter, depDir, dstDir).write(writer, aliasDeprecates, parseDraft, parseSubLocale, validLocales);
return;
}
if (supplementalDir != null) {
supplementalDoc = createSupplementalDoc();
supplementalDataInfo = SupplementalDataInfo.getInstance(supplementalDir);
}
if (options[SUPPLEMENTALONLY].doesOccur) {
// TODO(dougfelt): this assumes there is no data in list before this point. check.
// addToXPathList(supplementalDoc);
setXPathList(makeXPathList(supplementalDoc));
// Create the Resource linked list which will hold the
// data after parsing
// The assumption here is that the top
// level resource is always a table in ICU
log.log("Processing " + supplementalDataFile);
Resource res = new SupplementalDataParser(log, serviceAdapter).parse(supplementalDoc, supplementalDataFile);
if (res != null && ((ResourceTable) res).first != null) {
writer.writeResource(res, supplementalDataFile);
}
} else if (options[METADATA_ONLY].doesOccur) {
new SupplementalMetadataConverter(log, supplementalMetadataFile, supplementalDir).convert(writer);
} else if (options[METAZONES_ONLY].doesOccur) {
new MetaZonesConverter(log, metaZonesFile, supplementalDir).convert(writer);
} else if (options[WINDOWSZONES_ONLY].doesOccur) {
new WindowsZonesConverter(log, windowsZonesFile, supplementalDir).convert(writer);
} else if (options[LIKELYSUBTAGS_ONLY].doesOccur) {
new LikelySubtagsConverter(log, likelySubtagsFile, supplementalDir).convert(writer);
} else if (options[PLURALS_ONLY].doesOccur) {
new PluralsConverter(log, pluralsFile, supplementalDir).convert(writer);
} else if (options[NUMBERS_ONLY].doesOccur) {
new NumberingSystemsConverter(log, numberingSystemsFile, supplementalDir).convert(writer);
} else if (options[BCP47_KEY_TYPE].doesOccur) {
if (remainingArgc > 0) {
log.error("-k takes one argument, the bcp47 key/type data directory, no others.\n");
usage();
return;
}
String dirstr = options[BCP47_KEY_TYPE].value;
File bcp47Dir = new File(dirstr);
if (!bcp47Dir.isDirectory()) {
log.error(dirstr + " isn't a directory.");
usage();
return;
}
log.log("Processing " + bcp47Dir.getAbsolutePath());
// timezone type data will be externalized
String[] externalized = new String[] { "timezone" };
new KeyTypeDataConverter(log, dirstr, externalized).convert(writer);
} else {
spinUpFactories(sourceDir, specialsDir);
if (getLocalesMap() != null && getLocalesMap().size() > 0) {
for (Iterator<String> iter = getLocalesMap().keySet().iterator(); iter.hasNext();) {
String fileName = iter.next();
String draft = getLocalesMap().get(fileName);
if (draft != null && !draft.equals("false")) {
writeDraft = true;
} else {
writeDraft = false;
}
processFile(fileName);
}
} else if (remainingArgc > 0) {
for (int i = 0; i < remainingArgc; i++) {
if (args[i].equals("*")) {
for (String file : new File(sourceDir).list()) {
if (!file.endsWith(".xml")) {
continue;
}
processFile(file);
}
} else {
processFile(args[i]);
}
}
} else {
log.error("No files specified !");
}
}
}
/**
* Serves to narrow the interface to InputLocale so that it can be separated from LDML2ICUConverter.
*/
static interface LDMLServices {
/** Returns the cldr factory, or null */
CLDRFile.Factory cldrFactory();
/** Return a specials file for the locale */
CLDRFile getSpecialsFile(String locale);
/** Returns true if xpathlist contains the xpath */
boolean xpathListContains(String xpath);
// for DeprecatedConverter
/** Returns true if draft status is overridable. */
boolean isDraftStatusOverridable(String locName);
/** Parses the CLDRFile, with the given status string */
Resource parseBundle(CLDRFile file);
// for SupplementalDataParser
SupplementalDataInfo getSupplementalDataInfo();
}
private Document getSpecialsDoc(String locName) {
if (specialsDir != null) {
String locNameXml = locName + ".xml";
String icuSpecialFile = specialsDir + "/" + locNameXml;
if (new File(icuSpecialFile).exists()) {
return LDMLUtilities.parseAndResolveAliases(locNameXml, specialsDir, false, false);
}
if (ULocale.getCountry(locName).length() == 0) {
log.warning("ICU special not found for language-locale \"" + locName + "\"");
// System.exit(-1);
} else {
log.warning("ICU special file not found, continuing.");
}
}
return null;
}
private DocumentPair getDocumentPair(String locale) {
String localeXml = locale + ".xml";
String xmlfileName = LDMLUtilities.getFullPath(LDMLUtilities.XML, localeXml, sourceDir);
Document doc = LDMLUtilities.parse(xmlfileName, false);
Document specials = getSpecialsDoc(locale);
if (specials != null) {
StringBuilder xpath = new StringBuilder();
doc = (Document) LDMLUtilities.mergeLDMLDocuments(doc, specials, xpath, null/* unused */, null /* unused */, false, true);
}
Document fullyResolvedDoc = null;
if (!LDMLUtilities.isLocaleAlias(doc)) {
fullyResolvedDoc = LDMLUtilities.getFullyResolvedLDML(sourceDir, localeXml, false, false, false, false);
}
if (writeDraft == false && isDraftStatusOverridable(locale)) {
log.info("Overriding draft status, and including: " + locale);
writeDraft = true;
// TODO: save/restore writeDraft
}
setXPathList(makeXPathList(doc, fullyResolvedDoc, locale));
return new DocumentPair(doc, fullyResolvedDoc);
}
private void setXPathList(List<String> xpathList) {
_xpathList = xpathList;
}
private CLDRFile getSpecialsFile(String locale) {
if (specialsFactory != null) {
String icuSpecialFile = specialsDir + "/" + locale + ".xml";
if (new File(icuSpecialFile).exists()) {
log.info("Parsing ICU specials from: " + icuSpecialFile);
return specialsFactory.make(locale, false);
}
}
return null;
}
/*
* Sets some stuff up and calls createResourceBundle
*/
private void processFile(String fileName) {
// add 1 below to skip past the separator
int lastIndex = fileName.lastIndexOf(File.separator, fileName.length()) + 1;
fileName = fileName.substring(lastIndex, fileName.length());
String xmlfileName = LDMLUtilities.getFullPath(LDMLUtilities.XML, fileName, sourceDir);
String locName = fileName;
int index = locName.indexOf(".xml");
if (index > -1) {
locName = locName.substring(0, index);
}
log.setStatus(locName);
log.log("Processing " + xmlfileName);
ElapsedTimer timer = new ElapsedTimer();
LDML2ICUInputLocale loc = new LDML2ICUInputLocale(locName, serviceAdapter);
if (writeDraft == false && isDraftStatusOverridable(locName)) {
log.info("Overriding draft status, and including: " + locName);
writeDraft = true;
// TODO: save/restore writeDraft
}
createResourceBundle(loc);
log.info("Elapsed time: " + timer + "s");
}
private void spinUpFactories(String factoryDir, String specialsDir) {
if (cldrFactory == null) {
log.info("* Spinning up CLDRFactory on " + factoryDir);
cldrFactory = CLDRFile.Factory.make(factoryDir, ".*");
if (specialsDir != null) {
log.info("* Spinning up specials CLDRFactory on " + specialsDir);
specialsFactory = CLDRFile.Factory.make(specialsDir, ".*");
}
}
}
private static List<String> makeXPathList(Document doc) {
List<String> xpathList = new ArrayList<String>();
addToXPathList(xpathList, doc);
return xpathList;
}
private static void addToXPathList(List<String> xpathList, Document doc) {
addToXPathList(xpathList, doc, (StringBuilder) null);
}
private static void addToXPathList(List<String> xpathList, Node node, StringBuilder xpath) {
if (xpath == null) {
xpath = new StringBuilder("/");
}
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = child.getNodeName();
int savedLength = xpath.length();
xpath.append("/");
xpath.append(name);
LDMLUtilities.appendXPathAttribute(child, xpath, false, false);
if (name.equals("collation")) {
// special case for collation: draft attribute is set on the top level element
xpathList.add(xpath.toString());
} else if (LDMLUtilities.areChildrenElementNodes(child)) {
addToXPathList(xpathList, child, xpath);
} else {
xpathList.add(xpath.toString());
}
xpath.delete(savedLength, xpath.length());
}
}
private List<String> makeXPathList(LDML2ICUInputLocale loc) {
String locName = loc.getLocale();
boolean exemplarsContainAZ = exemplarsContainAZ(loc);
List<String> xpathList = new ArrayList<String>();
for (Iterator<String> iter = loc.getFile().iterator(); iter.hasNext();) {
xpathList.add(loc.getFile().getFullXPath(iter.next()));
}
addToXPathList(xpathList, supplementalDoc);
Collections.sort(xpathList);
return computeConvertibleXPathList(xpathList, exemplarsContainAZ, locName);
}
private List<String> computeConvertibleXPathList(List<String> xpathList, boolean exemplarsContainAZ, String locName) {
dumpXPathList(xpathList, "Before computeConvertibleXPaths", "log1.txt");
xpathList = computeConvertibleXPaths(xpathList, exemplarsContainAZ, locName, supplementalDir);
dumpXPathList(xpathList, "After computeConvertibleXPaths", "log2.txt");
return xpathList;
}
private void addSpaceForDebug(StringBuilder sb) {
if (DEBUG) {
sb.append(" ");
}
}
private static void dumpXPathList(List<String> xpathList, String msg, String fname) {
if (DEBUG) {
try {
PrintWriter log = new PrintWriter(new FileOutputStream(fname));
log.println("BEGIN: " + msg);
for (String xpath : xpathList) {
log.println(xpath);
}
log.println("END: " + msg);
log.flush();
log.close();
} catch (Exception ex) {
// debugging, throw away.
}
}
}
private List<String> makeXPathList(Document doc, Document fullyResolvedDoc, String locName) {
boolean exemplarsContainAZ = exemplarsContainAZ(fullyResolvedDoc);
List<String> xpathList = new ArrayList<String>();
addToXPathList(xpathList, doc);
addToXPathList(xpathList, supplementalDoc);
Collections.sort(xpathList);
return computeConvertibleXPathList(xpathList, exemplarsContainAZ, locName);
}
private static boolean exemplarsContainAZ(Document fullyResolvedDoc) {
if (fullyResolvedDoc == null) {
return false;
}
Node node = LDMLUtilities.getNode(fullyResolvedDoc, "//ldml/characters/exemplarCharacters");
if (node == null) {
return false;
}
String ex = LDMLUtilities.getNodeValue(node);
UnicodeSet set = new UnicodeSet(ex);
return set.containsAll(new UnicodeSet("[A-Z a-z]"));
}
private static boolean exemplarsContainAZ(LDML2ICUInputLocale loc) {
if (loc == null) {
return false;
}
UnicodeSet set = loc.getFile().getExemplarSet("", CLDRFile.WinningChoice.WINNING);
if (set == null) {
set = loc.resolved().getExemplarSet("", CLDRFile.WinningChoice.WINNING);
if (set == null) {
return false;
}
}
return set.containsAll(new UnicodeSet("[A-Z a-z]"));
}
private Document createSupplementalDoc() {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.matches(".*\\.xml") && !name.equals("characters.xml") && !name.equals(metaZonesFile) && !name.equals(likelySubtagsFile) && !name.equals(windowsZonesFile)) {
return true;
}
return false;
}
};
File myDir = new File(supplementalDir);
String[] files = myDir.list(filter);
if (files == null) {
String canonicalPath;
try {
canonicalPath = myDir.getCanonicalPath();
} catch (IOException e) {
canonicalPath = e.getMessage();
}
log.error("Supplemental files are missing " + canonicalPath);
System.exit(-1);
}
Document doc = null;
for (int i = 0; i < files.length; i++) {
try {
log.info("Parsing document " + files[i]);
String fileName = myDir.getAbsolutePath() + File.separator + files[i];
Document child = LDMLUtilities.parse(fileName, false);
if (doc == null) {
doc = child;
continue;
}
StringBuilder xpath = new StringBuilder();
LDMLUtilities.mergeLDMLDocuments(doc, child, xpath, files[i], myDir.getAbsolutePath(), true, false);
} catch (Throwable se) {
log.error("Parsing: " + files[i] + " " + se.toString(), se);
System.exit(1);
}
}
return doc;
}
/*
* Create the Resource tree, and then Call writeResource or LDML2ICUBinaryWriter.writeBinaryFile(), whichever is
* appropriate
*/
private void createResourceBundle(LDML2ICUInputLocale loc) {
try {
// calculate the list of vettable xpaths.
try {
setXPathList(makeXPathList(loc));
} catch (RuntimeException e) {
throw new IllegalArgumentException("Can't make XPathList for: " + loc).initCause(e);
}
// Create the Resource linked list which will hold the
// data after parsing
// The assumption here is that the top
// level resource is always a table in ICU
Resource res = parseBundle(loc);
if (res != null && ((ResourceTable) res).first != null) {
if (loc.getSpecialsFile() != null) {
String dir = specialsDir.replace('\\', '/');
dir = "<path>" + dir.substring(dir.indexOf("/xml"), dir.length());
String locName = loc.getLocale();
if (res.comment == null) {
res.comment = " ICU <specials> source: " + dir + "/" + locName + ".xml";
} else {
res.comment = res.comment + " ICU <specials> source: " + dir + "/" + locName + ".xml";
}
}
// write out the bundle depending on if writing Binary or txt
if (writeBinary) {
LDML2ICUBinaryWriter.writeBinaryFile(res, destDir, loc.getLocale());
} else {
String sourceInfo = sourceDir.replace('\\', '/') + "/" + loc.getLocale() + ".xml";
writer.writeResource(res, sourceInfo);
}
}
// writeAliasedResource();
} catch (Throwable se) {
log.error("Parsing and writing " + loc.getLocale() + " " + se.toString(), se);
System.exit(1);
}
}
private static final String LOCALE_SCRIPT = "LocaleScript";
private static final String NUMBER_ELEMENTS = "NumberElements";
private static final String NUMBER_PATTERNS = "NumberPatterns";
private static final String AM_PM_MARKERS = "AmPmMarkers";
private static final String DTP = "DateTimePatterns";
private static final String DTE = "DateTimeElements";
private static Map<String, String> keyNameMap = new TreeMap<String, String>();
private static final Map<String, String> deprecatedTerritories = new TreeMap<String, String>();
// TODO: should be a set?
static {
keyNameMap.put("days", "dayNames");
keyNameMap.put("months", "monthNames");
keyNameMap.put("territories", "Countries");
keyNameMap.put("languages", "Languages");
keyNameMap.put("languagesShort", "LanguagesShort");
keyNameMap.put("currencies", "Currencies");
keyNameMap.put("variants", "Variants");
keyNameMap.put("scripts", "Scripts");
keyNameMap.put("keys", "Keys");
keyNameMap.put("types", "Types");
keyNameMap.put("version", "Version");
keyNameMap.put("exemplarCharacters", "ExemplarCharacters");
keyNameMap.put("auxiliary", "AuxExemplarCharacters");
keyNameMap.put("currencySymbol", "ExemplarCharactersCurrency");
keyNameMap.put("index", "ExemplarCharactersIndex");
keyNameMap.put("punctuation", "ExemplarCharactersPunctuation");
keyNameMap.put("timeZoneNames", "zoneStrings");
// keyNameMap.put("localizedPatternChars", "localPatternChars");
keyNameMap.put("paperSize", "PaperSize");
keyNameMap.put("measurementSystem", "MeasurementSystem");
keyNameMap.put("measurementSystemNames", "measurementSystemNames");
keyNameMap.put("codePatterns", "codePatterns");
keyNameMap.put("fractions", "CurrencyData");
keyNameMap.put("quarters", "quarters");
keyNameMap.put("dayPeriods", "dayPeriods");
keyNameMap.put("displayName", "dn");
keyNameMap.put("icu:breakDictionaryData", "BreakDictionaryData");
deprecatedTerritories.put("BQ", "");
deprecatedTerritories.put("CT", "");
deprecatedTerritories.put("DD", "");
deprecatedTerritories.put("FQ", "");
deprecatedTerritories.put("FX", "");
deprecatedTerritories.put("JT", "");
deprecatedTerritories.put("MI", "");
deprecatedTerritories.put("NQ", "");
deprecatedTerritories.put("NT", "");
deprecatedTerritories.put("PC", "");
deprecatedTerritories.put("PU", "");
deprecatedTerritories.put("PZ", "");
deprecatedTerritories.put("SU", "");
deprecatedTerritories.put("VD", "");
deprecatedTerritories.put("WK", "");
deprecatedTerritories.put("YD", "");
// TODO: "FX", "RO", "TP", "ZR", /* obsolete country codes */
}
public static ResourceArray getResourceArray(String str, String name) {
if (str != null) {
String[] strs = str.split("\\s+");
ResourceArray arr = new ResourceArray();
arr.name = name;
Resource curr = null;
for (int i = 0; i < strs.length; i++) {
ResourceString string = new ResourceString();
string.val = strs[i];
if (curr == null) {
curr = arr.first = string;
} else {
curr.next = string;
curr = curr.next;
}
}
return arr;
}
return null;
}
public static String getICUAlias(String tzid) {
// This function is used to return the compatibility aliases for ICU.
// It should match the ICUZONES file in ICU4C source/tools/tzcode/icuzones.
// Note that since we don't expect this to change AT ALL over time, it is
// easier to just hard code the information here. We only include those
// aliases that are NOT in CLDR.
if (tzid.equals("Australia/Darwin")) return ("ACT");
if (tzid.equals("Australia/Sydney")) return ("AET");
if (tzid.equals("America/Argentina/Buenos_Aires")) return ("AGT");
if (tzid.equals("Africa/Cairo")) return ("ART");
if (tzid.equals("America/Anchorage")) return ("AST");
if (tzid.equals("America/Sao_Paulo")) return ("BET");
if (tzid.equals("Asia/Dhaka")) return ("BST");
if (tzid.equals("Africa/Harare")) return ("CAT");
if (tzid.equals("America/St_Johns")) return ("CNT");
if (tzid.equals("America/Chicago")) return ("CST");
if (tzid.equals("Asia/Shanghai")) return ("CTT");
if (tzid.equals("Africa/Addis_Ababa")) return ("EAT");
if (tzid.equals("Europe/Paris")) return ("ECT");
if (tzid.equals("America/Indianapolis")) return ("IET");
if (tzid.equals("Asia/Calcutta")) return ("IST");
if (tzid.equals("Asia/Tokyo")) return ("JST");
if (tzid.equals("Pacific/Apia")) return ("MIT");
if (tzid.equals("Asia/Yerevan")) return ("NET");
if (tzid.equals("Pacific/Auckland")) return ("NST");
if (tzid.equals("Asia/Karachi")) return ("PLT");
if (tzid.equals("America/Phoenix")) return ("PNT");
if (tzid.equals("America/Puerto_Rico")) return ("PRT");
if (tzid.equals("America/Los_Angeles")) return ("PST");
if (tzid.equals("Pacific/Guadalcanal")) return ("SST");
if (tzid.equals("Asia/Saigon")) return ("VST");
return null;
}
private String ldmlVersion_ = null;
private String getLdmlVersion() {
return ldmlVersion_;
}
private void setLdmlVersion(String version) {
ldmlVersion_ = version;
}
private Resource parseBundle(LDML2ICUInputLocale loc) {
final boolean SEPARATE_LDN = false;
setLdmlVersion("0.0");
String localeID = loc.getFile().getLocaleID();
ResourceTable mainTable = new ResourceTable();
mainTable.name = localeID;
// handle identity
Resource version = parseIdentity(loc);
if (version != null) {
mainTable.appendContents(version);
}
// handle alias, early exit
if (loc.getFile().isHere("//ldml/alias")) {
Resource res = ICUResourceWriter.createString("\"%%ALIAS\"", loc.getBasicAttributeValue("//ldml/alias", LDMLConstants.SOURCE));
mainTable.appendContents(res);
return mainTable;
}
// Short term workaround to skip adding %%Parent in collation data.
// See CldrBug#3589 and IcuBug#8425 - yoshito
boolean isCollationRes = false;
Iterator<String> xpathItr = loc.getFile().iterator("//ldml/collations");
if (xpathItr.hasNext()) {
isCollationRes = true;
}
// If this locale has an explicit parent, then put that into the resource file
if (supplementalDataInfo != null && supplementalDataInfo.getParentLocale(localeID) != null && !isCollationRes) {
ResourceString pl = new ResourceString();
pl.name = "%%Parent";
pl.val = supplementalDataInfo.getParentLocale(localeID);
mainTable.appendContents(pl);
}
// Now, loop over other stuff.
String stuff[] = {
// Following two resources are handled above
// LDMLConstants.ALIAS,
// LDMLConstants.IDENTITY,
LDMLConstants.SPECIAL, LDMLConstants.LDN, LDMLConstants.LAYOUT,
// LDMLConstants.FALLBACK
LDMLConstants.CHARACTERS, LDMLConstants.DELIMITERS, LDMLConstants.DATES, LDMLConstants.NUMBERS,
// LDMLConstants.POSIX,
// LDMLConstants.SEGMENTATIONS,
LDMLConstants.REFERENCES, LDMLConstants.RBNF, LDMLConstants.COLLATIONS, LDMLConstants.UNITS, LDMLConstants.UNITS_SHORT,
LDMLConstants.LIST_PART
};
for (String name : stuff) {
String xpath = "//ldml/" + name;
log.info(name + " ");
Resource res = null;
if (name.equals(LDMLConstants.SPECIAL)) {
res = parseSpecialElements(loc, xpath);
} else if (!SEPARATE_LDN && name.equals(LDMLConstants.LDN)) {
res = parseLocaleDisplayNames(loc);
} else if (name.equals(LDMLConstants.LAYOUT)) {
res = parseLayout(loc, xpath);
} else if (name.equals(LDMLConstants.FALLBACK)) {
// ignored
} else if (name.equals(LDMLConstants.CHARACTERS)) {
res = parseCharacters(loc, xpath);
} else if (name.equals(LDMLConstants.DELIMITERS)) {
res = parseDelimiters(loc, xpath);
} else if (name.equals(LDMLConstants.LIST_PART)) {
res = parseLists(loc, xpath);
} else if (name.equals(LDMLConstants.DATES)) {
res = parseDates(loc, xpath);
} else if (name.equals(LDMLConstants.NUMBERS)) {
res = parseNumbers(loc, xpath);
} else if (name.equals(LDMLConstants.COLLATIONS)) {
if (sourceDir.indexOf("coll") > 0) {
res = parseCollations(loc, xpath);
}
} else if (name.equals(LDMLConstants.POSIX)) {
// res = parsePosix(loc, xpath);
} else if (name.equals(LDMLConstants.RBNF)) {
res = parseRBNF(loc, xpath);
} else if (name.equals(LDMLConstants.SEGMENTATIONS)) {
// TODO: FIX ME with parseSegmentations();
if (DEBUG) {
log.warning("Not producing resource for " + xpath.toString());
}
} else if (name.indexOf("icu:") > -1 || name.indexOf("openOffice:") > -1) {
// TODO: these are specials .. ignore for now ... figure out
// what to do later
} else if (name.equals(LDMLConstants.REFERENCES)) {
// TODO: This is special documentation... ignore for now
if (DEBUG) {
log.warning("Not producing resource for " + xpath.toString());
}
} else if (name.equals(LDMLConstants.UNITS)) {
res = parseUnits(loc, name, null);
} else if (name.equals(LDMLConstants.UNITS_SHORT)) {
res = parseUnits(loc, name, LDMLConstants.SHORT);
} else {
log.error("Encountered unknown <" + "//ldml" + "> subelement: " + name);
System.exit(-1);
}
if (res != null) { // have an item
mainTable.appendContents(res);
}
}
if (sourceDir.indexOf("main") > 0 /* && !LDMLUtilities.isLocaleAlias(root) */) {
String locName = loc.getLocale();
String country = ULocale.getCountry(locName);
String variant = ULocale.getVariant(locName);
boolean isRoot = locName.equals("root");
Resource temp = parseMeasurement(country, variant, isRoot);
if (temp != null) {
mainTable.appendContents(temp);
}
}
log.info("");
if (supplementalDoc != null) {
/*
* TODO: comment this out for now. We shall revisit when we have information on how to present the script
* data with new API Resource res = parseLocaleScript(supplementalDoc); if (res != null) { if (current ==
* null) { table.first = res; current = findLast(res); }else{ current.next = res; current = findLast(res); }
* res = null; }
*
* Resource res = parseMetaData(supplementalDoc);
*/
}
return mainTable;
}
private static Resource findResource(Resource res, String type) {
Resource current = res;
Resource ret = null;
while (current != null) {
if (current.name != null && current.name.equals(type)) {
return current;
}
if (current.first != null) {
ret = findResource(current.first, type);
}
if (ret != null) {
break;
}
current = current.next;
}
return ret;
}
/**
* Higher convenience level than parseAliasResource Check to see if there is an alias at xpath + "/alias", if so,
* create & return it.
*/
private Resource getAliasResource(LDML2ICUInputLocale loc, String xpath) {
String name = XPPUtil.getXpathName(xpath);
String aliasPath = xpath + "/alias";
Resource aRes = parseAliasResource(loc, aliasPath);
if (aRes != null) {
aRes.name = name;
}
return aRes;
}
private Resource parseAliasResource(LDML2ICUInputLocale loc, String xpath) {
String source = loc.getBasicAttributeValue(xpath, LDMLConstants.SOURCE);
String path = loc.getBasicAttributeValue(xpath, LDMLConstants.PATH);
if (source == null && path == null) {
if (!loc.getFile().isHere(xpath)) {
return null;
}
}
try {
ResourceAlias alias = new ResourceAlias();
String basePath = xpath.replaceAll("/alias.*$", "");
String fullPath = loc.getFile().getFullXPath(xpath).replaceAll("/alias.*$", "");
if (path != null) {
path = path.replaceAll("='", "=\"").replaceAll("']", "\"]");
}
String val = LDMLUtilities.convertXPath2ICU(source, path, basePath, fullPath);
alias.val = val;
alias.name = basePath;
return alias;
} catch (TransformerException ex) {
log.error("Could not compile XPATH for source: " + source + " path: " + path + " Node: " + xpath, ex);
System.exit(-1);
}
return null;
// TODO update when XPATH is integrated into LDML
}
private Resource parseAliasResource(Node node, StringBuilder xpath) {
return parseAliasResource(node, xpath, false);
}
private Resource parseAliasResource(Node node, StringBuilder xpath, boolean isCollation) {
int saveLength = xpath.length();
getXPath(node, xpath);
try {
if (node != null && (isCollation || !isNodeNotConvertible(node, xpath))) {
ResourceAlias alias = new ResourceAlias();
xpath.setLength(saveLength);
String val = LDMLUtilities.convertXPath2ICU(node, null, xpath);
alias.val = val;
alias.name = node.getParentNode().getNodeName();
xpath.setLength(saveLength);
return alias;
}
} catch (TransformerException ex) {
log.error("Could not compile XPATH for" + " source: " + LDMLUtilities.getAttributeValue(node, LDMLConstants.SOURCE) + " path: "
+ LDMLUtilities.getAttributeValue(node, LDMLConstants.PATH) + " Node: " + node.getParentNode().getNodeName(), ex);
System.exit(-1);
}
xpath.setLength(saveLength);
// TODO update when XPATH is integrated into LDML
return null;
}
private Resource parseIdentity(LDML2ICUInputLocale loc) {
// version #
String verPath = "//ldml/" + LDMLConstants.IDENTITY + "/" + LDMLConstants.VERSION;
String version = XPPUtil.getBasicAttributeValue(loc.getFile(), verPath, LDMLConstants.NUMBER);
if (loc.resolved() != null) {
String version2 = XPPUtil.getBasicAttributeValue(loc.resolved(), verPath, LDMLConstants.NUMBER);
String foundIn = loc.resolved().getSourceLocaleID(verPath, null);
if (foundIn != null && foundIn.equals(loc.getLocale()) && version2 != null) {
// make sure it is in our 'original' locale.
version = version2; // use version from 'resolved' -
}
}
if (version == null) {
log.warning("No version #??");
return null;
}
version = version.replaceAll(".*?Revision: (.*?) .*", "$1");
int intversion;
try {
intversion = Integer.valueOf(version).intValue();
} catch (NumberFormatException ex) {
intversion = 1;
}
if (intversion > 1) { // This is a SVN changeset number
int x = intversion / 10000;
int y = (intversion - 10000 * x) / 100;
int z = (intversion - 10000 * x) % 100;
version = "2." + Integer.toString(x) + "." + Integer.toString(y) + "." + Integer.toString(z);
}
return ICUResourceWriter.createString(keyNameMap.get(LDMLConstants.VERSION), version);
}
private static final String[] registeredKeys = new String[] { "collation", "calendar", "currency", "numbers" };
private Resource parseLocaleDisplayNames(LDML2ICUInputLocale loc) {
Resource first = null;
Resource current = null;
Resource res = null;
String stuff[] = { LDMLConstants.LANGUAGES, LDMLConstants.SCRIPTS, LDMLConstants.TERRITORIES, LDMLConstants.KEYS, LDMLConstants.VARIANTS, LDMLConstants.MSNS, LDMLConstants.TYPES,
LDMLConstants.ALIAS, LDMLConstants.CODE_PATTERNS, LDMLConstants.LOCALEDISPLAYPATTERN, LDMLConstants.LANGUAGES_SHORT };
for (String name : stuff) {
if (name.equals(LDMLConstants.LANGUAGES) || name.equals(LDMLConstants.SCRIPTS) || name.equals(LDMLConstants.TERRITORIES) || name.equals(LDMLConstants.KEYS)
|| name.equals(LDMLConstants.VARIANTS) || name.equals(LDMLConstants.MSNS) || name.equals(LDMLConstants.CODE_PATTERNS)) {
res = parseList(loc, name);
} else if (name.equals(LDMLConstants.TYPES)) {
res = parseDisplayTypes(loc, name);
} else if (name.equals(LDMLConstants.LOCALEDISPLAYPATTERN)) {
res = parseLocaleDisplayPattern(loc);
} else if (name.equals(LDMLConstants.ALIAS)) {
// res = parseAliasResource(loc, name);
// TODO: parseAliasResource - these are different types in ICU, can't just alias them all
} else if (name.equals(LDMLConstants.LANGUAGES_SHORT)) {
res = parseListAlt(loc, LDMLConstants.LANGUAGES, name, LDMLConstants.SHORT);
} else {
log.error("Unknown element found: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
return first;
}
private Resource parseDisplayTypes(LDML2ICUInputLocale loc, String name) {
log.setStatus(loc.getLocale());
StringBuilder myXpath = new StringBuilder();
myXpath.append("//ldml/localeDisplayNames/types");
ResourceTable table = new ResourceTable();
table.name = keyNameMap.get(LDMLConstants.TYPES);
Resource alias = null;
// if the whole thing is an alias
if ((alias = getAliasResource(loc, myXpath.toString())) != null) {
alias.name = table.name;
return alias;
}
for (int i = 0; i < registeredKeys.length; i++) {
ResourceTable subTable = new ResourceTable();
subTable.name = registeredKeys[i];
for (Iterator<String> iter = loc.getFile().iterator(myXpath.toString()); iter.hasNext();) {
String xpath = iter.next();
String name2 = XPPUtil.getXpathName(xpath);
if (!LDMLConstants.TYPE.equals(name2)) {
log.error("Encountered unknown <" + xpath + "> subelement: " + name2 + " while looking for " + LDMLConstants.TYPE);
System.exit(-1);
}
String key = XPPUtil.getAttributeValue(xpath, LDMLConstants.KEY);
if (!registeredKeys[i].equals(key)) {
continue;
}
String type = XPPUtil.getAttributeValue(xpath, LDMLConstants.TYPE);
if (loc.isPathNotConvertible(xpath)) {
continue;
}
String val = loc.getFile().getStringValue(xpath);
Resource string = ICUResourceWriter.createString(type, val);
subTable.appendContents(string);
}
if (!subTable.isEmpty()) {
table.appendContents(subTable);
}
}
if (!table.isEmpty()) {
return table;
}
return null;
}
private Resource parseLocaleDisplayPattern(LDML2ICUInputLocale loc) {
log.setStatus(loc.getLocale());
StringBuilder myXpath = new StringBuilder();
myXpath.append("//ldml/localeDisplayNames/");
myXpath.append(LDMLConstants.LOCALEDISPLAYPATTERN);
ResourceTable table = new ResourceTable();
table.name = LDMLConstants.LOCALEDISPLAYPATTERN;
Resource alias = null;
// if the whole thing is an alias
if ((alias = getAliasResource(loc, myXpath.toString())) != null) {
alias.name = table.name;
return alias;
}
for (Iterator<String> iter = loc.getFile().iterator(myXpath.toString()); iter.hasNext();) {
String xpath = iter.next();
if (loc.isPathNotConvertible(xpath)) {
continue;
}
String element = XPPUtil.getXpathName(xpath);
String name = null;
if (LDMLConstants.LOCALE_PATTERN.equals(element)) {
name = LDMLConstants.PATTERN;
} else if (LDMLConstants.LOCALE_SEPARATOR.equals(element)) {
name = LDMLConstants.SEPARATOR;
} else if (LDMLConstants.LOCALE_KEYTYPE_PATTERN.equals(element)) {
name = LDMLConstants.KEYTYPE_PATTERN;
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + element + " while looking for " + LDMLConstants.TYPE);
System.exit(-1);
}
String value = loc.getFile().getStringValue(xpath);
Resource res = ICUResourceWriter.createString(name, value);
table.appendContents(res);
}
if (!table.isEmpty()) {
return table;
}
return null;
}
private Resource parseList(LDML2ICUInputLocale loc, String name) {
ResourceTable table = new ResourceTable();
String rootNodeName = name;
table.name = keyNameMap.get(rootNodeName);
Resource current = null;
boolean uc = rootNodeName.equals(LDMLConstants.VARIANTS);
boolean prohibit = rootNodeName.equals(LDMLConstants.TERRITORIES);
String origXpath = "//ldml/localeDisplayNames/" + name;
if ((current = getAliasResource(loc, origXpath)) != null) {
current.name = table.name;
return current;
}
for (Iterator<String> iter = loc.getFile().iterator(origXpath); iter.hasNext();) {
String xpath = iter.next();
if (loc.isPathNotConvertible(xpath)) {
continue;
}
ResourceString res = new ResourceString();
res.name = loc.getBasicAttributeValue(xpath, LDMLConstants.TYPE);
if (uc) {
res.name = res.name.toUpperCase();
}
res.val = loc.getFile().getStringValue(xpath);
if (res.name == null) {
log.error(name + " - " + res.name + " = " + res.val);
}
if (prohibit == true && deprecatedTerritories.get(res.name) != null) {
res = null;
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseListAlt(LDML2ICUInputLocale loc, String originalName, String name, String altValue) {
ResourceTable table = new ResourceTable();
String rootNodeName = name;
table.name = keyNameMap.get(rootNodeName);
Resource current = null;
boolean uc = rootNodeName.equals(LDMLConstants.VARIANTS);
boolean prohibit = rootNodeName.equals(LDMLConstants.TERRITORIES);
String origXpath = "//ldml/localeDisplayNames/" + originalName;
if ((current = getAliasResource(loc, origXpath)) != null) {
current.name = table.name;
return current;
}
for (Iterator<String> iter = loc.getFile().iterator(origXpath); iter.hasNext();) {
String xpath = iter.next();
// Check for the "alt" attribute, and process it if requested.
// Otherwise, skip it.
String alt = loc.getBasicAttributeValue(xpath, LDMLConstants.ALT);
if (alt == null || !alt.equals(altValue)) {
continue;
}
ResourceString res = new ResourceString();
res.name = loc.getBasicAttributeValue(xpath, LDMLConstants.TYPE);
if (uc) {
res.name = res.name.toUpperCase();
}
res.val = loc.getFile().getStringValue(xpath);
if (res.name == null) {
log.error(name + " - " + res.name + " = " + res.val);
}
if (prohibit == true && deprecatedTerritories.get(res.name) != null) {
res = null;
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseArray(LDML2ICUInputLocale loc, String xpath) {
ResourceArray array = new ResourceArray();
String name = XPPUtil.getXpathName(xpath);
array.name = keyNameMap.get(name);
Resource current = null;
// want them in sorted order (?)
Set<String> xpaths = new TreeSet<String>();
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
xpaths.add(xpath);
}
for (String apath : xpaths) {
name = XPPUtil.getXpathName(apath);
if (current == null) {
current = array.first = new ResourceString();
} else {
current.next = new ResourceString();
current = current.next;
}
((ResourceString) current).val = loc.getFile().getStringValue(apath);
}
if (array.first != null) {
return array;
}
return null;
}
/**
* Parse a table (k/v pair) into an ICU table
*
* @param loc
* locale
* @param xpath
* base xpath of items
* @param element
* the item to search for
* @param attribute
* the attribute which will become the 'key' in icu
* @return the table, or null
*/
private Resource parseTable(LDML2ICUInputLocale loc, String xpath, String element, String attribute) {
ResourceTable array = new ResourceTable();
String name = XPPUtil.getXpathName(xpath);
array.name = keyNameMap.get(name); // attempt
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
if (loc.isPathNotConvertible(xpath)) {
continue;
}
name = XPPUtil.getXpathName(xpath);
if (!name.equals(element)) {
log.error("Err: unknown item " + xpath + " / " + name + " - expected " + element);
continue;
}
String type = loc.getBasicAttributeValue(xpath, attribute);
String val = loc.getFile().getStringValue(xpath);
array.appendContents(ICUResourceWriter.createString(type, val));
}
if (array.first != null) {
return array;
}
return null;
}
private static final String ICU_SCRIPT = "icu:script";
private Resource parseCharacters(LDML2ICUInputLocale loc, String xpath) {
Resource first = null;
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String aPath = iter.next();
if (loc.isPathNotConvertible(aPath)) {
continue;
}
String name = XPPUtil.getXpathName(aPath);
Resource res = null;
if (name.equals(LDMLConstants.EXEMPLAR_CHARACTERS)) {
String type = loc.getBasicAttributeValue(aPath, LDMLConstants.TYPE);
res = parseStringResource(loc, aPath);
if (type != null && type.equals(LDMLConstants.AUXILIARY)) {
res.name = keyNameMap.get(LDMLConstants.AUXILIARY);
} else if (type != null && type.equals(LDMLConstants.CURRENCY_SYMBOL)) {
res.name = keyNameMap.get(LDMLConstants.CURRENCY_SYMBOL);
} else if (type != null && type.equals(LDMLConstants.INDEX)) {
res.name = keyNameMap.get(LDMLConstants.INDEX);
} else if (type != null && type.equals(LDMLConstants.PUNCTUATION)) {
res.name = keyNameMap.get(LDMLConstants.PUNCTUATION);
} else {
res.name = keyNameMap.get(name);
}
} else if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, aPath);
} else if (name.equals(LDMLConstants.MAPPING)) {
// Currently we dont have a way to represent this data in ICU !
// And we don't need to
// if (DEBUG)printXPathWarning(node, xpath);
} else if (aPath.contains(LDMLConstants.STOPWORDS)) {
// Skip for now
} else if (aPath.indexOf("/" + LDMLConstants.SPECIAL) > 0) {
res = parseSpecialElements(loc, aPath);
} else if (aPath.contains("/ellipsis")) {
System.out.println("TODO: Fix /ellipsis");
} else if (aPath.contains("/moreInformation")) {
System.out.println("TODO: Fix /moreInformation");
} else {
// skip ellipsis for now
log.error("Unknown character element found: " + aPath + " / " + name + " -> " + loc.getFile().getFullXPath(aPath));
System.exit(-1);
}
if (res != null) {
first = Resource.addAfter(first, res);
}
}
return first;
}
private Resource parseStringResource(LDML2ICUInputLocale loc, String xpath) {
ResourceString str = new ResourceString();
str.val = loc.getFile().getStringValue(xpath);
str.name = XPPUtil.getXpathName(xpath);
return str;
}
private Resource parseDelimiters(LDML2ICUInputLocale loc, String xpath) {
if (loc.isPathNotConvertible(xpath)) {
return null;
}
ResourceTable table = new ResourceTable();
table.name = XPPUtil.getXpathName(xpath);
Resource current = table.first;
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
String name = XPPUtil.getXpathName(xpath);
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.QS) || name.equals(LDMLConstants.QE) || name.equals(LDMLConstants.AQS) || name.equals(LDMLConstants.AQE)) {
// getXPath(node, xpath);
if (loc.isPathNotConvertible(xpath)) {
continue;
}
res = parseStringResource(loc, xpath);
} else if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
} else {
log.error("Unknown element found: " + xpath);
System.exit(-1);
}
// this code is ugly, and repeated all over. Should be encapsulated, but table.addAfter(res) doesn't do the right thing.
// TODO fix it.
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
/**
* Goal is to change:
<listPatterns>
<listPattern type="XXX">
<listPatternPart type="2">{0} and {1}</listPatternPart>
<listPatternPart type="end">{0}, and {1}</listPatternPart>
</listPattern>
</listPatterns>
to
listPattern{
XXX{
2{"{0} and {1}"}
end{"{0}, and {1}"}
}
}
// note that XXX = standard if "XXX" == ""
* @param loc
* @param xpath
* @return
*/
private Resource parseLists(LDML2ICUInputLocale loc, String xpath) {
if (loc.isPathNotConvertible(xpath)) {
return null;
}
// if the whole thing is an alias
Resource alias = null;
if ((alias = getAliasResource(loc, xpath.toString())) != null) {
alias.name = "listPattern";
return alias;
}
// Since we have a two-level table, make a map to store the contents
// If the items are always in order, we don't really need a map, but this is simpler to manage.
Map<String,ResourceTable> subtables = new TreeMap<String,ResourceTable>();
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
if (loc.isPathNotConvertible(xpath)) {
continue;
}
// since we are a two-level table, we need to have an intermediate table
String index = XPPUtil.getAttributeValue(xpath, "listPattern", "type");
if (index == null) {
index = "standard";
}
ResourceTable subtable = subtables.get(index);
if (subtable == null) {
subtable = new ResourceTable();
subtable.name = index;
subtables.put(index, subtable);
}
ResourceString res = new ResourceString();
res.name = XPPUtil.getAttributeValue(xpath, "listPatternPart", "type");
res.val = loc.getFile().getStringValue(xpath);
addToTable(subtable, res);
}
if (subtables.size() == 0) {
return null;
}
ResourceTable table = new ResourceTable();
table.name = "listPattern";
for (Resource res : subtables.values()) {
addToTable(table, res);
}
return table;
}
/**
* A hack to avoid duplicating code, and get around the fact that the model for resource tables doesn't keep an end-pointer.
* (And why it doesn't use standard collections??)
* @param table
* @param resource
*/
static void addToTable(Resource table, Resource resource) {
Resource current = table.first;
if (current == null) {
table.first = resource;
} else {
while (current.next != null) {
current = current.next;
}
current.next = resource;
}
}
private Resource parseMeasurement(String country, String variant, boolean isRoot) {
Resource ret = null;
// optimization
if (variant.length() != 0) {
return ret;
}
Resource current = null;
Resource first = null;
StringBuilder xpath = new StringBuilder("//supplementalData/measurementData");
Node root = LDMLUtilities.getNode(supplementalDoc, xpath.toString());
if (root == null) {
throw new RuntimeException("Could not load: " + xpath.toString());
}
int savedLength = xpath.length();
int oldLength = xpath.length();
// if the whole node is marked draft then
// don't write anything
if (isNodeNotConvertible(root, xpath)) {
return null;
}
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
Resource res = null;
if (name.equals(LDMLConstants.MS)) {
getXPath(node, xpath);
if (isNodeNotConvertible(node, xpath)) {
xpath.setLength(oldLength);
continue;
}
String terr = LDMLUtilities.getAttributeValue(node, LDMLConstants.TERRITORIES);
if (terr != null && ((isRoot && terr.equals("001")) || (country.length() > 0 && terr.indexOf(country) >= 0))) {
ResourceInt resint = new ResourceInt();
String sys = LDMLUtilities.getAttributeValue(node, LDMLConstants.TYPE);
if (sys.equals("US")) {
resint.val = "1";
} else {
resint.val = "0";
}
resint.name = keyNameMap.get(LDMLConstants.MS);
res = resint;
}
} else if (name.equals(LDMLConstants.PAPER_SIZE)) {
String terr = LDMLUtilities.getAttributeValue(node, LDMLConstants.TERRITORIES);
if (terr != null && ((isRoot && terr.equals("001")) || (country.length() > 0 && terr.indexOf(country) >= 0))) {
ResourceIntVector vector = new ResourceIntVector();
vector.name = keyNameMap.get(name);
ResourceInt height = new ResourceInt();
ResourceInt width = new ResourceInt();
vector.first = height;
height.next = width;
String type = LDMLUtilities.getAttributeValue(node, LDMLConstants.TYPE);
/*
* For A4 size paper the height and width are 297 mm and 210 mm repectively, and for US letter size
* the height and width are 279 mm and 216 mm respectively.
*/
if (type.equals("A4")) {
height.val = "297";
width.val = "210";
} else if (type.equals("US-Letter")) {
height.val = "279";
width.val = "216";
} else {
throw new RuntimeException("Unknown paper type: " + type);
}
res = vector;
}
} else {
log.error("Unknown element found: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
xpath.delete(oldLength, xpath.length());
}
xpath.delete(savedLength, xpath.length());
return first;
}
private Resource parseLayout(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
table.name = XPPUtil.getXpathName(xpath);
if (loc.isPathNotConvertible(xpath)) {
return null;
}
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String aPath = iter.next();
String name = XPPUtil.getXpathName(aPath);
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, aPath);
return res;
}
if (name.equals(LDMLConstants.INLIST)) {
ResourceString cs = null;
if (!loc.isPathNotConvertible(aPath)) {
String casing = loc.getBasicAttributeValue(xpath, LDMLConstants.CASING);
if (casing != null) {
cs = new ResourceString();
cs.comment = "Used for figuring out the casing of characters in a list.";
cs.name = LDMLConstants.CASING;
cs.val = casing;
res = cs;
}
}
} else if (name.equals(LDMLConstants.ORIENTATION)) {
ResourceString chs = null;
ResourceString lns = null;
if (!loc.isPathNotConvertible(aPath)) {
String characters = loc.getBasicAttributeValue(aPath, LDMLConstants.CHARACTERS);
String lines = loc.getBasicAttributeValue(aPath, LDMLConstants.LINES);
if (characters != null) {
chs = new ResourceString();
chs.name = LDMLConstants.CHARACTERS;
chs.val = characters;
}
if (lines != null) {
lns = new ResourceString();
lns.name = LDMLConstants.LINES;
lns.val = lines;
}
if (chs != null) {
res = chs;
chs.next = lns;
} else {
res = lns;
}
}
} else if (name.equals(LDMLConstants.INTEXT)) {
} else {
log.error("Unknown element found: " + xpath + " / " + name);
System.exit(-1);
}
if (res != null) {
table.appendContents(res);
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseDates(LDML2ICUInputLocale loc, String xpath) {
Resource first = null;
Resource current = null;
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
return current;
}
// if the whole node is marked draft then
// don't write anything
final String stuff[] = { LDMLConstants.DEFAULT,
// LDMLConstants.LPC,
LDMLConstants.CALENDARS, LDMLConstants.TZN,
// LDMLConstants.DRP,
};
String origXpath = xpath;
for (int jj = 0; jj < stuff.length; jj++) {
String name = stuff[jj];
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
// dont compute xpath
// res = parseAliasResource(loc, xpath);
// handled above
} else if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.LPC)) {
// localized pattern chars are deprecated
} else if (name.equals(LDMLConstants.CALENDARS)) {
res = parseCalendars(loc, xpath);
} else if (name.equals(LDMLConstants.TZN)) {
res = parseTimeZoneNames(loc, xpath);
} else if (name.equals(LDMLConstants.DRP)) {
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
return first;
}
private Resource parseCalendars(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = LDMLConstants.CALENDAR;
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name;
return current;
}
// if the whole node is marked draft then
// don't write anything
final String stuff[] = {
// LDMLConstants.ALIAS,
LDMLConstants.DEFAULT, LDMLConstants.CALENDAR, };
String origXpath = xpath;
for (int jj = 0; jj < stuff.length; jj++) {
String name = stuff[jj];
xpath = origXpath + "/" + name;
if (!loc.isNotOnDisk() && loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.CALENDAR)) {
Set<String> cals = loc.getByType(xpath, LDMLConstants.CALENDAR);
for (String cal : cals) {
res = parseCalendar(loc, xpath + "[@type=\"" + cal + "\"]");
if (res != null) {
table.appendContents(res);
res = null;
}
}
// if there was an item, resync current.
if (table.first != null) {
current = table.first.end();
}
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseTimeZoneNames(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = keyNameMap.get(XPPUtil.getXpathName(xpath));
Set<String> zones = new HashSet<String>();
Set<String> metazones = new HashSet<String>();
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String apath = iter.next();
String name = XPPUtil.getXpathName(apath, 3);
if (loc.isPathNotConvertible(apath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, apath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, apath, name);
} else if (name.equals(LDMLConstants.ZONE)) {
String tzname = XPPUtil.getAttributeValue(apath, LDMLConstants.ZONE, LDMLConstants.TYPE);
zones.add(tzname);
} else if (name.equals(LDMLConstants.METAZONE)) {
String mzname = XPPUtil.getAttributeValue(apath, LDMLConstants.METAZONE, LDMLConstants.TYPE);
metazones.add(mzname);
} else if (name.equals(LDMLConstants.HOUR_FORMAT) || name.equals(LDMLConstants.GMT_FORMAT) || name.equals(LDMLConstants.GMT_ZERO_FORMAT) || name.equals(LDMLConstants.REGION_FORMAT)
|| name.equals(LDMLConstants.FALLBACK_FORMAT) || name.equals(LDMLConstants.FALLBACK_REGION_FORMAT)) {
ResourceString str = new ResourceString();
str.name = name;
str.val = loc.getFile().getStringValue(apath);
if (str.val != null) {
res = str;
}
} else if (name.equals(LDMLConstants.ABBREVIATION_FALLBACK) || name.equals(LDMLConstants.HOURS_FORMAT) || name.equals(LDMLConstants.PREFERENCE_ORDERING)) {
// deprecated, skip
} else if (name.equals(LDMLConstants.SINGLE_COUNTRIES)) {
ResourceArray arr = new ResourceArray();
arr.name = name;
Resource c = null;
String[] values = null;
if (name.equals(LDMLConstants.SINGLE_COUNTRIES)) {
values = loc.getBasicAttributeValue(apath, LDMLConstants.LIST).split(" ");
} else {
String temp = loc.getBasicAttributeValue(apath, LDMLConstants.CHOICE);
if (temp == null) {
temp = loc.getBasicAttributeValue(apath, LDMLConstants.TYPE);
if (temp == null) {
throw new IllegalArgumentException("Node: " + name + " must have either type or choice attribute");
}
}
values = temp.split("\\s+");
}
for (int i = 0; i < values.length; i++) {
ResourceString str = new ResourceString();
str.val = values[i];
if (c == null) {
arr.first = c = str;
} else {
c.next = str;
c = c.next;
}
}
if (arr.first != null) {
res = arr;
}
} else {
log.error("Encountered unknown <" + apath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
for (Iterator<String> iter = zones.iterator(); iter.hasNext();) {
Resource res = null;
String zonepath = "//ldml/dates/timeZoneNames/zone[@type=\"" + iter.next() + "\"]";
res = parseZone(loc, zonepath);
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
for (Iterator<String> iter = metazones.iterator(); iter.hasNext();) {
Resource res = null;
String zonepath = "//ldml/dates/timeZoneNames/metazone[@type=\"" + iter.next() + "\"]";
res = parseMetazone(loc, zonepath);
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private ResourceString getDefaultResource(LDML2ICUInputLocale loc, String xpath) {
return getDefaultResource(loc, xpath, XPPUtil.getXpathName(xpath));
}
/**
* @deprecated
*/
@Deprecated
public static ResourceString getDefaultResource(Node node, StringBuilder xpath, String name) {
ResourceString str = new ResourceString();
String temp = LDMLUtilities.getAttributeValue(node, LDMLConstants.CHOICE);
if (temp == null) {
temp = LDMLUtilities.getAttributeValue(node, LDMLConstants.TYPE);
if (temp == null) {
throw new IllegalArgumentException("Node: " + name + " must have either type or choice attribute");
}
}
str.name = name;
str.val = temp;
return str;
}
private static ResourceString getDefaultResource(LDML2ICUInputLocale loc, String xpath, String name) {
ResourceString str = new ResourceString();
String temp = loc.getBasicAttributeValue(xpath, LDMLConstants.CHOICE);
if (temp == null) {
temp = loc.getBasicAttributeValue(xpath, LDMLConstants.TYPE);
if (temp == null) {
if (!loc.getFile().isHere(xpath)) {
return null;
}
throw new IllegalArgumentException("Node: " + xpath + " must have either type or choice attribute");
}
}
str.name = name;
str.val = temp;
return str;
}
private static ResourceString getDefaultResourceWithFallback(LDML2ICUInputLocale loc, String xpath, String name) {
ResourceString str = new ResourceString();
if (loc.isPathNotConvertible(xpath)) {
return null;
}
// try to get from the specified locale
String temp = loc.getBasicAttributeValue(xpath, LDMLConstants.CHOICE);
if (temp == null) {
temp = loc.getBasicAttributeValue(xpath, LDMLConstants.TYPE);
}
if (temp == null) {
temp = XPPUtil.getBasicAttributeValue(loc.resolved(), xpath, LDMLConstants.CHOICE);
}
if (temp == null) {
temp = XPPUtil.getBasicAttributeValue(loc.resolved(), xpath, LDMLConstants.TYPE);
}
// check final results
if (temp == null) {
if (!loc.getFile().isHere(xpath)) {
return null;
}
throw new IllegalArgumentException("Node: " + xpath + " must have either type or choice attribute");
}
// return data if we get here
str.name = name;
str.val = temp;
return str;
}
private Resource parseZone(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
ResourceTable uses_mz_table = new ResourceTable();
boolean containsUM = false;
int mz_count = 0;
String id = XPPUtil.getAttributeValue(xpath, LDMLConstants.ZONE, LDMLConstants.TYPE);
table.name = "\"" + id + "\"";
table.name = table.name.replace('/', ':');
Resource current = null;
Resource current_mz = null;
uses_mz_table.name = "um";
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String aPath = iter.next();
String name = XPPUtil.getXpathName(aPath);
Resource res = null;
if (loc.isPathNotConvertible(aPath)) {
continue;
}
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, aPath);
if (res != null) {
res.name = table.name;
}
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, aPath, name);
} else if (name.equals(LDMLConstants.STANDARD) || name.equals(LDMLConstants.DAYLIGHT) || name.equals(LDMLConstants.GENERIC)) {
String shortlong = XPPUtil.getXpathName(aPath, -2).substring(0, 1);
ResourceString str = new ResourceString();
str.name = shortlong + name.substring(0, 1);
str.val = loc.getFile().getStringValue(aPath);
if (str.val != null) {
res = str;
}
} else if (name.equals(LDMLConstants.COMMONLY_USED)) {
ResourceInt resint = new ResourceInt();
String used = loc.getFile().getStringValue(aPath);
if (used.equals("true")) {
resint.val = "1";
} else {
resint.val = "0";
}
resint.name = "cu";
res = resint;
} else if (name.equals(LDMLConstants.USES_METAZONE)) {
ResourceArray this_mz = new ResourceArray();
ResourceString mzone = new ResourceString();
ResourceString from = new ResourceString();
ResourceString to = new ResourceString();
this_mz.name = "mz" + String.valueOf(mz_count);
this_mz.first = mzone;
mzone.next = from;
from.next = to;
mz_count++;
mzone.val = loc.getBasicAttributeValue(aPath, LDMLConstants.MZONE);
String str = loc.getBasicAttributeValue(aPath, LDMLConstants.FROM);
if (str != null) {
from.val = str;
} else {
from.val = "1970-01-01 00:00";
}
str = loc.getBasicAttributeValue(aPath, LDMLConstants.TO);
if (str != null) {
to.val = str;
} else {
to.val = "9999-12-31 23:59";
}
if (current_mz == null) {
uses_mz_table.first = this_mz;
current_mz = this_mz.end();
} else {
current_mz.next = this_mz;
current_mz = this_mz.end();
}
containsUM = true;
res = null;
} else if (name.equals(LDMLConstants.EXEMPLAR_CITY)) {
String ec = loc.getFile().getStringValue(aPath);
if (ec != null) {
ResourceString str = new ResourceString();
str.name = "ec";
str.val = ec;
res = str;
}
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
// Add the metazone mapping table if mz mappings were present
if (containsUM) {
Resource res = uses_mz_table;
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseMetazone(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
String id = XPPUtil.getAttributeValue(xpath, LDMLConstants.METAZONE, LDMLConstants.TYPE);
table.name = "\"meta:" + id + "\"";
table.name = table.name.replace('/', ':');
Resource current = null;
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String aPath = iter.next();
String name = XPPUtil.getXpathName(aPath);
Resource res = null;
if (loc.isPathNotConvertible(aPath)) {
continue;
}
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, aPath);
if (res != null) {
res.name = table.name;
}
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, aPath, name);
} else if (name.equals(LDMLConstants.STANDARD) || name.equals(LDMLConstants.DAYLIGHT) || name.equals(LDMLConstants.GENERIC)) {
String shortlong = XPPUtil.getXpathName(aPath, -2).substring(0, 1);
ResourceString str = new ResourceString();
str.name = shortlong + name.substring(0, 1);
str.val = loc.getFile().getStringValue(aPath);
if (str.val != null) {
res = str;
}
} else if (name.equals(LDMLConstants.COMMONLY_USED)) {
ResourceInt resint = new ResourceInt();
String used = loc.getFile().getStringValue(aPath);
if (used.equals("true")) {
resint.val = "1";
} else {
resint.val = "0";
}
resint.name = "cu";
res = resint;
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private static final String ICU_IS_LEAP_MONTH = "icu:isLeapMonth";
private static final String ICU_LEAP_SYMBOL = "icu:leapSymbol";
private static final String ICU_NON_LEAP_SYMBOL = "icu:nonLeapSymbol";
private static final String leapStrings[] = { ICU_IS_LEAP_MONTH + "/" + ICU_NON_LEAP_SYMBOL, ICU_IS_LEAP_MONTH + "/" + ICU_LEAP_SYMBOL, };
private Resource parseLeapMonth(LDML2ICUInputLocale loc, String xpath) {
// So.
String theArray[] = leapStrings;
ResourceString strs[] = new ResourceString[theArray.length];
GroupStatus status = parseGroupWithFallback(loc, xpath, theArray, strs);
if (GroupStatus.EMPTY == status) {
log.warning("Could not load " + xpath + " - " + theArray[0] + ", etc.");
return null; // NO items were found - don't even bother.
}
if (GroupStatus.SPARSE == status) {
log.warning("Could not load all of " + xpath + " - " + theArray[0] + ", etc.");
return null; // NO items were found - don't even bother.
}
ResourceArray arr = new ResourceArray();
arr.name = "isLeapMonth";
for (ResourceString str : strs) {
arr.appendContents(str);
}
return arr;
}
private Resource parseIntervalFormats(LDML2ICUInputLocale loc, String parentxpath) {
String xpath = parentxpath + "/" + LDMLConstants.INTVL_FMTS;
Resource formats;
formats = parseAliasResource(loc, xpath + "/" + LDMLConstants.ALIAS);
if (formats != null) {
formats.name = LDMLConstants.INTVL_FMTS;
String val = ((ResourceAlias) formats).val;
((ResourceAlias) formats).val = val.replace(DTP + "/", "");
return formats;
}
formats = new ResourceTable();
formats.name = LDMLConstants.INTVL_FMTS;
Map<String, ResourceTable> tableMap = new HashMap<String, ResourceTable>();
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
Resource newres = null;
String localxpath = iter.next();
if (loc.isPathNotConvertible(localxpath)) {
continue;
}
String name = XPPUtil.getXpathName(localxpath);
if (name.equals(LDMLConstants.SPECIAL)) {
newres = parseSpecialElements(loc, xpath);
} else if (name.equals(LDMLConstants.INTVL_FMT_FALL)) {
newres = new ResourceString(LDMLConstants.FALLBACK, loc.getFile().getStringValue(localxpath));
} else if (name.equals(LDMLConstants.GREATEST_DIFF)) {
String parentName = XPPUtil.getXpathName(localxpath, -2);
String tableName = XPPUtil.getAttributeValue(localxpath, parentName, LDMLConstants.ID);
// See if we've already created a table for this particular
// intervalFormatItem.
ResourceTable table = tableMap.get(tableName);
if (table == null) {
// We haven't encountered this one yet, so
// create a new table and put it into the map.
table = new ResourceTable();
table.name = tableName;
tableMap.put(tableName, table);
// Update newres to reflect the fact we've created a new
// table. This will link the table into the resource chain
// for the enclosing table.
newres = table;
}
ResourceString str = new ResourceString();
str.name = XPPUtil.getAttributeValue(localxpath, name, LDMLConstants.ID);
str.val = loc.getFile().getStringValue(localxpath);
table.appendContents(str);
} else {
log.warning("Unknown item " + localxpath);
}
if (newres != null) {
formats.appendContents(newres);
}
}
if (formats.first != null) {
return formats;
}
return null;
}
private Resource parseCalendar(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
boolean writtenAmPm = false;
boolean writtenDTF = false;
table.name = XPPUtil.getAttributeValue(xpath, LDMLConstants.CALENDAR, LDMLConstants.TYPE);
String origXpath = xpath;
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name;
return current;
}
final String stuff[] = { LDMLConstants.DEFAULT, LDMLConstants.MONTHS, LDMLConstants.DAYS,
// LDMLConstants.WEEK,
LDMLConstants.ERAS, LDMLConstants.DATE_FORMATS, LDMLConstants.TIME_FORMATS, LDMLConstants.DATE_TIME_FORMATS, LDMLConstants.SPECIAL,
LDMLConstants.FIELDS, LDMLConstants.QUARTERS, LDMLConstants.DAYPERIODS, };
for (int jj = 0; jj < stuff.length; jj++) {
String name = stuff[jj];
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
if (res != null) {
res.name = table.name;
}
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.MONTHS) || name.equals(LDMLConstants.DAYS)) {
res = parseMonthsAndDays(loc, xpath);
} else if (name.equals(LDMLConstants.WEEK)) {
log.info("<week > element is deprecated and the data should moved to " + supplementalDataFile);
} else if (name.equals(LDMLConstants.DAYPERIODS)) {
if (writtenAmPm == false) {
writtenAmPm = true;
res = parseAmPm(loc, xpath);
}
} else if (name.equals(LDMLConstants.ERAS)) {
res = parseEras(loc, xpath);
} else if (name.equals(LDMLConstants.DATE_FORMATS) || name.equals(LDMLConstants.TIME_FORMATS) || name.equals(LDMLConstants.DATE_TIME_FORMATS)) {
// TODO what to do if a number of formats are present?
if (writtenDTF == false) {
res = parseDTF(loc, origXpath);
writtenDTF = true;
}
if (name.equals(LDMLConstants.DATE_TIME_FORMATS)) {
// handle flexi formats
Resource temp;
temp = parseAliasResource(loc, xpath + "/" + LDMLConstants.ALIAS);
if (temp != null) {
String dtpPath = ((ResourceAlias) temp).val;
// need to replace "/DateTimePatterns" = DTP at end with desired type
ResourceAlias afAlias = new ResourceAlias();
afAlias.name = LDMLConstants.AVAIL_FMTS;
afAlias.val = dtpPath.replace(DTP, LDMLConstants.AVAIL_FMTS);
res = Resource.addAfter(res, afAlias);
ResourceAlias aaAlias = new ResourceAlias();
aaAlias.name = LDMLConstants.APPEND_ITEMS;
aaAlias.val = dtpPath.replace(DTP, LDMLConstants.APPEND_ITEMS);
res = Resource.addAfter(res, aaAlias);
ResourceAlias ifAlias = new ResourceAlias();
ifAlias.name = LDMLConstants.INTVL_FMTS;
ifAlias.val = dtpPath.replace(DTP, LDMLConstants.INTVL_FMTS);
res = Resource.addAfter(res, ifAlias);
} else {
temp = parseTable(loc, xpath + "/" + LDMLConstants.AVAIL_FMTS, LDMLConstants.DATE_FMT_ITEM, LDMLConstants.ID);
if (temp != null) {
temp.name = LDMLConstants.AVAIL_FMTS;
res = Resource.addAfter(res, temp);
}
temp = parseTable(loc, xpath + "/" + LDMLConstants.APPEND_ITEMS, LDMLConstants.APPEND_ITEM, LDMLConstants.REQUEST);
if (temp != null) {
temp.name = LDMLConstants.APPEND_ITEMS;
res = Resource.addAfter(res, temp);
}
temp = parseIntervalFormats(loc, xpath);
if (temp != null) {
res = Resource.addAfter(res, temp);
}
}
}
} else if (name.equals(LDMLConstants.SPECIAL)) {
res = parseSpecialElements(loc, xpath);
} else if (name.equals(LDMLConstants.FIELDS)) {
// if the whole thing is an alias
if ((res = getAliasResource(loc, xpath)) == null) {
ResourceTable subTable = new ResourceTable();
subTable.name = LDMLConstants.FIELDS;
Set<String> fields = loc.getByType(xpath, LDMLConstants.FIELD);
for (String field : fields) {
res = parseField(loc, xpath + "/field[@type=\"" + field + "\"]", field);
if (res != null) {
subTable.appendContents(res);
}
}
if (!subTable.isEmpty()) {
res = subTable;
}
} else {
res.name = LDMLConstants.FIELDS;
}
} else if (name.equals(LDMLConstants.QUARTERS)) {
// if (DEBUG)printXPathWarning(node, xpath);
res = parseMonthsAndDays(loc, xpath);
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseField(LDML2ICUInputLocale loc, String xpath, String type) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = type;
ResourceString dn = null;
ResourceTable relative = new ResourceTable();
relative.name = LDMLConstants.RELATIVE;
// if the whole node is marked draft then
// dont write anything
if (loc.isPathNotConvertible(xpath)) {
return null;
}
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name;
return current;
}
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
String name = XPPUtil.getXpathName(xpath);
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.RELATIVE)) {
ResourceString str = new ResourceString();
str.name = "\"" + loc.getBasicAttributeValue(xpath, LDMLConstants.TYPE) + "\"";
str.val = loc.getFile().getStringValue(xpath);
res = str;
if (res != null) {
if (current == null) {
current = relative.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
} else if (name.equals(LDMLConstants.DISPLAY_NAME)) {
dn = new ResourceString();
dn.name = keyNameMap.get(LDMLConstants.DISPLAY_NAME);
dn.val = loc.getFile().getStringValue(xpath);
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
}
if (dn != null) {
table.first = dn;
}
if (relative.first != null) {
if (table.first != null) {
table.first.next = relative;
} else {
table.first = relative;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseMonthsAndDays(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
String name = XPPUtil.getXpathName(xpath);
table.name = keyNameMap.get(name);
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name; // months -> monthNames
return current;
}
final String stuff[] = { LDMLConstants.DEFAULT, LDMLConstants.MONTH_CONTEXT, LDMLConstants.DAY_CONTEXT, LDMLConstants.QUARTER_CONTEXT, };
String origXpath = xpath;
for (int jj = 0; jj < stuff.length; jj++) {
name = stuff[jj];
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.MONTH_CONTEXT) || name.equals(LDMLConstants.DAY_CONTEXT) || name.equals(LDMLConstants.QUARTER_CONTEXT)) {
Set<String> ctxs = loc.getByType(xpath, name);
for (String ctx : ctxs) {
res = parseContext(loc, xpath + "[@type=\"" + ctx + "\"]");
if (res != null) {
table.appendContents(res);
res = null;
}
}
// if there was an item, resync current.
if (table.first != null) {
current = table.first.end();
}
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseContext(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
// if the whole collation node is marked draft then
// don't write anything
if (loc.isPathNotConvertible(xpath)) {
return null;
}
String myName = XPPUtil.getXpathName(xpath);
String resName = myName.substring(0, myName.lastIndexOf("Context"));
table.name = XPPUtil.getAttributeValue(xpath, myName, LDMLConstants.TYPE);
if (table.name == null) {
throw new InternalError("Can't get table name for " + xpath + " / " + resName + " / " + LDMLConstants.TYPE);
}
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name;
return current;
}
String stuff[] = { LDMLConstants.DEFAULT, resName + "Width", };
String origXpath = xpath;
for (int jj = 0; jj < stuff.length; jj++) {
String name = stuff[jj];
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
if (res != null) {
res.name = table.name;
}
return res; // an alias if for the resource
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(resName + "Width")) {
Set<String> ctxs = loc.getByType(xpath, name);
for (String ctx : ctxs) {
res = parseWidth(loc, resName, xpath + "[@type=\"" + ctx + "\"]");
if (res != null) {
table.appendContents(res);
res = null;
}
}
// if there was an item, resync current.
if (table.first != null) {
current = table.first.end();
}
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
public static String getDayNumberAsString(String type) {
if (type.equals("sun")) {
return "1";
} else if (type.equals("mon")) {
return "2";
} else if (type.equals("tue")) {
return "3";
} else if (type.equals("wed")) {
return "4";
} else if (type.equals("thu")) {
return "5";
} else if (type.equals("fri")) {
return "6";
} else if (type.equals("sat")) {
return "7";
} else {
throw new IllegalArgumentException("Unknown type: " + type);
}
}
private Resource parseWidth(LDML2ICUInputLocale loc, String resName, String xpath) {
log.setStatus(loc.getLocale());
ResourceArray array = new ResourceArray();
Resource current = null;
array.name = XPPUtil.getAttributeValue(xpath, resName + "Width", LDMLConstants.TYPE);
// if the whole node is marked draft then
// don't write anything
if (loc.isPathNotConvertible(xpath)) {
return null;
}
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = array.name;
return current;
}
Map<String, String> map = getElementsMap(loc, resName, xpath, false);
if (map.size() == 0) {
log.info("No vals, exiting " + xpath);
return null;
}
Map<String, String> defMap = null;
if (loc.resolved() != null) {
defMap = getElementsMap(loc, resName, xpath, true);
}
Set<String> allThings = new TreeSet<String>();
allThings.addAll(map.keySet());
if (defMap != null) {
allThings.addAll(defMap.keySet());
}
if ((resName.equals(LDMLConstants.DAY) && allThings.size() < 7) || (resName.equals(LDMLConstants.MONTH) && allThings.size() < 12)) {
log.error("Could not get full " + resName + " array. [" + xpath + "] Only found " + map.size() + " items in target locale (" + allThings.size() + " including "
+ ((defMap != null) ? defMap.size() : 0) + " inherited). Skipping.");
return null;
}
if (map.size() > 0) {
for (int i = 0; i < allThings.size(); i++) {
String key = Integer.toString(i);
ResourceString res = new ResourceString();
res.val = map.get(key);
if (res.val == null && defMap != null) {
res.val = defMap.get(key);
if (verboseFallbackComments && res.val != null) {
res.smallComment = " fallback";
}
}
if (res.val == null) {
log.error("Could not get full " + resName + " array., in " + xpath + " - Missing #" + key + ". Only found " + map.size() + " items (" + allThings.size()
+ " including inherited). Skipping.");
return null;
}
// array of unnamed strings
if (res.val != null) {
if (current == null) {
current = array.first = res;
} else {
current.next = res;
current = current.next;
}
}
}
}
// parse the default node
{
ResourceString res = getDefaultResource(loc, xpath + "/default");
if (res != null) {
log.warning("Found def for " + xpath + " - " + res.val);
if (current == null) {
current = array.first = res;
} else {
current.next = res;
current = current.next;
}
}
}
if (array.first != null) {
return array;
}
return null;
}
private static Set<String> completion_day = null;
private static Set<String> completion_month = null;
private static Set<String> completion_era = null;
private static Set<String> completion_q = null;
private static Set<String> completion_era_j = null;
private Set<String> createNumericStringArray(int max) {
Set<String> set = new HashSet<String>();
for (int i = 0; i <= max; i++) {
set.add(new Integer(i).toString());
}
return set;
}
private Set<String> getSetCompletion(LDML2ICUInputLocale loc, String element, String xpath) {
if (element.equals(LDMLConstants.DAY)) {
if (completion_day == null) {
completion_day = new HashSet<String>();
String days[] = { LDMLConstants.SUN, LDMLConstants.MON, LDMLConstants.TUE, LDMLConstants.WED, LDMLConstants.THU, LDMLConstants.FRI, LDMLConstants.SAT };
for (String day : days) {
completion_day.add(day);
}
}
return completion_day;
}
if (element.equals(LDMLConstants.MONTH)) {
if (completion_month == null) {
completion_month = createNumericStringArray(13);
}
return completion_month;
}
if (element.equals(LDMLConstants.ERA)) {
if (completion_era == null) {
completion_era = createNumericStringArray(2);
completion_era_j = createNumericStringArray(235);
}
String type = XPPUtil.getAttributeValue(xpath, LDMLConstants.CALENDAR, LDMLConstants.TYPE);
if (type != null && type.equals("japanese")) {
return completion_era_j;
}
return completion_era;
}
if (element.equals(LDMLConstants.QUARTER)) {
if (completion_q == null) {
completion_q = createNumericStringArray(4);
}
return completion_q;
}
log.warning("No known completion for " + element);
return null;
}
private Map<String, String> getElementsMap(LDML2ICUInputLocale loc, String element, String xpath, boolean fromResolved) {
Map<String, String> map = new TreeMap<String, String>();
CLDRFile whichFile;
if (fromResolved) {
whichFile = loc.resolved();
} else {
whichFile = loc.getFile();
}
String origXpath = xpath;
for (Iterator<String> iter = whichFile.iterator(xpath); iter.hasNext();) {
xpath = iter.next();
if (loc.isPathNotConvertible(whichFile, xpath)) {
continue;
}
String name = XPPUtil.getXpathName(xpath);
String val = whichFile.getStringValue(xpath);
String caltype = XPPUtil.getAttributeValue(xpath, LDMLConstants.CALENDAR, LDMLConstants.TYPE);
String type = XPPUtil.getAttributeValue(xpath, name, LDMLConstants.TYPE);
String yeartype = XPPUtil.getAttributeValue(xpath, name, LDMLConstants.YEARTYPE);
if (name.equals(LDMLConstants.DAY)) {
map.put(LDMLUtilities.getDayIndexAsString(type), val);
} else if (name.equals(LDMLConstants.MONTH)) {
if (caltype.equals("hebrew") && type.equals("7") && yeartype != null && yeartype.equals("leap")) {
type = "14"; // Extra month name for hebrew Adar II in leap years
}
map.put(LDMLUtilities.getMonthIndexAsString(type), val);
} else if (name.equals(LDMLConstants.ERA)) {
map.put(type, val);
} else if (name.equals(LDMLConstants.QUARTER)) {
map.put(LDMLUtilities.getMonthIndexAsString(type), val);
} else if (name.equals(LDMLConstants.ALIAS)) {
if (fromResolved) {
continue; // OK - inherits .
}
log.error("Encountered unknown alias <res:" + fromResolved + " - " + xpath + " / " + name + "> subelement: " + name);
System.exit(-1);
} else {
log.error("Encountered unknown <res:" + fromResolved + " - " + xpath + " / " + name + "> subelement: " + name);
System.exit(-1);
}
}
Set<String> completion = getSetCompletion(loc, element, xpath);
if (completion != null) {
for (String type : completion) {
xpath = origXpath + "/" + element + "[@type=\"" + type + "\"]";
if (loc.isPathNotConvertible(whichFile, xpath)) {
continue;
}
String name = XPPUtil.getXpathName(xpath);
String val = whichFile.getStringValue(xpath);
if (val == null) {
continue;
}
if (name.equals(LDMLConstants.DAY)) {
map.put(LDMLUtilities.getDayIndexAsString(type), val);
} else if (name.equals(LDMLConstants.MONTH)) {
map.put(LDMLUtilities.getMonthIndexAsString(type), val);
} else if (name.equals(LDMLConstants.ERA)) {
map.put(type, val);
} else if (name.equals(LDMLConstants.QUARTER)) {
map.put(LDMLUtilities.getMonthIndexAsString(type), val);
} else {
throw new InternalError("Unknown name " + name);
}
}
}
return map;
}
public static int getMillis(String time) {
String[] strings = time.split(":"); // time is in hh:mm format
int hours = Integer.parseInt(strings[0]);
int minutes = Integer.parseInt(strings[1]);
return (hours * 60 + minutes) * 60 * 1000;
}
private Node getVettedNode(Node ctx, String node, String attrb, String attrbVal, StringBuilder xpath) {
int savedLength = xpath.length();
NodeList list = LDMLUtilities.getNodeList(ctx, node, null, xpath.toString());
Node ret = null;
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String val = LDMLUtilities.getAttributeValue(item, attrb);
getXPath(item, xpath);
if (val.matches(".*\\b" + attrbVal + "\\b.*")) {
if (!isNodeNotConvertible(item, xpath)) {
ret = item;
}
break;
}
xpath.setLength(savedLength);
}
xpath.setLength(savedLength);
return ret;
}
private Resource parseEras(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = LDMLConstants.ERAS;
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = table.name;
return current;
}
// if the whole node is marked draft then
// don't write anything
final String stuff[] = { LDMLConstants.DEFAULT, LDMLConstants.ERAABBR, LDMLConstants.ERANAMES, LDMLConstants.ERANARROW, };
String origXpath = xpath;
for (int jj = 0; jj < stuff.length; jj++) {
String name = stuff[jj];
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.ERAABBR)) {
res = parseEra(loc, xpath, LDMLConstants.ABBREVIATED);
} else if (name.equals(LDMLConstants.ERANAMES)) {
res = parseEra(loc, xpath, LDMLConstants.WIDE);
} else if (name.equals(LDMLConstants.ERANARROW)) {
res = parseEra(loc, xpath, LDMLConstants.NARROW);
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseEra(LDML2ICUInputLocale loc, String xpath, String name) {
ResourceArray array = new ResourceArray();
Resource current = null;
array.name = name;
String resName = LDMLConstants.ERA;
// if the whole node is marked draft then
// don't write anything
if (loc.isPathNotConvertible(xpath)) {
return null;
}
// if the whole thing is an alias
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = array.name;
return current;
}
Map<String, String> map = getElementsMap(loc, resName, xpath, false);
if (map.size() == 0) {
log.info("No vals, exiting " + xpath);
return null;
}
Map<String, String> defMap = null;
if (loc.resolved() != null) {
defMap = getElementsMap(loc, resName, xpath, true);
}
Set<String> allThings = new TreeSet<String>();
allThings.addAll(map.keySet());
if (defMap != null) {
allThings.addAll(defMap.keySet());
}
// / "special" hack for japanese narrow. If so, we'll have an alternate
// set on standby.
Map<String, String> nonNarrow = null;
boolean isJapaneseNarrow = xpath.equals("//ldml/dates/calendars/calendar[@type=\"japanese\"]/eras/eraNarrow");
if (isJapaneseNarrow) {
nonNarrow = getElementsMap(loc, resName, xpath.replaceAll("eraNarrow", "eraAbbr"), true); // will NOT
// fallback from
// specials.
// log.info("xpath: " + xpath + ", resName: " + resName +
// " - needs japanese hack.");
allThings.addAll(nonNarrow.keySet());
}
if (map.size() > 0) {
for (int i = 0; i < allThings.size(); i++) {
String key = Integer.toString(i);
ResourceString res = new ResourceString();
res.val = map.get(key);
if (res.val == null && defMap != null) {
res.val = defMap.get(key);
if (verboseFallbackComments && res.val != null) {
res.smallComment = " fallback";
}
}
if (res.val == null && nonNarrow != null) {
res.val = nonNarrow.get(key);
if (res.val != null) {
res.smallComment = "(abbr.)";
}
}
if (res.val == null) {
log.error("Could not get full " + resName + " array at " + xpath + " - Missing #" + key + ". Only found " + map.size() + " items (" + allThings.size()
+ " including inherited). Fatal error exiting.");
// NB: see workaround for Japanese-narrow above.
throw new InternalError("data problem");
}
// array of unnamed strings
if (res.val != null) {
if (current == null) {
current = array.first = res;
} else {
current.next = res;
current = current.next;
}
}
}
}
if (array.first != null) {
return array;
}
return null;
}
private boolean isNodeNotConvertible(Node node, StringBuilder xpath) {
return isNodeNotConvertible(node, xpath, false, false);
}
private boolean isNodeNotConvertible(Node node, StringBuilder xpath, boolean isCollation, boolean isNodeFromParent) {
// only deal with leaf nodes!
// Here we assume that the CLDR files are normalized
// and that the draft attributes are only on leaf nodes
if (LDMLUtilities.areChildrenElementNodes(node) && !isCollation) {
return false;
}
if (isNodeFromParent) {
return false;
}
return !xpathListContains(xpath.toString());
}
public boolean xpathListContains(String xpath) {
return _xpathList.contains(xpath);
}
public Node getVettedNode(Document fullyResolvedDoc, Node parent, String childName, StringBuilder xpath, boolean ignoreDraft) {
String ctx = "./" + childName;
NodeList list = LDMLUtilities.getNodeList(parent, ctx);
int saveLength = xpath.length();
Node ret = null;
if (list == null || list.getLength() < 0) {
if (fullyResolvedDoc != null) {
int oldLength = xpath.length();
xpath.append("/");
xpath.append(childName);
// try from fully resolved
list = LDMLUtilities.getNodeList(fullyResolvedDoc, xpath.toString());
// we can't depend on isNodeNotConvertible to return the correct
// data since xpathList will not contain xpaths of nodes from
// parent so we just return the first one we encounter.
// This has a side effect of ignoring the config specifiation!
if (list != null && list.getLength() > 0) {
ret = list.item(0);
}
xpath.setLength(oldLength);
}
} else {
// getVettedNode adds the node name of final node to xpath.
// chop off the final node name from xpath.
int end = childName.lastIndexOf('/');
if (end > 0) {
xpath.append('/');
xpath.append(childName.substring(0, end));
}
ret = getVettedNode(list, xpath, ignoreDraft);
}
xpath.setLength(saveLength);
return ret;
}
private Node getVettedNode(NodeList list, StringBuilder xpath, boolean ignoreDraft) {
Node node = null;
int oldLength = xpath.length();
for (int i = 0; i < list.getLength(); i++) {
node = list.item(i);
getXPath(node, xpath);
if (isNodeNotConvertible(node, xpath)) {
xpath.setLength(oldLength);
node = null;
continue;
}
break;
}
xpath.setLength(oldLength);
return node;
}
private Resource parseAmPm(LDML2ICUInputLocale loc, String xpath) {
// if the whole thing is an alias
Resource current = new Resource();
if ((current = getAliasResource(loc, xpath)) != null) {
current.name = AM_PM_MARKERS;
// if dayPeriods is an alias, then we force AmPmMarkers to be an alias, too
String val = ((ResourceAlias) current).val;
((ResourceAlias) current).val = val.replace(LDMLConstants.DAYPERIODS, AM_PM_MARKERS);
return current;
}
String[] AMPM = { LDMLConstants.AM, LDMLConstants.PM };
ResourceString[] strs = new ResourceString[AMPM.length];
String[] paths = new String[AMPM.length];
Resource first = null;
int validCount = 0;
for (int i = 0; i < AMPM.length; i++) {
strs[i] = new ResourceString();
first = ResourceString.addAfter(first, strs[i]);
paths[i] = xpath + "/"
+ LDMLConstants.DAYPERIOD_CONTEXT + "[@" + LDMLConstants.TYPE + "=\"" + LDMLConstants.FORMAT + "\"]/"
+ LDMLConstants.DAYPERIOD_WIDTH + "[@" + LDMLConstants.TYPE + "=\"" + LDMLConstants.WIDE + "\"]/"
+ LDMLConstants.DAYPERIOD + "[@" + LDMLConstants.TYPE + "=\"" + AMPM[i] + "\"]";
if (!loc.isPathNotConvertible(paths[i])) {
strs[i].val = loc.getFile().getStringValue(paths[i]);
if (strs[i].val != null) {
validCount++;
}
}
}
if (validCount == 0) {
return null;
}
if (validCount < AMPM.length) {
for (int i = 0; i < AMPM.length; i++) {
if (strs[i].val == null && !loc.isPathNotConvertible(loc.resolved(), paths[i])) {
strs[i].val = loc.resolved().getStringValue(paths[i]);
if (strs[i].val != null) {
if (verboseFallbackComments) {
strs[i].smallComment = " fallback";
}
validCount++;
}
}
}
}
if (validCount != AMPM.length) {
throw new InternalError("On " + xpath + " (AMPM) - need " + AMPM.length + " strings but only have " + validCount + " after inheritance.");
}
// ok, set up the res
ResourceArray arr = new ResourceArray();
arr.name = AM_PM_MARKERS;
arr.first = first;
return arr;
}
// TODO figure out what to do for alias, draft and alt elements
private static final String STD_SUFFIX = "[@type=\"standard\"]/pattern[@type=\"standard\"]";
private static final String[] dtf_paths = new String[] { "timeFormats/timeFormatLength[@type=\"full\"]/timeFormat" + STD_SUFFIX,
"timeFormats/timeFormatLength[@type=\"long\"]/timeFormat" + STD_SUFFIX, "timeFormats/timeFormatLength[@type=\"medium\"]/timeFormat" + STD_SUFFIX,
"timeFormats/timeFormatLength[@type=\"short\"]/timeFormat" + STD_SUFFIX, "dateFormats/dateFormatLength[@type=\"full\"]/dateFormat" + STD_SUFFIX,
"dateFormats/dateFormatLength[@type=\"long\"]/dateFormat" + STD_SUFFIX, "dateFormats/dateFormatLength[@type=\"medium\"]/dateFormat" + STD_SUFFIX,
"dateFormats/dateFormatLength[@type=\"short\"]/dateFormat" + STD_SUFFIX, "dateTimeFormats/dateTimeFormatLength[@type=\"medium\"]/dateTimeFormat" + STD_SUFFIX,
"dateTimeFormats/dateTimeFormatLength[@type=\"full\"]/dateTimeFormat" + STD_SUFFIX, "dateTimeFormats/dateTimeFormatLength[@type=\"long\"]/dateTimeFormat" + STD_SUFFIX,
"dateTimeFormats/dateTimeFormatLength[@type=\"medium\"]/dateTimeFormat" + STD_SUFFIX, "dateTimeFormats/dateTimeFormatLength[@type=\"short\"]/dateTimeFormat" + STD_SUFFIX, };
private Resource parseDTF(LDML2ICUInputLocale loc, String xpath) {
log.setStatus(loc.getLocale());
// TODO change the ICU format to reflect LDML format
/*
* The prefered ICU format would be timeFormats{ default{} full{} long{} medium{} short{} .... } dateFormats{
* default{} full{} long{} medium{} short{} ..... } dateTimeFormats{ standard{} .... }
*/
ResourceArray arr = new ResourceArray();
String[] theArray = dtf_paths;
arr.name = DTP;
Resource current = null;
ResourceString strs[] = new ResourceString[theArray.length];
String nsov[] = new String[theArray.length];
GroupStatus status = parseGroupWithFallback(loc, xpath, theArray, strs);
if (GroupStatus.EMPTY == status) {
// TODO: cldrbug #2188: What follows is a hack because of
// mismatch between CLDR & ICU format, need to do something
// better for next versions of CLDR (> 1.7) & ICU (> 4.2). If
// any dateFormats/dateFormatLength,
// timeFormats/timeFormatLength, or
// dateTimeFormats/dateTimeFormatLength items are present,
// status != GroupStatus.EMPTY and we don't get here. If we do
// get here, then dateFormats and timeFormats elements are empty
// or aliased, and dateTimeFormats has at least no
// dateTimeFormats items, and is probably aliased (currently in
// this case it is always aliased, and this only happens in
// root). We need to get an alias from one of these elements
// (for ICU format we need to create a single alias covering all
// three of these elements). However, parseAliasResource doesn't
// know how to make an alias from the dateFormats or timeFormats
// elements (since there is no direct match in ICU to either of
// these alone). It does know how from the dateTimeFormats, so
// we will try that. This would fail if dateTimeFormats were not
// aliased when dateFormats and timeFormats both were, but that
// does not happen currently.
//
Resource alias = parseAliasResource(loc, xpath + "/" + LDMLConstants.DATE_TIME_FORMATS + "/" + LDMLConstants.ALIAS);
if (alias != null) {
alias.name = DTP;
}
return alias;
}
if (GroupStatus.SPARSE == status) {
// Now, we have a problem.
String type = XPPUtil.getAttributeValue(xpath, LDMLConstants.CALENDAR, LDMLConstants.TYPE);
if (!type.equals("gregorian")) {
log.info(loc.getLocale() + " " + xpath + " - some items are missing, attempting fallback from gregorian");
ResourceString gregstrs[] = new ResourceString[theArray.length];
GroupStatus gregstatus = parseGroupWithFallback(loc, xpath.replaceAll("\"" + type + "\"", "\"gregorian\""), theArray, gregstrs);
if ((gregstatus != GroupStatus.EMPTY) && (gregstatus != GroupStatus.SPARSE)) {
// They have something, let's see if it is enough;
for (int j = 0; j < theArray.length; j++) {
if (strs[j].val == null && gregstrs[j].val != null) {
strs[j].val = gregstrs[j].val;
strs[j].smallComment = " fallback from 'gregorian' ";
}
}
}
}
}
// Now determine if any Numbering System Overrides are present
for (int i = 0; i < theArray.length; i++) {
XPathParts xpp = new XPathParts();
String aPath = xpath + "/" + dtf_paths[i];
if (loc.getFile().isHere(aPath)) {
String fullPath = loc.getFile().getFullXPath(aPath);
xpp.set(fullPath);
String numbersOverride = xpp.findAttributeValue(LDMLConstants.PATTERN, LDMLConstants.NUMBERS);
if (numbersOverride != null) {
nsov[i] = numbersOverride;
}
}
}
// Glue pattern default
ResourceString res = getDefaultResourceWithFallback(loc, xpath + "/dateTimeFormats/" + LDMLConstants.DEFAULT, LDMLConstants.DEFAULT);
int glueIndex = 8;
if (res != null && res.val.trim().equalsIgnoreCase("full")) {
glueIndex += 1;
}
if (res != null && res.val.trim().equalsIgnoreCase("long")) {
glueIndex += 2;
}
if (res != null && res.val.trim().equalsIgnoreCase("medium")) {
glueIndex += 3;
}
if (res != null && res.val.trim().equalsIgnoreCase("short")) {
glueIndex += 4;
}
strs[8].val = strs[glueIndex].val;
// write out the data
int n = 0;
for (ResourceString str : strs) {
if (str.val == null) {
log.error(xpath + " - null value at " + n);
System.exit(-1);
}
if (nsov[n] != null) {
// We have a numbering system override - output an array containing the override
ResourceString nso = new ResourceString();
nso.val = nsov[n];
ResourceArray nso_array = new ResourceArray();
nso_array.first = str;
str.next = nso;
if (current == null) {
current = arr.first = nso_array;
} else {
current.next = nso_array;
current = current.next;
}
} else {
// Just a normal pattern - output a string
if (current == null) {
current = arr.first = str;
} else {
current.next = str;
current = current.next;
}
}
n++;
}
if (arr.first != null) {
return arr;
}
return null;
}
private Resource parseNumbers(LDML2ICUInputLocale loc, String xpath) {
Resource current = null, first = null;
boolean writtenNumberElements = false;
boolean writtenCurrencyFormatPlurals = false;
boolean writtenCurrencies = false;
boolean writtenCurrencyPlurals = false;
boolean writtenCurrencySpacing = false;
String origXpath = xpath;
String names[] = { LDMLConstants.ALIAS, LDMLConstants.DEFAULT, LDMLConstants.SYMBOLS, LDMLConstants.DECIMAL_FORMATS, LDMLConstants.PERCENT_FORMATS, LDMLConstants.SCIENTIFIC_FORMATS,
LDMLConstants.CURRENCY_FORMATS, LDMLConstants.CURRENCIES,
// Currencies appears twice so we can handle the plurals.
LDMLConstants.CURRENCIES, LDMLConstants.DEFAULT_NUMBERING_SYSTEM };
for (String name : names) {
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
if (!loc.getFile().isHere(xpath)) {
continue;
}
res = parseAliasResource(loc, xpath);
res.name = name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
if (!loc.getFile().isHere(xpath)) {
continue;
}
res = getDefaultResource(loc, xpath, name);
} else if (name.equals(LDMLConstants.SYMBOLS)|| name.equals(LDMLConstants.DECIMAL_FORMATS) || name.equals(LDMLConstants.PERCENT_FORMATS) || name.equals(LDMLConstants.SCIENTIFIC_FORMATS)
|| name.equals(LDMLConstants.CURRENCY_FORMATS) || name.equals(LDMLConstants.DEFAULT_NUMBERING_SYSTEM)) {
if (writtenNumberElements == false) {
Resource ne = parseNumberElements(loc,origXpath);
res = ne;
writtenNumberElements = true;
} else if (writtenCurrencyFormatPlurals == false) {
res = parseCurrencyFormatPlurals(loc, origXpath);
writtenCurrencyFormatPlurals = true;
} else if (writtenCurrencySpacing == false) {
res = parseCurrencySpacing(loc, origXpath);
writtenCurrencySpacing = true;
}
} else if (name.equals(LDMLConstants.CURRENCIES)) {
if (writtenCurrencies == false) {
res = parseCurrencies(loc, xpath);
writtenCurrencies = true;
} else if (writtenCurrencyPlurals == false) {
res = parseCurrencyPlurals(loc, origXpath);
writtenCurrencyPlurals = true;
}
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
if (first != null) {
return first;
}
return null;
}
private Resource parseNumberElements(LDML2ICUInputLocale loc, String xpath) {
String[] numSystems = { "latn" };
if ( supplementalDataInfo != null ) {
numSystems = supplementalDataInfo.getNumberingSystems().toArray(new String[0]);
}
Resource current = null;
ResourceTable numElements = new ResourceTable();
numElements.name = NUMBER_ELEMENTS;
Resource defaultNS = parseDefaultNumberingSystem(loc,xpath);
if ( defaultNS != null ) {
numElements.first = defaultNS;
current = defaultNS;
}
for ( String ns : numSystems ) {
Resource syms = parseSymbols(loc,ns, xpath +"/" + LDMLConstants.SYMBOLS);
Resource formats = parseNumberFormats(loc,ns,xpath);
if ( syms != null || formats != null ) {
ResourceTable nsTable = new ResourceTable();
nsTable.name = ns;
Resource current2 = null;
if ( syms != null ) {
nsTable.first = syms;
current2 = syms;
}
if ( formats != null ) {
if ( current2 == null ) {
nsTable.first = formats;
} else {
current2.next = formats;
}
}
if ( current != null ) {
current.next = nsTable;
} else {
numElements.first = nsTable;
}
current = nsTable;
}
}
if ( current != null ) {
return numElements;
}
return null;
}
private Resource parseUnits(LDML2ICUInputLocale loc, String tableName, String altValue) {
String xpath = "//ldml/" + LDMLConstants.UNITS;
ResourceTable unitsTable = new ResourceTable();
unitsTable.name = tableName;
Resource current = null;
Resource first = null;
// if the whole thing is an alias
Resource alias = null;
if ((alias = getAliasResource(loc, xpath.toString())) != null) {
alias.name = tableName;
return alias;
}
String origXpath = xpath;
String names[] = { LDMLConstants.ALIAS, LDMLConstants.UNIT, LDMLConstants.SPECIAL };
for (String name : names) {
xpath = origXpath + "/" + name;
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
if (!loc.getFile().isHere(xpath)) {
continue;
}
res = parseAliasResource(loc, xpath);
res.name = name;
return res;
}
if (name.equals(LDMLConstants.UNIT)) {
res = parseUnit(loc, xpath, altValue);
} else if (name.equals(LDMLConstants.SPECIAL)) {
res = parseSpecialElements(loc, xpath);
} else {
log.error("Encountered unknown <" + xpath + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
first = res;
} else {
current.next = res;
}
current = res;
res = null;
}
}
if (first != null) {
unitsTable.first = first;
return unitsTable;
}
return null;
}
private Resource parseUnit(LDML2ICUInputLocale loc, String xpath, String altValue) {
Map<String, ResourceTable> tableMap = new HashMap<String, ResourceTable>();
Resource first = null;
Resource last = null;
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
String localxpath = iter.next();
if (altValue == null && loc.isPathNotConvertible(localxpath)) {
continue;
}
String name = XPPUtil.getXpathName(localxpath);
if (name.equals(LDMLConstants.UNIT)) {
log.error("Unknown item " + localxpath);
continue;
}
if (name.equals(LDMLConstants.UNIT_PATTERN)) {
String currentAltValue = XPPUtil.getAttributeValue(localxpath, LDMLConstants.ALT);
if (altValue != null) {
if (currentAltValue == null || !altValue.equals(currentAltValue)) {
continue;
}
// OK
} else if (altValue == null && currentAltValue != null) {
continue;
}
String parentName = XPPUtil.getXpathName(localxpath, -2);
String tableName = XPPUtil.getAttributeValue(localxpath, parentName, LDMLConstants.TYPE);
ResourceTable current = tableMap.get(tableName);
if (current == null) {
current = new ResourceTable();
current.name = tableName;
tableMap.put(tableName, current);
// Hook everything up, because we need to
// return the sibling chain.
if (last == null) {
first = current;
} else {
last.next = current;
}
last = current;
}
ResourceString str = new ResourceString();
str.name = XPPUtil.getAttributeValue(localxpath, name, LDMLConstants.COUNT);
str.val = loc.getFile().getStringValue(localxpath);
current.appendContents(str);
} else {
log.error("Unknown item " + localxpath);
continue;
}
}
return first;
}
enum GroupStatus {
EMPTY, SPARSE, FALLBACK, COMPLETE
}
/**
* Parse some things, with fallback behavior
*
* @param loc
* @param xpathBase
* the base xpath
* @param xpaths
* the xpath (with slash before) to append to the base
* @param res
* output array to hold res strings. must be same size as xpaths
* @return Will return the lowest possible value that applies to any item, or GROUP_EMPTY if no items could be
* filled in
*/
private GroupStatus parseGroupWithFallback(LDML2ICUInputLocale loc, String xpathBase, String xpaths[], ResourceString res[]) {
String[] values = new String[xpaths.length];
XPathParts xpp = new XPathParts();
boolean someNonDraft = false;
boolean anyExtant = false;
for (int i = 0; i < xpaths.length; i++) {
String aPath = xpathBase + "/" + xpaths[i];
if (loc.getFile().isHere(aPath)) {
anyExtant = true;
if (!loc.isPathNotConvertible(aPath)) {
values[i] = loc.getFile().getStringValue(aPath);
if (values[i] != null) {
someNonDraft = true;
}
}
}
}
GroupStatus status = GroupStatus.EMPTY;
if (!anyExtant && !someNonDraft) {
// log.warning("No " + xpathBase + " for " + loc.locale);
return status;
}
if (someNonDraft == true) {
status = GroupStatus.COMPLETE;
for (int i = 0; i < xpaths.length; i++) {
res[i] = new ResourceString();
String temp = values[i];
if (temp == null) {
String aPath = xpathBase + "/" + xpaths[i];
temp = loc.resolved().getStringValue(aPath);
if (temp != null) {
CLDRFile.Status fileStatus = new CLDRFile.Status();
String foundIn = loc.resolved().getSourceLocaleID(aPath, fileStatus);
if (verboseFallbackComments) {
res[i].smallComment = " From " + foundIn;
}
if (status != GroupStatus.SPARSE) {
status = GroupStatus.FALLBACK;
}
// log.warning("Fallback from " + foundIn + " in "
// + loc.locale + " / " + aPath);
} else {
log.info("Can't complete array for " + xpathBase + " at " + aPath);
status = GroupStatus.SPARSE;
}
}
res[i].val = temp;
}
return status;
}
return GroupStatus.EMPTY;
}
private String reviseAPath(LDML2ICUInputLocale loc, XPathParts xpp, String aPath) {
// This is a clumsy way to do it, but the code for the converter is so convoluted...
Set<String> paths = loc.getFile().getPaths(aPath, null, null);
// We have all the paths that match, now. We prefer ones that have an
// alt value that is a valid number system
for (String path : paths) {
String distinguishing = CLDRFile.getDistinguishingXPath(path, null, false);
if (distinguishing.contains("@numberSystem")) {
String alt = xpp.set(distinguishing).getAttributeValue(-1, "numberSystem");
if (supplementalDataInfo.getNumberingSystems().contains(alt)) {
aPath = distinguishing;
break;
}
}
}
return aPath;
}
private static final String[] sym_paths = new String[] { LDMLConstants.DECIMAL, LDMLConstants.GROUP, LDMLConstants.LIST, LDMLConstants.PERCENT_SIGN,
LDMLConstants.MINUS_SIGN, LDMLConstants.EXPONENTIAL, LDMLConstants.PER_MILLE, LDMLConstants.INFINITY, LDMLConstants.NAN, LDMLConstants.PLUS_SIGN, };
private Resource parseSymbols(LDML2ICUInputLocale loc, String ns, String xpath) {
ResourceTable tbl = new ResourceTable();
tbl.name = LDMLConstants.SYMBOLS;
Resource current = null;
String pathToTest;
for ( String sym : sym_paths ) {
pathToTest = xpath + "[@numberSystem=\"" + ns + "\"]/" + sym;
String value = loc.getFile().getWinningValue(pathToTest);
if (loc.isPathNotConvertible(pathToTest) || value == null) {
continue;
}
ResourceString str = new ResourceString();
str.name = sym;
str.val = value;
if ( current == null ) {
tbl.first = str;
} else {
current.next = str;
}
current = str;
}
if ( current != null ) {
return tbl;
}
return null;
}
private Resource parseCurrencyPlurals(LDML2ICUInputLocale loc, String xpath) {
// This resource is a table of tables, with each subtable containing
// the data for a particular currency. The structure of the XML file
// is as follows:
//
// <ldml>
// <numbers>
// <currencies>
// <currency type="ADP">
// <displayName>Andorran Peseta</displayName>
// <displayName count="one">Andorran peseta</displayName>
// <displayName count="other">Andorran pesetas</displayName>
// </currency>
// <currency type="AED">
// <displayName>United Arab Emirates Dirham</displayName>
// <displayName count="one">UAE dirham</displayName>
// <displayName count="other">UAE dirhams</displayName>
// <symbol>AED</symbol>
// </currency>
// </currencies>
// </numbers>
// </ldml>
//
// For this resource, the only interesting parts are the "displayName"
// elements that have a "count" attribute.
//
// The resulting resource for this particular example would look like this:
//
// CurrencyPlurals{
// ADP{
// one{"Andorran peseta"}
// other{"Andorran pesetas"}
// }
// AED{
// one{"UAE dirham"}
// other{"UAE dirhams"}
// }
ResourceTable parentTable = new ResourceTable();
parentTable.name = LDMLConstants.CURRENCY_PLURALS;
String xpathCurrency = xpath + "/currencies/currency";
// Since the leaf elements are not grouped by currency in the InputLocale
// instance, this map will hold the table for each currency.
Map<String, ResourceTable> tableMap = new HashMap<String, ResourceTable>();
Resource last = null;
for (Iterator<String> iter = loc.getFile().iterator(xpathCurrency); iter.hasNext();) {
String localxpath = iter.next();
if (loc.isPathNotConvertible(localxpath)) {
continue;
}
String name = XPPUtil.getXpathName(localxpath);
if (!name.equals(LDMLConstants.DISPLAY_NAME)) {
continue;
}
// We only care about the elements with a "count" attribute.
String count = XPPUtil.getAttributeValue(localxpath, name, LDMLConstants.COUNT);
if (count != null) {
String parentName = XPPUtil.getXpathName(localxpath, -2);
String tableName = XPPUtil.getAttributeValue(localxpath, parentName, LDMLConstants.TYPE);
ResourceTable current = tableMap.get(tableName);
if (current == null) {
current = new ResourceTable();
current.name = tableName;
tableMap.put(tableName, current);
// If this is the first table, then update the
// start of the children in the parent table.
if (last == null) {
parentTable.first = current;
} else {
last.next = current;
}
last = current;
}
ResourceString str = new ResourceString();
str.name = count;
str.val = loc.getFile().getStringValue(localxpath);
current.appendContents(str);
}
}
if (parentTable.first != null) {
return parentTable;
}
return null;
}
private Resource parseCurrencyFormatPlurals(LDML2ICUInputLocale loc, String xpath) {
// This table contains formatting patterns for this locale's currency.
// Each pattern is represented by a "unitPattern" element in the XML file.
// Each pattern is represented as a string in the resource format, with
// the name of the string being the value of the "count" attribute.
ResourceTable table = new ResourceTable();
table.name = LDMLConstants.CURRENCY_UNIT_PATTERNS;
String xpathUnitPattern = xpath + "/currencyFormats/unitPattern";
for (Iterator<String> iter = loc.getFile().iterator(xpathUnitPattern); iter.hasNext();) {
String localxpath = iter.next();
if (loc.isPathNotConvertible(localxpath)) {
continue;
}
String name = XPPUtil.getXpathName(localxpath);
ResourceString str = new ResourceString();
str.name = XPPUtil.getAttributeValue(localxpath, name, LDMLConstants.COUNT);
str.val = loc.getFile().getStringValue(localxpath);
table.appendContents(str);
}
if (table.first != null) {
return table;
}
return null;
}
private static final String[] CurrencySections = new String[] { LDMLConstants.CURRENCY_SPC_BEFORE, LDMLConstants.CURRENCY_SPC_AFTER };
private Resource parseCurrencySpacing(LDML2ICUInputLocale loc, String xpath) {
// This table contains formatting patterns for this locale's currency.
// Syntax example in XML file:
// <currencyFormats>
// <currencySpacing>
// <beforeCurrency>
// <currencyMatch>[:letter:]</currencyMatch>
// <surroundingMatch>[:digit:]</surroundingMatch>
// <insertBetween> </insertBetween>
// </beforeCurrency>
// <afterCurrency>
// <currencyMatch>[:letter:]</currencyMatch>
// <surroundingMatch>[:digit:]</surroundingMatch>
// <insertBetween> </insertBetween>
// </afterCurrency>
// </currencySpacing>
// </currencyFormats>
ResourceTable table = null;
ResourceTable current = null;
ResourceTable first = null;
for (String section : CurrencySections) {
String xpathUnitPattern = xpath + "/" + LDMLConstants.CURRENCY_FORMATS + "/" + LDMLConstants.CURRENCY_SPACING + "/" + section;
int count = 0;
for (Iterator<String> iter = loc.getFile().iterator(xpathUnitPattern); iter.hasNext();) {
String localxpath = iter.next();
if (loc.isPathNotConvertible(localxpath)) {
continue;
}
if (table == null) {
table = new ResourceTable();
table.name = LDMLConstants.CURRENCY_SPACING;
}
if (count++ == 0) {
current = new ResourceTable();
current.name = section;
if (first == null) {
table.first = current;
first = current;
} else {
first.next = current;
}
}
String name = XPPUtil.getXpathName(localxpath);
ResourceString str = new ResourceString();
str.name = name;
str.val = loc.getFile().getStringValue(localxpath);
current.appendContents(str);
}
}
if (table != null) {
return table;
}
return null;
}
// TODO figure out what to do for alias, draft and alt elements
private static final String[] numFmtKeys =
new String[] { "decimalFormat", "currencyFormat", "percentFormat", "scientificFormat" };
private Resource parseNumberFormats(LDML2ICUInputLocale loc, String ns, String xpath) {
ResourceTable tbl = new ResourceTable();
tbl.name = LDMLConstants.PATTERNS;
Resource current = null;
String pathToTest;
for ( String numFmtKey : numFmtKeys ) {
pathToTest = xpath + "/" + numFmtKey + "s/" + numFmtKey + "Length/" + numFmtKey + STD_SUFFIX;
if ( !ns.equals("latn")) {
pathToTest = pathToTest + "[@numberSystem=\"" + ns + "\"]";
}
String value = loc.getFile().getWinningValue(pathToTest);
if (loc.isPathNotConvertible(pathToTest) || value == null) {
continue;
}
ResourceString str = new ResourceString();
str.name = numFmtKey;
str.val = value;
if ( current == null ) {
tbl.first = str;
} else {
current.next = str;
}
current = str;
}
if ( current != null ) {
return tbl;
}
return null;
}
private Resource parseCurrencies(LDML2ICUInputLocale loc, String xpath) {
ResourceTable table = new ResourceTable();
Resource current = null;
// if the whole node is marked draft then
// don't write anything
String origXpath = xpath;
// collect a list of all currencies, ensure no dups.
Set<String> currs = new HashSet<String>();
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
String name = XPPUtil.getXpathName(xpath);
if (loc.isPathNotConvertible(xpath)) {
continue;
}
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(loc, xpath);
res.name = name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(loc, xpath, name);
} else /* if (name.equals(LDMLConstants.CURRENCY)) */{
String type = loc.findAttributeValue(xpath, LDMLConstants.TYPE);
if ((type == null) || (type.equals("standard"))) {
continue;
}
if (currs.contains(type)) {
// log.warning("$$$ dup " + type);
continue; // dup
}
res = parseCurrency(loc, origXpath + "/currency[@type=\"" + type + "\"]", type);
currs.add(type);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
if (table.first != null) {
// lookup only if needed
table.name = keyNameMap.get(XPPUtil.getXpathName(origXpath));
return table;
}
return null;
}
private static final String curr_syms[] = { LDMLConstants.SYMBOL, // 0
LDMLConstants.DISPLAY_NAME, // 1
LDMLConstants.PATTERN, // 2
LDMLConstants.DECIMAL, // 3
LDMLConstants.GROUP, // 4
};
private Resource parseCurrency(LDML2ICUInputLocale loc, String xpath, String type) {
ResourceArray arr = new ResourceArray();
arr.name = type;
ResourceString strs[] = new ResourceString[curr_syms.length];
GroupStatus status = parseGroupWithFallback(loc, xpath, curr_syms, strs);
if (status == GroupStatus.EMPTY) {
String full = loc.resolved().getFullXPath(xpath);
String val = loc.resolved().getStringValue(xpath);
log.warning("totally empty - Failed to parse: " + type + " at xpath " + xpath + " - full value " + full + " value " + val);
return null;
}
// aliases - for sanity
ResourceString symbol = strs[0];
ResourceString displayName = strs[1];
ResourceString pattern = strs[2];
ResourceString decimal = strs[3];
ResourceString group = strs[4];
// 0 - symb
if (symbol.val != null) {
String choice = loc.getBasicAttributeValue(xpath + "/" + curr_syms[0], LDMLConstants.CHOICE);
if (choice == null) {
String fullPathInh = loc.resolved().getFullXPath(xpath + "/" + curr_syms[0]);
if (fullPathInh != null) {
choice = XPPUtil.getAttributeValue(fullPathInh, LDMLConstants.CHOICE);
}
}
if (choice != null && choice.equals("true") && !loc.isPathNotConvertible(xpath + "/symbol")) {
symbol.val = "=" + symbol.val.replace('\u2264', '#').replace("<", "<");
if (true || verboseFallbackComments) {
if (symbol.smallComment != null) {
symbol.smallComment = symbol.smallComment + " - (choice)";
} else {
symbol.smallComment = "(choice)";
}
}
}
} else {
symbol.val = type;
if (true || verboseFallbackComments) {
symbol.smallComment = "===";
}
}
// 1 - disp
if (displayName.val == null) {
displayName.val = type;
if (true || verboseFallbackComments) {
symbol.smallComment = "===";
}
}
arr.first = symbol;
symbol.next = displayName;
if (pattern.val != null || decimal.val != null || group.val != null) {
boolean isPatternDup = false;
boolean isDecimalDup = false;
boolean isGroupDup = false;
if (pattern.val == null) {
pattern.val = loc.getResolvedString("//ldml/numbers/currencyFormats/currencyFormatLength/currencyFormat" + STD_SUFFIX);
isPatternDup = true;
if (pattern.val == null) {
throw new RuntimeException("Could not get pattern currency resource!!");
}
}
XPathParts xpp = new XPathParts();
if (decimal.val == null) {
String aPath = "//ldml/numbers/symbols/decimal";
if (!asciiNumbers) {
aPath = reviseAPath(loc, xpp, aPath);
}
decimal.val = loc.getResolvedString(aPath);
isDecimalDup = true;
if (decimal.val == null) {
throw new RuntimeException("Could not get decimal currency resource!!");
}
}
if (group.val == null) {
String aPath = "//ldml/numbers/symbols/group";
if (!asciiNumbers) {
aPath = reviseAPath(loc, xpp, aPath);
}
group.val = loc.getResolvedString(aPath);
isGroupDup = true;
if (group.val == null) {
throw new RuntimeException("Could not get group currency resource!!");
}
}
ResourceArray elementsArr = new ResourceArray();
pattern.comment = isPatternDup ? "Duplicated from NumberPatterns resource" : null;
decimal.comment = isDecimalDup ? "Duplicated from NumberElements resource" : null;
group.comment = isGroupDup ? "Duplicated from NumberElements resource" : null;
elementsArr.first = pattern;
pattern.next = decimal;
decimal.next = group;
if (displayName.val != null) {
displayName.next = elementsArr;
} else {
log.warning("displayName and symbol not vetted/available for currency resource " + arr.name + " not generating the resource");
}
}
if (arr.first != null) {
return arr;
}
return null;
}
/**
* Shim. Transitions us from CLDRFile based processing to DOM.
*/
public Resource parseCollations(LDML2ICUInputLocale loc, String xpath) {
log.setStatus(loc.getLocale());
if (loc.isNotOnDisk()) {
// attempt to parse a 'fake' locale.
Resource first = getAliasResource(loc, xpath);
if (first != null) {
first.name = LDMLConstants.COLLATIONS;
return first;
}
// now, look for a default
first = getDefaultResource(loc, xpath + "/" + LDMLConstants.DEFAULT, LDMLConstants.DEFAULT);
if (first != null) {
ResourceTable table = new ResourceTable();
table.name = LDMLConstants.COLLATIONS;
table.first = first;
return table;
}
// now, look for aliases
Set<String> collTypes = loc.getByType(xpath, LDMLConstants.COLLATION, LDMLConstants.TYPE);
for (String type : collTypes) {
Resource res = getAliasResource(loc, xpath + "/" + LDMLConstants.COLLATION + "[@type=\"" + type + "\"]");
if (res != null) {
first = Resource.addAfter(first, res);
} else {
throw new InternalError("FAIL: locale " + loc.getLocale() + " not on disc, and non-alias collation " + type + " encountered.");
}
}
return first; // could be null.
}
// parse using DOM-based code
DocumentPair docPair = getDocumentPair(loc);
Node collations = getTopNode(docPair.doc, LDMLConstants.COLLATIONS);
if (collations == null) {
throw new InternalError("Can't get top level collations node");
}
Resource table = parseCollations(collations, docPair.fullyResolvedDoc, new StringBuilder("//ldml"), true);
if (table == null || (table.isEmpty() && table instanceof ResourceTable)) {
log.warning(" warning: No collations found. Bundle will be empty.");
return null;
}
return table;
}
public Resource parseCollations(Node root, Document fullyResolvedDoc, StringBuilder xpath, boolean checkIfConvertible) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = root.getNodeName();
int savedLength = xpath.length();
getXPath(root, xpath);
int oldLength = xpath.length();
// if the whole collation node is marked draft then
// don't write anything
if (isNodeNotConvertible(root, xpath)) {
xpath.setLength(savedLength);
return null;
}
current = table.first = null; // parseValidSubLocales(root, xpath);
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(node, xpath);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.DEFAULT)) {
res = getDefaultResource(node, xpath, name);
} else if (name.equals(LDMLConstants.COLLATION)) {
res = parseCollation(node, fullyResolvedDoc, xpath, checkIfConvertible);
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
xpath.delete(oldLength, xpath.length());
}
xpath.delete(savedLength, xpath.length());
if (table.first != null) {
return table;
}
return null;
}
private Resource parseCollation(Node root, Document fullyResolvedDoc, StringBuilder xpath, boolean checkIfConvertible) {
ResourceTable table = new ResourceTable();
Resource current = null;
table.name = LDMLUtilities.getAttributeValue(root, LDMLConstants.TYPE);
int savedLength = xpath.length();
getXPath(root, xpath);
int oldLength = xpath.length();
// if the whole collation node is marked draft then
// don't write anything
if (checkIfConvertible && isNodeNotConvertible(root, xpath, true, false)) {
xpath.setLength(savedLength);
return null;
}
lastStrengthSymbol = "";
StringBuilder rules = new StringBuilder();
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
Resource res = null;
if (name.equals(LDMLConstants.ALIAS)) {
res = parseAliasResource(node, xpath, true);
res.name = table.name;
return res;
}
if (name.equals(LDMLConstants.RULES)) {
Node alias = LDMLUtilities.getNode(node, LDMLConstants.ALIAS, fullyResolvedDoc, xpath.toString());
getXPath(node, xpath);
if (alias != null) {
res = parseAliasResource(alias, xpath);
} else {
rules.append(parseRules(node, xpath));
}
} else if (name.equals(LDMLConstants.SETTINGS)) {
rules.append(parseSettings(node));
} else if (name.equals(LDMLConstants.SUPPRESS_CONTRACTIONS)) {
if (DEBUG) {
log.debug("");
}
int index = rules.length();
rules.append("[suppressContractions ");
rules.append(LDMLUtilities.getNodeValue(node));
rules.append(" ]");
if (DEBUG) {
log.debug(rules.substring(index));
}
} else if (name.equals(LDMLConstants.OPTIMIZE)) {
rules.append("[optimize ");
rules.append(LDMLUtilities.getNodeValue(node));
rules.append(" ]");
} else if (name.equals(LDMLConstants.BASE)) {
// TODO Dont know what to do here
// if (DEBUG)printXPathWarning(node, xpath);
rules.append(parseBase(node, fullyResolvedDoc, xpath, oldLength));
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
current = table.first = res;
} else {
current.next = res;
current = current.next;
}
res = null;
}
xpath.delete(oldLength, xpath.length());
}
if (rules != null) {
ResourceString str = new ResourceString();
str.name = LDMLConstants.SEQUENCE;
str.val = rules.toString();
if (current == null) {
current = table.first = str;
} else {
current.next = str;
current = current.next;
}
str = new ResourceString();
str.name = "Version";
str.val = getLdmlVersion(); // "1.0"
current.next = str;
}
xpath.delete(savedLength, xpath.length());
if (table.first != null) {
return table;
}
return null;
}
private String parseBase(Node node, Document fullyResolvedDoc, StringBuilder xpath, int oldLength) {
String myxp = xpath.substring(0, oldLength);
// backward compatibility
String locale = LDMLUtilities.getNodeValue(node);
if (locale == null) {
locale = LDMLUtilities.getAttributeValue(node, LDMLConstants.LOCALE);
}
if (locale != null) {
String fn = locale + ".xml";
Document colDoc = LDMLUtilities.getFullyResolvedLDML(sourceDir, fn, false, false, false, true);
Node col = LDMLUtilities.getNode(colDoc, myxp);
if (col != null) {
ResourceTable table = (ResourceTable) parseCollation(col, fullyResolvedDoc, new StringBuilder(myxp), false);
if (table != null) {
Resource current = table.first;
while (current != null) {
if (current instanceof ResourceString) {
ResourceString temp = (ResourceString) current;
if (temp.name.equals(LDMLConstants.SEQUENCE)) {
return temp.val;
}
}
current = current.next;
}
} else {
log.warning("Locale (" + fn + ") Collation node could not be parsed for " + myxp);
}
} else {
log.warning("Locale (" + fn + ") Could not find col from xpath: " + myxp);
}
} else {
log.warning("Could not find locale from xpath: " + xpath.toString());
}
return "";
}
private StringBuilder parseSettings(Node node) {
StringBuilder rules = new StringBuilder();
String strength = LDMLUtilities.getAttributeValue(node, LDMLConstants.STRENGTH);
if (strength != null) {
rules.append(" [strength ");
rules.append(getStrength(strength));
rules.append(" ]");
}
String alternate = LDMLUtilities.getAttributeValue(node, LDMLConstants.ALTERNATE);
if (alternate != null) {
rules.append(" [alternate ");
rules.append(alternate);
rules.append(" ]");
}
String backwards = LDMLUtilities.getAttributeValue(node, LDMLConstants.BACKWARDS);
if (backwards != null && backwards.equals("on")) {
rules.append(" [backwards 2]");
}
String normalization = LDMLUtilities.getAttributeValue(node, LDMLConstants.NORMALIZATION);
if (normalization != null) {
rules.append(" [normalization ");
rules.append(normalization);
rules.append(" ]");
}
String caseLevel = LDMLUtilities.getAttributeValue(node, LDMLConstants.CASE_LEVEL);
if (caseLevel != null) {
rules.append(" [caseLevel ");
rules.append(caseLevel);
rules.append(" ]");
}
String caseFirst = LDMLUtilities.getAttributeValue(node, LDMLConstants.CASE_FIRST);
if (caseFirst != null) {
rules.append(" [caseFirst ");
rules.append(caseFirst);
rules.append(" ]");
}
String hiraganaQ = LDMLUtilities.getAttributeValue(node, LDMLConstants.HIRAGANA_Q);
if (hiraganaQ == null) {
// try the deprecated version
hiraganaQ = LDMLUtilities.getAttributeValue(node, LDMLConstants.HIRAGANA_Q_DEP);
}
if (hiraganaQ != null) {
rules.append(" [hiraganaQ ");
rules.append(hiraganaQ);
rules.append(" ]");
}
String numeric = LDMLUtilities.getAttributeValue(node, LDMLConstants.NUMERIC);
if (numeric != null) {
rules.append(" [numericOrdering ");
rules.append(numeric);
rules.append(" ]");
}
return rules;
}
private static final TreeMap<String, String> collationMap = new TreeMap<String, String>();
static {
collationMap.put("first_tertiary_ignorable", "[first tertiary ignorable ]");
collationMap.put("last_tertiary_ignorable", "[last tertiary ignorable ]");
collationMap.put("first_secondary_ignorable", "[first secondary ignorable ]");
collationMap.put("last_secondary_ignorable", "[last secondary ignorable ]");
collationMap.put("first_primary_ignorable", "[first primary ignorable ]");
collationMap.put("last_primary_ignorable", "[last primary ignorable ]");
collationMap.put("first_variable", "[first variable ]");
collationMap.put("last_variable", "[last variable ]");
collationMap.put("first_non_ignorable", "[first regular]");
collationMap.put("last_non_ignorable", "[last regular ]");
// TODO check for implicit
// collationMap.put("??", "[first implicit]");
// collationMap.put("??", "[last implicit]");
collationMap.put("first_trailing", "[first trailing ]");
collationMap.put("last_trailing", "[last trailing ]");
}
private StringBuilder parseRules(Node root, StringBuilder xpath) {
StringBuilder rules = new StringBuilder();
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
if (name.equals(LDMLConstants.PC) || name.equals(LDMLConstants.SC) || name.equals(LDMLConstants.TC) || name.equals(LDMLConstants.QC) || name.equals(LDMLConstants.IC)) {
Node lastVariable = LDMLUtilities.getNode(node, LDMLConstants.LAST_VARIABLE, null, null);
if (lastVariable != null) {
addSpaceForDebug(rules);
rules.append(collationMap.get(lastVariable.getNodeName()));
} else {
String data = getData(node, name);
rules.append(data);
}
} else if (name.equals(LDMLConstants.P) || name.equals(LDMLConstants.S) || name.equals(LDMLConstants.T) || name.equals(LDMLConstants.Q) || name.equals(LDMLConstants.I)) {
Node lastVariable = LDMLUtilities.getNode(node, LDMLConstants.LAST_VARIABLE, null, null);
if (lastVariable != null) {
addSpaceForDebug(rules);
rules.append(collationMap.get(lastVariable.getNodeName()));
} else {
String data = getData(node, name);
rules.append(data);
}
} else if (name.equals(LDMLConstants.X)) {
rules.append(parseExtension(node));
} else if (name.equals(LDMLConstants.RESET)) {
rules.append(parseReset(node));
} else if (name.equals(LDMLConstants.IMPORT)) {
rules.append(parseImport(node));
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
}
return rules;
}
private static final UnicodeSet needsQuoting = new UnicodeSet("[[:whitespace:][[:c:]-[:co:]][:z:][[:ascii:]-[a-zA-Z0-9]]]");
private static StringBuilder quoteOperandBuffer = new StringBuilder(); // faster
private static final String quoteOperand(String s) {
// s = Normalizer.normalize(s, Normalizer.NFC);
quoteOperandBuffer.setLength(0);
boolean noQuotes = true;
boolean inQuote = false;
int cp;
for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
cp = UTF16.charAt(s, i);
if (!needsQuoting.contains(cp)) {
if (inQuote) {
quoteOperandBuffer.append('\'');
inQuote = false;
}
quoteOperandBuffer.append(UTF16.valueOf(cp));
} else {
noQuotes = false;
if (cp == '\'') {
quoteOperandBuffer.append("''");
} else {
if (!inQuote) {
quoteOperandBuffer.append('\'');
inQuote = true;
}
if (cp > 0xFFFF) {
quoteOperandBuffer.append("\\U").append(Utility.hex(cp, 8));
} else if (cp <= 0x20 || cp > 0x7E) {
quoteOperandBuffer.append("\\u").append(Utility.hex(cp));
} else {
quoteOperandBuffer.append(UTF16.valueOf(cp));
}
}
}
}
if (inQuote) {
quoteOperandBuffer.append('\'');
}
if (noQuotes) {
return s; // faster
}
return quoteOperandBuffer.toString();
}
private String getData(Node root, String strength) {
StringBuilder data = new StringBuilder();
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
String name = node.getNodeName();
if (name.equals(LDMLConstants.CP)) {
String hex = LDMLUtilities.getAttributeValue(node, LDMLConstants.HEX);
addSpaceForDebug(data);
data.append(getStrengthSymbol(strength));
addSpaceForDebug(data);
String cp = UTF16.valueOf(Integer.parseInt(hex, 16));
data.append(quoteOperand(cp));
}
}
if (node.getNodeType() == Node.TEXT_NODE) {
String val = node.getNodeValue();
if (val != null) {
if (strength.equals(LDMLConstants.PC) || strength.equals(LDMLConstants.SC) ||
strength.equals(LDMLConstants.TC) || strength.equals(LDMLConstants.QC) ||
strength.equals(LDMLConstants.IC)) {
data.append(getExpandedRules(val, strength));
} else {
addSpaceForDebug(data);
data.append(getStrengthSymbol(strength));
addSpaceForDebug(data);
data.append(quoteOperand(val));
lastStrengthSymbol = "";
}
}
}
}
return data.toString();
}
private String getStrengthSymbol(String name) {
String strengthSymbol = "";
if (name.equals(LDMLConstants.PC) || name.equals(LDMLConstants.P)) {
strengthSymbol = "<";
} else if (name.equals(LDMLConstants.SC) || name.equals(LDMLConstants.S)) {
strengthSymbol = "<<";
} else if (name.equals(LDMLConstants.TC) || name.equals(LDMLConstants.T)) {
strengthSymbol = "<<<";
} else if (name.equals(LDMLConstants.QC) || name.equals(LDMLConstants.Q)) {
strengthSymbol = "<<<<";
} else if (name.equals(LDMLConstants.IC) || name.equals(LDMLConstants.I)) {
strengthSymbol = "=";
} else {
log.error("Encountered strength: " + name);
System.exit(-1);
}
if(name.equals(LDMLConstants.PC) || name.equals(LDMLConstants.SC) ||
name.equals(LDMLConstants.TC)|| name.equals(LDMLConstants.QC) ||
name.equals(LDMLConstants.IC)){
strengthSymbol += "*";
}
return strengthSymbol;
}
private String getStrength(String name) {
if (name.equals(LDMLConstants.PRIMARY)) {
return "1";
} else if (name.equals(LDMLConstants.SECONDARY)) {
return "2";
} else if (name.equals(LDMLConstants.TERTIARY)) {
return "3";
} else if (name.equals(LDMLConstants.QUARTERNARY)) {
return "4";
} else if (name.equals(LDMLConstants.IDENTICAL)) {
return "5";
} else {
log.error("Encountered strength: " + name);
System.exit(-1);
}
return null;
}
private StringBuilder parseReset(Node root) {
/*
* variableTop at & x= [last variable] <reset>x</reset><i><last_variable/></i> after & x < [last variable]
* <reset>x</reset><p><last_variable/></p> before & [before 1] x< [last variable] <reset
* before="primary">x</reset> <p><last_variable/></p>
*/
/*
* & [first tertiary ignorable] << \u00e1 <reset><first_tertiary_ignorable/></reset><s>?</s>
*/
StringBuilder ret = new StringBuilder();
addSpaceForDebug(ret);
ret.append("&");
addSpaceForDebug(ret);
String val = LDMLUtilities.getAttributeValue(root, LDMLConstants.BEFORE);
if (val != null) {
addSpaceForDebug(ret);
ret.append("[before ");
ret.append(getStrength(val));
ret.append("]");
}
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
short type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
String key = node.getNodeName();
addSpaceForDebug(ret);
ret.append(collationMap.get(key));
}
if (type == Node.TEXT_NODE) {
ret.append(quoteOperand(node.getNodeValue()));
}
}
lastStrengthSymbol = "";
return ret;
}
private StringBuilder parseImport(Node node) {
StringBuilder ret = new StringBuilder();
org.w3c.dom.NamedNodeMap attributes = node.getAttributes();
if (attributes == null || attributes.getLength() == 0) {
throw new InternalError("<import> doesn't have any attributes.");
}
Node source = attributes.getNamedItem("source");
Node type = attributes.getNamedItem("type");
if (source == null) {
throw new InternalError("<import> doesn't have a source attribute.");
}
ret.append("[import ");
ret.append(source.getNodeValue().replace("_", "-"));
if (type != null) {
ret.append("-u-co-");
ret.append(type.getNodeValue());
}
ret.append("]");
return ret;
}
/**
* Expand rules to include compact collation syntax to produce an equivalent
* but possibly more compact rule string.
*
* This function is called when one of the <pc></pc>, <sc></sc>, <tc></tc>,
* <qc></qc>, <ic></ic> rules are evaluated. These rules contain a list of
* characters to which the given strength operator need to be applied
* consecutively. Rather than applying a series of consecutive operators
* (For example '<' for <pc></pc>), this function introduces two new syntax
* characters:
*
* <li> A '*' after an operator signifies a list: For example, "&a<*hrbk"
* means "&a<h<r<b<k".
*
* <li> A '-' indicates a range of consecutive (codepointwise) characters.
* For example, "&a<*dh-ls" means "&a<*dhijkls" or "&a<d<h<i<j<k<l<s".
*
* This is done in such a way that the resulting string is not longer than
* the original string.
*/
private StringBuilder getExpandedRules(String data, String name) {
UCharacterIterator iter = UCharacterIterator.getInstance(data);
StringBuilder ret = new StringBuilder();
// The strength symbol with an extra '*' added at the end.
String strengthSymbol = getStrengthSymbol(name);
// The strength symbol without the extra '*'.
String nonExpandedStrengthSymbol = strengthSymbol.substring(0, strengthSymbol.length()-1);
// The set on which the expansion works. It consists of all nfd_inert
// characters minus the syntax characters.
UnicodeSet inertSet = new UnicodeSet("[:nfd_inert:]");
inertSet.remove("-<=");
// This flag keeps track of whether we are at the beginning of an
// expanded rule. The expansion breaks when non-nfd_inert character or
// a syntax character is encountered.
boolean restartExpandedRules = true;
startOfRange = lastOfRange = 0;
int ch;
while ((ch = iter.nextCodePoint()) != UCharacterIterator.DONE) {
if (inertSet.contains(ch)) { // The character is nfd_inert.
if (restartExpandedRules){
addSpaceForDebug(ret);
// This is the start of an expanded rule. Add the strength
// symbol, with a star, and then the first character.
if (!strengthSymbol.equals(lastStrengthSymbol)) {
ret.append(strengthSymbol);
lastStrengthSymbol = strengthSymbol;
}
addSpaceForDebug(ret);
ret.append(quoteOperand(UTF16.valueOf(ch)));
startOfRange = lastOfRange = ch;
restartExpandedRules = false;
} else {
// This character, in the middle of a rule, may or may not
// be added, depending on whether it belongs to a range or
// not. So, leave it to the checking function.
checkAndProcessRange(ret, ch);
}
} else { // The character is not nfd_inert.
addSpaceForDebug(ret);
// Process any pending range.
writePendingRange(ret);
// This character is not NFD inert.
// Treat it without compact collation syntax.
ret.append(nonExpandedStrengthSymbol);
ret.append(quoteOperand(UTF16.valueOf(ch)));
lastStrengthSymbol = nonExpandedStrengthSymbol;
// Restart expanded rules so that if there are more characters,
// they will use compact collation syntax.
restartExpandedRules = true;
startOfRange = lastOfRange = ch;
}
addSpaceForDebug(ret);
}
// Process any pending range
writePendingRange(ret);
return ret;
}
/**
* Checks whether a character belongs to a range and output accordingly.
*/
private void checkAndProcessRange(StringBuilder ret, int ch) {
if (ch == startOfRange) {
// This happens when a character is repeated more than once. In
// this case, we need to output (repeat) the character.
ret.append(quoteOperand(UTF16.valueOf(ch)));
} else if (ch == lastOfRange + 1) {
// Wait till the range is finished
lastOfRange = ch;
} else {
// Print the pending range starting from startOfRange (exclusive)
// till lastOfRange (inclusive)
writePendingRange(ret);
// Then write the current character. This will take care of the
// repeating character as well.
ret.append(quoteOperand(UTF16.valueOf(ch)));
startOfRange = lastOfRange = ch;
}
}
/**
* Writes a range from startOfRange (exclusive) to lastOfRange (inclusive).
*/
private void writePendingRange(StringBuilder ret) {
if (lastOfRange < startOfRange) {
// This should not happen. Should be an error.
// Just returning for the time being.
return;
}
if (lastOfRange == startOfRange) {
// These variables are initialized and have not changed.
// Since we don't process the first character in this function, skip.
return;
}
// The first character is already input, so skip it.
// ret.DO_NOT_append(quoteOperand(UTF16.valueOf(startOfRange)));
// Add hyphen if three or more characters are there.
if (lastOfRange > startOfRange + 1) {
ret.append("-");
}
// Add last character.
ret.append(quoteOperand(UTF16.valueOf(lastOfRange)));
}
private StringBuilder parseExtension(Node root) {
/*
* strength context string extension <strength> <context> | <string> / <extension> < a | [last variable]
* <x><context>a</context><p><last_variable/></p></x> < [last variable] / a
* <x><p><last_variable/></p><extend>a</extend></x> << k / h <x><s>k</s> <extend>h</extend></x> << d | a
* <x><context>d</context><s>a</s></x> = e | a <x><context>e</context><i>a</i></x> = f | a
* <x><context>f</context><i>a</i></x>
*/
StringBuilder rules = new StringBuilder();
Node contextNode = null;
Node extendNode = null;
Node strengthNode = null;
String strength = null;
String string = null;
String context = null;
String extend = null;
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
if (name.equals(LDMLConstants.CONTEXT)) {
contextNode = node;
} else if (name.equals(LDMLConstants.P) || name.equals(LDMLConstants.S) || name.equals(LDMLConstants.T) || name.equals(LDMLConstants.I)) {
strengthNode = node;
} else if (name.equals(LDMLConstants.EXTEND)) {
extendNode = node;
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
}
if (contextNode != null) {
context = LDMLUtilities.getNodeValue(contextNode);
}
if (strengthNode != null) {
Node lastVariable = LDMLUtilities.getNode(strengthNode, LDMLConstants.LAST_VARIABLE, null, null);
if (lastVariable != null) {
string = collationMap.get(lastVariable.getNodeName());
} else {
strength = getStrengthSymbol(strengthNode.getNodeName());
string = LDMLUtilities.getNodeValue(strengthNode);
}
}
if (extendNode != null) {
extend = LDMLUtilities.getNodeValue(extendNode);
}
addSpaceForDebug(rules);
rules.append(strength);
addSpaceForDebug(rules);
if (context != null) {
rules.append(quoteOperand(context));
addSpaceForDebug(rules);
rules.append("|");
addSpaceForDebug(rules);
}
rules.append(string);
if (extend != null) {
addSpaceForDebug(rules);
rules.append("/");
addSpaceForDebug(rules);
rules.append(quoteOperand(extend));
}
return rules;
}
private Resource parseBoundaries(Node root, StringBuilder xpath) {
ResourceTable table = new ResourceTable();
int savedLength = xpath.length();
getXPath(root, xpath);
Resource current = null;
String name = root.getNodeName();
table.name = name.substring(name.indexOf(':') + 1, name.length());
// we don't care if special elements are marked draft or not!
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
name = node.getNodeName();
Resource res = null;
if (name.equals(ICU_GRAPHEME) || name.equals(ICU_WORD) || name.equals(ICU_LINE) || name.equals(ICU_SENTENCE) || name.equals(ICU_TITLE) || name.equals(ICU_XGC)) {
ResourceProcess str = new ResourceProcess();
str.ext = ICUResourceWriter.DEPENDENCY;
str.name = name.substring(name.indexOf(':') + 1, name.length());
str.val = LDMLUtilities.getAttributeValue(node, ICU_DEPENDENCY);
if (str.val != null) {
res = str;
}
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
xpath.delete(savedLength, xpath.length());
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseDictionaries(Node root, StringBuilder xpath) {
ResourceTable table = new ResourceTable();
int savedLength = xpath.length();
getXPath(root, xpath);
Resource current = null;
String name = root.getNodeName();
table.name = name.substring(name.indexOf(':') + 1, name.length());
// we don't care if special elements are marked draft or not
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
name = node.getNodeName();
Resource res = null;
if (name.equals(ICU_DICTIONARY)) {
ResourceProcess str = new ResourceProcess();
str.ext = ICUResourceWriter.DEPENDENCY;
str.name = LDMLUtilities.getAttributeValue(node, LDMLConstants.TYPE);
str.val = LDMLUtilities.getAttributeValue(node, ICU_DEPENDENCY);
if (str.val != null) {
res = str;
}
} else {
log.error("Encountered unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
table.first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
xpath.delete(savedLength, xpath.length());
}
if (table.first != null) {
return table;
}
return null;
}
private Resource parseSpecialElements(LDML2ICUInputLocale loc, String xpath) {
Resource current = null;
Resource first = null;
String origXpath = xpath;
for (Iterator<String> iter = loc.getFile().iterator(xpath); iter.hasNext();) {
xpath = iter.next();
String name = XPPUtil.getXpathName(xpath);
log.info("parseSpecial: " + name);
// we don't care if special elements are marked draft or not
Resource res = null;
if (name.equals(ICU_SCRIPT)) {
if (!loc.beenHere(ICU_SCRIPT)) {
res = parseArray(loc, "//ldml/characters/special/icu:scripts");
res.name = LOCALE_SCRIPT;
}
} else if (name.equals(ICU_UCARULES)) {
ResourceProcess process = new ResourceProcess();
process.name = "UCARules";
process.ext = "uca_rules";
process.val = loc.findAttributeValue(xpath, ICU_UCA_RULES);
res = process;
} else if (name.equals(ICU_DEPENDS)) {
ResourceProcess process = new ResourceProcess();
process.name = "depends";
process.ext = "dependency";
process.val = loc.findAttributeValue(xpath, ICU_DEPENDENCY);
res = process;
} else if (xpath.startsWith("//ldml/special/" + ICU_BRKITR_DATA)) {
res = parseBrkItrData(loc, "//ldml/special/" + ICU_BRKITR_DATA);
} else if (name.equals(ICU_IS_LEAP_MONTH) || name.equals(ICU_LEAP_SYMBOL) || name.equals(ICU_NON_LEAP_SYMBOL)) {
if (!loc.beenHere(origXpath + ICU_IS_LEAP_MONTH)) {
res = parseLeapMonth(loc, origXpath);
}
} else if (name.equals(LDMLConstants.SPECIAL)) {
// just continue, already handled
} else {
log.error("Encountered unknown <" + xpath + "> special subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
}
return first;
}
public static class DocumentPair {
public final Document doc;
public final Document fullyResolvedDoc;
DocumentPair(Document doc, Document fullyResolvedDoc) {
this.doc = doc;
this.fullyResolvedDoc = fullyResolvedDoc;
}
}
/**
* Use the input locale as a cache for the document pair.
*/
private DocumentPair getDocumentPair(LDML2ICUInputLocale loc) {
if (loc.isNotOnDisk()) {
throw new InternalError("Error: locale (" + loc.getLocale() + ") isn't on disk, can't parse with DOM.");
}
DocumentPair result = loc.getDocumentPair();
if (result == null) {
result = getDocumentPair(loc.getLocale());
loc.setDocumentPair(result);
}
return result;
}
/**
* Get the node of the 'top' item named. Similar to DOM-based parseBundle()
*/
public Node getTopNode(Document doc, String topName) {
StringBuilder xpath = new StringBuilder();
xpath.append("//ldml");
org.w3c.dom.Element ldmlElement = doc.getDocumentElement();
NodeList identityList = ldmlElement.getElementsByTagName(LDMLConstants.IDENTITY);
Element identity = (Element) identityList.item(0);
NodeList versionList = identity.getElementsByTagName(LDMLConstants.VERSION);
Node version = versionList.item(0);
setLdmlVersion(LDMLUtilities.getAttributeValue(version, LDMLConstants.CLDR_VERSION));
Node ldml = doc.getDocumentElement();
for (Node node = ldml.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
if (topName.equals(name)) {
return node;
}
}
return null;
}
private Resource parseBrkItrData(LDML2ICUInputLocale loc, String xpath) {
// "//ldml/special/"
if (loc.beenHere(ICU_BRKITR_DATA)) {
return null;
}
DocumentPair docPair = getDocumentPair(loc);
Node root = getTopNode(docPair.doc, LDMLConstants.SPECIAL);
StringBuilder xpathBuffer = new StringBuilder();
getXPath(root, xpathBuffer);
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
if (name.equals(ICU_BRKITR_DATA)) {
return parseBrkItrData(node, xpathBuffer);
}
}
throw new InternalError("Could not find node for " + ICU_BRKITR_DATA);
}
private Resource parseBrkItrData(Node root, StringBuilder xpath) {
Resource current = null, first = null;
int savedLength = xpath.length();
getXPath(root, xpath);
// we don't care if special elements are marked draft or not!
for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String name = node.getNodeName();
Resource res = null;
if (name.equals(ICU_BOUNDARIES)) {
res = parseBoundaries(node, xpath);
} else if (name.equals(ICU_DICTIONARIES)) {
res = parseDictionaries(node, xpath);
} else {
log.error("Encountered @ " + xpath + " unknown <" + root.getNodeName() + "> subelement: " + name);
System.exit(-1);
}
if (res != null) {
if (current == null) {
first = res;
current = res.end();
} else {
current.next = res;
current = res.end();
}
res = null;
}
xpath.delete(savedLength, xpath.length());
}
return first;
}
private Resource parseDefaultNumberingSystem(LDML2ICUInputLocale loc, String xpath) {
ResourceString str = new ResourceString();
str.name = LDMLConstants.DEFAULT;;
str.val = loc.getFile().getStringValue(xpath+"/"+LDMLConstants.DEFAULT_NUMBERING_SYSTEM);
if (str.val != null) {
return str;
}
return null;
}
private Resource parseRBNF(LDML2ICUInputLocale loc, String xpath) {
char LARROW = 0x2190;
char RARROW = 0x2192;
ResourceTable table = new ResourceTable();
table.name = "RBNFRules";
Resource current = null;
Resource res = null;
ResourceArray ruleset = new ResourceArray();
if (loc.isPathNotConvertible(xpath)) {
return null;
}
String currentRulesetGrouping = "";
String currentRulesetType = "";
for (Iterator<String> iter = loc.getFile().iterator(xpath, CLDRFile.ldmlComparator); iter.hasNext();) {
String aPath = iter.next();
String fullPath = loc.getFile().getFullXPath(aPath);
String name = XPPUtil.getXpathName(aPath);
if (name.equals(LDMLConstants.RBNFRULE)) {
XPathParts xpp = new XPathParts();
xpp.set(fullPath);
String rulesetGrouping = xpp.findAttributeValue(LDMLConstants.RULESETGROUPING, LDMLConstants.TYPE);
String rulesetType = xpp.findAttributeValue(LDMLConstants.RULESET, LDMLConstants.TYPE);
String rulesetAccess = xpp.findAttributeValue(LDMLConstants.RULESET, LDMLConstants.ACCESS);
String ruleValue = xpp.findAttributeValue(LDMLConstants.RBNFRULE, LDMLConstants.VALUE);
String ruleRadix = xpp.findAttributeValue(LDMLConstants.RBNFRULE, LDMLConstants.RADIX);
String ruleDecExp = xpp.findAttributeValue(LDMLConstants.RBNFRULE, LDMLConstants.DECEXP);
if (rulesetGrouping != null && !rulesetGrouping.equals(currentRulesetGrouping)) {
if (!currentRulesetGrouping.equals("")) {
res = ruleset;
table.appendContents(res);
res = null;
}
ruleset = new ResourceArray();
ruleset.name = rulesetGrouping;
currentRulesetGrouping = rulesetGrouping;
currentRulesetType = "";
}
if (!rulesetType.equals(currentRulesetType)) {
ResourceString rsname = new ResourceString();
String rsNamePrefix = "%";
if (rulesetAccess != null && rulesetAccess.equals("private")) {
rsNamePrefix = "%%";
}
rsname.val = rsNamePrefix + rulesetType + ":";
ruleset.appendContents(rsname);
currentRulesetType = rulesetType;
}
String radixString = "";
if (ruleRadix != null) {
radixString = "/" + ruleRadix;
}
String decExpString = "";
if (ruleDecExp != null) {
int decExp = Integer.valueOf(ruleDecExp).intValue();
while (decExp > 0) {
decExpString = decExpString.concat(">");
decExp--;
}
}
ResourceString rs = new ResourceString();
if (rulesetType.equals(LDMLConstants.LENIENT_PARSE)) {
rs.val = Utility.escape(loc.getFile().getStringValue(aPath).replace(LARROW, '<').replace(RARROW, '>'));
} else {
rs.val = ruleValue + radixString + decExpString + ": " + Utility.escape(loc.getFile().getStringValue(aPath).replace(LARROW, '<').replace(RARROW, '>'));
}
ruleset.appendContents(rs);
} else {
log.error("Unknown element found: " + xpath + " / " + name);
System.exit(-1);
}
}
if (ruleset.first != null) {
table.appendContents(ruleset);
}
if (table.first != null) {
return table;
}
return null;
}
public boolean isDraftStatusOverridable(String locName) {
if (getLocalesMap() != null && getLocalesMap().size() > 0) {
String draft = getLocalesMap().get(locName + ".xml");
if (draft != null && (draft.equals("true") || locName.matches(draft))) {
return true;
}
return false;
}
// check to see if the destination file already exists
// maybe override draft was specified in the run that produced
// the txt files
File f = new File(destDir, locName + ".txt");
return f.exists();
}
// utility
public static StringBuilder getXPath(Node node, StringBuilder xpath) {
xpath.append("/");
xpath.append(node.getNodeName());
LDMLUtilities.appendXPathAttribute(node, xpath);
return xpath;
}
}
| [
"emmons@b1474bd8-1051-4aae-843b-7d7c63456b9e"
] | emmons@b1474bd8-1051-4aae-843b-7d7c63456b9e |
1a977135a1c78a0cf842776251cfb4ade89b92d7 | 29f78bfb928fb6f191b08624ac81b54878b80ded | /generated_SPs_SCs/test/large2/src/main/java/large2/service/ServiceName_6Bean.java | cd7edab6928d9ee4043ad3211e6143f65d166fd9 | [] | no_license | MSPL4SOA/MSPL4SOA-tool | 8a78e73b4ac7123cf1815796a70f26784866f272 | 9f3419e416c600cba13968390ee89110446d80fb | refs/heads/master | 2020-04-17T17:30:27.410359 | 2018-07-27T14:18:55 | 2018-07-27T14:18:55 | 66,304,158 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 14,518 | java | package large2.service;
import org.switchyard.component.bean.Service;
import javax.inject.Inject;
import org.switchyard.Context;
import large2.input.InputDataClassName_6_4;
import large2.input.InputDataClassName_6_5;
import large2.input.InputDataClassName_6_6;
import large2.input.InputDataClassName_6_1;
import large2.input.InputDataClassName_6_2;
import large2.input.InputDataClassName_6_3;
import large2.output.OutputDataClassName_6_4;
import large2.output.OutputDataClassName_6_5;
import large2.output.OutputDataClassName_6_6;
import large2.output.OutputDataClassName_6_1;
import large2.output.OutputDataClassName_6_2;
import large2.output.OutputDataClassName_6_3;
import large2.state.State_ServiceName_6_CapabilityName_6_4;
import large2.state.State_ServiceName_6_CapabilityName_6_5;
import large2.state.State_ServiceName_6_CapabilityName_6_6;
import large2.state.State_ServiceName_6_CapabilityName_6_1;
import large2.state.State_ServiceName_6_CapabilityName_6_2;
import large2.state.State_ServiceName_6_CapabilityName_6_3;
import large2.util.ConsumerHeader;
@Service(ServiceName_6.class)
public class ServiceName_6Bean implements ServiceName_6 {
@Inject
private Context context;
@Inject
State_ServiceName_6_CapabilityName_6_4 instanceState_ServiceName_6_CapabilityName_6_4;
@Inject
State_ServiceName_6_CapabilityName_6_5 instanceState_ServiceName_6_CapabilityName_6_5;
@Inject
State_ServiceName_6_CapabilityName_6_6 instanceState_ServiceName_6_CapabilityName_6_6;
@Inject
State_ServiceName_6_CapabilityName_6_1 instanceState_ServiceName_6_CapabilityName_6_1;
@Inject
State_ServiceName_6_CapabilityName_6_2 instanceState_ServiceName_6_CapabilityName_6_2;
@Inject
State_ServiceName_6_CapabilityName_6_3 instanceState_ServiceName_6_CapabilityName_6_3;
@Override
public OutputDataClassName_6_4 CapabilityName_6_4(
InputDataClassName_6_4 inputDataClassName_6_4) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_4 : ********//");
System.out.println("InputName_6_4_7 : "
+ inputDataClassName_6_4.getInputName_6_4_7());
System.out.println("InputName_6_4_8 : "
+ inputDataClassName_6_4.getInputName_6_4_8());
System.out.println("InputName_6_4_9 : "
+ inputDataClassName_6_4.getInputName_6_4_9());
System.out.println("InputName_6_4_1 : "
+ inputDataClassName_6_4.getInputName_6_4_1());
System.out.println("InputName_6_4_2 : "
+ inputDataClassName_6_4.getInputName_6_4_2());
System.out.println("InputName_6_4_3 : "
+ inputDataClassName_6_4.getInputName_6_4_3());
System.out.println("InputName_6_4_4 : "
+ inputDataClassName_6_4.getInputName_6_4_4());
System.out.println("InputName_6_4_5 : "
+ inputDataClassName_6_4.getInputName_6_4_5());
System.out.println("InputName_6_4_6 : "
+ inputDataClassName_6_4.getInputName_6_4_6());
OutputDataClassName_6_4 out = new OutputDataClassName_6_4();
out.setOutputName_6_4_5(Integer.valueOf("660"));
out.setOutputName_6_4_4("CapabilityName_6_4");
out.setOutputName_6_4_7(Integer.valueOf("712"));
out.setOutputName_6_4_6(Integer.valueOf("399"));
out.setOutputName_6_4_1("CapabilityName_6_4");
out.setOutputName_6_4_3("CapabilityName_6_4");
out.setOutputName_6_4_2(Integer.valueOf("673"));
out.setOutputName_6_4_9(Integer.valueOf("122"));
out.setOutputName_6_4_8(Float.valueOf("732"));
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_4
.setState(instanceState_ServiceName_6_CapabilityName_6_4
.getState() + " ServiceName_6 CapabilityName_6_4");
return out;
}
@Override
public OutputDataClassName_6_5 CapabilityName_6_5(
InputDataClassName_6_5 inputDataClassName_6_5) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_5 : ********//");
System.out.println("InputName_6_5_6 : "
+ inputDataClassName_6_5.getInputName_6_5_6());
System.out.println("InputName_6_5_7 : "
+ inputDataClassName_6_5.getInputName_6_5_7());
System.out.println("InputName_6_5_8 : "
+ inputDataClassName_6_5.getInputName_6_5_8());
System.out.println("InputName_6_5_9 : "
+ inputDataClassName_6_5.getInputName_6_5_9());
System.out.println("InputName_6_5_1 : "
+ inputDataClassName_6_5.getInputName_6_5_1());
System.out.println("InputName_6_5_2 : "
+ inputDataClassName_6_5.getInputName_6_5_2());
System.out.println("InputName_6_5_3 : "
+ inputDataClassName_6_5.getInputName_6_5_3());
System.out.println("InputName_6_5_4 : "
+ inputDataClassName_6_5.getInputName_6_5_4());
System.out.println("InputName_6_5_5 : "
+ inputDataClassName_6_5.getInputName_6_5_5());
OutputDataClassName_6_5 out = new OutputDataClassName_6_5();
out.setOutputName_6_5_4(Float.valueOf("558"));
out.setOutputName_6_5_3(Float.valueOf("358"));
out.setOutputName_6_5_6(Float.valueOf("118"));
out.setOutputName_6_5_5(Integer.valueOf("328"));
out.setOutputName_6_5_2(Float.valueOf("674"));
out.setOutputName_6_5_1("CapabilityName_6_5");
out.setOutputName_6_5_8(Float.valueOf("259"));
out.setOutputName_6_5_7(Float.valueOf("155"));
out.setOutputName_6_5_9(Float.valueOf("538"));
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_5
.setState(instanceState_ServiceName_6_CapabilityName_6_5
.getState() + " ServiceName_6 CapabilityName_6_5");
return out;
}
@Override
public OutputDataClassName_6_6 CapabilityName_6_6(
InputDataClassName_6_6 inputDataClassName_6_6) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_6 : ********//");
System.out.println("InputName_6_6_5 : "
+ inputDataClassName_6_6.getInputName_6_6_5());
System.out.println("InputName_6_6_6 : "
+ inputDataClassName_6_6.getInputName_6_6_6());
System.out.println("InputName_6_6_7 : "
+ inputDataClassName_6_6.getInputName_6_6_7());
System.out.println("InputName_6_6_8 : "
+ inputDataClassName_6_6.getInputName_6_6_8());
System.out.println("InputName_6_6_1 : "
+ inputDataClassName_6_6.getInputName_6_6_1());
System.out.println("InputName_6_6_2 : "
+ inputDataClassName_6_6.getInputName_6_6_2());
System.out.println("InputName_6_6_3 : "
+ inputDataClassName_6_6.getInputName_6_6_3());
System.out.println("InputName_6_6_4 : "
+ inputDataClassName_6_6.getInputName_6_6_4());
OutputDataClassName_6_6 out = new OutputDataClassName_6_6();
out.setOutputName_6_6_3(Integer.valueOf("255"));
out.setOutputName_6_6_2(Float.valueOf("316"));
out.setOutputName_6_6_5(Integer.valueOf("419"));
out.setOutputName_6_6_4("CapabilityName_6_6");
out.setOutputName_6_6_1(Float.valueOf("565"));
out.setOutputName_6_6_7(Float.valueOf("137"));
out.setOutputName_6_6_6(Float.valueOf("601"));
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_6
.setState(instanceState_ServiceName_6_CapabilityName_6_6
.getState() + " ServiceName_6 CapabilityName_6_6");
return out;
}
@Override
public OutputDataClassName_6_1 CapabilityName_6_1(
InputDataClassName_6_1 inputDataClassName_6_1) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_1 : ********//");
System.out.println("InputName_6_1_2 : "
+ inputDataClassName_6_1.getInputName_6_1_2());
System.out.println("InputName_6_1_3 : "
+ inputDataClassName_6_1.getInputName_6_1_3());
System.out.println("InputName_6_1_4 : "
+ inputDataClassName_6_1.getInputName_6_1_4());
System.out.println("InputName_6_1_5 : "
+ inputDataClassName_6_1.getInputName_6_1_5());
System.out.println("InputName_6_1_6 : "
+ inputDataClassName_6_1.getInputName_6_1_6());
System.out.println("InputName_6_1_7 : "
+ inputDataClassName_6_1.getInputName_6_1_7());
System.out.println("InputName_6_1_8 : "
+ inputDataClassName_6_1.getInputName_6_1_8());
System.out.println("InputName_6_1_1 : "
+ inputDataClassName_6_1.getInputName_6_1_1());
OutputDataClassName_6_1 out = new OutputDataClassName_6_1();
out.setOutputName_6_1_1(Integer.valueOf("799"));
out.setOutputName_6_1_2(Float.valueOf("356"));
out.setOutputName_6_1_7("CapabilityName_6_1");
out.setOutputName_6_1_8(Integer.valueOf("432"));
out.setOutputName_6_1_3("CapabilityName_6_1");
out.setOutputName_6_1_4(Integer.valueOf("600"));
out.setOutputName_6_1_5(Float.valueOf("222"));
out.setOutputName_6_1_6("CapabilityName_6_1");
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_1
.setState(instanceState_ServiceName_6_CapabilityName_6_1
.getState() + " ServiceName_6 CapabilityName_6_1");
return out;
}
@Override
public OutputDataClassName_6_2 CapabilityName_6_2(
InputDataClassName_6_2 inputDataClassName_6_2) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_2 : ********//");
System.out.println("InputName_6_2_1 : "
+ inputDataClassName_6_2.getInputName_6_2_1());
System.out.println("InputName_6_2_2 : "
+ inputDataClassName_6_2.getInputName_6_2_2());
System.out.println("InputName_6_2_3 : "
+ inputDataClassName_6_2.getInputName_6_2_3());
System.out.println("InputName_6_2_4 : "
+ inputDataClassName_6_2.getInputName_6_2_4());
System.out.println("InputName_6_2_5 : "
+ inputDataClassName_6_2.getInputName_6_2_5());
System.out.println("InputName_6_2_6 : "
+ inputDataClassName_6_2.getInputName_6_2_6());
System.out.println("InputName_6_2_7 : "
+ inputDataClassName_6_2.getInputName_6_2_7());
System.out.println("InputName_6_2_8 : "
+ inputDataClassName_6_2.getInputName_6_2_8());
OutputDataClassName_6_2 out = new OutputDataClassName_6_2();
out.setOutputName_6_2_1(Float.valueOf("420"));
out.setOutputName_6_2_7("CapabilityName_6_2");
out.setOutputName_6_2_6(Float.valueOf("592"));
out.setOutputName_6_2_8("CapabilityName_6_2");
out.setOutputName_6_2_3(Integer.valueOf("436"));
out.setOutputName_6_2_2("CapabilityName_6_2");
out.setOutputName_6_2_5(Integer.valueOf("757"));
out.setOutputName_6_2_4("CapabilityName_6_2");
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_2
.setState(instanceState_ServiceName_6_CapabilityName_6_2
.getState() + " ServiceName_6 CapabilityName_6_2");
return out;
}
@Override
public OutputDataClassName_6_3 CapabilityName_6_3(
InputDataClassName_6_3 inputDataClassName_6_3) {
// TODO Auto-generated stub
System.out
.println("\\\\******* The output of ServiceName_6 : CapabilityName_6_3 : ********//");
System.out.println("InputName_6_3_8 : "
+ inputDataClassName_6_3.getInputName_6_3_8());
System.out.println("InputName_6_3_9 : "
+ inputDataClassName_6_3.getInputName_6_3_9());
System.out.println("InputName_6_3_1 : "
+ inputDataClassName_6_3.getInputName_6_3_1());
System.out.println("InputName_6_3_2 : "
+ inputDataClassName_6_3.getInputName_6_3_2());
System.out.println("InputName_6_3_3 : "
+ inputDataClassName_6_3.getInputName_6_3_3());
System.out.println("InputName_6_3_4 : "
+ inputDataClassName_6_3.getInputName_6_3_4());
System.out.println("InputName_6_3_5 : "
+ inputDataClassName_6_3.getInputName_6_3_5());
System.out.println("InputName_6_3_6 : "
+ inputDataClassName_6_3.getInputName_6_3_6());
System.out.println("InputName_6_3_7 : "
+ inputDataClassName_6_3.getInputName_6_3_7());
OutputDataClassName_6_3 out = new OutputDataClassName_6_3();
out.setOutputName_6_3_6(Float.valueOf("396"));
out.setOutputName_6_3_5(Float.valueOf("989"));
out.setOutputName_6_3_8(Integer.valueOf("105"));
out.setOutputName_6_3_7(Integer.valueOf("876"));
out.setOutputName_6_3_2(Integer.valueOf("787"));
out.setOutputName_6_3_1(Float.valueOf("481"));
out.setOutputName_6_3_4(Float.valueOf("453"));
out.setOutputName_6_3_3("CapabilityName_6_3");
out.setOutputName_6_3_9(Float.valueOf("630"));
boolean checkAuth = ConsumerHeader.checkAuthentification(context);
if (checkAuth == true) {
// TODO Auto-generated stub
System.out.println("Correct authentification");
} else {
// TODO Auto-generated stub
System.out.println("Incorrect authentification");
}
// TODO Auto-generated stub
System.out.println("State header in: "
+ ConsumerHeader.getConsumerState(context));
instanceState_ServiceName_6_CapabilityName_6_3
.setState(instanceState_ServiceName_6_CapabilityName_6_3
.getState() + " ServiceName_6 CapabilityName_6_3");
return out;
}
}
| [
"akram.kamoun@gmail.com"
] | akram.kamoun@gmail.com |
c59dd80bfd749b8528d2076f1884277c8916082a | 2057b1bf203dc8c59becf89b9f9131a85de100e6 | /src/main/java/com/w951/zsbus/permission/entity/User.java | fa1e3ef253997c9fad340b01b92b0ee428aff129 | [] | no_license | W951-ZSBUS/java-web-zsbus-permission | cd2709c3a51493dde81388a90838855619d113da | 5a8b8ef3a99f7b00e2d4658767800da70fb8a7eb | refs/heads/master | 2021-01-15T22:02:07.266083 | 2014-06-06T08:50:12 | 2014-06-06T08:50:12 | 19,519,825 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,444 | java | package com.w951.zsbus.permission.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "zsbus_permission_user")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements java.io.Serializable {
private static final long serialVersionUID = 8803821759605380509L;
private String userId;
private String userNm;
private String userName;
private String userPass;
private Integer userSex;
private Integer userAge;
private String userDept;
private String userZw;
private String userPhone;
private String userQq;
private String userEmail;
private String userDate;
private String userCompany;
private String userCreatename;
private Integer userVerify;
private String userBack;
private List<UserGroup> userGroups = new ArrayList<UserGroup>();
@GenericGenerator(name = "generator", strategy = "uuid.hex")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "user_id", unique = true, nullable = false, length = 32)
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column(name = "user_nm", length = 20)
public String getUserNm() {
return this.userNm;
}
public void setUserNm(String userNm) {
this.userNm = userNm;
}
@Column(name = "user_name", length = 8)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "user_pass", length = 32)
public String getUserPass() {
return this.userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
@Column(name = "user_sex")
public Integer getUserSex() {
return this.userSex;
}
public void setUserSex(Integer userSex) {
this.userSex = userSex;
}
@Column(name = "user_age")
public Integer getUserAge() {
return this.userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
@Column(name = "user_dept", length = 20)
public String getUserDept() {
return this.userDept;
}
public void setUserDept(String userDept) {
this.userDept = userDept;
}
@Column(name = "user_zw", length = 20)
public String getUserZw() {
return this.userZw;
}
public void setUserZw(String userZw) {
this.userZw = userZw;
}
@Column(name = "user_phone", length = 20)
public String getUserPhone() {
return this.userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
@Column(name = "user_qq", length = 20)
public String getUserQq() {
return this.userQq;
}
public void setUserQq(String userQq) {
this.userQq = userQq;
}
@Column(name = "user_email", length = 50)
public String getUserEmail() {
return this.userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Column(name = "user_date", length = 19)
public String getUserDate() {
return this.userDate;
}
public void setUserDate(String userDate) {
this.userDate = userDate;
}
@Column(name = "user_company", length = 50)
public String getUserCompany() {
return this.userCompany;
}
public void setUserCompany(String userCompany) {
this.userCompany = userCompany;
}
@Column(name = "user_createname", length = 20)
public String getUserCreatename() {
return this.userCreatename;
}
public void setUserCreatename(String userCreatename) {
this.userCreatename = userCreatename;
}
@Column(name = "user_verify")
public Integer getUserVerify() {
return this.userVerify;
}
public void setUserVerify(Integer userVerify) {
this.userVerify = userVerify;
}
@Column(name = "user_back", length = 300)
public String getUserBack() {
return this.userBack;
}
public void setUserBack(String userBack) {
this.userBack = userBack;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
public List<UserGroup> getUserGroups() {
return this.userGroups;
}
public void setUserGroups(List<UserGroup> userGroups) {
this.userGroups = userGroups;
}
} | [
"topsale@vip.qq.com"
] | topsale@vip.qq.com |
dd6cd7e519d3d9c4b5cc117a6392b850c1f6d4b5 | 7ee0fcdeaface1cba1f09760584a0f0bf09f75bc | /tob-order/src/main/java/com/service/details/DetailsService.java | cb797c8403955ff6cfab376173b8ae2b9b160fec | [] | no_license | wongshandev/tob_mall | 6508eb40f6cf5afc3a1f77dad9b587a9984db3ab | 09ca19cf5dcbbec2d6e9bf391cabd7dc23364524 | refs/heads/master | 2020-11-27T21:01:37.113488 | 2019-10-31T08:15:19 | 2019-10-31T08:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 987 | java | package com.service.details;
import com.github.pagehelper.PageInfo;
import com.pojo.DeliveryDetailVO;
import com.pojo.InstallDetailVO;
import com.pojo.OtherCostInfo;
import com.utils.ReqPage;
public interface DetailsService {
/**
* 查看送貨列表
*
* @param orderId
* @param reqPage
* @return
*/
PageInfo<DeliveryDetailVO> findDeliveryDetailsByOrderId(long orderId, ReqPage reqPage);
/**
* 查看安装列表
*
* @param orderId
* @param reqPage
* @return
*/
PageInfo<InstallDetailVO> findInstallDetailsByOrderId(long orderId, ReqPage reqPage);
/**
* 查看费用列表
* @param orderId
* @param reqPage
* @return 费用类型,费用
* 0其他费用,
* 1安装费,
* 2运费,
* 3耗材费,
* 4高空作业费
*/
PageInfo<OtherCostInfo> findOtherCostDetailsByOrderId(long orderId, ReqPage reqPage);
}
| [
"guanyimail@126.com"
] | guanyimail@126.com |
a114f0adf8201dd41ba28ffa7dcfc9a54ec74682 | 6c70be184b7a6369a31c40b24f48b2d87491cb86 | /Práctica 1-AStar/AStar-Dielam/src/Business/heuristic/Heuristic.java | 4048eee34c28638b2bf201636ffa6b9d4d23e305 | [
"MIT"
] | permissive | Dielam/IC | 557a0dc498708dc0fee9c66274d86f79f0aff90b | 3b3f1e8951567d79d99f66a1b7a3abf74e43e286 | refs/heads/master | 2020-04-21T02:50:21.067074 | 2019-04-11T18:11:03 | 2019-04-11T18:11:03 | 169,266,878 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 618 | 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 Business.heuristic;
/**
* Heuristic
* Calculate the distance to the goal
* @author Diego Laguna Martín
*/
public class Heuristic{
public float DistanceToGoal(int startX, int startY, int goalX, int goalY) {
//Distance in the x
float x = goalX - startX;
//Distance in the y
float y = goalY - startY;
//Pythagoras theorem
return (float) Math.sqrt((x*x)+(y*y));
}
}
| [
"dielagun@ucm.es"
] | dielagun@ucm.es |
3b5f9a71498a5ecdad5792d997cdd28bd6128990 | 53d677a55e4ece8883526738f1c9d00fa6560ff7 | /com/tencent/mm/plugin/appbrand/o$3.java | fad68753af12bc1d9d89ccfe3e940c9a23089898 | [] | no_license | 0jinxing/wechat-apk-source | 544c2d79bfc10261eb36389c1edfdf553d8f312a | f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d | refs/heads/master | 2020-06-07T20:06:03.580028 | 2019-06-21T09:17:26 | 2019-06-21T09:17:26 | 193,069,132 | 9 | 4 | null | null | null | null | UTF-8 | Java | false | false | 830 | java | package com.tencent.mm.plugin.appbrand;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.ui.MMActivity;
final class o$3
implements y.a
{
o$3(o paramo, boolean paramBoolean, long paramLong, i.b paramb)
{
}
private void atQ()
{
AppMethodBeat.i(128978);
this.gPy.atM().runOnUiThread(new o.3.1(this));
AppMethodBeat.o(128978);
}
public final void atR()
{
AppMethodBeat.i(128979);
atQ();
AppMethodBeat.o(128979);
}
public final void atS()
{
AppMethodBeat.i(128980);
atQ();
AppMethodBeat.o(128980);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes8-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.appbrand.o.3
* JD-Core Version: 0.6.2
*/ | [
"172601673@qq.com"
] | 172601673@qq.com |
f42e2a19b7272bec837c5534ea811f90c9c96bf1 | 88edccd61f60642457ea4b485f6333ca5912658c | /src/main/java/com/common/ConvertService.java | 622afcc3742af952439695eb0ba4ed34988e647d | [] | no_license | bwlloveistrue/logisticsCenter | d22cd0719d1a5d00508e7a36a54a40b783662df6 | 35202a2a0b215613d8bd31bbc9826e5ba8b1d10a | refs/heads/master | 2022-07-12T23:30:10.230690 | 2020-08-29T08:39:58 | 2020-08-29T08:39:58 | 160,008,734 | 0 | 2 | null | 2022-06-17T02:02:28 | 2018-12-02T03:08:02 | Java | UTF-8 | Java | false | false | 13,535 | java | package com.common;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.util.ConstantUtils;
import com.util.Utils;
public class ConvertService {
public static Object convertBeanToEntity(Object obj,Object entity){
Class beanClass = obj.getClass();
System.out.println("Class:" + beanClass.getName());
//通过默认的构造函数创建一个新的对象
try {
//获得对象的所有属性
Field fields[] = beanClass.getDeclaredFields();
Method m = null;
for(int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
// 将属性的首字符大写,方便构造get,set方法
String firstLetter = fieldName.substring(0, 1).toUpperCase();
//获得get方法
String getMethodName = "get" + firstLetter + fieldName.substring(1);
//获得set方法
String setMethodName = "set" + firstLetter + fieldName.substring(1);
//获取属性的类型
String type = field.getGenericType().toString();
System.out.println(type);
if(type.equals("class java.lang.String")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
String value = ConvertService.null2String(((String) getMethod.invoke(obj)));
m = entity.getClass().getMethod(setMethodName,String.class);
m.invoke(entity, value);
}else if(type.equals("class java.lang.Integer")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Integer value = Utils.getIntValue((Integer) getMethod.invoke(obj)+"");
m = entity.getClass().getMethod(setMethodName,Integer.class);
m.invoke(entity, value);
}else if(type.equals("int")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
int value = Utils.getIntValue((Integer) getMethod.invoke(obj)+"");;
m = entity.getClass().getMethod(setMethodName,int.class);
m.invoke(entity, value);
}else if(type.equals("class java.math.BigDecimal")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
BigDecimal value = (BigDecimal) getMethod.invoke(obj);
if(value == null){
value=ConstantUtils.defaultDecimal;
}
m = entity.getClass().getMethod(setMethodName,BigDecimal.class);
m.invoke(entity, value);
}else if(type.equals("class java.lang.Boolean")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Boolean value = (Boolean) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,Boolean.class);
m.invoke(entity, value);
}else if(type.equals("class java.util.Date")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Date value = (Date) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,Date.class);
m.invoke(entity, value);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return entity;
}
public static Object convertEntityToBean(Object obj,Object entity){
Class beanClass = obj.getClass();
System.out.println("Class:" + beanClass.getName());
//通过默认的构造函数创建一个新的对象
try {
//获得对象的所有属性
Field fields[] = beanClass.getDeclaredFields();
Method m = null;
for(int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
// 将属性的首字符大写,方便构造get,set方法
String firstLetter = fieldName.substring(0, 1).toUpperCase();
//获得get方法
String getMethodName = "get" + firstLetter + fieldName.substring(1);
//获得set方法
String setMethodName = "set" + firstLetter + fieldName.substring(1);
//获取属性的类型
String type = field.getGenericType().toString();
System.out.println(type);
if(type.equals("class java.lang.String")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
String value = ConvertService.null2String((String) getMethod.invoke(obj));
m = entity.getClass().getMethod(setMethodName,String.class);
m.invoke(entity, value);
}else if(type.equals("class java.lang.Integer")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Integer value = (Integer) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,Integer.class);
m.invoke(entity, value);
}else if(type.equals("int")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Object value = getMethod.invoke(obj);
if(value == null){
value=ConstantUtils.defaultDecimal;
}
m = entity.getClass().getMethod(setMethodName,int.class);
m.invoke(entity, value);
}else if(type.equals("class java.math.BigDecimal")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
BigDecimal value = (BigDecimal) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,BigDecimal.class);
m.invoke(entity, value);
}else if(type.equals("class java.lang.Boolean")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Boolean value = (Boolean) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,Boolean.class);
m.invoke(entity, value);
}else if(type.equals("class java.util.Date")){
// 获得和属性对应的get方法
Method getMethod = beanClass.getMethod(getMethodName,new Class[] {});
// 调用getter方法获取属性值
Date value = (Date) getMethod.invoke(obj);
m = entity.getClass().getMethod(setMethodName,Date.class);
m.invoke(entity, value);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return entity;
}
/**
* @return YYYYMMDD
*/
public static String getDate(String format){
String dateStr = "";
try{
SimpleDateFormat sf1 = new SimpleDateFormat(format);
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
dateStr = sf1.format(date);
}catch(Exception e){
}
return dateStr;
}
/**
* @return YYYY-MM-DD
*/
public static String getDate(){
Calendar cal = Calendar.getInstance();
String currentdate = ConvertService.add0(cal.get(Calendar.YEAR), 4) + "-" +
ConvertService.add0(cal.get(Calendar.MONTH) + 1, 2) + "-" +
ConvertService.add0(cal.get(Calendar.DAY_OF_MONTH), 2) ;
return currentdate;
}
/**
* @return HH:MM
*/
public static String getTime(){
Calendar cal = Calendar.getInstance();
String currenttime = ConvertService.add0(cal.get(Calendar.HOUR_OF_DAY), 2) + ":" +
ConvertService.add0(cal.get(Calendar.MINUTE), 2);
return currenttime;
}
/**
* @param days
* @return
*/
public static String getDate(int days){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, days);
String currentdate = ConvertService.add0(cal.get(Calendar.YEAR), 4) + "-" +
ConvertService.add0(cal.get(Calendar.MONTH) + 1, 2) + "-" +
ConvertService.add0(cal.get(Calendar.DAY_OF_MONTH), 2) ;
return currentdate;
}
public static String add0(int paramInt1, int len)
{
long l = (long) Math.pow(10.0D, len);
return String.valueOf(l + paramInt1).substring(1);
}
public static ArrayList arrayToArrayList(Object aobj[])
{
ArrayList arraylist = new ArrayList();
if (aobj == null)
return arraylist;
for (int i = 0; i < aobj.length; i++)
arraylist.add(aobj[i]);
return arraylist;
}
/**
* @param aobj 数组
* @param msg 拼接字符串
* @return obj+msg
*/
public static ArrayList arrayToArrayList(Object aobj[],String msg)
{
ArrayList arraylist = new ArrayList();
if (aobj == null)
return arraylist;
for (int i = 0; i < aobj.length; i++)
arraylist.add(msg + aobj[i]);
return arraylist;
}
/**
* @param aobj 数组
* @param msg 拼接字符串
* @return msg+obj
*/
public static String arrayToString(Object aobj[],String msg)
{
String str = "";
if (aobj == null)
return str;
for (int i = 0; i < aobj.length; i++)
str += str.equals("")?msg+aobj[i]:","+msg+aobj[i];
return str;
}
/**
* @param s
* @param i
* @return
*/
public static int getIntValue(String s, int i)
{
try{
return Integer.parseInt(s);
}catch(Exception e){
return i;
}
}
public static int getIntValue(String s)
{
try{
return Integer.parseInt(s);
}catch(Exception e){
return -1;
}
}
public static BigDecimal getDecimalValue(String s, BigDecimal i)
{
try{
BigDecimal bd=new BigDecimal(s);
return bd;
}catch(Exception e){
return i;
}
}
public static String null2String(String s)
{
return s != null ? s : "";
}
public static String null2String(String s, String def)
{
return s != null ? s : def;
}
public static String getWarn(String s, String msg)
{
try{
if("".equals(s) && s!=null){
return s;
}else{
return msg;
}
}catch(Exception e){
return msg;
}
}
/**
* @param sou
* @param s1
* @param s2
* @return
*/
public static String StringReplace(String sou, String s1, String s2) {
sou = null2String(sou);
s1 = null2String(s1);
s2 = null2String(s2);
try{
sou = sou.replace(s1, s2);
}catch(Exception e){
}
return sou;
}
public static float getFloatValue(String s)
{
return getFloatValue(s, -1F);
}
public static float getFloatValue(String s, float f)
{
if(s==null || s.equals("")){
return 0f;
}
return Float.parseFloat(s);
}
public static double getDoubleValue(String s)
{
return getDoubleValue(s, -1D);
}
public static double getDoubleValue(String s, double d)
{
return Double.parseDouble(s);
}
public static String getPointValue(String s)
{
return getPointValue(s, 2);
}
public static String getPointValue(String s, int i)
{
return getPointValue(s, 2, "-1");
}
public static String getPointValue(String s, int i, String s1)
{
if(s.equals("") || s==null || s.equals("null")){
return "0.00";
}
String s2;
Double.parseDouble(s);
s2 = s;
if (s.indexOf("E") != -1)
s2 = getfloatToString(s);
if (s2.indexOf(".") == -1)
{
s2 = (new StringBuilder()).append(s2).append(".").toString();
for (int j = 0; j < i; j++)
s2 = (new StringBuilder()).append(s2).append("0").toString();
} else
if (s2.length() - s2.lastIndexOf(".") <= i)
{
for (int k = 0; k < (i - s2.length()) + s2.lastIndexOf(".") + 1; k++)
s2 = (new StringBuilder()).append(s2).append("0").toString();
} else
{
s2 = s2.substring(0, s2.lastIndexOf(".") + i + 1);
}
return s2;
}
public static String getfloatToString(String s)
{
boolean flag = false;
if (s.indexOf("-") != -1)
{
flag = true;
s = s.substring(1, s.length());
}
int i = s.indexOf("E");
if (i == -1)
return s;
int j = Integer.parseInt(s.substring(i + 1, s.length()));
s = s.substring(0, i);
i = s.indexOf(".");
s = (new StringBuilder()).append(s.substring(0, i)).append(s.substring(i + 1, s.length())).toString();
String s1 = s;
if (s.length() <= j)
{
for (int k = 0; k < (j - s.length()) + 1; k++)
s1 = (new StringBuilder()).append(s1).append("0").toString();
} else
{
s1 = (new StringBuilder()).append(s1.substring(0, j + 1)).append(".").append(s1.substring(j + 1)).append("0").toString();
}
if (flag)
s1 = (new StringBuilder()).append("-").append(s1).toString();
return s1;
}
public static String getIntValues(String s)
{
String s1 = s;
if (s.indexOf(".") == -1)
s1 = s;
else
s1 = s.substring(0, s.indexOf("."));
return s1;
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
System.out.println(getDate(5));;
}
}
| [
"bwlloveistrue@163.com"
] | bwlloveistrue@163.com |
777d01baa4904ba7b0fa8a3ef27669f3df1a1e42 | f1946b7934d7deec8a2d5b1e8e59342a002ef2ab | /Task11.java | d6fd7515527cdaf761d2141ecdcb913db4ef475b | [] | no_license | nickeysilich/JB29_HT1 | 185182cb3b9bbf2d8409688305dcbaef57263d96 | 4da667596137be47516cc856c1b25f36ca5b4073 | refs/heads/master | 2020-07-11T05:51:24.274374 | 2019-08-26T11:29:02 | 2019-08-26T11:29:02 | 204,460,321 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 907 | java | package by.htp.les02.main;
/*
* 11. Вычислить периметр и площадь прямоугольного треугольника по длинам а и b двух катетов.
*/
import java.util.Scanner;
import static java.lang.Math.sqrt;
public class Task11 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Введите длинну двух катетов" + "(Нажмите Enter после каждого числа)");
double a;
double b;
double c;
double p;
double s;
a = sc.nextDouble();
b = sc.nextDouble();
c = sqrt(a*a + b*b);
p = a + b + c;
s = (a*b)/2;
System.out.println("Периметр прямоугольного треугольника= " + p);
System.out.println("Площадь прямоугольного треугольника = " + s);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
c628bf06134796dc8c3d665faf9cc7277346914c | 15cd283f0dda74dcce4a3de657b0170989e7cc4a | /src/com/company/ksort.java | 965ff92a31d1a42d9d4a9ced4dc89a483bfce9fe | [] | no_license | ErnestoChe/Algorithms | a0c21b10e7a98c50f3188d24081fd8fdc977c980 | afd1da5825ac9d100cde27e9c4ade540e90624e5 | refs/heads/master | 2020-07-04T04:25:56.489109 | 2019-11-07T19:40:05 | 2019-11-07T19:40:05 | 202,154,403 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,673 | java | package com.company;
public class ksort {
public String[] items;
ksort(){
items = new String[800];
}
public boolean add(String s)
{
int ind = index(s);
if(ind == -1){
return false;
}else{
items[ind] = s;
return true;
}
}
//todo make private
public static int index(String s)
{
if(!checkFormat(s)){
return -1;
}else{
int res = 0;
res += Character.getNumericValue(s.charAt(1)) * 10 + Character.getNumericValue(s.charAt(2));
char letter = s.charAt(0);
//a b c d e f g h
switch (letter) {
case ('b'):
res += 100;
break;
case ('c'):
res += 200;
break;
case ('d'):
res += 300;
break;
case ('e'):
res += 400;
break;
case ('f'):
res += 500;
break;
case ('g'):
res += 600;
break;
case ('h'):
res += 700;
break;
}
return res;
}
}
public static boolean checkFormat(String s)
{
if(s.length()!= 3) return false;
if(s.charAt(0) < 'a' || s.charAt(0) > 'h') return false;
if(s.charAt(1) < '0' || s.charAt(1) > '9') return false;
if(s.charAt(2) < '0' || s.charAt(2) > '9') return false;
return true;
}
}
| [
"ernestfilippov@mail.ru"
] | ernestfilippov@mail.ru |
579338096be09f7bc8ac04c9c13e1eec3d6d3fda | ced738663cfa2caf64e458840132777f8447380a | /src/view/InstructionsView.java | 1a03585f2885374015e95a4fabf32cd271489157 | [] | no_license | JPSanin/handball-frenzy-game | 9a821f9bf1b171659698842e52af32a5b42d662e | 08aad376d1ff744b73f83a5a9b57e46a0433428c | refs/heads/main | 2023-08-17T09:27:49.038104 | 2021-10-18T02:59:43 | 2021-10-18T02:59:43 | 415,199,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package view;
import processing.core.PApplet;
import processing.core.PImage;
public class InstructionsView {
private PImage background;
private PApplet app;
public InstructionsView(PApplet app) {
this.app = app;
background= app.loadImage("../img/Instructions.png");
}
public void drawScreen() {
app.image(background, 0, 0);
}
}
| [
"juanpablosaninb@gmail.com"
] | juanpablosaninb@gmail.com |
9de96e6e1c48db935211ad0a3ee8ec5ba2d9d274 | f444b36b2d8122f54c81ba738e898edf3ef54b94 | /src/com/syntax/class02/Recap.java | b183b3860edf892ff9a50fdd4b48e29cad55d45b | [] | no_license | alex198815/Java8code | 2f33032c42c33d3f09ce72e66fa3d3e3f3bddf82 | 9b54962531bfc97cb6e7d9c712da69fd1376d596 | refs/heads/main | 2022-12-30T11:25:55.233977 | 2020-10-17T17:41:31 | 2020-10-17T17:41:31 | 304,908,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 504 | java | package com.syntax.class02;
public class Recap {
public static void main(String[]args) {
byte smallnum=127;
short mindum=9877;
int largenum=1948577;
long xlnum=29623854;
float variable5=08.99f;
double variable6=9.99999;
boolean variable7=true;
boolean variable8=false;
char variable9='C';
char variable10='%';
char variable11='9';
int large=1000;
System.out.print(smallnum);
System.out.println();
System.out.println(large);
}
}
| [
"alexkozachok26@gmail.com"
] | alexkozachok26@gmail.com |
056498443d7e8e3d362bf468a265f1ee8fb83033 | 2bdc1bbca0edccbe0b4d3207cce4c31c711b4988 | /src/chapter22/e22_7/src/main/java/Point2D.java | 26c47404b92a24b1a301278e6c64e9ffb61ef86a | [] | no_license | dawids21/introduction-to-java-exercises | 850c3fe07834776c792d4c6e9263e714d8f49899 | 108b96e57ab4114e7c7b5d01ae9e29c60d263f96 | refs/heads/master | 2021-03-21T23:44:22.763352 | 2020-09-18T08:18:35 | 2020-09-18T08:18:35 | 247,335,951 | 0 | 0 | null | 2020-10-13T21:47:06 | 2020-03-14T18:58:07 | Java | UTF-8 | Java | false | false | 843 | java | import java.util.Objects;
public class Point2D {
private double x = 0;
private double y = 0;
public Point2D() {
}
public Point2D(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Point2D point = (Point2D) o;
return getX() == point.getX() && getY() == point.getY();
}
@Override
public int hashCode() {
return Objects.hash(getX(), getY());
}
@Override
public String toString() {
return "Point2D{" + "x=" + x + ", y=" + y + '}';
}
}
| [
"dawid.stasiak21@gmail.com"
] | dawid.stasiak21@gmail.com |
5819c80fe38df68e294780d68f040d4778a2ebdc | b61edff15f2706e5321785bd44e9a916d4bc5bfa | /custom/cuppy/gensrc/de/hybris/platform/cuppy/jalo/GeneratedUpdateCompetitionCronJob.java | 8c3212fbcb1e9b4939928c2d82538d66066b89c9 | [] | no_license | ReddySrini/jenkins_setup_test | b8711a5da3483ec020730a74e2d6fb6e3424be65 | 1a08c72ae22290019744b4e430b04fafc0d27941 | refs/heads/master | 2021-04-09T17:17:15.029015 | 2015-07-14T08:31:19 | 2015-07-14T08:31:19 | 39,058,331 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,142 | java | /*
* ----------------------------------------------------------------
* --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! ---
* --- Generated at Jul 13, 2015 5:05:16 PM ---
* ----------------------------------------------------------------
*
* [y] hybris Platform
*
* Copyright (c) 2000-2014 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*
*/
package de.hybris.platform.cuppy.jalo;
import de.hybris.platform.cuppy.constants.CuppyConstants;
import de.hybris.platform.cuppy.jalo.Competition;
import de.hybris.platform.cuppy.jalo.LastStartTimeAwareCronJob;
import de.hybris.platform.jalo.Item.AttributeMode;
import de.hybris.platform.jalo.SessionContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Generated class for type {@link de.hybris.platform.cuppy.jalo.UpdateCompetitionCronJob UpdateCompetitionCronJob}.
*/
@SuppressWarnings({"deprecation","unused","cast","PMD"})
public abstract class GeneratedUpdateCompetitionCronJob extends LastStartTimeAwareCronJob
{
/** Qualifier of the <code>UpdateCompetitionCronJob.competition</code> attribute **/
public static final String COMPETITION = "competition";
protected static final Map<String, AttributeMode> DEFAULT_INITIAL_ATTRIBUTES;
static
{
final Map<String, AttributeMode> tmp = new HashMap<String, AttributeMode>(LastStartTimeAwareCronJob.DEFAULT_INITIAL_ATTRIBUTES);
tmp.put(COMPETITION, AttributeMode.INITIAL);
DEFAULT_INITIAL_ATTRIBUTES = Collections.unmodifiableMap(tmp);
}
@Override
protected Map<String, AttributeMode> getDefaultAttributeModes()
{
return DEFAULT_INITIAL_ATTRIBUTES;
}
/**
* <i>Generated method</i> - Getter of the <code>UpdateCompetitionCronJob.competition</code> attribute.
* @return the competition - Competition this CronJob will update.
*/
public Competition getCompetition(final SessionContext ctx)
{
return (Competition)getProperty( ctx, COMPETITION);
}
/**
* <i>Generated method</i> - Getter of the <code>UpdateCompetitionCronJob.competition</code> attribute.
* @return the competition - Competition this CronJob will update.
*/
public Competition getCompetition()
{
return getCompetition( getSession().getSessionContext() );
}
/**
* <i>Generated method</i> - Setter of the <code>UpdateCompetitionCronJob.competition</code> attribute.
* @param value the competition - Competition this CronJob will update.
*/
public void setCompetition(final SessionContext ctx, final Competition value)
{
setProperty(ctx, COMPETITION,value);
}
/**
* <i>Generated method</i> - Setter of the <code>UpdateCompetitionCronJob.competition</code> attribute.
* @param value the competition - Competition this CronJob will update.
*/
public void setCompetition(final Competition value)
{
setCompetition( getSession().getSessionContext(), value );
}
}
| [
"rsrinivas4u@gmail.com"
] | rsrinivas4u@gmail.com |
81806930c31778611f70b243fd821f611cf60693 | 5d530fded5ec5ecba909569b0a3ffed6a0afd40f | /src/src/day14_multi_branch_if_statements/MultiBranchIfStatement.java | e399f1a2648584de9f87fd9c7861ec4c81c22ad7 | [] | no_license | Dilnoz8605/java-programming2 | 1861a2ce26f8004c0981d7e7fca58e052e74ff91 | 39d68235959cd4fa4321aaca2d316d386d43720b | refs/heads/master | 2023-05-06T18:15:44.055613 | 2021-06-03T16:05:56 | 2021-06-03T16:05:56 | 373,556,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 980 | java | package src.day14_multi_branch_if_statements;
public class MultiBranchIfStatement {
public static void main(String[] args) {
int day = 3;
if (day == 1) {
System.out.println("Monday");
} else {
System.out.println("Not Monday");
}
if (day == 2) {
System.out.println("Tuesday");
}
if (day == 3) {
System.out.println("Wednesday");
}
System.out.println("=================MULTI BRANCH IF STATEMENT==================");
day = 1;
if (day == 1) {
System.out.println("Monday");
} else if (day == 2) {
System.out.println("Tuesday");
} else if (day == 3) {
System.out.println("Wednesday");
} else if (day == 4) {
System.out.println("Thursday");
} else {
System.out.println("java day");
}
System.out.println("Everyday code java");
}
}
| [
"dilnoz8605@gmail.com"
] | dilnoz8605@gmail.com |
975fa67624b3db2cb9206def83a86e4948936fb2 | f051f0ee60c8f6d5ecf5214252a1676e622dac48 | /src/main/java/com/jdbcpcf/demo/MyjdbcsqlpcfdemoApplication.java | 352420a127bb595615cfe42a09c50fc8308e25ec | [] | no_license | ramanarv66/springbootsecurity | e378d6950c015d14785fe3a4df8bc9bbcf7ea72d | 2e1bd14b28ee03750158753edfec5bd7ac221dea | refs/heads/master | 2020-07-11T00:47:31.719103 | 2019-08-26T06:57:07 | 2019-08-26T06:57:07 | 204,412,290 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.jdbcpcf.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyjdbcsqlpcfdemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyjdbcsqlpcfdemoApplication.class, args);
}
}
| [
"m.ramanarv@gmail.com"
] | m.ramanarv@gmail.com |
406d17b410339bb088bfd739d8c6537eb7a08954 | 49a7392aa975f44947330357776acb7e0adac3f8 | /src/module-info.java | 84edaaf53528f08ae09f1469200e0fbbdb03aebd | [] | no_license | sophieyzq/comp346a2 | d40596360771a861995a0f573e58fd03222f96e0 | f08a4ff0b1d8a7e7a9f76e52232a4bf47674fb5e | refs/heads/master | 2021-01-16T11:59:47.819807 | 2020-03-04T00:29:41 | 2020-03-04T00:29:41 | 243,111,676 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20 | java | module comp346A2 {
} | [
"sophieyzq@gmail.com"
] | sophieyzq@gmail.com |
94ba6812606c78999217c3395c8eb11195e759c9 | 1b82895e9deaee93f5fe8b399c4e1b344323845b | /springcloud-02-shopping-fileserver/src/main/java/com/springcloud/SpringCloudFileServer.java | 14441b8a38b9aa0cd7f9fb099843c522af4c5944 | [] | no_license | liaoguyue/gmd-shopping | e4af7c723ac75d51b198e2091d5e21cbe280f7b2 | 97b19ebc9e967c77f534b729fbe435ac96f4b797 | refs/heads/master | 2022-06-22T10:58:04.942302 | 2019-06-17T01:41:16 | 2019-06-17T01:41:16 | 192,257,881 | 0 | 0 | null | 2022-06-21T01:17:37 | 2019-06-17T01:57:08 | Java | UTF-8 | Java | false | false | 328 | java | package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringCloudFileServer {
public static void main(String[] args) {
SpringApplication.run(SpringCloudFileServer.class, args);
}
}
| [
"51807044+liaoguyue@users.noreply.github.com"
] | 51807044+liaoguyue@users.noreply.github.com |
2b0471a072a09b81d41ab044f4c981e4f2714b41 | b8411ac46d1d17c7448045310e8a7bc21470d61a | /src/main/java/com/example/instinctools/TextAnalyzer/TextAnalyzerApplication.java | 109d73c7d82c992a1d3b3b81aafbed71bc6e02e9 | [] | no_license | TurkmenHaker/TextAnalyzer | 03c1594132a416e14e8f52e5f4a59461dd17ed10 | 6223cb561cb767bda9086005ba7f30fec9617961 | refs/heads/master | 2020-03-22T12:23:47.577855 | 2018-07-07T00:08:37 | 2018-07-07T00:08:37 | 140,037,440 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.example.instinctools.TextAnalyzer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TextAnalyzerApplication {
public static void main(String[] args) {
SpringApplication.run(TextAnalyzerApplication.class, args);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
c54afd4cdc31de16b2c6a9d69fb6a2c7228a76cf | 13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3 | /crash-reproduction-ws/results/LANG-16b-1-8-Single_Objective_GGA-WeightedSum/org/apache/commons/lang3/math/NumberUtils_ESTest.java | 4ab081b82ece12d5e534f836a258c4a09adfc97a | [
"MIT",
"CC-BY-4.0"
] | permissive | STAMP-project/Botsing-basic-block-coverage-application | 6c1095c6be945adc0be2b63bbec44f0014972793 | 80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da | refs/heads/master | 2022-07-28T23:05:55.253779 | 2022-04-20T13:54:11 | 2022-04-20T13:54:11 | 285,771,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 948 | java | /*
* This file was automatically generated by EvoSuite
* Tue Mar 31 09:42:56 UTC 2020
*/
package org.apache.commons.lang3.math;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.apache.commons.lang3.math.NumberUtils;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class NumberUtils_ESTest extends NumberUtils_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
try {
NumberUtils.createNumber("g.b~");
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// g.b~ is not a valid number.
//
verifyException("org.apache.commons.lang3.math.NumberUtils", e);
}
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
7485d7fdfb22cc4637ad8216325e1c4b6e0b05b0 | 0b273f7f54bde020fd1e50d92273fd36b1497eaa | /healthin/src/main/java/org/kosta/healthin/model/service/MentoringServiceImpl.java | 3e4a5e3438ee321de79bbb006152ba4fb1a9113f | [] | no_license | rlgurtm/final-HealIN | fe6dd661dd1ff7b8769f158e8483a26570c588e1 | 07f3f3e5dee54300bd054b6d1e28f8d0026ba797 | refs/heads/master | 2021-01-22T03:17:31.236765 | 2017-06-27T01:16:32 | 2017-06-27T01:16:32 | 92,364,600 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,186 | java | package org.kosta.healthin.model.service;
import java.util.Map;
import javax.annotation.Resource;
import org.kosta.healthin.model.dao.MentoringDAO;
import org.kosta.healthin.model.vo.ListVO;
import org.kosta.healthin.model.vo.MentoringVO;
import org.springframework.stereotype.Service;
@Service
public class MentoringServiceImpl implements MentoringService {
@Resource
private MentoringDAO mentoringDAO;
@Override
public ListVO findByTrainerMatchingMemberList(String trainerId){
return mentoringDAO.findByTrainerMatchingMemberList(trainerId);
}
@Override
public ListVO findByUserMatchingMemberList(String userId){
return mentoringDAO.findByUserMatchingMemberList(userId);
}
@Override
public void mentoringDetailHits(MentoringVO mentoring){
mentoringDAO.mentoringDetailHits(mentoring);
}
@Override
public int mentoringTotalCount(MentoringVO mentoring){
return mentoringDAO.mentoringTotalCount(mentoring);
}
@Override
public ListVO mentoringDetail(Map map){
return mentoringDAO.mentoringDetail(map);
}
@Override
public void insertMentoring(MentoringVO mentoring){
mentoringDAO.insertMentoring(mentoring);
}
}
| [
"Administrator@192.168.0.142"
] | Administrator@192.168.0.142 |
2069f77630755496a1ce2076b21aa821bf2164e2 | c799366915d3436075a3220969affca089f7ad7c | /src/com/study/main/ui/media/ArrayAdapter.java | 5fee6e5eb39560a80dafbe47c208ea404eea79d8 | [] | no_license | laixiao/AndroidStudy | 61230fea8a0f045f91a9aa1b45242177ae4e48d0 | af1d60639bbd1a8c935827de5dea05773cc9678d | refs/heads/master | 2021-01-23T07:02:39.277899 | 2014-12-08T02:44:48 | 2014-12-08T02:44:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,323 | java | package com.study.main.ui.media;
import java.util.ArrayList;
import java.util.Collection;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;
public abstract class ArrayAdapter<T> extends BaseAdapter {
// 数据
protected ArrayList<T> mObjects;
protected LayoutInflater mInflater;
public ArrayAdapter(final Context ctx, final ArrayList<T> l) {
mObjects = l == null ? new ArrayList<T>() : l;
mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mObjects.size();
}
@Override
public T getItem(int position) {
return mObjects.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
public void add(T item) {
this.mObjects.add(item);
}
/**
* Adds the specified items at the end of the array.
*
* @param items The items to add at the end of the array.
*/
public void addAll(T... items) {
ArrayList<T> values = this.mObjects;
for (T item : items) {
values.add(item);
}
this.mObjects = values;
}
/**
*
* @param collection
*/
public void addAll(Collection<? extends T> collection) {
mObjects.addAll(collection);
}
/**
* Remove all elements from the list.
*/
public void clear() {
mObjects.clear();
}
}
| [
"2515097216@qq.com"
] | 2515097216@qq.com |
41c37fa6193ec3c4a624f42480d1d07669475936 | 4379c2d8e1eba0f973b516b5ced58856693a2bfe | /spring07/src/main/java/com/mega/mvc07/test/BoyMain1.java | 10b21e7ff71648b7e13be52098a0c474c1d6493b | [] | no_license | jinseka/java_project0 | b78fe0230bf22da050a1cac6a754ebd8b9f1a410 | ea4623d159981edc6cd9df3d31b6396510b6937b | refs/heads/main | 2023-07-18T20:03:41.913757 | 2021-09-22T23:54:13 | 2021-09-22T23:54:13 | 379,206,363 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package com.mega.mvc07.test;
public class BoyMain1 {
public static void main(String[] args) {
Boy1 boy1 = new Boy1();
Boy1 boy2 = new Boy1();
System.out.println(boy1);
System.out.println(boy2);
System.out.println(Boy1.count);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
50445e27ef14d60aa0848c848df17735ac8875f9 | e3a587b74d75d86c93506102911eba27fb677485 | /src/main/java/com/pedro/vacinaagora/repositories/PessoaRepository.java | 79a3bb1f98b241caddc7d68203713a72bdf7998e | [] | no_license | MatheusPedroSS/code-orange-talents | 7f39fd86709ca298dd585df177faea85059ebce5 | 544efc9bfe65f95a06d0d98668cf6787a1784d6c | refs/heads/main | 2023-04-14T08:00:20.542997 | 2021-04-06T01:32:55 | 2021-04-06T01:32:55 | 355,009,090 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 296 | java | package com.pedro.vacinaagora.repositories;
import com.pedro.vacinaagora.entities.Pessoa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PessoaRepository extends JpaRepository<Pessoa, Long> {
}
| [
"matheus.pedro1214@gmail.com"
] | matheus.pedro1214@gmail.com |
f5a04b8f1e58f1de4dbc8ca6917b7999b5be3d31 | 2c844e20ac325274761bdcc3479572646e1c4611 | /a4/loi_cheng_assignment4/src/cscie97/ledger/LedgerApi.java | d509dee51758c95d1f3a48cc2255fb31261523bc | [] | no_license | loibucket/hes-2020-CSCI-E-97-Software-Design | 7349f5d140749a7f07cb115d09920854cdd05c25 | e2c71acf8ba46bf13134abb268ddaca5e9ade8bf | refs/heads/master | 2023-02-02T18:12:19.076125 | 2020-12-13T20:13:35 | 2020-12-13T20:13:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,263 | java | package cscie97.ledger;
import cscie97.smartcity.authenticator.AuthToken;
import cscie97.smartcity.model.ServiceException;
import cscie97.smartcity.shared.FileProcessor;
import java.io.*;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The CommandProcessor is a utility class for feeding the Ledger a set of
* operations, using command syntax. The command syntax specification follows:
* <p>
* Create Ledger Create a new ledger with the given name, description, and seed
* value.
* <p>
* create-ledger <name> description <description> seed <seed>
* <p>
* Create Account Create a new account with the given account id.
* <p>
* create-account <account-id>
* <p>
* Process Transaction Process a new transaction. Return an error message if the
* transaction is invalid, otherwise output the transaction id.
* <p>
* process-transaction <transaction-id> amount <amount> fee <fee> note <note>
* payer <account-address> receiver <account-address>
* <p>
* Get Account Balance Output the account balance for the given account
* get-account-balance <account-id>
* <p>
* Get Account Balances Output the account balances for the most recent
* completed block.
* <p>
* get-account-balances
* <p>
* Get Block Output the details for the given block number.
* <p>
* get-block <block-number>
* <p>
* Get Transaction Output the details of the given transaction id. Return an
* error if the transaction was not found in the Ledger.
* <p>
* get-transaction <transaction-id>
* <p>
* Validate
* <p>
* Validate the current state of the blockchain. validate Comment lines are
* denoted with a # in the first column.
* <p>
* validate
*
* @author Loi Cheng
* v1.0 2020-09-05 initial
* v1.1 2020-10-19 auto-increment transaction id, passed in id is discarded
* @version 1.1
* @since 2020-10-19
*/
public class LedgerApi extends FileProcessor {
// the ledger, this is static so there can only be 1 ledger
private static Ledger ledger = null;
// current transaction id
private static int transactionId = 0;
/**
* Process a single command. The output of the command is formatted and
* displayed to stdout. Throw a CommandProcessorException on error.
*
* @param command the command
* @param lineNumber the line number
* @throws LedgerApiException if process errors
*/
public static void processCommand(String command, int lineNumber) {
System.out.println("LEDGER-OPEN: " + command);
// replace special quotes to normal
command = command.replace('“', '"');
command = command.replace('”', '"');
// split string by whitespace, except when between quotes
// stackoverflow.com/questions/18893390/splitting-on-comma-outside-quotes
List<String> a = Arrays.asList(command.split("\\s+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"));
// do different action with commands
String action = a.get(0);
try {
// use helper function procTransHelp
switch (action) {
case "create-ledger" -> ledger = new Ledger(a.get(1), a.get(3), a.get(4));
case "create-account" -> ledger.createAccount(a.get(1));
case "process-transaction" -> System.out.println("transaction id: " + procTransHelp(a, lineNumber));
case "get-account-balance" -> {
System.out.println("confirmed:" + ledger.getAccountBalance(a.get(1)));
System.out.println("unconfirmed:" + ledger.getUnconfirmedBalance(a.get(1)));
}
case "get-account-balances" -> System.out.println(ledger.getAccountBalances());
case "get-block" -> System.out.println(ledger.getBlock(Integer.parseInt(a.get(1))));
case "get-transaction" -> System.out.println(ledger.getTransaction(a.get(1)).toString().replace("\n", ""));
case "Validate" -> {
ledger.validate();
System.out.println("ledger is valid");
}
default -> System.out.println("command not recognized!");
}
} catch (LedgerException e) {
// print error message, and continue processing next line
System.out.println((new LedgerApiException(e.action, e.reason, lineNumber)).toString());
} catch (Exception e) {
System.out.println((new LedgerApiException(action, "processing error!", lineNumber)).toString());
}
System.out.println(" :LEDGER-CLOSE");
}
/**
* Process a set of commands provided within the given commandFile. Throw a
* CommandProcessorException on error.
* java
*
* @param commandFile the filename
*/
public static void processCommandFile(String commandFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(commandFile));
String line;
AtomicInteger lineNumber = new AtomicInteger(1);
while ((line = reader.readLine()) != null) {
if (!line.isEmpty()) {
if (line.charAt(0) != "#".charAt(0)) {
processCommand(line, lineNumber.get());
} else {
System.out.println("# LINE " + lineNumber.get() + " " + line);
}
}
lineNumber.getAndIncrement();
}
reader.close();
} catch (Exception e) {
System.out.println(e);
}
}
/**
* helper function, check process-transaction command for missing items and
* report it otherwise, process transaction
*/
public static String procTransHelp(List<String> a, int lineNumber) {
String action = a.get(0);
// id
String id;
id = a.get(1);
// amount tag
if (!a.get(2).equals("amount")) {
System.out.println((new LedgerApiException(action, "amount missing", lineNumber)).toString());
}
// amount value
int amount = Integer.parseInt(a.get(3));
// fee tag
if (!a.get(4).equals("fee")) {
System.out.println((new LedgerApiException(action, "fee missing", lineNumber)).toString());
}
int fee = Integer.parseInt(a.get(5));
// note tag
if (!a.get(6).equals("note")) {
System.out.println((new LedgerApiException(action, "note missing", lineNumber)).toString());
}
// note text
String note = a.get(7);
if (note.length() > 1024) {
System.out.println(
(new LedgerApiException(action, "note must be less than 1024 characters", lineNumber)).toString());
}
// payer tag
if (!a.get(8).equals("payer")) {
System.out.println(a.get(8));
System.out.println((new LedgerApiException(action, "payer missing", lineNumber)).toString());
}
// payer account
Account payer = null;
try {
payer = ledger.getBalancePool().get(a.get(9));
} catch (Exception e) {
System.out.println((new LedgerApiException(action, "payer not found", lineNumber)).toString());
}
// receiver tag
if (!a.get(10).equals("receiver")) {
System.out.println((new LedgerApiException(action, "receiver missing", lineNumber)).toString());
}
// receiver account
Account receiver = null;
try {
receiver = ledger.getBalancePool().get(a.get(11));
} catch (Exception e) {
System.out.println((new LedgerApiException(action, "receiver not found", lineNumber)).toString());
}
// command should be ok, process transaction
String transId = "-1";
try {
//auto increment transactions
transactionId++;
transId = ledger.processTransaction(new Transaction(Integer.toString(transactionId), amount, fee, note, payer, receiver));
} catch (LedgerException e) {
System.out.println((new LedgerApiException(e.action, e.reason, lineNumber)).toString());
}
return transId;
}
}
| [
"loibucket@users.noreply.github.com"
] | loibucket@users.noreply.github.com |
d6b01cf5101754f181a75f20847ddf369f538508 | 4c5a4f19af0eebdcdcfe46e9c06121807727f391 | /ScotlYard/src/kj/scotlyard/game/model/PlayerListener.java | 473a06c901f2f90aa0b63293a9d0592ff3abe73a | [] | no_license | schoettl/ScotlYard | 78db4295d12f644b70acb893eb2d0e01ae2def61 | c70bd9e7bef672de25d667b43260509f5d7adee5 | refs/heads/master | 2016-09-06T20:03:08.869895 | 2012-03-31T16:03:52 | 2012-03-31T16:03:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package kj.scotlyard.game.model;
public interface PlayerListener {
void detectiveAdded(GameState gameState, DetectivePlayer detective, int atIndex);
void detectiveRemoved(GameState gameState, DetectivePlayer detective, int atIndex);
void mrXSet(GameState gameState, MrXPlayer oldMrX, MrXPlayer newMrX);
}
| [
"jschoett@gmail.com"
] | jschoett@gmail.com |
c04595324c87f6a1ea06915eee9a32cc5f9f6a29 | 6a7b3516f7e8c40e268d691667d38fd0c913d37d | /src/me/cyberstalk/plugin/sunburn/SunburnPlayer.java | 9873fef1756440c712708f6ea689d2e1d3af7c11 | [] | no_license | mikenon/Sunburn | 92ad021bdefa3c330ddddbf3001677f7c3921fbc | 9b8329322ababefcbecba5363ae78e024c482df3 | refs/heads/master | 2020-03-24T23:34:31.638836 | 2012-06-23T00:46:37 | 2012-06-23T00:46:37 | 4,644,346 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,044 | java | package me.cyberstalk.plugin.sunburn;
import me.cyberstalk.plugin.sunburn.util.Config;
import me.cyberstalk.plugin.sunburn.util.Melden;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.getspout.spoutapi.player.SpoutPlayer;
public class SunburnPlayer {
public SpoutPlayer player;
public String name;
public boolean immune;
public String world;
public int lightLevel;
public int burnLevel;
public int imgLevel;
public int itemLotionUsed = 0;
private int itemLastUsed;
private int itemDuration;
private int itemStrength;
SunburnPlayer(String name){
this.name = name;
this.player = (SpoutPlayer)Sunburn.getInstance().getServer().getPlayer(this.name);
this.immune = Sunburn.perms.has(player, "sunburn.immunity");
this.world = player.getWorld().getName();
Sunburn.getWidget().initWidget(player);
}
public void onMove(){
calcLightLevel();
updateWidget();
updateBurnTicks();
}
public void updateWidget(){
int itemLevel = getItemStatus();
if(itemLevel > -1){
Sunburn.getWidget().setFrame(1);
} else if(this.lightLevel < Config.getBurnLevel()){
Sunburn.getWidget().setFrame(0);
} else {
Sunburn.getWidget().setFrame(2);
}
if(itemLevel > -1){
Sunburn.getWidget().setLotion(itemLevel);
}
Sunburn.getWidget().setRegular(this.lightLevel);
}
public void updateBurnTicks(){
if(creativeOrImmune()) return;
int item = getItemStatus();
if(item > -1){
Melden.chat(player, "Item Immunity: "+item);
} else {
if(Config.worldEnabled(player.getWorld().getName())){
if(lightLevel>=Config.getBurnLevel()){
burnPlayer(Config.getBurnTicksOn());
} else if (lightLevel < Config.getBurnLevel() && player.getFireTicks() > 20){
burnPlayer(Config.getBurnTicksOff());
}
}
}
}
public void burnPlayer(int ticks){
player.setFireTicks(ticks);
}
public boolean creativeOrImmune(){
if(player.getGameMode()==GameMode.CREATIVE)
return true;
if(getItemStatus()>-1)
return true;
return this.immune;
// return false;
}
public void calcLightLevel(){
Location loc = player.getLocation();
Block block = loc.getBlock();
byte lightAll = block.getLightLevel();
byte lightSky = block.getLightFromSky();
byte lightBlock = block.getLightFromBlocks();
this.lightLevel = (int) Math.ceil(((lightAll-lightBlock) * lightSky)/25);
}
public int getLightLevel(){
calcLightLevel();
return this.lightLevel;
}
public void itemUsed(ItemType type){
if(type.compareTo(ItemType.Lotion1x)==0){
this.itemStrength = 1;
} else if(type.compareTo(ItemType.Lotion2x)==0){
this.itemStrength = 2;
} else if(type.compareTo(ItemType.Lotion3x)==0){
this.itemStrength = 3;
}
long t = System.currentTimeMillis();
this.itemLastUsed = (int) (t / 1000);
this.itemDuration = this.itemStrength * 10;
Sunburn.getWidget().setFrame(1);
Sunburn.getWidget().setLotion(9);
if(Sunburn.asyncTaskId == -1){
Sunburn.asyncTaskId = Bukkit.getServer().getScheduler().scheduleAsyncRepeatingTask(
Sunburn.getInstance(),
Sunburn.lotionUpdater, 20, 10);
}
}
public int getItemStatus(){
long t = System.currentTimeMillis();
int currentTime = (int) (t / 1000);
int endTime = this.itemLastUsed + this.itemDuration;
if(currentTime > endTime){
return -1;
} else {
int numb = (int) Math.ceil((endTime - currentTime) / this.itemStrength);
numb -= 1;
return numb;
}
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setImmune(boolean i){
this.immune = i;
}
public boolean getImmune(){
return this.immune;
}
public void setWorld(String w){
this.world = w;
}
public String getWorld(){
return this.world;
}
public void setBurnLevel(int b){
this.burnLevel = b;
}
public int getBurnLevel(){
return this.burnLevel;
}
public void setImageLevel(int i){
this.imgLevel = i;
}
public int getImageLevel(){
return this.imgLevel;
}
}
| [
"mike@cyberstalk.me"
] | mike@cyberstalk.me |
5a80b691d21fd2acac2a50f2f508d20293a93a3b | 8a596d37b9d7d0b4f340845516e3758999e13cf7 | /log4j2-elasticsearch-jest/src/test/java/org/appenders/log4j2/elasticsearch/jest/WrappedHttpClientConfigTest.java | 12199d678176c6bf8cb3078724b98ec23b171f0b | [
"Apache-2.0"
] | permissive | rfoltyns/log4j2-elasticsearch | 906cb3838305ace9a676e1157feafab278abfc54 | 1ebe4c30daf2474bfaa2e046d4e2617cd312119a | refs/heads/master | 2022-11-21T17:47:34.259237 | 2022-11-14T22:17:32 | 2022-11-14T22:25:24 | 89,024,696 | 173 | 56 | Apache-2.0 | 2022-10-05T07:32:24 | 2017-04-21T21:23:12 | Java | UTF-8 | Java | false | false | 1,998 | java | package org.appenders.log4j2.elasticsearch.jest;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2019 Rafal Foltynski
* %%
* 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.
* #L%
*/
import io.searchbox.client.config.HttpClientConfig;
import org.junit.jupiter.api.Test;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WrappedHttpClientConfigTest {
@Test
public void builderBuildsWithGivenHttpClientConfig() {
// given
HttpClientConfig givenConfig = new HttpClientConfig.Builder("http://localhost:9200").build();
WrappedHttpClientConfig.Builder builder = new WrappedHttpClientConfig.Builder(givenConfig);
// when
WrappedHttpClientConfig config = builder.build();
// then
assertTrue(config.getHttpClientConfig() == givenConfig);
}
@Test
public void builderBuildsWithGivenIoThreadCount() {
// given
HttpClientConfig givenConfig = new HttpClientConfig.Builder("http://localhost:9200").build();
WrappedHttpClientConfig.Builder builder = new WrappedHttpClientConfig.Builder(givenConfig);
int ioThreadCount = new Random().nextInt(1000) + 10;
builder.ioThreadCount(ioThreadCount);
// when
WrappedHttpClientConfig config = builder.build();
// then
assertEquals(ioThreadCount, config.getIoThreadCount());
}
}
| [
"r.foltynski@gmail.com"
] | r.foltynski@gmail.com |
4838f7d6c4ab1b7f743a5515a85d16651a5bec2b | f77ccc622da57ce9a3d4056443175054133ff969 | /src/java/Entity/Home.java | f07c0fa90bbea7b2c2392771386bd46d532f9f7a | [] | no_license | aliendude/vivienda-arqsof2015 | 65ebe23cf1709bf12f2f61f9a4aa79195f5a874f | 12b981ba783f5f8ff02b7003ff7072b1b5ca8da1 | refs/heads/master | 2021-01-21T13:48:58.791933 | 2015-09-12T16:54:01 | 2015-09-12T16:54:01 | 42,193,381 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,431 | 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 Entity;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author mac
*/
@Entity
@Table(name = "HOME")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Home.findAll", query = "SELECT h FROM Home h"),
@NamedQuery(name = "Home.findByIdhome", query = "SELECT h FROM Home h WHERE h.idhome = :idhome"),
@NamedQuery(name = "Home.findByCity", query = "SELECT h FROM Home h WHERE h.city = :city"),
@NamedQuery(name = "Home.findByContracttype", query = "SELECT h FROM Home h WHERE h.contracttype = :contracttype"),
@NamedQuery(name = "Home.findByHomevalue", query = "SELECT h FROM Home h WHERE h.homevalue = :homevalue")})
public class Home implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "IDHOME")
private Long idhome;
@Size(max = 255)
@Column(name = "CITY")
private String city;
@Size(max = 255)
@Column(name = "CONTRACTTYPE")
private String contracttype;
@Lob
@Size(max = 2147483647)
@Column(name = "HOMEADDRESS")
private String homeaddress;
@Lob
@Size(max = 2147483647)
@Column(name = "HOMETYPE")
private String hometype;
@Column(name = "HOMEVALUE")
private BigInteger homevalue;
@JoinColumn(name = "IDPERSON", referencedColumnName = "IDPERSON")
@ManyToOne
private Person idperson;
@OneToMany(mappedBy = "idhome")
private List<Benefit> benefitList;
public Home() {
}
public Home(Long idhome) {
this.idhome = idhome;
}
public Long getIdhome() {
return idhome;
}
public void setIdhome(Long idhome) {
this.idhome = idhome;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getContracttype() {
return contracttype;
}
public void setContracttype(String contracttype) {
this.contracttype = contracttype;
}
public String getHomeaddress() {
return homeaddress;
}
public void setHomeaddress(String homeaddress) {
this.homeaddress = homeaddress;
}
public String getHometype() {
return hometype;
}
public void setHometype(String hometype) {
this.hometype = hometype;
}
public BigInteger getHomevalue() {
return homevalue;
}
public void setHomevalue(BigInteger homevalue) {
this.homevalue = homevalue;
}
public Person getIdperson() {
return idperson;
}
public void setIdperson(Person idperson) {
this.idperson = idperson;
}
@XmlTransient
public List<Benefit> getBenefitList() {
return benefitList;
}
public void setBenefitList(List<Benefit> benefitList) {
this.benefitList = benefitList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idhome != null ? idhome.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Home)) {
return false;
}
Home other = (Home) object;
if ((this.idhome == null && other.idhome != null) || (this.idhome != null && !this.idhome.equals(other.idhome))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entity.Home[ idhome=" + idhome + " ]";
}
}
| [
"pjrodriguezg@unal.edu.co"
] | pjrodriguezg@unal.edu.co |
94ad7a3979b2cf7791242422180d6228a3a812a3 | d7d3d6a68dc54efdc846f9e17a6cee1b9d35c08e | /SuperCell-ELM-C-master/src/com/supercell/service/DishesService.java | 88e134adc54e6977c206ecee9c9492688f9139f4 | [
"Apache-2.0"
] | permissive | chasesem/SuperCell-ELM | 5d520e7a01b7be6f8d66c0ce00a647d3562bd457 | 4177c777b50fe4708b8d1932c13b58dadf3bce9c | refs/heads/master | 2021-01-20T20:15:05.209636 | 2016-08-15T08:44:00 | 2016-08-15T08:44:00 | 65,717,132 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package com.supercell.service;
import java.util.List;
import com.supercell.entity.Dishes;
public interface DishesService {
List<Dishes> getAllDishesOfMerchant(Integer merchantId);
Dishes getDishes(Integer dishesId);
} | [
"yam.cheng@oocl.com"
] | yam.cheng@oocl.com |
e435c11d35b92d9c659d723d01897f3591de2667 | 36f01bd605e5fc032e65c9efe39975b3271195d5 | /src/de.sormuras.bach/test/java/de/sormuras/bach/api/MavenTests.java | 8a3b599580a82bd4d6313800d6993d00b717356d | [
"Apache-2.0"
] | permissive | Malax/bach | fa30c35a1dd0515b5ce59459d220081014eb973b | 5a16c4bb7b37b56e798ca699fcc3416d84d5e35e | refs/heads/master | 2021-05-18T16:42:28.197128 | 2020-03-30T07:19:30 | 2020-03-30T07:19:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,827 | java | /*
* Bach - Java Shell Builder
* Copyright (C) 2020 Christian Stein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sormuras.bach.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class MavenTests {
@Nested
class Resources {
@ParameterizedTest
@ValueSource(strings = {"3.7", "4.13"})
void centralJUnit(String version) {
var uri = "https://repo.maven.apache.org/maven2/junit/junit/{VERSION}/junit-{VERSION}.jar";
var expected = URI.create(uri.replace("{VERSION}", version));
var actual = Maven.central("junit", "junit", version);
assertEquals(expected, actual);
}
@Test
void customBuiltMavenResource() throws Exception {
var expected = new URI("https", "host", "/path/g/a/v/a-v-c.t", null);
var actual =
Maven.newResource()
.repository("https://host/path")
.group("g")
.artifact("a")
.version("v")
.classifier("c")
.type("t")
.build()
.get();
assertEquals(expected, actual);
}
}
}
| [
"sormuras@gmail.com"
] | sormuras@gmail.com |
e7d79d541a82b5b63a68310819143e8e69253b71 | f903b4e8136d66c3dcf59feda0fa47fbacb7e6fc | /java_examples/threading/src/threading/TestJoinMethod2.java | a5eceb099660d1c6ce77e7ced13acfff98a55b16 | [] | no_license | alec-patterson/revature_repository | ecde3296c3513a802abf10123bcb47596e04cdea | da24ee41c8272bc8ac16bf527267d00f6536a9fd | refs/heads/main | 2023-08-22T21:33:38.859260 | 2021-10-12T16:15:42 | 2021-10-12T16:15:42 | 384,232,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 557 | java | package threading;
public class TestJoinMethod2 extends Thread{
public void run() {
for(int i = 1; i <= 5; i++ ) {
try {
Thread.sleep(500);
}
catch(Exception e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args) {
TestJoinMethod1 t1 = new TestJoinMethod1();
TestJoinMethod1 t2 = new TestJoinMethod1();
TestJoinMethod1 t3 = new TestJoinMethod1();
t1.start();
try {
t1.join(1500);
} catch (Exception e) {
System.out.println(e);
}
t2.start();
t3.start();
}
}
| [
"alec.patterson@revature.net"
] | alec.patterson@revature.net |
0bc9923d8058c44967ea4a86d35b995bb4389d73 | 33987a2b200e6e268a17195bb9c2bcbead86fda6 | /src/golem/lex/MatcherRule.java | 0093090850734fca3ca58d26eeabcd15a0958009 | [] | no_license | KLIMaka/golem | 4737fbbc91aed31a8111b297d3bbe3966ae25f2a | 7c74752e7d63e8ab5db9d3a798bd006d05f2e989 | refs/heads/master | 2021-06-27T23:11:16.810355 | 2016-11-21T10:26:43 | 2016-11-21T10:26:43 | 3,314,314 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 818 | java | package golem.lex;
import java.util.regex.*;
import com.google.common.base.Predicate;
public class MatcherRule {
public Pattern pattern;
public String patt;
public int id;
public String name;
public boolean hidden;
public Matcher matcher;
public MatcherRule(String patt, int i, String n, boolean h) {
this.patt = patt;
pattern = Pattern.compile("^" + patt);
id = i;
name = n;
hidden = h;
}
@Override
public String toString() {
return name;
}
public Object convert(Matcher m) {
return m.group();
}
public void action(GenericMatcher lex) {
}
public void setSource(CharSequence cs) {
matcher = pattern.matcher(cs);
}
public static Predicate<MatcherRule> isHidden = new Predicate<MatcherRule>() {
@Override
public boolean apply(MatcherRule r) {
return r.hidden;
}
};
} | [
"kirill@trustename.com"
] | kirill@trustename.com |
738d961ba14fa95a4b7639063b94b08a70ac0d0d | b3c327209a3bc2e202f76b188ca69459daf5d3d6 | /nifi-api-builder/nifi-1-client-parent/nifi-1.1.2-component-properties-builders/src/main/java/com/tibtech/nifi/processors/aws/sqs/PutSQS.java | 79bd8467c60e245d62e56df5340f8a3e8f3d9581 | [] | no_license | dtmo/nifi-client | c49e26a1f9bef795f5a1417dcebea5f514833c3c | 8478af5620144f3db15fe508967833e173d0019b | refs/heads/master | 2021-01-19T20:48:22.506050 | 2019-02-27T20:55:29 | 2019-02-27T20:55:29 | 88,555,587 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,646 | java | package com.tibtech.nifi.processors.aws.sqs;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import java.lang.String;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public final class PutSQS {
/**
* The component type name.
*/
public static final String COMPONENT_TYPE = "org.apache.nifi.processors.aws.sqs.PutSQS";
/**
* The URL of the queue to act upon
*/
public static final String QUEUE_URL_PROPERTY = "Queue URL";
/**
*
*/
public static final String ACCESS_KEY_PROPERTY = "Access Key";
/**
*
*/
public static final String SECRET_KEY_PROPERTY = "Secret Key";
/**
* Path to a file containing AWS access key and secret key in properties file format.
*/
public static final String CREDENTIALS_FILE_PROPERTY = "Credentials File";
/**
* The Controller Service that is used to obtain aws credentials provider
*/
public static final String AWS_CREDENTIALS_PROVIDER_SERVICE_PROPERTY = "AWS Credentials Provider service";
/**
*
*/
public static final String REGION_PROPERTY = "Region";
/**
* The amount of time to delay the message before it becomes available to consumers
*/
public static final String DELAY_PROPERTY = "Delay";
/**
*
*/
public static final String COMMUNICATIONS_TIMEOUT_PROPERTY = "Communications Timeout";
/**
* Proxy host name or IP
*/
public static final String PROXY_HOST_PROPERTY = "Proxy Host";
/**
* Proxy host port
*/
public static final String PROXY_HOST_PORT_PROPERTY = "Proxy Host Port";
private final Map<String, String> properties;
public PutSQS() {
this.properties = new HashMap<>();
}
public PutSQS(final Map<String, String> properties) {
this.properties = new HashMap<>(properties);
}
/**
* The URL of the queue to act upon
*/
public final String getQueueUrl() {
return properties.get(QUEUE_URL_PROPERTY);
}
/**
* The URL of the queue to act upon
*/
public final PutSQS setQueueUrl(final String queueUrl) {
properties.put(QUEUE_URL_PROPERTY, queueUrl);
return this;
}
/**
* The URL of the queue to act upon
*/
public final PutSQS removeQueueUrl() {
properties.remove(QUEUE_URL_PROPERTY);
return this;
}
/**
*
*/
public final String getAccessKey() {
return properties.get(ACCESS_KEY_PROPERTY);
}
/**
*
*/
public final PutSQS setAccessKey(final String accessKey) {
properties.put(ACCESS_KEY_PROPERTY, accessKey);
return this;
}
/**
*
*/
public final PutSQS removeAccessKey() {
properties.remove(ACCESS_KEY_PROPERTY);
return this;
}
/**
*
*/
public final String getSecretKey() {
return properties.get(SECRET_KEY_PROPERTY);
}
/**
*
*/
public final PutSQS setSecretKey(final String secretKey) {
properties.put(SECRET_KEY_PROPERTY, secretKey);
return this;
}
/**
*
*/
public final PutSQS removeSecretKey() {
properties.remove(SECRET_KEY_PROPERTY);
return this;
}
/**
* Path to a file containing AWS access key and secret key in properties file format.
*/
public final String getCredentialsFile() {
return properties.get(CREDENTIALS_FILE_PROPERTY);
}
/**
* Path to a file containing AWS access key and secret key in properties file format.
*/
public final PutSQS setCredentialsFile(final String credentialsFile) {
properties.put(CREDENTIALS_FILE_PROPERTY, credentialsFile);
return this;
}
/**
* Path to a file containing AWS access key and secret key in properties file format.
*/
public final PutSQS removeCredentialsFile() {
properties.remove(CREDENTIALS_FILE_PROPERTY);
return this;
}
/**
* The Controller Service that is used to obtain aws credentials provider
*/
public final String getAwsCredentialsProviderService() {
return properties.get(AWS_CREDENTIALS_PROVIDER_SERVICE_PROPERTY);
}
/**
* The Controller Service that is used to obtain aws credentials provider
*/
public final PutSQS setAwsCredentialsProviderService(final String awsCredentialsProviderService) {
properties.put(AWS_CREDENTIALS_PROVIDER_SERVICE_PROPERTY, awsCredentialsProviderService);
return this;
}
/**
* The Controller Service that is used to obtain aws credentials provider
*/
public final PutSQS removeAwsCredentialsProviderService() {
properties.remove(AWS_CREDENTIALS_PROVIDER_SERVICE_PROPERTY);
return this;
}
/**
*
*/
public final String getRegion() {
return properties.get(REGION_PROPERTY);
}
/**
*
*/
public final PutSQS setRegion(final String region) {
properties.put(REGION_PROPERTY, region);
return this;
}
/**
*
*/
public final PutSQS removeRegion() {
properties.remove(REGION_PROPERTY);
return this;
}
/**
* The amount of time to delay the message before it becomes available to consumers
*/
public final String getDelay() {
return properties.get(DELAY_PROPERTY);
}
/**
* The amount of time to delay the message before it becomes available to consumers
*/
public final PutSQS setDelay(final String delay) {
properties.put(DELAY_PROPERTY, delay);
return this;
}
/**
* The amount of time to delay the message before it becomes available to consumers
*/
public final PutSQS removeDelay() {
properties.remove(DELAY_PROPERTY);
return this;
}
/**
*
*/
public final String getCommunicationsTimeout() {
return properties.get(COMMUNICATIONS_TIMEOUT_PROPERTY);
}
/**
*
*/
public final PutSQS setCommunicationsTimeout(final String communicationsTimeout) {
properties.put(COMMUNICATIONS_TIMEOUT_PROPERTY, communicationsTimeout);
return this;
}
/**
*
*/
public final PutSQS removeCommunicationsTimeout() {
properties.remove(COMMUNICATIONS_TIMEOUT_PROPERTY);
return this;
}
/**
* Proxy host name or IP
*/
public final String getProxyHost() {
return properties.get(PROXY_HOST_PROPERTY);
}
/**
* Proxy host name or IP
*/
public final PutSQS setProxyHost(final String proxyHost) {
properties.put(PROXY_HOST_PROPERTY, proxyHost);
return this;
}
/**
* Proxy host name or IP
*/
public final PutSQS removeProxyHost() {
properties.remove(PROXY_HOST_PROPERTY);
return this;
}
/**
* Proxy host port
*/
public final String getProxyHostPort() {
return properties.get(PROXY_HOST_PORT_PROPERTY);
}
/**
* Proxy host port
*/
public final PutSQS setProxyHostPort(final String proxyHostPort) {
properties.put(PROXY_HOST_PORT_PROPERTY, proxyHostPort);
return this;
}
/**
* Proxy host port
*/
public final PutSQS removeProxyHostPort() {
properties.remove(PROXY_HOST_PORT_PROPERTY);
return this;
}
public final String getDynamicProperty(final String name) {
return properties.get(name);
}
public final PutSQS setDynamicProperty(final String name, final String value) {
properties.put(name, value);
return this;
}
public final PutSQS removeDynamicProperty(final String name) {
properties.remove(name);
return this;
}
public final Map<String, String> build() {
return properties;
}
public static final Map<String, String> build(final Function<PutSQS, PutSQS> configurator) {
return configurator.apply(new PutSQS()).build();
}
public static final Map<String, String> build(@DelegatesTo(strategy = Closure.DELEGATE_ONLY, value = PutSQS.class) final Closure<PutSQS> closure) {
return build(c -> {
final Closure<com.tibtech.nifi.processors.aws.sqs.PutSQS> code = closure.rehydrate(c, com.tibtech.nifi.processors.aws.sqs.PutSQS.class, com.tibtech.nifi.processors.aws.sqs.PutSQS.class);
code.setResolveStrategy(Closure.DELEGATE_ONLY);
code.call();
return c;
} );
}
public static final Map<String, String> update(final Map<String, String> properties,
final Function<PutSQS, PutSQS> configurator) {
return configurator.apply(new PutSQS(properties)).build();
}
public static final Map<String, String> update(final Map<String, String> properties,
@DelegatesTo(strategy = Closure.DELEGATE_ONLY, value = PutSQS.class) final Closure<PutSQS> closure) {
return update(properties, c -> {
final Closure<com.tibtech.nifi.processors.aws.sqs.PutSQS> code = closure.rehydrate(c, com.tibtech.nifi.processors.aws.sqs.PutSQS.class, com.tibtech.nifi.processors.aws.sqs.PutSQS.class);
code.setResolveStrategy(Closure.DELEGATE_ONLY);
code.call();
return c;
} );
}
}
| [
"dtmorgan@gmail.com"
] | dtmorgan@gmail.com |
865d9b637a8a21469d10f9290eeb45d2401b3db0 | 730f00a3241098ee6a6c1ef3684e04e7cefbb146 | /Assignment6/Assignment6TuesdaySection/PartII/randomwords/RandomWords.java | be98324ba5d0a8e7e0e6ecdbed772e7f783f3c23 | [
"Apache-2.0"
] | permissive | wzcwzcwzc/nyu-java-homework | 468248741a4f3dda6b811f4d06be20668071d81c | fe567091681b976b7798291ed973b3454504f317 | refs/heads/master | 2022-07-23T22:18:50.365678 | 2020-05-22T03:09:58 | 2020-05-22T03:09:58 | 266,001,859 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,713 | java | package randomwords;
import java.io.*;
import java.util.*;
import javafx.util.Pair;
/**
* @author Barry
* */
public class RandomWords {
private String filename;
private static final int SIZE = 10;
/**
* choose 10 different words from file and use wordList to store
*/
private List<String> wordList;
/**
* come up with different pair of words from wordList and store in pairs
*/
private List<Pair<String, String>> pairs;
public RandomWords() {
wordList = new ArrayList<>(SIZE);
pairs = new ArrayList<>(SIZE);
}
public RandomWords(String filename) throws IOException{
wordList = new ArrayList<>();
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
Map<Integer, String> wordMap = new HashMap<>();
int i = 0;
while(line != null){
line = line.trim();
wordMap.put(i, line);
i++;
line = reader.readLine();
}
// get 10 random different words into list
wordList = randomWordList(wordMap);
// generate different pairs
pairs = generatePairs(wordList);
}catch (FileNotFoundException e){
e.printStackTrace();
}finally {
if(reader == null){
System.out.println("the file is not open");
System.exit(0);
}else{
reader.close();
}
}
}
public static int levenshteinDistance(String word1, String word2) {
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for(int i = 1; i <= word1.length(); i++){
dp[i][0] = i;
}
for(int i = 1; i <= word2.length(); i++){
dp[0][i] = i;
}
for(int i = 1; i <= word1.length(); i++){
for(int j = 1; j <= word2.length(); j++){
if(word1.charAt(i - 1) == word2.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1];
}else {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
}
}
}
return dp[word1.length()][word2.length()];
}
static class PairComparator implements Comparator<Pair<String, String>>{
// minHeap, sort the Pair in ascending order
@Override
public int compare(Pair<String, String> p1, Pair<String, String> p2){
// get distance of each pair and compare the distance value
int dis1 = levenshteinDistance(p1.getKey(), p1.getValue());
int dis2 = levenshteinDistance(p2.getKey(), p2.getValue());
// do compare, minHeap
if(dis1 == dis2){
return 0;
}else if (dis1 > dis2){
return 1;
}else{
return -1;
}
}
}
public List<Pair<String, String>> sortedPairsComparator() {
PairComparator pc = new PairComparator();
pairs.sort(pc);
return pairs;
}
public List<Pair<String, String>> sortedPairsLambda() {
pairs.sort((a, b) -> (levenshteinDistance(a.getKey(), a.getValue()) - levenshteinDistance(b.getKey(), b.getValue())));
return pairs;
}
public List<Pair<String, String>> generatePairs(List<String> wordList){
List<Pair<String, String>> pairs = new ArrayList<>();
if(wordList == null || wordList.size() == 0){
return pairs;
}
for(int i = 0; i < wordList.size() - 1; i++){
for(int j = i + 1; j < wordList.size(); j++){
Pair<String, String> pair = new Pair<>(wordList.get(i), wordList.get(j));
pairs.add(pair);
}
}
return pairs;
}
public List<String> randomWordList(Map<Integer, String> wordMap){
Set<String> wordSet = new HashSet<>();
List<String> wordList = new ArrayList<>();
if(wordMap == null || wordMap.size() < SIZE){
return wordList;
}
int j = 0;
while(j < SIZE){
int key = (int)(Math.random() * 100);
String str = wordMap.get(key);
if(!wordSet.contains(str)){
wordSet.add(str);
wordList.add(str);
j++;
}
}
return wordList;
}
public static void main(String[] args) throws IOException {
RandomWords rw = new RandomWords("data/words");
List<Pair<String, String>> sort1 = rw.sortedPairsComparator();
List<Pair<String, String>> sort2 = rw.sortedPairsLambda();
// true
System.out.println(sort1.equals(sort2));
/* test for comparator and lambda
Pair<String, String> p1 = new Pair<>("abc", "ab");//1
Pair<String, String> p2 = new Pair<>("kitten", "sitting");//3
Pair<String, String> p3 = new Pair<>("ab", "ab"); //0
List<Pair<String, String>> pairs = new ArrayList<>();
pairs.add(p1);
pairs.add(p2);
pairs.add(p3);
for (int i = 0; i < pairs.size(); i++){
System.out.println(pairs.get(i).getKey() + " " + pairs.get(i).getValue());
}
// PairComparator pc = new PairComparator();
// pairs.sort(pc);
// pairs.sort((a, b) -> (levenshteinDistance(a.getKey(), a.getValue()) - levenshteinDistance(b.getKey(), b.getValue())));
for (int i = 0; i < pairs.size(); i++){
System.out.println(pairs.get(i).getKey() + " " + pairs.get(i).getValue());
}
*/
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fe1afaf37fa1982f32d9b87952c16e65b8b2d17d | b4a58062ec9198c4ee57a457c8eac0242bd6d2f0 | /src/main/java/com/palmaplus/data/amqp/common/PropertiesUtil.java | 0cb9313d7fd75394b724627568cadffd867a0815 | [] | no_license | megaer/amqp | 8b08dd8a7713de4db9fb9c0d22896bc60ab54e41 | a294c3c74f6b2ef662d27835222b71b40715cf4f | refs/heads/master | 2021-01-11T19:04:31.167029 | 2017-01-18T06:08:35 | 2017-01-18T06:08:35 | 79,309,234 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,343 | java | package com.palmaplus.data.amqp.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by jiabing.zhu on 2016/10/8.
*/
public class PropertiesUtil {
private final static Properties properries = new Properties();
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
static {
//读取本地配置
// readProperty("localProperties.properties");
//读取服务器相关配置
readProperty("properties.properties");
}
private static void readProperty(String filename){
try {
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(filename);
properries.load(in);
} catch (IOException e){
logger.debug("read properties exception : " + e.getMessage());
}
}
/**
* 获取某个属性
*/
public static String getProperty(String key){
return properries.getProperty(key);
}
public static void main(String[] args) {
System.out.println(getProperty("{\"uid\":\"735809317\",\"youmengId\":\"564a8cb8e0f55ad413001489\",\"timeStatmp\":\"4744006524089843801\",\"clientId\":\"\",\"sourceId\":\"203007\",\"token\":\"\",\"appType\":\"3\"}"));
}
}
| [
"18670100827@163.com"
] | 18670100827@163.com |
99744bd6974de033ddba178b7ad627ef9950b153 | fce32d628b213038f2dce83450e5c37b73c81a46 | /net.funkyjava.gametheory_net.funkyjava.gametheory.gameutil/net.funkyjava.gametheory_net.funkyjava.gametheory.gameutil.cards/src/main/java/net/funkyjava/gametheory/gameutil/cards/DefaultIntCardsSpecs.java | 1b4d3af60b31b8271c9eed695611f80aee0d0589 | [] | no_license | mkatsimpris/gametheory | 347806c6d20d6a9e10e034cc8b2d79ad9187021c | 9dbd7b1a97b23cc2824dfc0b60229da1d349cd36 | refs/heads/master | 2021-01-18T08:10:37.769642 | 2015-10-11T13:23:50 | 2015-10-11T13:23:50 | 65,678,774 | 4 | 0 | null | 2016-08-14T17:44:11 | 2016-08-14T17:44:11 | null | UTF-8 | Java | false | false | 1,284 | java | package net.funkyjava.gametheory.gameutil.cards;
/**
*
* The default int cards specifications
*
* @author Pierre Mardon
* */
public class DefaultIntCardsSpecs implements IntCardsSpec {
private final int offset;
/**
* Constructor for offset 0
*/
public DefaultIntCardsSpecs() {
this.offset = 0;
}
/**
* Constructor for a given offset
*
* @param offset
*/
public DefaultIntCardsSpecs(int offset) {
this.offset = offset;
}
@Override
public boolean sameRank(int card1, int card2) {
return (card1 - offset) / 4 == (card2 - offset) / 4;
}
@Override
public boolean sameColor(int card1, int card2) {
return (card1 - offset) % 4 == (card2 - offset) % 4;
}
@Override
public int getStandardRank(int card) {
return (card - offset) / 4;
}
@Override
public int getStandardColor(int card) {
return (card - offset) % 4;
}
@Override
public int getOffset() {
return offset;
}
@Override
public int getCard(int stdRank, int stdColor) {
return offset + 4 * stdRank + stdColor;
}
private static DefaultIntCardsSpecs defaultSpec = new DefaultIntCardsSpecs();
/**
* Get default cards specifications
*
* @return the default cards specifications
*/
public static DefaultIntCardsSpecs getDefault() {
return defaultSpec;
}
} | [
"pierre.mardon@gmail.com"
] | pierre.mardon@gmail.com |
08275d947d4345e1bd384e2c098de0f1decd312c | f3414e405d68daa615b8010a949847b3fb7bd5b9 | /utilities/idcserver.src/intradoc/server/DocumentSecurityUtils.java | 33092db3596b8bdded8d91282f5dba6f74d1c928 | [] | no_license | osgirl/ProjectUCM | ac2c1d554746c360f24414d96e85a6c61e31b102 | 5e0cc24cfad53d1f359d369d57b622c259f88311 | refs/heads/master | 2020-04-22T04:11:13.373873 | 2019-03-04T19:26:48 | 2019-03-04T19:26:48 | 170,114,287 | 0 | 0 | null | 2019-02-11T11:02:25 | 2019-02-11T11:02:25 | null | UTF-8 | Java | false | false | 1,399 | java | /* */ package intradoc.server;
/* */
/* */ import intradoc.common.ServiceException;
/* */ import intradoc.data.DataBinder;
/* */ import intradoc.data.DataException;
/* */ import intradoc.shared.SharedObjects;
/* */ import intradoc.shared.UserData;
/* */
/* */ public class DocumentSecurityUtils
/* */ {
/* */ public static boolean canUpdateOwnershipSecurity(String newOwner, String currentOwner, DataBinder binder, Service service)
/* */ throws ServiceException, DataException
/* */ {
/* 45 */ UserData userData = service.getUserData();
/* */
/* 47 */ if ((((currentOwner == null) || (currentOwner.length() == 0) || (currentOwner.equalsIgnoreCase(userData.m_name)))) && ((
/* 50 */ (newOwner.equalsIgnoreCase(userData.m_name)) || (SharedObjects.getEnvValueAsBoolean("AllowOwnerToChangeAuthor", false)))))
/* */ {
/* 53 */ return true;
/* */ }
/* */
/* 57 */ return service.checkAccess(binder, 8);
/* */ }
/* */
/* */ public static Object idcVersionInfo(Object arg)
/* */ {
/* 62 */ return "releaseInfo=7.3.5.185,relengDate=2013-07-11 17:07:21Z,releaseRevision=$Rev: 72978 $";
/* */ }
/* */ }
/* Location: C:\Documents and Settings\rastogia.EMEA\My Documents\idcserver\
* Qualified Name: intradoc.server.DocumentSecurityUtils
* JD-Core Version: 0.5.4
*/ | [
"ranjodh.singh@hays.com"
] | ranjodh.singh@hays.com |
48b678b559b5cd317be6eb6935b19fee970d2908 | 1cc54ac5fb68875198ad0dae714062c3e732249c | /E-mail-master/app/src/main/java/com/example/sander/email/MainActivity.java | b8deb2a82a7aa0c89526f385fdf8dd79e1d949b3 | [] | no_license | MartinBachverk/E-mail-bachverk | 1e3cc9286480921f59b4dca49d75d23e10bfa76d | f8c11e851ca3ed8a4afa1233a971f8564afbd2c1 | refs/heads/master | 2021-07-22T03:34:27.064888 | 2017-10-31T11:49:16 | 2017-10-31T11:49:16 | 108,988,530 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,599 | java | package com.example.bachverk.email;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editEmail, editSubject, editMessage;
Button btn_Send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editEmail = (EditText)findViewById(R.id.editEmail);
editSubject = (EditText)findViewById(R.id.editSubject);
editMessage = (EditText)findViewById(R.id.editMessage);
btn_Send = (Button)findViewById(R.id.btn_send);
btn_Send.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
String to = editEmail.getText().toString();
String subject = editSubject.getText().toString();
String message = editMessage.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
//brackets [] because you have a list of people to send it to
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Select Email app"));
}
});
}
}
| [
"opilane@tthk.ee"
] | opilane@tthk.ee |
f96ced340ae9c1404ac0ab1ad8710959712fd9f6 | a7658cc248a2bebc359e81c9fa2b348a967423a9 | /src/main/java/com/github/opaluchlukasz/eventsourcingtodo/query/ReadDbConfig.java | 852deb186b427805585a2dd6cef1eefa5ba54d85 | [] | no_license | opaluchlukasz/eventsourcing-todo | c635afc28d386c6c2b7fdbce91464327321cdf7b | 44d479ab18354a0f1198deef413ab335f68f7ec0 | refs/heads/master | 2020-03-31T22:09:55.141943 | 2018-10-17T18:23:16 | 2018-10-17T18:23:16 | 152,608,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,079 | java | package com.github.opaluchlukasz.eventsourcingtodo.query;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class ReadDbConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory(@Value("${spring.redis.host}") String host,
@Value("${spring.redis.port}") Integer port) {
return new JedisConnectionFactory(new RedisStandaloneConfiguration(host, port
));
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
return template;
}
}
| [
"opaluch.lukasz@gmail.com"
] | opaluch.lukasz@gmail.com |
aac247455c8fce925b32869a2b000e115e43edd5 | 7cc3e8ac97541410646a705fa5f67e658246dc01 | /assignments/assignment3a/app/src/test/java/edu/vanderbilt/imagecrawler/helpers/TestHelpers.java | 1a11846067cb93a52f745ad5e80fb0b8f96dd6e3 | [] | no_license | jubincn/CS891 | 76e720dabd9028c8a338400de5fd41c2b56295a5 | 5c335e21ea794988ec6426f777e4fb1b9f9aac38 | refs/heads/master | 2020-04-02T04:00:13.891490 | 2018-10-17T20:02:42 | 2018-10-17T20:02:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,158 | java | package edu.vanderbilt.imagecrawler.helpers;
import junit.framework.AssertionFailedError;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import edu.vanderbilt.crawlers.framework.CrawlerFactory;
import edu.vanderbilt.crawlers.framework.ImageCrawlerBase;
import edu.vanderbilt.filters.FilterFactory;
import edu.vanderbilt.platform.Device;
import edu.vanderbilt.platform.JavaPlatform;
import edu.vanderbilt.utils.CacheUtils;
import edu.vanderbilt.utils.Options;
import edu.vanderbilt.utils.WebPageCrawler;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
public class TestHelpers {
public static void testDownloadCacheMatchesGroundTruthFiles(
String groundTruthDirPath,
boolean localImageCrawl) throws Exception {
// Device protects itself from multiple builds and this
// method gets around that restriction.
Device.setPrivateInstanceFieldToNullForUnitTestingOnly();
// Create a new device along with default options so that we
// can call CacheUtils.getCacheDir(). This method needs to get
// the default download directory name from the Options
// instance that lives in the Device object.
Device.newBuilder()
.platform(new JavaPlatform())
.options(Options.newBuilder()
.local(localImageCrawl)
.diagnosticsEnabled(true)
.build())
.crawler(new WebPageCrawler())
.build();
File groundTruthDir = new File(groundTruthDirPath);
File downloadCacheDir = CacheUtils.getCacheDir();
// First clear the cache of any files from a previous run.
CacheUtils.clearCache();
// This assignment only uses the NULL_FILTER.
List<FilterFactory.Type> filterTypes =
Collections.singletonList(FilterFactory.Type.NULL_FILTER);
// Create and run the crawler.
CrawlerFactory.newCrawler(
CrawlerFactory.Type.SEQUENTIAL_STREAMS,
filterTypes,
Device.options().getRootUri()).run();
// Call helper method to recursively compare the downloadCacheDir
// directory with groundTruthDir directory.
recursivelyCompareDirectories(groundTruthDir,
downloadCacheDir);
}
/**
* Recursively compare the contents of the directory of downloaded
* files with the contents of the "ground truth" directory.
*/
public static void recursivelyCompareDirectories(File expected,
File generated)
throws IOException {
// Checks parameters.
assertTrue("Generated Folder doesn't exist: " + generated,
generated.exists());
assertTrue("Generated is not a folder?!?!: " + generated,
generated.isDirectory());
assertTrue("Expected Folder doesn't exist: " + expected,
expected.exists());
assertTrue("Expected is not a folder?!?!: " + expected,
expected.isDirectory());
Files.walkFileTree(expected.toPath(),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
throws IOException {
FileVisitResult result =
super.preVisitDirectory(dir, attrs);
// Get the relative file name from
// path "expected"
Path relativize =
expected.toPath().relativize(dir);
// Construct the path for the
// counterpart file in "generated"
File otherDir =
generated.toPath().resolve(relativize).toFile();
assertEquals("Folders doesn't contain same file!?!?",
Arrays.toString(dir.toFile().list()),
Arrays.toString(otherDir.list()));
return result;
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
throws IOException {
FileVisitResult result =
super.visitFile(file, attrs);
// Get the relative file name from
// path "expected".
Path relativize =
expected.toPath().relativize(file);
// Construct the path for the
// counterpart file in "generated".
Path fileInOther =
generated.toPath().resolve(relativize);
byte[] otherBytes = Files.readAllBytes(fileInOther);
byte[] thisBytes = Files.readAllBytes(file);
if (!Arrays.equals(otherBytes, thisBytes))
throw new AssertionFailedError(file + " is not equal to " + fileInOther);
return result;
}
});
}
/**
* Helper to make printing output less verbose.
*/
public static void info(String msg) {
System.out.println(msg);
}
/**
* Helper to make printing output less verbose.
*/
public static void error(String msg) {
System.err.println(msg);
}
}
| [
"d.schmidt@vanderbilt.edu"
] | d.schmidt@vanderbilt.edu |
badb434c18180928332dd27ea69c6d3f41fb433e | 1879a63e377632371c26caee6ec3f303d65b10b0 | /TravelExperts_Java/_OLD/data/dummy/ProductSupplierData.java | 17d8fcb82218a09bc73a93c2b8ee70a0b1b55324 | [] | no_license | cherifsalah/Final-project-Travel-Expert | 935f697480c37cb13d3a98bcf6d00e022ca2c3a8 | e903e7bf0cdfd96b4a7f37313a3cc1c9d7c47acb | refs/heads/master | 2022-12-12T13:56:55.636048 | 2019-10-30T06:45:45 | 2019-10-30T06:45:45 | 215,192,281 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,781 | java | package data.dummy;
public class ProductSupplierData implements data.ProductSupplierData {
@Override
public String getProductSupplier(int productSupplierId) {
return "{\"ProductSupplierId\":1,\"ProductId\":1,\"SupplierId\":5492}";
}
@Override
public String getAllProductSuppliers() {
return "[{\"ProductSupplierId\":1,\"ProductId\":1,\"SupplierId\":5492},{\"ProductSupplierId\":2,\"ProductId\":1,\"SupplierId\":6505},{\"ProductSupplierId\":3,\"ProductId\":8,\"SupplierId\":796},{\"ProductSupplierId\":4,\"ProductId\":1,\"SupplierId\":4196},{\"ProductSupplierId\":6,\"ProductId\":8,\"SupplierId\":1040},{\"ProductSupplierId\":7,\"ProductId\":1,\"SupplierId\":3576},{\"ProductSupplierId\":8,\"ProductId\":3,\"SupplierId\":845},{\"ProductSupplierId\":9,\"ProductId\":7,\"SupplierId\":828},{\"ProductSupplierId\":10,\"ProductId\":8,\"SupplierId\":5777},{\"ProductSupplierId\":11,\"ProductId\":8,\"SupplierId\":5827},{\"ProductSupplierId\":12,\"ProductId\":5,\"SupplierId\":3273},{\"ProductSupplierId\":13,\"ProductId\":1,\"SupplierId\":80},{\"ProductSupplierId\":14,\"ProductId\":8,\"SupplierId\":9396},{\"ProductSupplierId\":15,\"ProductId\":8,\"SupplierId\":3589},{\"ProductSupplierId\":16,\"ProductId\":1,\"SupplierId\":69},{\"ProductSupplierId\":19,\"ProductId\":1,\"SupplierId\":3376},{\"ProductSupplierId\":20,\"ProductId\":3,\"SupplierId\":323},{\"ProductSupplierId\":23,\"ProductId\":1,\"SupplierId\":3549},{\"ProductSupplierId\":24,\"ProductId\":5,\"SupplierId\":1918},{\"ProductSupplierId\":25,\"ProductId\":3,\"SupplierId\":11156},{\"ProductSupplierId\":26,\"ProductId\":8,\"SupplierId\":8837},{\"ProductSupplierId\":28,\"ProductId\":8,\"SupplierId\":8089},{\"ProductSupplierId\":29,\"ProductId\":1,\"SupplierId\":1028},{\"ProductSupplierId\":30,\"ProductId\":1,\"SupplierId\":2466},{\"ProductSupplierId\":31,\"ProductId\":5,\"SupplierId\":1406},{\"ProductSupplierId\":32,\"ProductId\":3,\"SupplierId\":1416},{\"ProductSupplierId\":33,\"ProductId\":5,\"SupplierId\":13596},{\"ProductSupplierId\":34,\"ProductId\":1,\"SupplierId\":9323},{\"ProductSupplierId\":35,\"ProductId\":5,\"SupplierId\":11237},{\"ProductSupplierId\":36,\"ProductId\":8,\"SupplierId\":9785},{\"ProductSupplierId\":37,\"ProductId\":5,\"SupplierId\":11163},{\"ProductSupplierId\":39,\"ProductId\":9,\"SupplierId\":11172},{\"ProductSupplierId\":40,\"ProductId\":8,\"SupplierId\":9285},{\"ProductSupplierId\":41,\"ProductId\":5,\"SupplierId\":3622},{\"ProductSupplierId\":42,\"ProductId\":5,\"SupplierId\":9323},{\"ProductSupplierId\":43,\"ProductId\":1,\"SupplierId\":1766},{\"ProductSupplierId\":44,\"ProductId\":1,\"SupplierId\":3212},{\"ProductSupplierId\":45,\"ProductId\":9,\"SupplierId\":11174},{\"ProductSupplierId\":46,\"ProductId\":8,\"SupplierId\":3600},{\"ProductSupplierId\":47,\"ProductId\":9,\"SupplierId\":11160},{\"ProductSupplierId\":48,\"ProductId\":8,\"SupplierId\":11549},{\"ProductSupplierId\":49,\"ProductId\":4,\"SupplierId\":2827},{\"ProductSupplierId\":50,\"ProductId\":9,\"SupplierId\":12657},{\"ProductSupplierId\":51,\"ProductId\":8,\"SupplierId\":7377},{\"ProductSupplierId\":52,\"ProductId\":5,\"SupplierId\":6550},{\"ProductSupplierId\":53,\"ProductId\":4,\"SupplierId\":1634},{\"ProductSupplierId\":54,\"ProductId\":8,\"SupplierId\":2140},{\"ProductSupplierId\":55,\"ProductId\":3,\"SupplierId\":317},{\"ProductSupplierId\":56,\"ProductId\":1,\"SupplierId\":1205},{\"ProductSupplierId\":57,\"ProductId\":8,\"SupplierId\":3633},{\"ProductSupplierId\":58,\"ProductId\":2,\"SupplierId\":6873},{\"ProductSupplierId\":59,\"ProductId\":1,\"SupplierId\":7377},{\"ProductSupplierId\":60,\"ProductId\":5,\"SupplierId\":7244},{\"ProductSupplierId\":61,\"ProductId\":3,\"SupplierId\":2938},{\"ProductSupplierId\":63,\"ProductId\":2,\"SupplierId\":5081},{\"ProductSupplierId\":64,\"ProductId\":1,\"SupplierId\":3119},{\"ProductSupplierId\":65,\"ProductId\":9,\"SupplierId\":2998},{\"ProductSupplierId\":66,\"ProductId\":8,\"SupplierId\":3576},{\"ProductSupplierId\":67,\"ProductId\":8,\"SupplierId\":2592},{\"ProductSupplierId\":68,\"ProductId\":4,\"SupplierId\":100},{\"ProductSupplierId\":69,\"ProductId\":9,\"SupplierId\":2987},{\"ProductSupplierId\":70,\"ProductId\":4,\"SupplierId\":1005},{\"ProductSupplierId\":71,\"ProductId\":4,\"SupplierId\":908},{\"ProductSupplierId\":72,\"ProductId\":1,\"SupplierId\":5796},{\"ProductSupplierId\":73,\"ProductId\":10,\"SupplierId\":2386},{\"ProductSupplierId\":74,\"ProductId\":1,\"SupplierId\":3650},{\"ProductSupplierId\":75,\"ProductId\":4,\"SupplierId\":1425},{\"ProductSupplierId\":76,\"ProductId\":8,\"SupplierId\":6346},{\"ProductSupplierId\":78,\"ProductId\":1,\"SupplierId\":1685},{\"ProductSupplierId\":79,\"ProductId\":2,\"SupplierId\":2588},{\"ProductSupplierId\":80,\"ProductId\":6,\"SupplierId\":1620},{\"ProductSupplierId\":81,\"ProductId\":4,\"SupplierId\":1542},{\"ProductSupplierId\":82,\"ProductId\":5,\"SupplierId\":9766},{\"ProductSupplierId\":83,\"ProductId\":5,\"SupplierId\":5228},{\"ProductSupplierId\":84,\"ProductId\":6,\"SupplierId\":9396},{\"ProductSupplierId\":87,\"ProductId\":1,\"SupplierId\":1859},{\"ProductSupplierId\":90,\"ProductId\":1,\"SupplierId\":1713},{\"ProductSupplierId\":93,\"ProductId\":4,\"SupplierId\":3650}]";
}
@Override
public String insertProductSupplier(String jsonData) {
return "INSERT on \n" + jsonData + "\n...attemtped.\nMethod not yet implemented";
}
@Override
public String updateProductSupplier(String jsonData) {
return "UPDATE on \n" + jsonData + "\n...attemtped.\nMethod not yet implemented";
}
@Override
public String deleteProductSupplier(int productSupplierId) {
return "DELETE on " + productSupplierId + "\n...attemtped.\nMethod not yet implemented";
}
}
| [
"51454408+cherifsalah@users.noreply.github.com"
] | 51454408+cherifsalah@users.noreply.github.com |
99efff98190366acb76d77f73bf75fc8a820d5bb | a0d6551a15a5cbf0ee77c8f16a95fd2c67e9b044 | /ngoy/src/main/java/ngoy/common/DatePipe.java | 2c81e7ded0df4a7392ddeb963dbf6dd3fe124f70 | [
"Apache-2.0"
] | permissive | krizzdewizz/ngoy | fa3e6e40ec975c467eb1e3dde7d78711b74f43db | 54762efce853d2bd00acc9a26bc6f508426a23bb | refs/heads/master | 2020-04-05T09:49:34.985705 | 2019-02-05T22:57:17 | 2019-02-05T22:57:17 | 156,776,643 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,444 | java | package ngoy.common;
import static java.util.Arrays.asList;
import static ngoy.core.Util.isSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import ngoy.core.Inject;
import ngoy.core.LocaleProvider;
import ngoy.core.NgoyException;
import ngoy.core.Nullable;
import ngoy.core.Optional;
import ngoy.core.Pipe;
import ngoy.core.PipeTransform;
/**
* Formats a {@link LocalDateTime}, {@link LocalDate} or {@link Date}/Long
* instance in the current locale, accepting an optional format pattern as the
* first argument.
* <p>
* Another {@link Config} may be provided to override defaults.
* <p>
* Example:
* <p>
*
* <pre>
*
* {{ java.time.LocalDateTime.of(2018, 10, 28, 12, 44) | date:'MMMM' }}
* </pre>
* <p>
* Output:
*
* <pre>
* October
* </pre>
*
* @author krizz
*/
@Pipe("date")
public class DatePipe implements PipeTransform {
/**
* Provide a Config to override default format patterns.
*/
public static class Config {
/**
* Pattern used to format {@link Date}/Long instances.
* <p>
* If null or empty, uses {@link SimpleDateFormat#getDateTimeInstance()}
*/
public String defaultDatePattern;
/**
* Pattern used to format {@link LocalDate} instances.
* <p>
* If null or empty, uses {@link DateTimeFormatter#ISO_LOCAL_DATE}
*/
public String defaultLocalDatePattern;
/**
* Pattern used to format {@link LocalDateTime} instances.
* <p>
* If null or empty, uses {@link DateTimeFormatter#ISO_LOCAL_DATE_TIME}
*/
public String defaultLocalDateTimePattern;
}
private static final Config DEFAULT_CONFIG = new Config();
@Inject
public LocaleProvider localeProvider;
@Inject
@Optional
public Config config = DEFAULT_CONFIG;
@Override
public Object transform(@Nullable Object obj, Object... params) {
if (obj == null) {
return null;
}
if (obj instanceof LocalDateTime) {
return formatter(formatPattern(params, config.defaultLocalDateTimePattern), DateTimeFormatter.ISO_LOCAL_DATE_TIME).format((LocalDateTime) obj);
} else if (obj instanceof LocalDate) {
return formatter(formatPattern(params, config.defaultLocalDatePattern), DateTimeFormatter.ISO_LOCAL_DATE).format((LocalDate) obj);
} else if (obj instanceof Date) {
return formatDate((Date) obj, params, config.defaultDatePattern);
} else if (obj instanceof Long) {
return formatDate(new Date((long) obj), params, config.defaultDatePattern);
} else {
throw new NgoyException("DatePipe: input must be one of type %s", asList(LocalDate.class.getName(), LocalDateTime.class.getName(), Date.class.getName(), long.class.getName()));
}
}
private String formatDate(Date date, Object[] params, String defPattern) {
String pattern = formatPattern(params, defPattern);
return (isSet(pattern) ? new SimpleDateFormat(pattern, localeProvider.getLocale()) : DateFormat.getDateTimeInstance()).format(date);
}
private DateTimeFormatter formatter(String pattern, DateTimeFormatter def) {
return isSet(pattern) ? DateTimeFormatter.ofPattern(pattern, localeProvider.getLocale()) : def;
}
private String formatPattern(Object[] params, String def) {
return params.length == 0 ? def : params[0].toString();
}
}
| [
"christian.oetterli@bison-group.com"
] | christian.oetterli@bison-group.com |
bb11c4b7915f66ebbd2d94e8efb23297854e3d29 | b93d24fd7d6f9501ec814d9c15d0a9aa7f56ec14 | /src/cracking/ch09/C02.java | 06c57fc7c1a8fb53b693c3848ef8a1ea023a8da3 | [] | no_license | wmcalyj/cracking | 068c0925bd822769998fa2fc5d34703d87eaef4d | e7f46ce7e44a5116eeed44efa6df4c9c200f20be | refs/heads/master | 2020-04-19T08:13:44.402219 | 2016-09-01T02:56:23 | 2016-09-01T02:56:23 | 67,091,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,024 | java | package cracking.ch09;
/**
* Image a robot sitting on the upper left corner of an X by Y grid. The robot
* can only move in two directions: right and down. How many possible paths are
* there for the robot to go from (0, 0) to (X, Y)?
*
* FOLLOW UP
*
* Imagine certain spots are "off limits," such that the robot cannot step on
* them. Design an algorithm to find a path for the robot from the top left to
* the bottom.
*
*
*
* @author mengchaowang
*
*/
public class C02 {
public int countWays(int X, int Y) {
int[][] pos = new int[X + 1][Y + 1];
pos[0][0] = 0;
pos[0][1] = 1;
pos[1][0] = 1;
return countWays(pos, X, Y);
}
public int countWays(int[][] pos, int X, int Y) {
if (X <= 0) {
return 1;
}
if (Y <= 0) {
return 1;
}
if (pos[X][Y] != 0) {
return pos[X][Y];
}
int fromTop = countWays(pos, X - 1, Y);
pos[X - 1][Y] = fromTop;
int fromLeft = countWays(pos, X, Y - 1);
pos[X][Y - 1] = fromLeft;
pos[X][Y] = fromTop + fromLeft;
return pos[X][Y];
}
}
| [
"mengchaowang@gmail.com"
] | mengchaowang@gmail.com |
a58c2f47a6946be7978ba9eddf2a7959ffce3010 | 3a284e16597bb4a359a99a3aa04dbf93da9d1f35 | /voter/src/main/java/org/acme/model/Customer.java | 17e4120be13a1312603081d92ca2ce16906fea51 | [] | no_license | jeanouii/javaee-security-proposals | 2db3da7f6e9779c5d098894b44487cebda27d6e5 | f693b62e2b089aea893b76f2d7bbac392e149382 | refs/heads/master | 2021-01-17T08:46:33.801970 | 2015-11-10T13:17:44 | 2015-11-10T13:17:44 | 32,861,063 | 1 | 0 | null | 2015-03-25T11:45:43 | 2015-03-25T11:45:42 | Java | UTF-8 | Java | false | false | 62 | java | package org.acme.model;
/**
*
*/
public class Customer {
}
| [
"rudy.debusscher@c4j.be"
] | rudy.debusscher@c4j.be |
931d8fdf2b97617acdfb4b1daf3d5fc89a21de50 | 5982792823768278d71d4d29c8d9d65a4bb82db5 | /HotelBookingMVC/src/controller/ClientInfoController.java | 748b458e61b26efd3a4eb40ea6f0d8b820b8ffb5 | [] | no_license | Pboy208/JavaProjectHotel | d2d8b80166619e94200dd69e125b63a2910c3d84 | 5f62d06a1cd1dc3433802340cb20630db9b3b5b7 | refs/heads/main | 2023-06-10T19:03:06.521442 | 2021-06-24T15:52:27 | 2021-06-24T15:52:27 | 356,856,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,050 | java | package controller;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
import controller.ClientInfoController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import model.database.AccountsDB;
import model.database.HotelEmployeesDB;
import model.database.ReceiptsDB;
import model.database.UsersDB;
import model.library.Functions;
import model.receipts.Receipts;
import model.users.HotelEmployees;
import model.users.Users;
public class ClientInfoController implements Initializable {
// -----------------------------------------------------------------------
@FXML
private Pane infoPane;
@FXML
private Pane detailPane;
@FXML
private Label employeeName;
@FXML
private Label employeeEmail;
@FXML
private Label employeePhoneNumber;
// -----------------------------------------------------------------------
@FXML
private Label accountName;
@FXML
private TextField name;
@FXML
private TextField phone;
@FXML
private TextField email;
@FXML
private PasswordField oldPW;
@FXML
private PasswordField newPW;
@FXML
private PasswordField newPWConfirm;
@FXML
private Label alert;
@FXML
private Label viewDetailsLabel;
// -----------------------------------------------------------------------
@FXML
private TableView<Receipts> receiptsListTable;
@FXML
private TableColumn<Receipts, String> hotelNameColumn;
@FXML
private TableColumn<Receipts, String> hotelAddressColumn;
@FXML
private TableColumn<Receipts, String> checkinDateColumn;
@FXML
private TableColumn<Receipts, String> checkoutDateColumn;
@FXML
private TableColumn<Receipts, String> orderDateColumn;
@FXML
private TableColumn<Receipts, String> priceColumn;
@FXML
private TableColumn<Receipts, String> receiptStatusColumn;
@FXML
private TableColumn<Receipts, String> receiptIDColumn;
// -----------------------------------------------------------------------
public void backToFilter(ActionEvent event) {
new SceneChanging().changeScene(event, "Filter.fxml");
}
public void signOut(ActionEvent event) {
new SceneChanging().changeScene(event, "Login.fxml");
LoginController.signOut();
}
public void saveChange(ActionEvent event) throws SQLException {
alert.setText("");
boolean visibleFlag = false;
if (oldPW.isVisible() == true) {
visibleFlag = true;
}
if (name.getText().trim().isEmpty() || email.getText().trim().isEmpty() || phone.getText().trim().isEmpty()) {
alert.setText("Some fields is Missing");
return;
}
if (visibleFlag) {
if (oldPW.getText().trim().isEmpty() || newPW.getText().trim().isEmpty()
|| newPWConfirm.getText().trim().isEmpty()) {
alert.setText("Some fields is Missing");
return;
}
}
String newName = name.getText();
String newEmail = email.getText();
String newPhone = phone.getText();
if(!Functions.checkPhoneNumber(newPhone)) {
alert.setText("Phone number must be a sequence of 10 numbers");
phone.clear();
return;
}
if(!Functions.checkEmail(newEmail)) {
alert.setText("Invalid email address");
email.clear();
return;
}
Users user = LoginController.getUser();
user.setName(newName);
user.setPhoneNumber(newPhone);
user.setEmail(newEmail);
if (visibleFlag) {
String oldPwString = oldPW.getText();
String newPWString = newPW.getText();
String newPWConfirmString = newPWConfirm.getText();
if (AccountsDB.checkPassword(user.getUsername(), oldPwString) == -1) {
alert.setText("Current password is incorrect");
return;
}
if (!newPWString.equals(newPWConfirmString)) {
alert.setText("Password confirmation is not match");
return;
}
if (user.getPassword().equals(newPWString)) {
alert.setText("New password must be different than current password");
return;
}
user.setPassword(newPWString);
}
new UsersDB().updateInstance(user);
alert.setText("Information changed");
}
public void changePassword(ActionEvent event) {
alert.setText("");
viewDetailsLabel.setText("");
oldPW.setVisible(!oldPW.isVisible());
newPW.setVisible(!newPW.isVisible());
newPWConfirm.setVisible(!newPWConfirm.isVisible());
}
public void cancelReceipt(ActionEvent event) throws SQLException {
alert.setText("");
viewDetailsLabel.setText("");
Receipts chosenReceipt = receiptsListTable.getSelectionModel().getSelectedItem();
if (chosenReceipt == null) {
viewDetailsLabel.setText("Choose a receipt");
return;
}
if (chosenReceipt.getStatus() == -1) {
viewDetailsLabel.setText("The receipt has already been finished");
return;
}
if (chosenReceipt.getStatus() == 1) {
viewDetailsLabel.setText("Can not cancel this receipt");
return;
}
if (chosenReceipt.getStatus() == 2) {
viewDetailsLabel.setText("The receipt has already been cancelled");
return;
}
ReceiptsDB.cancelReciepts(chosenReceipt.getReceiptID());
ReceiptsDB.updateReceiptStatus(LoginController.getUser());
ArrayList<Receipts> receipts = ReceiptsDB.queryReceipts(LoginController.getUser());
if (receipts == null) {
Label noResult = new Label("You have no room");
receiptsListTable.setPlaceholder(noResult);
ObservableList<Receipts> tableListNull = FXCollections.observableArrayList();
receiptsListTable.setItems(tableListNull);
return;
}
ObservableList<Receipts> roomsList = FXCollections.observableArrayList(receipts);
receiptsListTable.setItems(roomsList);
viewDetailsLabel.setText("Booking cancelled");
}
public void back(ActionEvent event) {
alert.setText("");
viewDetailsLabel.setText("");
detailPane.setVisible(false);
infoPane.setEffect(null);
}
public void viewDetails(ActionEvent event) throws SQLException {
alert.setText("");
viewDetailsLabel.setText("");
Receipts chosenReceipt = receiptsListTable.getSelectionModel().getSelectedItem();
if (chosenReceipt == null) {
viewDetailsLabel.setText("Choose a receipt");
return;
}
Receipts chosenReceipts = (Receipts) new ReceiptsDB().queryInstance(chosenReceipt.getReceiptID());
// --------------------------------------------------------------
infoPane.setEffect(new GaussianBlur(20));
detailPane.setVisible(true);
detailPane.toFront();
detailPane.setBorder(new Border(
new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(3))));
detailPane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
// --------------------------------------------------------------
HotelEmployees employee = HotelEmployeesDB.queryEmployeeInfoByHotelID(chosenReceipts.getHotelID());
try {
employeeName.setText("Employee's Name: " + employee.getName());
employeeEmail.setText("Employee's Email: " + employee.getEmail());
employeePhoneNumber.setText("Employee's Phone Number: " + employee.getPhoneNumber());
} catch (Exception e) {
employeeName.setText("Employee's Name: N/A");
employeeEmail.setText("Employee's Email: N/A");
employeePhoneNumber.setText("Employee's Phone Number: N/A");
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
alert.setText("");
Users user = LoginController.getUser();
accountName.setText("Username: " + user.getUsername());
name.setText(user.getName());
email.setText(user.getEmail());
phone.setText(user.getPhoneNumber());
// -------------------------------------------------------
reloadPage();
}
private void reloadPage() {
Users user = LoginController.getUser();
try {
ReceiptsDB.updateReceiptStatus(user);
} catch (SQLException e) {
System.out.println("This user don't have any receipt to udpate status");
e.printStackTrace();
System.out.println("damn it");
}
System.out.println("Done update receipt list");
ArrayList<Receipts> receipts = null;
try {
receipts = ReceiptsDB.queryReceipts(user);
} catch (SQLException e) {
System.out.println("This user don't have any receipt to query out");
e.printStackTrace();
}
if (receipts == null) {
Label noResult = new Label("You have no receipt");
receiptsListTable.setPlaceholder(noResult);
ObservableList<Receipts> tableListNull = FXCollections.observableArrayList();
receiptsListTable.setItems(tableListNull);
} else {
ObservableList<Receipts> receiptsList = FXCollections.observableArrayList(receipts);
hotelAddressColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("hotelAddressProperty"));
hotelNameColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("hotelNameProperty"));
checkinDateColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("checkinDateProperty"));
checkoutDateColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("checkoutDateProperty"));
orderDateColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("orderDateProperty"));
receiptStatusColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("statusProperty"));
receiptIDColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("receiptIDProperty"));
priceColumn.setCellValueFactory(new PropertyValueFactory<Receipts, String>("priceProperty"));
receiptsListTable.setItems(receiptsList);
}
}
}
| [
"73631714+phuonghoang2k@users.noreply.github.com"
] | 73631714+phuonghoang2k@users.noreply.github.com |
e3f9001c63e12391ef3a4b8041f932c4f4192677 | 0c4bdf8ae4af7942ef7a07033b58eb2c07d16a3e | /src/main/java/com/ale/crud/util/common/ConfigUtil.java | 845aeaa27596e9d1cc0af462b0d9aa2f3ea90610 | [] | no_license | 15ME/crud-xml | 06e4470fa02095b638ab090224adce7190cb45b4 | df35213c006b3fe0b5872dbe942be0ed0f7ac6d9 | refs/heads/master | 2022-12-06T01:25:43.920763 | 2020-05-12T05:32:06 | 2020-05-12T05:32:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 700 | java | package com.ale.crud.util.common;
import com.fasterxml.jackson.core.util.VersionUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author alewu
* @date 2017/10/17 19:12
* @description 获取属性文件配置的参数
*/
public class ConfigUtil {
public static String getParameter(String key){
Properties prop = new Properties();
InputStream in = VersionUtil.class.getClassLoader().getResourceAsStream("config.properties");
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return prop.getProperty(key).trim();
}
public static void main(String[] args) {
System.out.println(getParameter("appID"));
}
}
| [
"wywujiawei@163.com"
] | wywujiawei@163.com |
ca5204be380cc3ddf08c8bce5bb8114f6e6b020e | f8ba07a3c0ce92dd9d6175f0e1d3bbb351e11665 | /src/test/java/com/data/connection/test/AstronautInformation.java | 2f2d7f893a0669d16ab1f2a35f21188590f19963 | [] | no_license | adnanrahin/Nasa-Space-Exploration-Data | 881d336fe1b591560c73030902750932ff98b7fc | b2f9c951c0bed7a7ee3ae8e67dd990d05890e10a | refs/heads/master | 2023-01-28T05:36:08.768847 | 2020-12-05T21:26:27 | 2020-12-05T21:26:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,625 | java | package com.data.connection.test;
import com.astronaut.space.jdbc.dao.connection.manager.Gateway;
import com.astronaut.space.jdbc.model.Astronaut;
import com.astronaut.space.jdbc.model.AstronautChildInfo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class AstronautInformation {
public static void main(String[] args) {
try {
Connection connection = Gateway.getDBConnection();
Statement statement = connection.createStatement();
String query = "select * from astronaut_info";
ResultSet rs = statement.executeQuery(query);
List<Astronaut> astronauts = new ArrayList<>();
while (rs.next()) {
int id = Integer.parseInt(rs.getString("astronaut_id"));
String fName = rs.getString("astronaut_fname");
String lName = rs.getString("astronaut_lname");
String dob = rs.getString("astronaut_dob");
String country = rs.getString("astronaut_country");
String gender = rs.getString("astronaut_gender");
Astronaut astronaut = new Astronaut.Builder(id, fName, lName).
dateOfBirth(dob).gender(gender).country(country).build();
astronauts.add(astronaut);
}
for (Astronaut astronaut : astronauts) {
System.out.println(astronaut);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| [
"adnan.rahin13@gmail.com"
] | adnan.rahin13@gmail.com |
9fa706a40b6e52584bcb59f4ce110505b57169d3 | 3f6b51e547716e4f442cb1b8d9cd0299a30dd3cb | /src/com/tonyyuzhang/sis/search/Search.java | 2b1df5c1f697f2d133dccd67986fa70b7e437b22 | [] | no_license | zhangyu/com.tonyyuzhang.sis | a64670abb02b58347de6938b9949b603d65f11be | f0e86a47224bc1df7c211e0bea156e0a3838afc8 | refs/heads/master | 2020-06-04T18:14:08.917095 | 2011-07-27T21:43:17 | 2011-07-27T21:43:17 | 1,908,339 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,445 | java | package com.tonyyuzhang.sis.search;
import java.io.*;
import java.net.*;
import com.tonyyuzhang.sis.util.StringUtil;
public class Search {
private URL url;
private String searchString;
private int matches = 0;
private Exception exception = null;
public Search(String url, String searchString) throws MalformedURLException {
this.url = new URL(url);
this.searchString = searchString;
}
public String getUrl() {
return url.toString();
}
public String getText() {
return searchString;
}
public void execute() {
try {
searchUrl();
}
catch (IOException e) {
exception = e;
}
}
private void searchUrl() throws IOException {
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null)
matches += StringUtil.occurrences(line, searchString);
}
finally {
if (reader != null)
reader.close();
}
}
public int matches() {
return matches;
}
public boolean errored() {
return exception != null;
}
public Exception getError() {
return exception;
}
}
| [
"zhangyu.main@gmail.com"
] | zhangyu.main@gmail.com |
53742387468ec4e07137c6c3f820d3baffdf78ed | dd8dc5b098b1fdbc2bc0f679a29f6c4683c17d96 | /ActivityCardTongShan/src/com/byid/utils/HttpUtil.java | cda87fcb1be38ef831a6069308b1818157efff55 | [] | no_license | lwcye/touch | 38d32494d5be20813141c11c2ff5c3f005730a76 | 999b641fc43c2a10c89e89e0096ddf1d8001e3f0 | refs/heads/master | 2020-03-15T11:37:25.189370 | 2018-06-02T09:47:08 | 2018-06-02T09:47:08 | 132,124,433 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,333 | java | package com.byid.utils;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.byid.activity.BrowserActivity;
import com.byid.model.ApiBean;
import com.byid.model.ConfigBean;
import com.byid.model.SyncBean;
import com.byid.model.UpdateBean;
import com.byid.model.UserInfoBean;
import com.google.gson.Gson;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.concurrent.TimeUnit;
import android_serialport_api.sample.base.RWCrashApplication;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
/**
* Created by 41569 on 2018/5/19.
*/
public class HttpUtil {
//mac
public static final String MAC_KEY = "mac";
//mac
public static final String MAC_VALUE = DeviceUtils.getMacAddress();
//更新状态
public static final String URL_CHANGE_STATUS = "/amain/romstatus";
//获得配置文件
public static final String URL_CONFIG = "/logintoken/getrooturl";
/** 获取该触摸屏的api */
private static final String URL_API = "/amain/peizhiinfo";
//url 同步数据
private static final String URL_SYNC = "/amain/syncinfo";
//更新APK
private static final String URL_UPDATE_ROM = "/amain/updaterom";
//config time
private static final String SP_HOST = "host";
//config time
private static final String SP_TIME_SYNC = "time_sync";
//config time
private static final String SP_TIME_CONFIG = "time_config";
//登录接口
private static final String SP_API_URL = "api_url";
//触摸屏的IP
private static final String SP_CM_WEB = "cm_web";
//触摸屏的TOKEN
private static final String SP_CM_TOKEN = "cm_token";
//Token
private static final String TOKEN_KEY = "api_cmtoken";
private static final String TOKEN_VALUE = "HBAPI@20180517";
private static final HttpUtil ourInstance = new HttpUtil();
//HOST
private String HTTP_HOST = "";
//触摸屏的登陆API
private String API_UTL = "";
//触摸屏的WEB地址
private String CM_WEB = "";
//触摸屏的TOKEN
private String CM_TOKEN = "";
//同步的请求
private Subscription mSyncObserver;
//配置的请求
private Subscription mConfigObserver;
private HttpUtil() {
HTTP_HOST = RWCrashApplication.spUtils.getString(SP_HOST, "http://223.113.65.26:10080/newswulian/public/api");
API_UTL = RWCrashApplication.spUtils.getString(SP_API_URL, "http://223.113.65.26:8088/tongshanweb");
CM_WEB = RWCrashApplication.spUtils.getString(SP_CM_WEB, "http://125.62.26.233/tongshanweb");
CM_TOKEN = RWCrashApplication.spUtils.getString(SP_CM_TOKEN, "HBAPI@20180310tongshanweb");
}
public static HttpUtil getInstance() {
return ourInstance;
}
/**
* 请求同步
*
* @param time 时间
* @param b 是否强制更新
*/
public void sync(int time, boolean b) {
if (mSyncObserver == null) {
b = true;
}
if (time == RWCrashApplication.spUtils.getInt(SP_TIME_SYNC)) {
if (!b) {
return;
}
} else {
RWCrashApplication.spUtils.put(SP_TIME_SYNC, time);
}
//如果在1s内重复点击,则取消订阅,以免重复读取
if (null != mSyncObserver) {
mSyncObserver.unsubscribe();
}
mSyncObserver = Observable
.interval(time, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Action1<Long>() {
@Override
public void call(Long count) {
HttpUtil.getInstance().requestSync();
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
LogUtils.e(throwable.getMessage());
}
});
}
/**
* 请求配置参数
*
* @param time 间隔时间
* @param b 是否强制更新
*/
public void getConfig(int time, boolean b) {
if (mConfigObserver == null) {
b = true;
}
if (time == RWCrashApplication.spUtils.getInt(SP_TIME_CONFIG)) {
if (!b) {
return;
}
} else {
RWCrashApplication.spUtils.put(SP_TIME_CONFIG, time);
}
//如果在1s内重复点击,则取消订阅,以免重复读取
if (null != mConfigObserver) {
mConfigObserver.unsubscribe();
}
mConfigObserver = Observable
.interval(time, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Action1<Long>() {
@Override
public void call(Long count) {
HttpUtil.getInstance().requestConfig();
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
LogUtils.e(throwable.getMessage());
}
});
}
/**
* 同步数据
*/
public void requestSync() {
RequestParams params = new RequestParams(HTTP_HOST + URL_SYNC);
params.addBodyParameter(TOKEN_KEY, TOKEN_VALUE);
params.addBodyParameter(MAC_KEY, MAC_VALUE);
x.http().post(params, new StringCallback() {
@Override
void onNext(String result) {
LogUtils.e(result);
SyncBean syncBean = new Gson().fromJson(result, SyncBean.class);
if (syncBean.status == 1 && syncBean.info.is_update == 1) {
requestUpdateRom();
}
}
@Override
void onFail(Throwable ex) {
}
});
}
/**
* 升级APK
*/
private void requestUpdateRom() {
RequestParams params = new RequestParams(HTTP_HOST + URL_UPDATE_ROM);
params.addBodyParameter(TOKEN_KEY, TOKEN_VALUE);
params.addBodyParameter(MAC_KEY, MAC_VALUE);
x.http().get(params, new StringCallback() {
@Override
void onNext(String result) {
LogUtils.e(result);
UpdateBean updateBean = new Gson().fromJson(result, UpdateBean.class);
if (updateBean.status == 1) {
FileDownUtil.getInstance().downloadApk(updateBean.info.rompath);
}
}
@Override
void onFail(Throwable ex) {
}
});
}
/**
* 改变状态
*/
public void requestChangeStatus(final Action1<String> action1) {
RequestParams params = new RequestParams(HTTP_HOST + URL_CHANGE_STATUS);
params.addBodyParameter(TOKEN_KEY, TOKEN_VALUE);
params.addBodyParameter(MAC_KEY, MAC_VALUE);
x.http().post(params, new StringCallback() {
@Override
void onNext(String result) {
if (action1 != null) {
action1.call(result);
}
}
@Override
void onFail(Throwable ex) {
}
});
}
/**
* 获得配置文件
*/
public void requestConfig() {
RequestParams params = new RequestParams(HTTP_HOST + URL_CONFIG);
params.addBodyParameter(TOKEN_KEY, TOKEN_VALUE);
x.http().post(params, new StringCallback() {
@Override
void onNext(String result) {
LogUtils.e(result);
ConfigBean configBean = new Gson().fromJson(result, ConfigBean.class);
if (configBean.status == 1) {
boolean b = resetHost(configBean.info.url);
LogUtils.e(b);
sync(configBean.info.synctime, b);
getConfig(configBean.info.peizhitime, b);
requestApi();
}
}
@Override
void onFail(Throwable ex) {
LogUtils.e(ex.getMessage());
}
});
}
/**
* 获得API
*/
public void requestApi() {
RequestParams params = new RequestParams(HTTP_HOST + URL_API);
params.addBodyParameter(TOKEN_KEY, TOKEN_VALUE);
params.addBodyParameter(MAC_KEY, MAC_VALUE);
x.http().post(params, new StringCallback() {
@Override
void onNext(String result) {
LogUtils.d(result);
ApiBean apiBean = new Gson().fromJson(result, ApiBean.class);
if (apiBean.status == 1 && !TextUtils.isEmpty(apiBean.info.apiurl)) {
RWCrashApplication.spUtils.put(SP_API_URL, apiBean.info.apiurl);
}
if (apiBean.status == 1 && !TextUtils.isEmpty(apiBean.info.weburl)) {
RWCrashApplication.spUtils.put(SP_CM_WEB, apiBean.info.weburl);
}
if (apiBean.status == 1 && !TextUtils.isEmpty(apiBean.info.token)) {
RWCrashApplication.spUtils.put(SP_CM_TOKEN, apiBean.info.token);
}
}
@Override
void onFail(Throwable ex) {
LogUtils.e(ex.getMessage());
}
});
}
/**
* 获得配置文件
*/
public void login(String username, String password, Activity activity) {
if (TextUtils.isEmpty(username)) {
return;
}
if (TextUtils.isEmpty(password)) {
int length = username.length();
password = username.substring(length - 6, length);
}
RequestParams params = new RequestParams(API_UTL + "/public/api/logintoken/login");
params.addBodyParameter("username", username);
params.addBodyParameter("password", password);
params.addBodyParameter("api_token", CM_TOKEN);
LogUtils.e(params.getUri() + new Gson().toJson(params.getQueryStringParams()));
x.http().post(params, new StringCallback() {
@Override
void onNext(String result) {
LogUtils.e("result" + result);
Gson gson = new Gson();
UserInfoBean userInfoBean = gson.fromJson(result, UserInfoBean.class);
if (userInfoBean.status == 1) {
String url = CM_WEB + "/#/home/myMoney/huiminzijin?userinfo=" + gson.toJson(gson.fromJson(userInfoBean.info.toString(), UserInfoBean.InfoBean.class));
LogUtils.e(url);
activity.startActivity(new Intent(activity, BrowserActivity.class)
.putExtra(BrowserActivity.PARAM_URL, url));
} else {
ToastUtils.showShort(userInfoBean.info.toString());
}
}
@Override
void onFail(Throwable ex) {
ToastUtils.showShort("网络错误");
}
});
}
/**
* 重新设置Host
*/
private boolean resetHost(String host) {
if (host.equalsIgnoreCase(RWCrashApplication.spUtils.getString(SP_HOST))) {
return false;
} else {
HTTP_HOST = host;
RWCrashApplication.spUtils.put(SP_HOST, host);
return true;
}
}
/**
* 回调
*/
abstract class StringCallback implements Callback.CommonCallback<String> {
abstract void onNext(String result);
abstract void onFail(Throwable ex);
@Override
public void onSuccess(String result) {
onNext(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
onFail(ex);
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
}
}
| [
"15213024302@139.com"
] | 15213024302@139.com |
e6acafd04606ae7b165b2f7efde1f2644fbdab5c | 4d3941e62c762b27de2333fe301fd93094902dda | /src/test/java/nl/rostykerei/cci/ch01/q04/PalindromePermutationAbstractTest.java | f9162a69b9904d1f4710db4d17b2dcd78d55a7ab | [
"MIT"
] | permissive | rostykerei/cci | f0d5ba3c004d80dfcabcde3d211fadc41f21091e | ee16c2ee9067c44af4a23d6f92969a6f03d44d5b | refs/heads/master | 2021-12-25T08:41:25.814915 | 2021-10-27T16:11:13 | 2021-10-27T16:11:13 | 100,109,531 | 3 | 1 | MIT | 2018-04-01T09:03:26 | 2017-08-12T11:58:36 | Java | UTF-8 | Java | false | false | 1,008 | java | package nl.rostykerei.cci.ch01.q04;
import nl.rostykerei.cci.common.AbstractFactoryTest;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public abstract class PalindromePermutationAbstractTest extends AbstractFactoryTest<PalindromePermutation> {
@Test
public void testTrue() {
assertTrue(testInstance.isPalindromePermutation("abcxcba"));
assertTrue(testInstance.isPalindromePermutation("tacocat"));
assertTrue(testInstance.isPalindromePermutation("xxxyyyxxx"));
assertTrue(testInstance.isPalindromePermutation("aabxb"));
assertTrue(testInstance.isPalindromePermutation("a"));
assertTrue(testInstance.isPalindromePermutation("xx"));
}
@Test
public void testFalse() {
assertFalse(testInstance.isPalindromePermutation("axxb"));
assertFalse(testInstance.isPalindromePermutation("abcd"));
assertFalse(testInstance.isPalindromePermutation("ab"));
}
}
| [
"rosty.kerei@gmail.com"
] | rosty.kerei@gmail.com |
7d7f13339d27246aa1557becaa42b9a484ee48e9 | 5d32348ec4ae9b871751662ba2735fc196eeb5e5 | /datastructure_imook/src/main/java/datastructure/u_12_AVLTree/t_02_Calculating_Balance_Factor/src/AVLTree.java | d7af28b5981962bb54850cd229cf9913e3d929bd | [] | no_license | kingdelee/JDK11_Lee_Mvn_20181213 | 0060e4a3269dcf7a635ba20871fb6077aa47a790 | c106c2b98ac466dba85756827fa26c0b2302550a | refs/heads/master | 2020-04-13T11:56:27.280624 | 2019-03-28T10:06:20 | 2019-03-28T10:06:20 | 163,188,239 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,984 | java | package datastructure.u_12_AVLTree.t_02_Calculating_Balance_Factor.src;
import java.util.ArrayList;
public class AVLTree<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
public int height;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
height = 1;
}
}
private Node root;
private int size;
public AVLTree() {
root = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// 获得节点node的高度
private int getHeight(Node node) {
if (node == null)
return 0;
return node.height;
}
// 获得节点node的平衡因子
private int getBalanceFactor(Node node) {
if (node == null)
return 0;
return getHeight(node.left) - getHeight(node.right);
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value) {
root = add(root, key, value);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value) {
if (node == null) {
size++;
return new Node(key, value);
}
if (key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if (key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
// 更新height
node.height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
// 计算平衡因子
int balanceFactor = getBalanceFactor(node);
if (Math.abs(balanceFactor) > 1)
System.out.println("unbalanced : " + balanceFactor);
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key) {
if (node == null)
return null;
if (key.equals(node.key))
return node;
else if (key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key) {
return getNode(root, key) != null;
}
public V get(K key) {
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node) {
if (node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node) {
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二分搜索树中删除键为key的节点
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key) {
if (node == null)
return null;
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
return node;
} else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
return node;
} else { // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
// 待删除节点右子树为空的情况
if (node.right == null) {
Node leftNode = node.left;
node.left = null;
size--;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
AVLTree<String, Integer> map = new AVLTree<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| [
"137211319@qq.com"
] | 137211319@qq.com |
45f10c4ffbf52c9634bc648938e5c59d5db9d54f | 76ad64ad8a606e03f3b6d92dba99cd9eb22fd366 | /kikaha-modules/kikaha-cloud-aws-xray/tests/kikaha/cloud/aws/xray/it/SampleResourceIntegrationTest.java | 73c09585b5ed3536161bc69b9b879b4f81d524a9 | [
"Apache-2.0"
] | permissive | Skullabs/kikaha | 069cd66d1dbfda9bface09d12a13436c6f2a8804 | 0df3ca87e1ffe50e5f53b582fc0f734ac69e422c | refs/heads/version-2.1.x | 2023-08-27T12:43:15.321098 | 2021-06-14T04:11:42 | 2021-06-14T04:11:42 | 20,723,726 | 73 | 27 | Apache-2.0 | 2023-04-15T20:20:58 | 2014-06-11T12:09:38 | Java | UTF-8 | Java | false | false | 1,791 | java | package kikaha.cloud.aws.xray.it;
import com.amazonaws.xray.entities.TraceHeader;
import kikaha.core.test.KikahaServerRunner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
/**
* Created by miere.teixeira on 16/06/2017.
*/
@RunWith(KikahaServerRunner.class)
public class SampleResourceIntegrationTest {
final static String TRACE_ID = "Root=1-59440aea-229915288782207bac24d65e;";
final OkHttpClient client = new OkHttpClient()
.newBuilder()
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.followRedirects(false).build();
@Test
public void ensureWillReceivedATraceIdEvenWhenNoTraceIdIsSendToBackend() throws IOException {
final Request.Builder url = new Request.Builder().url("http://localhost:9000/api/sample/trace-id");
final Response response = client.newCall( url.build() ).execute();
assertEquals( 200, response.code() );
final String responseAsString = response.body().string();
assertNotNull(responseAsString );
}
@Test
public void ensureWillReceiveTheSentTraceId() throws IOException {
final Request.Builder url = new Request.Builder().url("http://localhost:9000/api/sample/trace-id")
.addHeader( TraceHeader.HEADER_KEY, TRACE_ID );
final Response response = client.newCall( url.build() ).execute();
assertEquals( 200, response.code() );
final String responseAsString = response.body().string();
assertEquals( TRACE_ID, responseAsString );
}
} | [
"miere.teixeira@ibratan.com.br"
] | miere.teixeira@ibratan.com.br |
1bd9f4f0e093e441e528b35d8d594abb5a900bf9 | 4a675850241635cd95dc2e7f8bb63046f606c301 | /app/src/androidTest/java/com/hedong/android/ApplicationTest.java | 7e417882728755e9ed06d88ef2f0698c92e60d0d | [] | no_license | eastbrave/teacherdemo | 567dcc94cafc8825e2f3c41c1ca43f932c2c494d | 01c4d1bc521905e6407a9d2db9edf3ed2e6248fe | refs/heads/master | 2021-01-17T08:36:45.472895 | 2016-06-27T05:54:21 | 2016-06-27T05:54:21 | 62,027,123 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 349 | java | package com.hedong.android;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"351372902@qq.com"
] | 351372902@qq.com |
532ccc746696202b72e526b23429833356e7df43 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/21/21_9a8018cca4cd1e135537a3a7005437e6c9a278a1/PhraseParserImpl/21_9a8018cca4cd1e135537a3a7005437e6c9a278a1_PhraseParserImpl_t.java | e93f2668ceb61f668b59ab624374a0b5e38a05c9 | [] | 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 | 1,823 | java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
public class PhraseParserImpl implements PhraseParser {
LinkedList<String> des;
ArrayList<HashMap<String, Integer>> maps;
public PhraseParserImpl(Webpage w){
des=new LinkedList<String>();
maps=new ArrayList<HashMap<String, Integer>>();
parse(w);
}
private void parse(Webpage w) {
// TODO Auto-generated method stub
LinkedList<CourseDescription> cdes=w.getCourseDescriptions();
for(CourseDescription c:cdes){
des.add(c.getDescription());
}
generateMap(1);
generateMap(2);
generateMap(3);
generateMap(4);
}
private void generateMap(int length){
HashMap<String,Integer> map=new HashMap<String, Integer>();
ArrayList<String> phrases=generatePhrases(length);
for(String s: phrases){
if(map.containsKey(s))
map.put(s, map.get(s)+1);
else map.put(s, 1);
}
maps.add(map);
}
private ArrayList<String> generatePhrases(int length){
ArrayList<String> result=new ArrayList<String>();
ArrayList<String> temp=new ArrayList<String>();
for(String s: des){
String[] array=s.split("\\.|,");
for(String ss: array){
temp.add(ss.trim());
}
}
for(String s: temp){
String[] array=s.split(" ");
int index=0;
while(array.length-index>length){
StringBuilder phrase=new StringBuilder();
for(int i=index; i<index+length; i++)
phrase.append(array[i]+" ");
result.add(phrase.toString());
index++;
}
}
return result;
}
@Override
public HashMap<String, Integer> getPhrase(int length) {
// TODO Auto-generated method stub
return maps.get(length-1);
}
@Override
public String getDescription(String title) {
// TODO Auto-generated method stub
return null;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
d163e743632b827ef92479251e9baec6d19aabc3 | fa72756b8e9e0837a71aa092b99656d006e37e86 | /day02/负数的二进制转换.java | 1bbe6064fe771ce88a910e0cb200be4ea8d54660 | [] | no_license | Yutrue/javalearn | c38c5a539fb161d9d1564661af71579637b3ece4 | 4dece156488ebfe54c23add0472cbd7de5edada8 | refs/heads/master | 2020-07-12T02:17:54.594467 | 2019-09-06T04:09:33 | 2019-09-06T04:09:33 | 204,691,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 144 | java | class varDemo
{
public static void main(String[] args)
{
System.out.println(Integer.toBinaryString(-6));
System.out.println(0x3c);
}
}
| [
"aff1994611@gmail.com"
] | aff1994611@gmail.com |
09e95fff43a3dce54f4b5505cc1b13c96a535193 | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-900-Files/boiler-To-Generate-900-Files/syncregions-900Files/BoilerActuator4061.java | 3eb67df76c039872be1ca789ebc0bd8313d04a34 | [] | no_license | soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464889 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | Java | UTF-8 | Java | false | false | 263 | java | package syncregions;
public class BoilerActuator4061 {
public execute(int temperatureDifference4061, boolean boilerStatus4061) {
//sync _bfpnGUbFEeqXnfGWlV4061, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| [
"sultanalmutairi@172.20.10.2"
] | sultanalmutairi@172.20.10.2 |
6aa061e460f4bc48732a920aa53581cb98149449 | e7ee311e20b40c87bf6d23a53a1d7b11fd29d2c3 | /src/chosun/ciis/fc/acct/rec/FC_ACCT_2283_ICURLIST1Record.java | 2269c7fe4df45163d7e797feaf118556c5363ad2 | [] | no_license | nosmoon/misdevteam | 4e3695ef7bbdcd231bb84d7d8d7df54a23ff0a60 | 1829d5bd489eb6dd307ca244f0e183a31a1de773 | refs/heads/master | 2020-04-15T15:57:05.480056 | 2019-01-10T01:12:01 | 2019-01-10T01:12:01 | 164,812,547 | 1 | 0 | null | null | null | null | UHC | Java | false | false | 1,492 | java | /***************************************************************************************************
* 파일명 : .java
* 기능 : 독자우대-구독신청
* 작성일자 : 2007-05-22
* 작성자 : 김대섭
***************************************************************************************************/
/***************************************************************************************************
* 수정내역 :
* 수정자 :
* 수정일자 :
* 백업 :
***************************************************************************************************/
package chosun.ciis.fc.acct.rec;
import java.sql.*;
import chosun.ciis.fc.acct.dm.*;
import chosun.ciis.fc.acct.ds.*;
/**
*
*/
public class FC_ACCT_2283_ICURLIST1Record extends java.lang.Object implements java.io.Serializable{
public String slip_occr_dt;
public String slip_clsf_cd;
public String slip_seq;
public FC_ACCT_2283_ICURLIST1Record(){}
public void setSlip_occr_dt(String slip_occr_dt){
this.slip_occr_dt = slip_occr_dt;
}
public void setSlip_clsf_cd(String slip_clsf_cd){
this.slip_clsf_cd = slip_clsf_cd;
}
public void setSlip_seq(String slip_seq){
this.slip_seq = slip_seq;
}
public String getSlip_occr_dt(){
return this.slip_occr_dt;
}
public String getSlip_clsf_cd(){
return this.slip_clsf_cd;
}
public String getSlip_seq(){
return this.slip_seq;
}
}
/* 작성시간 : Sat May 30 10:47:53 KST 2009 */ | [
"DLCOM000@172.16.30.11"
] | DLCOM000@172.16.30.11 |
8846b7006fdf4b5d1df1ec9835305329c39cb411 | 4e004bc0da5692e88d166aa1a605d378880cf306 | /stock-pcweb-multiproject/stock-webapp-base/src/main/java/com/stock/webapp/base/controller/stock/BuyerEntrustPriceQueueController.java | b22d7d09db31f2565cb66d5cef19f609016a4733 | [] | no_license | AmmyWu/stock2 | 2cd323536839ae68c8a3b224966e159f2f415cd6 | e2ab9a6b9b007af5e6a55a3758959f38c708f6b1 | refs/heads/master | 2020-04-03T14:21:52.622729 | 2018-11-11T13:15:05 | 2018-11-11T13:15:05 | 155,319,146 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,299 | java | package com.stock.webapp.base.controller.stock;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.stock.dao.model.stock.BuyerEntrustPriceQueue;
import com.stock.service.stock.BuyerEntrustPriceQueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.stock.common.exceptions.BizException;
import com.stock.common.util.CommonUtils;
import com.stock.common.util.JsonFastUtil;
import com.stock.pojo.vo.RequestResultVO;
import com.stock.service.sys.utils.HttpResponseConstants.Public;
@Controller
@RequestMapping(value="/buyerEntrustPriceQueue")
public class BuyerEntrustPriceQueueController {
@Autowired
private BuyerEntrustPriceQueueService buyerEntrustPriceQueueService;
/**
* 新增
* @param request
* @return
*/
@RequestMapping(value="/insert.do")
public @ResponseBody RequestResultVO insert(HttpServletRequest request){
String buyerEntrustPriceQueueString = request.getParameter("buyerEntrustPriceQueue");
BuyerEntrustPriceQueue buyerEntrustPriceQueue = null;
try{
buyerEntrustPriceQueue = JsonFastUtil.parseObject(buyerEntrustPriceQueueString, BuyerEntrustPriceQueue.class);
}catch(Exception e){
throw new BizException(Public.ERROR_700);
}
return buyerEntrustPriceQueueService.insert(buyerEntrustPriceQueue);
}
/**
* 修改
* @param request
* @return
*/
@RequestMapping(value="/update.do")
public @ResponseBody RequestResultVO update(HttpServletRequest request){
String buyerEntrustPriceQueueString = request.getParameter("buyerEntrustPriceQueue");
BuyerEntrustPriceQueue buyerEntrustPriceQueue = null;
try{
buyerEntrustPriceQueue = JsonFastUtil.parseObject(buyerEntrustPriceQueueString, BuyerEntrustPriceQueue.class);
}catch(Exception e){
throw new BizException(Public.ERROR_700);
}
return buyerEntrustPriceQueueService.update(buyerEntrustPriceQueue);
}
/**
* 删除
* @param request
* @return
*/
@RequestMapping(value="/delete.do")
public @ResponseBody RequestResultVO delete(HttpServletRequest request){
String buyerEntrustPriceQueueIdsString = request.getParameter("buyerEntrustPriceQueueIds");
List<Integer> buyerEntrustPriceQueueIds;
try{
buyerEntrustPriceQueueIds = CommonUtils.idsArrayToList(buyerEntrustPriceQueueIdsString);
}catch(Exception e){
throw new BizException(Public.ERROR_700);
}
return buyerEntrustPriceQueueService.delete(buyerEntrustPriceQueueIds);
}
/**
* 分页查询
* @param request
* @return
*/
@RequestMapping(value="/getByPage.do")
public @ResponseBody Object getByPage(HttpServletRequest request){
String keys = request.getParameter("keys");
Integer length = Integer.parseInt(request.getParameter("length"));
Integer start = Integer.parseInt(request.getParameter("start"));
return buyerEntrustPriceQueueService.getByPage(keys, length, start);
}
}
| [
"wmw_0818@126.com"
] | wmw_0818@126.com |
574f5b531fd0daf70994fb857342bb6e75d88723 | 84dbc8b2517e1730c172ff69ff32130db050b01a | /cj.netos.flow.job.program/src/cj/netos/flow/job/entities/ChannelDocumentMedia.java | cf868216238eb9ba9c7d61a55fab544fb3b2c2c1 | [] | no_license | carocean/cj.netos.flow.job | 894f0d6c4f371962b313d9a457aebeaef2be2b40 | 57c041722440d73cc09f4af39ed34f1a66ffa979 | refs/heads/master | 2023-02-17T15:30:14.525808 | 2021-01-12T18:59:02 | 2021-01-12T18:59:02 | 282,622,936 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,280 | java | package cj.netos.flow.job.entities;
public class ChannelDocumentMedia {
String id;
String type;
String src;
String docid;
String channel;
String text;
String leading;
long ctime;
public long getCtime() {
return ctime;
}
public void setCtime(long ctime) {
this.ctime = ctime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDocid() {
return docid;
}
public void setDocid(String docid) {
this.docid = docid;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLeading() {
return leading;
}
public void setLeading(String leading) {
this.leading = leading;
}
}
| [
"cj@ss.com"
] | cj@ss.com |
687755a27d990b0236a3f28151ceee3ce16759e8 | 35383f03a0fd6e68e5b799a0ee1adbfdfc05fba0 | /chapter06/chapter06.03/src/test/java/io/baselogic/springsecurity/service/UserContextTests.java | dc93c89fcd3629a1c77e53b8af7320591ee312d9 | [
"BSD-2-Clause"
] | permissive | mickknutson/spring_security_course | 459d55b1cb158ef6fac1438a325e3a08f655f677 | ae9d6993bf109f791621dc2be9abcf8f49e4ed33 | refs/heads/master | 2021-06-28T18:02:43.937796 | 2021-03-08T21:49:40 | 2021-03-08T21:49:40 | 220,356,903 | 8 | 17 | BSD-2-Clause | 2020-11-27T16:44:26 | 2019-11-08T00:52:24 | Java | UTF-8 | Java | false | false | 2,148 | java | package io.baselogic.springsecurity.service;
import io.baselogic.springsecurity.dao.TestUtils;
import io.baselogic.springsecurity.domain.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* UserContextTests
*
* @since chapter01.00
* @since chapter04.02 Can only setCurrentUser() with a user that exist in the db.
*/
@Transactional
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
class UserContextTests {
@Autowired
private UserContext userContext;
private AppUser owner = new AppUser();
@BeforeEach
void beforeEachTest() {
owner.setId(1);
}
@Test
void initJdbcOperations() {
assertThat(userContext).isNotNull();
}
@Test
void test_setCurrentUser() {
// Not in the database:
// userContext.setCurrentUser(TestUtils.TEST_APP_USER_1);
userContext.setCurrentUser(TestUtils.user1);
AppUser appUser = userContext.getCurrentUser();
assertThat(appUser).isNotNull();
assertThat(appUser.getId()).isZero();
}
@Test
void test_setCurrentUser_null_User() {
assertThrows(NullPointerException.class, () -> {
userContext.setCurrentUser(null);
});
}
@Test
void test_setCurrentUser_invalid_User() {
AppUser user = new AppUser();
assertThrows(IllegalArgumentException.class, () -> {
userContext.setCurrentUser(user);
});
}
@Test
@DisplayName("getCurrentUser with a null authentication from SecurityContext")
void test_getCurrentUser_null_authentication() {
SecurityContextHolder.clearContext();
AppUser result = userContext.getCurrentUser();
assertThat(result).isNull();
}
} // The End...
| [
"mickknutson@gmail.com"
] | mickknutson@gmail.com |
bd997caeb825a1f5fd56f13d5de346f2bda29ac1 | ce781c00619f5eb63c2c882d23bb5b38535a621e | /jbpm-examples/src/main/java/org/jbpm/examples/checklist/context/PotentialOwnerContextConstraint.java | fabfef125c4af53753767ad9de617b5caba33d2c | [] | no_license | jsvitak/jbpm | c96131394bfa15eb08dcb685e222327c9340c911 | 8531651a244bd50dac377fa76b3077bb928739aa | refs/heads/master | 2021-01-16T19:40:08.268821 | 2015-03-23T15:33:11 | 2015-04-20T09:44:06 | 2,874,968 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 602 | java | package org.jbpm.examples.checklist.context;
import org.jbpm.examples.checklist.ChecklistContextConstraint;
import org.jbpm.examples.checklist.ChecklistItem;
public class PotentialOwnerContextConstraint implements ChecklistContextConstraint {
private String userId;
public PotentialOwnerContextConstraint(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public boolean acceptsTask(ChecklistItem item) {
String[] ss = item.getActors().split(",");
for (String s: ss) {
if (s.equals(userId)) {
return true;
}
}
return false;
}
}
| [
"kris.verlaenen@gmail.com"
] | kris.verlaenen@gmail.com |
7a5dfbc6550466477bfd59c171ab01517430f381 | a0a6fa4b061c23c210c38df4b5d2f93fa1fe5557 | /src/fclib/DbmsInt.java | 723c6ad5b25d0c3ead25d4614f4640468448fb6f | [] | no_license | rmdurkin/findcopy | c19627b1080a8f243aab4bdc407b02c6db21fd60 | 535c3f60184760649832496314ea7d34ae4f15e0 | refs/heads/master | 2016-09-06T17:33:58.458676 | 2015-01-27T18:24:21 | 2015-01-27T18:24:21 | 29,928,014 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 954 | java | package fclib;
import java.util.*;
// interface to a database
public interface DbmsInt {
// get a work list of owner IDs whose documents
// need to be analyzed for copy/paste instances
ArrayList<String> getWorkOwnerIds();
// get a large list of owner IDs for purposes
// of analyzing a random sample of documents
ArrayList<String> getAllOwnerIds();
// get all the documents for an owner
ArrayList<RawDoc> getAllForOwner(String ownerid);
// get all the documents for an owner in DocAttr form
ArrayList<DocAttr> getAllDocAttrForOwner(String ownerid);
// rest of these are obsolete ???
// get a list of document IDs for a specific owner
ArrayList<String> getDocumentIds(String ownerid);
// get the owner for a specific document
String getOwner(String docid);
// get the text for a specific document
ArrayList<String> getLines(String docid);
// get a timestamp for a specific document
Date getTimeStamp(String docid);
}
| [
"robertmdurkin@gmail.com"
] | robertmdurkin@gmail.com |
ece47b142c035cf4c97d2f078337de97f8b3b91f | aeff477049551493ea146a323d95a28facf50713 | /src/com/litian/utils/RC4.java | 4418c63ddd1e42cdd75305cfd815bd14587e04a9 | [] | no_license | lars-lee/litian | d31623dfbfd27ac9b5e26821eb33b918658add4f | 3eca1a9483f378ccc364bfdffc07277000f90346 | refs/heads/master | 2021-01-09T20:37:46.555475 | 2016-06-29T06:46:03 | 2016-06-29T06:46:03 | 60,939,353 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,501 | java | package com.litian.utils;
/**
* Created by litian on 2016/6/14.
*/
public class RC4 {
public static String encry_RC4(String data, String key) {
if (data == null || key == null) {
return null;
}
return toHexString(asString(encry_RC4_byte(data, key)));
}
public static String decry_RC4(String data, String key) {
if (data == null || key == null) {
return null;
}
return new String(RC4Base(HexString2Bytes(data), key));
}
private static String decry_RC4(byte[] data, String key) {
if (data == null || key == null) {
return null;
}
return asString(RC4Base(data, key));
}
private static byte[] encry_RC4_byte(String data, String key) {
if (data == null || key == null) {
return null;
}
byte b_data[] = data.getBytes();
return RC4Base(b_data, key);
}
private static String asString(byte[] buf) {
StringBuffer strbuf = new StringBuffer(buf.length);
for (int i = 0; i < buf.length; i++) {
strbuf.append((char) buf[i]);
}
return strbuf.toString();
}
private static byte[] initKey(String aKey) {
byte[] b_key = aKey.getBytes();
byte state[] = new byte[256];
for (int i = 0; i < 256; i++) {
state[i] = (byte) i;
}
int index1 = 0;
int index2 = 0;
if (b_key == null || b_key.length == 0) {
return null;
}
for (int i = 0; i < 256; i++) {
index2 = ((b_key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
byte tmp = state[i];
state[i] = state[index2];
state[index2] = tmp;
index1 = (index1 + 1) % b_key.length;
}
return state;
}
private static String toHexString(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch & 0xFF);
if (s4.length() == 1) {
s4 = '0' + s4;
}
str = str + s4;
}
return str;// 0x表示十六进制
}
private static byte[] HexString2Bytes(String src) {
int size = src.length();
byte[] ret = new byte[size / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < size / 2; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
private static byte uniteBytes(byte src0, byte src1) {
char _b0 = (char) Byte.decode("0x" + new String(new byte[]{src0}))
.byteValue();
_b0 = (char) (_b0 << 4);
char _b1 = (char) Byte.decode("0x" + new String(new byte[]{src1}))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
private static byte[] RC4Base(byte[] input, String mKkey) {
int x = 0;
int y = 0;
byte key[] = initKey(mKkey);
int xorIndex;
byte[] result = new byte[input.length];
for (int i = 0; i < input.length; i++) {
x = (x + 1) & 0xff;
y = ((key[x] & 0xff) + y) & 0xff;
byte tmp = key[x];
key[x] = key[y];
key[y] = tmp;
xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
result[i] = (byte) (input[i] ^ key[xorIndex]);
}
return result;
}
} | [
"ltdeyx@sina.com"
] | ltdeyx@sina.com |
d5f2792a442d594e7feac9d0075607596363082a | de897af3b71f6d5c9db3cdf80e51bab158cc6a16 | /timingframework-classic/src/org/jdesktop/animation/timing/interpolation/LinearInterpolator.java | 81c7a3ac4cee763854adcb6be083b93fb1e2efbe | [
"MIT"
] | permissive | himmodi/Timing-framework | c519eb27623466475cfda23dd996d850d6c2905d | c25c41a3eaead4e84fd4bc0057c32c6312dfe66f | refs/heads/master | 2021-07-11T00:08:02.498702 | 2019-06-28T13:07:26 | 2019-06-28T13:07:26 | 194,270,990 | 1 | 0 | MIT | 2020-10-13T14:14:16 | 2019-06-28T12:33:34 | Java | UTF-8 | Java | false | false | 3,113 | java | /**
* Copyright (c) 2005-2006, Sun Microsystems, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the TimingFramework project 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jdesktop.animation.timing.interpolation;
import org.jdesktop.animation.timing.*;
/**
* This class implements the Interpolator interface by providing a
* simple interpolate function that simply returns the value that
* it was given. The net effect is that callers will end up calculating
* values linearly during intervals.
* <p>
* Because there is no variation to this class, it is a singleton and
* is referenced by using the {@link #getInstance} static method.
*
* @author Chet
*/
public final class LinearInterpolator implements Interpolator {
private static LinearInterpolator instance = null;
private LinearInterpolator() {}
/**
* Returns the single DiscreteInterpolator object
*/
public static LinearInterpolator getInstance() {
if (instance == null) {
instance = new LinearInterpolator();
}
return instance;
}
/**
* This method always returns the value it was given, which will cause
* callers to calculate a linear interpolation between boundary values.
* @param fraction a value between 0 and 1, representing the elapsed
* fraction of a time interval (either an entire animation cycle or an
* interval between two KeyTimes, depending on where this Interpolator has
* been set)
* @return the same value passed in as <code>fraction</code>
*/
public float interpolate(float fraction) {
return fraction;
}
}
| [
"chet@3b6d4fe7-4653-6685-b3f4-cd575a8fdea3"
] | chet@3b6d4fe7-4653-6685-b3f4-cd575a8fdea3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.