code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package com.min.vacation.business.impl; import java.util.Calendar; import java.util.Date; import org.springframework.stereotype.Component; import com.min.vacation.business.DayOffBusiness; /** * The {@link DayOffBusinessImpl} class. * * @author wpetit */ @Component public class DayOffBusinessImpl implements DayOffBusiness { /** The NOVEMBER_11TH_DAY. */ private static final int NOVEMBER_11TH_DAY = 11; /** The JANUARY_1ST_DAY. */ private static final int JANUARY_1ST_DAY = 1; /** The NOVEMBER_1ST_DAY. */ private static final int NOVEMBER_1ST_DAY = 1; /** The AUGUST_15TH_DAY. */ private static final int AUGUST_15TH_DAY = 15; /** The JULY_14TH_DAY. */ private static final int JULY_14TH_DAY = 14; /** The MAY_8TH_DAY. */ private static final int MAY_8TH_DAY = 8; /** The MAY_1ST_DAY. */ private static final int MAY_1ST_DAY = 1; /** The CHRISTMAS_DAY. */ private static final int CHRISTMAS_DAY = 25; /** {@inheritDoc} **/ @Override public boolean isDayOff(final Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return isFixedDayOff(calendar) || isWeekend(calendar) || isAscension(calendar) || isEasterMonday(calendar) || isPentecost(calendar); } /** * Check if the date is a fixed day off (e.g 14/07). * * @param date * the date to check * @return if is day off */ private boolean isFixedDayOff(final Calendar date) { return isChristmasDay(date) || isAugustFifteenth(date) || isJanuaryFirst(date) || isJulyFourteenth(date) || isMayFirst(date) || isMayEighth(date) || isNovemberFirst(date) || isNovemberEleventh(date); } /** * Check if the date is the Christmas day. * * @param date * the date to check * @return if is day off */ private boolean isChristmasDay(final Calendar date) { return CHRISTMAS_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.DECEMBER == date.get(Calendar.MONTH); } /** * Check if the date is 01/05. * * @param date * the date to check * @return if is day off */ private boolean isMayFirst(final Calendar date) { return MAY_1ST_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.MAY == date.get(Calendar.MONTH); } /** * Check if the date is 08/05. * * @param date * the date to check * @return if is day off */ private boolean isMayEighth(final Calendar date) { return MAY_8TH_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.MAY == date.get(Calendar.MONTH); } /** * Check if the date is 14/07. * * @param date * the date to check * @return if is day off */ private boolean isJulyFourteenth(final Calendar date) { return JULY_14TH_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.JULY == date.get(Calendar.MONTH); } /** * Check if the date is 15/08. * * @param date * the date to check * @return if is day off */ private boolean isAugustFifteenth(final Calendar date) { return AUGUST_15TH_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.AUGUST == date.get(Calendar.MONTH); } /** * Check if the date is 1/11. * * @param date * the date to check * @return if is day off */ private boolean isNovemberFirst(final Calendar date) { return NOVEMBER_1ST_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.NOVEMBER == date.get(Calendar.MONTH); } /** * Check if the date is 11/11. * * @param date * the date to check * @return if is day off */ private boolean isNovemberEleventh(final Calendar date) { return NOVEMBER_11TH_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.NOVEMBER == date.get(Calendar.MONTH); } /** * Check if the date is 01/01. * * @param date * the date to check * @return if is day off */ private boolean isJanuaryFirst(final Calendar date) { return JANUARY_1ST_DAY == date.get(Calendar.DAY_OF_MONTH) && Calendar.JANUARY == date.get(Calendar.MONTH); } /** * Get the easter date fot the given year. * * @param year * the year. * @return if is easter day. */ private Calendar getEasterDate(final int year) { double g = year % 19; int c = year / 100; int c4 = c / 4; int e = (8 * c + 13) / 25; int h = (int) (19 * g + c - c4 - e + 15) % 30; int k = h / 28; int p = 29 / (h + 1); int q = (int) (21 - g) / 11; int i = (k * p * q - 1) * k + h; int b = year / 4 + year; int j1 = b + i + 2 + c4 - c; int j2 = j1 % 7; int r = 28 + i - j2; int monthNumber = 4; int dayNumber = r - 31; boolean negativeDayNumber = dayNumber <= 0; if (negativeDayNumber) { monthNumber = 3; dayNumber = r; } Calendar paques = Calendar.getInstance(); paques.set(year, monthNumber - 1, dayNumber); return paques; } /** * Check if the date is in week-end. * * @param date * the date to check * @return if is day off */ private boolean isWeekend(final Calendar date) { return Calendar.SATURDAY == date.get(Calendar.DAY_OF_WEEK) || Calendar.SUNDAY == date.get(Calendar.DAY_OF_WEEK); } /** * Check if the date is Easter Monday. * * @param date * the date to check * @return if is day off */ private boolean isEasterMonday(final Calendar date) { Calendar paquesMonday = getEasterDate(date.get(Calendar.YEAR)); paquesMonday.add(Calendar.DATE, 1); return date.get(Calendar.DAY_OF_YEAR) == paquesMonday .get(Calendar.DAY_OF_YEAR) && date.get(Calendar.MONTH) == paquesMonday.get(Calendar.MONTH); } /** * Check if the date is Pentecost. * * @param date * the date to check * @return if is day off */ private boolean isPentecost(final Calendar date) { Calendar paquesMonday = getEasterDate(date.get(Calendar.YEAR)); paquesMonday.add(Calendar.DAY_OF_YEAR, 50); return date.get(Calendar.DAY_OF_YEAR) == paquesMonday .get(Calendar.DAY_OF_YEAR) && date.get(Calendar.MONTH) == paquesMonday.get(Calendar.MONTH); } /** * Check if the date is Ascension. * * @param date * the date to check * @return if is day off */ private boolean isAscension(final Calendar date) { Calendar paquesMonday = getEasterDate(date.get(Calendar.YEAR)); paquesMonday.add(Calendar.DATE, 39); return date.get(Calendar.DAY_OF_YEAR) == paquesMonday .get(Calendar.DAY_OF_YEAR) && date.get(Calendar.MONTH) == paquesMonday.get(Calendar.MONTH); } }
wpetit/vacation
vacation-business/src/main/java/com/min/vacation/business/impl/DayOffBusinessImpl.java
Java
apache-2.0
7,403
package com.justplay1.shoppist.entity; import android.content.ContentValues; import android.database.MatrixCursor; import com.justplay1.shoppist.ApplicationTestCase; import org.junit.Test; import static com.justplay1.shoppist.entity.DAOUtil.FAKE_COLOR; import static com.justplay1.shoppist.entity.DAOUtil.FAKE_CREATE_BY_USER; import static com.justplay1.shoppist.entity.DAOUtil.FAKE_ID; import static com.justplay1.shoppist.entity.DAOUtil.FAKE_NAME; import static com.justplay1.shoppist.entity.DAOUtil.createFakeCategoryDAO; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; /** * Created by Mkhytar Mkhoian. */ public class CategoryDAOTest extends ApplicationTestCase { @Test public void categoryConstructor_HappyCase() { CategoryDAO model = createFakeCategoryDAO(); assertThat(model.getId(), is(FAKE_ID)); assertThat(model.getColor(), is(FAKE_COLOR)); assertThat(model.getName(), is(FAKE_NAME)); assertThat(model.isCreateByUser(), is(FAKE_CREATE_BY_USER)); } @Test public void categoryHashCode_HappyCase() { CategoryDAO model = createFakeCategoryDAO(); int hashCode = model.hashCode(); assertThat(hashCode, is(FAKE_ID.hashCode())); } @Test public void categoryEquals_HappyCase() { CategoryDAO x = createFakeCategoryDAO(); CategoryDAO y = createFakeCategoryDAO(); CategoryDAO z = createFakeCategoryDAO(); // reflection rule assertEquals(x, x); // symmetry rule assertEquals(x, y); assertEquals(y, x); // transitivity rule assertEquals(x, y); assertEquals(y, z); assertEquals(x, z); assertNotEquals(x, null); } @Test public void categoryContentValuesBuilder_HappyCase() { CategoryDAO.Builder builder = new CategoryDAO.Builder(); builder.id(FAKE_ID); builder.name(FAKE_NAME); builder.color(FAKE_COLOR); builder.createByUser(FAKE_CREATE_BY_USER); ContentValues contentValues = builder.build(); assertThat(contentValues.getAsString(CategoryDAO.COL_ID), is(FAKE_ID)); assertThat(contentValues.getAsString(CategoryDAO.COL_NAME), is(FAKE_NAME)); assertThat(contentValues.getAsInteger(CategoryDAO.COL_COLOR), is(FAKE_COLOR)); assertThat(contentValues.getAsBoolean(CategoryDAO.COL_CREATE_BY_USER), is(FAKE_CREATE_BY_USER)); } @Test public void categoryMAPPER_HappyCase() { MatrixCursor cursor = new MatrixCursor(new String[]{CategoryDAO.COL_ID, CategoryDAO.COL_NAME, CategoryDAO.COL_COLOR, CategoryDAO.COL_CREATE_BY_USER}); MatrixCursor.RowBuilder rowBuilder = cursor.newRow(); rowBuilder.add(FAKE_ID); rowBuilder.add(FAKE_NAME); rowBuilder.add(FAKE_COLOR); rowBuilder.add(1); cursor.moveToFirst(); CategoryDAO model = CategoryDAO.MAPPER.call(cursor); assertThat(model.getId(), is(FAKE_ID)); assertThat(model.getName(), is(FAKE_NAME)); assertEquals(model.getColor(), FAKE_COLOR); assertEquals(model.isCreateByUser(), FAKE_CREATE_BY_USER); } }
justplay1/Shoppist
data/src/test/java/com/justplay1/shoppist/entity/CategoryDAOTest.java
Java
apache-2.0
3,333
/* * Copyright 2017, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.persistence.db.converter; import androidx.room.TypeConverter; import java.util.Date; public class DateConverter { @TypeConverter public static Date toDate(Long timestamp) { return timestamp == null ? null : new Date(timestamp); } @TypeConverter public static Long toTimestamp(Date date) { return date == null ? null : date.getTime(); } }
android/architecture-components-samples
BasicSample/app/src/main/java/com/example/android/persistence/db/converter/DateConverter.java
Java
apache-2.0
1,027
/* Copyright 2002 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.css.engine.sac; import org.w3c.css.sac.DescendantSelector; import org.w3c.css.sac.Selector; import org.w3c.css.sac.SimpleSelector; /** * This class provides an abstract implementation of the {@link * org.w3c.css.sac.DescendantSelector} interface. * * @author <a href="mailto:[email protected]">Stephane Hillion</a> * @version $Id$ */ public abstract class AbstractDescendantSelector implements DescendantSelector, ExtendedSelector { /** * The ancestor selector. */ protected Selector ancestorSelector; /** * The simple selector. */ protected SimpleSelector simpleSelector; /** * Creates a new DescendantSelector object. */ protected AbstractDescendantSelector(Selector ancestor, SimpleSelector simple) { ancestorSelector = ancestor; simpleSelector = simple; } /** * Indicates whether some other object is "equal to" this one. * @param obj the reference object with which to compare. */ public boolean equals(Object obj) { if (obj == null || (obj.getClass() != getClass())) { return false; } AbstractDescendantSelector s = (AbstractDescendantSelector)obj; return s.simpleSelector.equals(simpleSelector); } /** * Returns the specificity of this selector. */ public int getSpecificity() { return ((ExtendedSelector)ancestorSelector).getSpecificity() + ((ExtendedSelector)simpleSelector).getSpecificity(); } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.DescendantSelector#getAncestorSelector()}. */ public Selector getAncestorSelector() { return ancestorSelector; } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.DescendantSelector#getSimpleSelector()}. */ public SimpleSelector getSimpleSelector() { return simpleSelector; } }
Uni-Sol/batik
sources/org/apache/batik/css/engine/sac/AbstractDescendantSelector.java
Java
apache-2.0
2,581
package grails.plugin.multitenant.core.datasource; /** * Created by Felipe Cypriano * Date: 08/04/2009 * Time: 08:30:29 * <p/> * Base interface to TentantDataSource. To be able to use it injected by Spring. * DataSource extension that allows for a custom url per tenant. */ public interface TenantDataSource extends javax.sql.DataSource { /** * This tells spring to manage a datasource per tenant */ public boolean multiTenant = true; public String getUrl(); public void setDataSourceUrlResolver(DataSourceUrlResolver dataSourceUrlResolver); }
multi-tenant/grails-multi-tenant-core
src/java/grails/plugin/multitenant/core/datasource/TenantDataSource.java
Java
apache-2.0
580
package com.full.cn.utils; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.junit.Test; import java.io.IOException; import java.util.*; /** * Created by full on 2017/7/5. */ public class SolrUtil { private static SolrClient server; //@Test public static void solrSearch(String fileName,String keyword){ server = new HttpSolrClient(PropertiesUtils.readProperty("solr_server")); SolrInputDocument doc = new SolrInputDocument(); //String fileName = "E:\\text\\SanDisk_SecureAccess_QSG.pdf"; Map<String,String> contextmap = PdfReaderUtils.Pdfread(fileName); doc.addField("objectId", 0); doc.addField("webTitle", contextmap.get("fileName")); doc.addField("webTime", new java.util.Date()); doc.addField("webContent", contextmap.get("context")); try { // 添加一个doc文档 UpdateResponse response = server.add(doc); // commit后才保存到索引库 server.commit(); // 输出统计信息 System.out.println("Query Time:" + response.getQTime()); System.out.println("Elapsed Time:" + response.getElapsedTime()); System.out.println("Status:" + response.getStatus()); } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("--------------------------"); query("webContent:"+keyword); System.out.println("--------------------------"); } public void solrAllSearch() { String[] title = new String[] { "IK Analyzer介绍", "观前街介绍", "服务业情况", "人大动态", "高技能" }; String[] content = new String[] { "IK Analyzer是一个结合词典分词和文法分词的中文分词开源工具包。它使用了全新的正向迭代最细粒度切分算法。", "观前街实际上就是玄妙观前面的那条街,卫道观前当然也有一个观,那就是卫道", "服务业集聚区加快建设。全市完成全社会固定资产投资5265亿元,比上年增长17%", "为了提高加快立法质量和实效,市人大常委会还首次开展了立法后评估工作,对《苏州市公路条例》", "继续位居动态全国地级市首位。2012年新增高技能人才7.6万人,其中新培养技师、高级技师4600人" }; Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); for (int i = 0; i < title.length; i++) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("objectId", (i + 1)); doc.addField("webTitle", title[i]); doc.addField("webContent", content[i]); doc.addField("webTime", new java.util.Date()); docs.add(doc); } try { UpdateResponse response = server.add(docs); server.commit(); } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } query("webTitle:介绍"); System.out.println("--------------------------"); } @Test public void queryCase() { // 这是一个稍复杂点的查询 server = new HttpSolrClient(PropertiesUtils.readProperty("solr_server")); SolrQuery params = new SolrQuery("正确答案"); // params.set("q.op", "OR"); //params.set("start", 0); //params.set("rows", 4); // params.set("fl", "*,score"); // params.setIncludeScore(true); // params.set("sort", "webTime desc"); params.setHighlight(true); // 开启高亮组件 params.addHighlightField("webTitle");// 高亮字段 params.addHighlightField("webContent");// 高亮字段 // params.set("hl.useFastVectorHighlighter", "true"); params.set("hl.fragsize", "200"); // params.setHighlightSimplePre("<SPAN class=\"red\">");// 高亮关键字前缀; // params.setHighlightSimplePost("</SPAN>");// 高亮关键字后缀 params.setHighlightSnippets(2); //结果分片数,默认为1 try { QueryResponse response = server.query(params); // 输出查询结果集 SolrDocumentList list = response.getResults(); System.out.println("总计:" + list.getNumFound() + "条,本批次:" + list.size() + "条"); for (int i = 0; i < list.size(); i++) { SolrDocument doc = list.get(i); System.out.println("webTitle:"+doc.get("webTitle")); } // 第一种:常用遍历Map方法; Map<String, Map<String, List<String>>> map = response.getHighlighting(); Iterator<String> iterator = map.keySet().iterator(); while(iterator.hasNext()) { String keyname = (String) iterator.next(); Map<String, List<String>> keyvalue = map.get(keyname); System.out.println("objectId:" + keyname); // 第二种:JDK1.5之后的新遍历Map方法。 for (Map.Entry<String, List<String>> entry : keyvalue.entrySet()) { String subkeyname = entry.getKey().toString(); List<String> subkeyvalue = entry.getValue(); System.out.print(subkeyname + ":\n"); for(String str: subkeyvalue) { System.out.print(str); } System.out.println(); } } } catch (SolrServerException e) { e.printStackTrace(); } System.out.println("--------------------------"); } public static void query(String query) { SolrQuery params = new SolrQuery(query); params.set("rows", 5); QueryResponse response = null; try { response = server.query(params); } catch (SolrServerException e) { e.printStackTrace(); } SolrDocumentList list = response.getResults(); System.out.println("总计:" + list.getNumFound() + "条,本批次:" + list.size() + "条"); for (int i = 0; i < list.size(); i++) { SolrDocument doc = list.get(i); System.out.println(doc.get("webTitle")); } } }
caomm/javaUtils
sptingboot-utils/src/main/java/com/full/cn/utils/SolrUtil.java
Java
apache-2.0
6,927
/******************************************************************************* * Copyright 2011 Clockwork * * 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. ******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.10.28 at 11:40:06 AM CEST // package nl.clockwork.mule.ebms.model.cpp.cpa; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.oasis-open.org/committees/ebxml-cppa/schema/cpp-cpa-2_0.xsd}CollaborationActivity" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="name" type="{http://www.oasis-open.org/committees/ebxml-cppa/schema/cpp-cpa-2_0.xsd}non-empty-string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "collaborationActivity" }) @XmlRootElement(name = "CollaborationActivity") public class CollaborationActivity { @XmlElement(name = "CollaborationActivity") protected CollaborationActivity collaborationActivity; @XmlAttribute(namespace = "http://www.oasis-open.org/committees/ebxml-cppa/schema/cpp-cpa-2_0.xsd") protected String name; /** * Gets the value of the collaborationActivity property. * * @return * possible object is * {@link CollaborationActivity } * */ public CollaborationActivity getCollaborationActivity() { return collaborationActivity; } /** * Sets the value of the collaborationActivity property. * * @param value * allowed object is * {@link CollaborationActivity } * */ public void setCollaborationActivity(CollaborationActivity value) { this.collaborationActivity = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
MartinMulder/ebmsadapter
src/main/java/nl/clockwork/mule/ebms/model/cpp/cpa/CollaborationActivity.java
Java
apache-2.0
3,712
package org.motovs.pubmed; import au.com.bytecode.opencsv.CSVReader; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.GZIPInputStream; import static org.elasticsearch.common.collect.Lists.newArrayList; import static org.elasticsearch.common.collect.Maps.newHashMap; /** */ public class MedlineLoader { private final BulkProcessor bulkProcessor; private final TransportClient client; private final Map<String, Float> ifMap = newHashMap(); private final File dataDir; private final ExecutorService executor; private final AtomicLong current = new AtomicLong(); public MedlineLoader(File ifFile, File dataDir, Settings settings) throws IOException { this.dataDir = dataDir; if (ifFile != null) { loadIf(ifFile); } client = new TransportClient(settings); client.addTransportAddress( new InetSocketTransportAddress( settings.get("pubmed.host", "localhost"), settings.getAsInt("pubmed.port", 9300))); bulkProcessor = BulkProcessor.builder(client, new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { System.out.println("Processed bulk " + executionId + " success"); current.addAndGet(-request.numberOfActions()); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { System.out.println("Processed bulk " + executionId + " failure" + failure); current.addAndGet(-request.numberOfActions()); } }) .setBulkActions(settings.getAsInt("pubmed.bulk.size", 1000)) .setConcurrentRequests(settings.getAsInt("pubmed.bulk.threads", 4)).build(); executor = Executors.newFixedThreadPool(settings.getAsInt("pubmed.parsing.threads", 1)); } public void loadIf(File file) throws IOException { try (CSVReader reader = new CSVReader(new FileReader(file))) { String[] headers = reader.readNext(); if (headers == null) { return; } String[] line; while ((line = reader.readNext()) != null) { for(int i=1; i<line.length; i++) { ifMap.put(line[0] + "-" + headers[i], parseFloat(line[i])); } } } } public float parseFloat(String str) { try { return Float.parseFloat(str); } catch (NumberFormatException ex) { return 0.0f; } } public void process(int skip) throws Exception { processDirectory(dataDir, skip); executor.shutdown(); executor.awaitTermination(10, TimeUnit.DAYS); bulkProcessor.flush(); while (current.get() > 0) { Thread.sleep(100); } bulkProcessor.close(); bulkProcessor.awaitClose(10, TimeUnit.MINUTES); client.close(); } private void processDirectory(File file, final int skip) throws Exception { final File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.endsWith(".xml.gz")) { int len = name.length(); String num = name.substring(len - 11, len - 7); return Integer.parseInt(num) > skip; } return false; } }); for (int i = 0; i < files.length; i++) { final int cur = i; if (files[cur].isFile()) { if (executor != null) { executor.execute(new Runnable() { @Override public void run() { try { System.out.println(files[cur]); processFile(files[cur]); } catch (Exception ex) { System.out.println(files[cur] + " " + ex); } } }); } else { try { System.out.println(files[cur]); processFile(files[cur]); } catch (Exception ex) { System.out.println(files[cur] + " " + ex); } } } else if (files[i].isDirectory()) { processDirectory(files[i], skip); } } } private float impactFactor(String str, int year) { Float impactFactor = ifMap.get(str.toUpperCase() + "-" + year + " Impact Factor"); if (impactFactor == null) { return 0.0f; } else { return impactFactor; } } public void processFile(File file) throws IOException, SAXException, ParserConfigurationException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); try (InputStream fileStream = new FileInputStream(file)) { InputStream gzipStream = new GZIPInputStream(fileStream); saxParser.parse(gzipStream, new DefaultHandler() { private LinkedList<String> currentName = new LinkedList<>(); String id; int year; String journalTitle; String journalAbbrTitle; String articleTitle; String abstractText; ArrayList<String> headingDescriptions; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("MedlineCitation")) { id = null; year = 0; journalTitle = null; journalAbbrTitle = null; articleTitle = null; abstractText = null; headingDescriptions = newArrayList(); } currentName.push(localName); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("MedlineCitation")) { Float factor = null; if (journalAbbrTitle != null) { factor = impactFactor(journalAbbrTitle.toUpperCase(), year); } if (factor == null) { factor = 0f; } IndexRequestBuilder indexRequestBuilder = new IndexRequestBuilder(client) .setId(id) .setSource("id", id, "year", year, "journal", journalTitle, "journal-abbr", journalAbbrTitle, "title", articleTitle, "abstract", abstractText, "keyword", headingDescriptions, "if", factor) .setIndex("pubmed") .setType("article"); bulkProcessor.add(indexRequestBuilder.request()); current.incrementAndGet(); } currentName.pop(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { String current = currentName.peek(); String prev = currentName.get(1); if (current.equals("Title") && journalTitle == null) { journalTitle = new String(ch, start, length); } else if (prev.equals("PubDate") && current.equals("Year") && year == 0) { year = Integer.parseInt(new String(ch, start, length)); } else if (current.equals("ISOAbbreviation") && journalAbbrTitle == null) { journalAbbrTitle = new String(ch, start, length); } else if (current.equals("ArticleTitle") && articleTitle == null) { articleTitle = new String(ch, start, length); } else if (current.equals("AbstractText") && abstractText == null) { abstractText = new String(ch, start, length); } else if (current.equals("DescriptorName")) { headingDescriptions.add(new String(ch, start, length)); } else if (current.equals("PMID") && id == null) { id = new String(ch, start, length); } } }); } } }
imotov/pubmed-loader
src/main/java/org/motovs/pubmed/MedlineLoader.java
Java
apache-2.0
10,049
/* * Copyright 2010 Media Service Provider Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License./* * */ package org.apache.commons.daemon; /** * Throw this during init if you can't initialise yourself for some expected * reason. Using this exception will cause the exception's message to come out * on stdout, rather than a dirty great stacktrace. * @author Nick Griffiths ([email protected]) * @version $Id$ */ public class DaemonInitException extends Exception { private static final long serialVersionUID = 5665891535067213551L; // don't rely on Throwable#getCause (jdk1.4) private final Throwable cause; public DaemonInitException(String message) { super(message); this.cause = null; } public DaemonInitException(String message, Throwable cause) { super(message); this.cause = cause; } public String getMessageWithCause() { String extra = this.cause == null ? "" : ": " + this.cause.getMessage(); return getMessage() + extra; } }
mohanaraosv/commons-daemon
src/main/java/org/apache/commons/daemon/DaemonInitException.java
Java
apache-2.0
1,557
package com.jsteamkit.steam; import com.google.protobuf.ByteString; import com.jsteamkit.cm.CMServer; import com.jsteamkit.cm.CMServerList; import com.jsteamkit.event.EventHandler; import com.jsteamkit.event.EventListener; import com.jsteamkit.internals.messages.MsgChannelEncryptRequest; import com.jsteamkit.internals.messages.MsgChannelEncryptResponse; import com.jsteamkit.internals.messages.MsgChannelEncryptResult; import com.jsteamkit.internals.net.TcpConnection; import com.jsteamkit.internals.proto.SteammessagesBase; import com.jsteamkit.internals.proto.SteammessagesClientserver2; import com.jsteamkit.internals.proto.SteammessagesClientserverLogin; import com.jsteamkit.internals.steamlanguage.EAccountType; import com.jsteamkit.internals.steamlanguage.EMsg; import com.jsteamkit.internals.steamlanguage.EResult; import com.jsteamkit.internals.steamlanguage.EUniverse; import com.jsteamkit.internals.steamlanguageinternal.Msg; import com.jsteamkit.internals.steamlanguageinternal.MsgHeader; import com.jsteamkit.internals.steamlanguageinternal.MsgHeaderProtoBuf; import com.jsteamkit.internals.steamlanguageinternal.MsgProtoBuf; import com.jsteamkit.internals.stream.BinaryReader; import com.jsteamkit.steam.guard.SteamAuthenticator; import com.jsteamkit.util.CryptoUtil; import com.jsteamkit.util.PublicKeys; import com.jsteamkit.util.ZipUtil; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; public class SteamClient { private TcpConnection connection; private EUniverse connectedUniverse = EUniverse.Invalid; private long steamId; private Map<EMsg, EventListener> eventListeners = new HashMap<>(); private Timer heartBeatTimer; public SteamClient() { this.registerEventHandler(EMsg.ChannelEncryptRequest, (d) -> { MsgChannelEncryptRequest body = new MsgChannelEncryptRequest(); try { new Msg(new MsgHeader(), body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(MessageFormat.format("Received encryption request. Universe: {0}, Protocol version: {1}", body.universe, body.protocolVersion)); BigInteger[] keys = PublicKeys.keys.get(connectedUniverse = body.universe); if (keys != null) { connection.sessionKey = CryptoUtil.getRandomBytes(32); try { MsgHeader replyHeader = new MsgHeader(); replyHeader.msg = EMsg.ChannelEncryptResponse; MsgChannelEncryptResponse replyBody = new MsgChannelEncryptResponse(); Msg replyMsg = new Msg(replyHeader, replyBody); byte[] encryptedSessionKey = CryptoUtil.encryptWithRsa(connection.sessionKey, keys[0], keys[1]); byte[] sessionKeyCrc = CryptoUtil.getCrcHash(encryptedSessionKey); replyMsg.writer.write(encryptedSessionKey); replyMsg.writer.write(sessionKeyCrc); replyMsg.writer.write(0); byte[] encodedMsg = replyMsg.encode(); connection.sendPacket(encodedMsg); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException(e); } } else { System.out.println("Universe " + body.universe + " is not supported!"); } }); this.registerEventHandler(EMsg.ChannelEncryptResult, (d) -> { MsgChannelEncryptResult body = new MsgChannelEncryptResult(); try { new Msg(new MsgHeader(), body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(MessageFormat.format("Received encryption result. Result: {0}", body.result)); if (body.result == EResult.OK) { connection.encrypted = true; System.out.println("Successfully connected to Steam. You can now attempt to login."); } else { System.out.println(MessageFormat.format("Encryption failed. Result: {0}", body.result)); } }); this.registerEventHandler(EMsg.Multi, (d) -> { MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(); SteammessagesBase.CMsgMulti.Builder body = SteammessagesBase.CMsgMulti.newBuilder(); try { new MsgProtoBuf(header, body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } byte[] payload = body.getMessageBody().toByteArray(); if (body.getSizeUnzipped() > 0) { try { payload = ZipUtil.unzip(payload); } catch (IOException e) { throw new RuntimeException(e); } } BinaryReader reader = new BinaryReader(payload); try { while (!reader.reader.isAtEnd()) { int size = reader.readInt(); byte[] data = reader.readBytes(size); connection.handleMsg(data); } } catch (IOException e) { throw new RuntimeException(e); } }); this.registerEventHandler(EMsg.ClientLogOnResponse, (d) -> { MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(); SteammessagesClientserverLogin.CMsgClientLogonResponse.Builder body = SteammessagesClientserverLogin.CMsgClientLogonResponse.newBuilder(); try { new MsgProtoBuf(header, body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } EResult result = EResult.get(body.getEresult()); if (result == EResult.OK) { steamId = header.proto.getSteamid(); heartBeatTimer = new Timer(); heartBeatTimer.schedule(new TimerTask() { @Override public void run() { try { SteammessagesBase.CMsgProtoBufHeader.Builder proto = SteammessagesBase.CMsgProtoBufHeader.newBuilder(); MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(proto); header.msg = EMsg.ClientHeartBeat; SteammessagesClientserverLogin.CMsgClientHeartBeat.Builder body = SteammessagesClientserverLogin.CMsgClientHeartBeat.newBuilder(); MsgProtoBuf msg = new MsgProtoBuf(header, body); byte[] encodedMsg = msg.encode(); connection.sendPacket(encodedMsg); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException(e); } } }, 0, body.getOutOfGameHeartbeatSeconds() * 1000); System.out.println("Successfully logged in. Steam ID: " + steamId); } else { System.out.println("Failed login. Result: " + result); } }); this.registerEventHandler(EMsg.ClientLoggedOff, (d) -> { MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(); SteammessagesClientserverLogin.CMsgClientLoggedOff.Builder body = SteammessagesClientserverLogin.CMsgClientLoggedOff.newBuilder(); try { new MsgProtoBuf(header, body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } if (heartBeatTimer != null) { heartBeatTimer.cancel(); heartBeatTimer = null; } System.out.println("Logged out of Steam. Result: " + EResult.get(body.getEresult())); }); } public void connect(boolean verbose) throws IOException { connect(verbose, CMServerList.getBestServer()); } public void connect(boolean verbose, CMServer cmServer) throws IOException { connection = new TcpConnection() { @Override public void handleEvent(EMsg eventMsg, byte[] data) { if (verbose) { System.out.println("Received msg: " + eventMsg); } EventListener eventListener = eventListeners.get(eventMsg); if (eventListener != null) { eventListener.runHandlers(data); } } }; connection.connect(cmServer); } public void login(LoginCredentials credentials) { if (credentials.username.length() != 0 && credentials.password.length() != 0) { try { SteammessagesBase.CMsgProtoBufHeader.Builder proto = SteammessagesBase.CMsgProtoBufHeader.newBuilder(); MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(proto); header.msg = EMsg.ClientLogon; SteammessagesClientserverLogin.CMsgClientLogon.Builder body = SteammessagesClientserverLogin.CMsgClientLogon.newBuilder(); MsgProtoBuf msg = new MsgProtoBuf(header, body); proto.setSteamid(new SteamId(0, credentials.accountInstance, connectedUniverse, EAccountType.Individual).toLong()); body.setAccountName(credentials.username); body.setPassword(credentials.password); body.setProtocolVersion(65575); if (credentials.authCode.length() > 0) { body.setAuthCode(credentials.authCode); } if (credentials.authenticatorSecret.length() > 0) { SteamAuthenticator authenticator = new SteamAuthenticator(credentials.authenticatorSecret); body.setTwoFactorCode(authenticator.generateCode()); } if (credentials.acceptSentry) { Path sentryFile = Paths.get("data/sentry.bin"); if (sentryFile.toFile().exists()) { byte[] sentryBytes = Files.readAllBytes(sentryFile); byte[] shaHash = CryptoUtil.shaHash(sentryBytes); if (shaHash != null) { body.setShaSentryfile(ByteString.copyFrom(shaHash)); body.setEresultSentryfile(EResult.OK.getCode()); } } else { body.clearShaSentryfile(); body.setEresultSentryfile(EResult.FileNotFound.getCode()); } registerSentryListener(); } byte[] encodedMsg = msg.encode(); connection.sendPacket(encodedMsg); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException(e); } } else { System.out.println("A username and password must be specified in order to login."); } } private void registerSentryListener() { this.registerEventHandler(EMsg.ClientUpdateMachineAuth, (d) -> { MsgHeaderProtoBuf header = new MsgHeaderProtoBuf(); SteammessagesClientserver2.CMsgClientUpdateMachineAuth.Builder body = SteammessagesClientserver2.CMsgClientUpdateMachineAuth.newBuilder(); try { new MsgProtoBuf(header, body).decode(d); } catch (IOException e) { throw new RuntimeException(e); } Path sentryFile = Paths.get("data/sentry.bin"); byte[] sentryBytes = body.getBytes().toByteArray(); try { Files.createDirectories(sentryFile.getParent()); Files.write(sentryFile, sentryBytes); } catch (IOException e) { throw new RuntimeException(e); } SteammessagesBase.CMsgProtoBufHeader.Builder proto = SteammessagesBase.CMsgProtoBufHeader.newBuilder(); MsgHeaderProtoBuf responseHeader = new MsgHeaderProtoBuf(proto); responseHeader.msg = EMsg.ClientUpdateMachineAuthResponse; SteammessagesClientserver2.CMsgClientUpdateMachineAuthResponse.Builder responseBody = SteammessagesClientserver2.CMsgClientUpdateMachineAuthResponse.newBuilder(); MsgProtoBuf msg = new MsgProtoBuf(responseHeader, responseBody); proto.setSteamid(steamId); proto.setJobidTarget(header.proto.getJobidSource()); responseBody.setFilenameBytes(body.getFilenameBytes()); responseBody.setFilesize(sentryBytes.length); byte[] shaHash = CryptoUtil.shaHash(sentryBytes); responseBody.setShaFile(ByteString.copyFrom(shaHash)); responseBody.setCubwrote(body.getCubtowrite()); responseBody.setOffset(body.getOffset()); responseBody.setEresult(EResult.OK.getCode()); responseBody.setGetlasterror(0); responseBody.setOtpType(body.getOtpType()); responseBody.setOtpValue(0); responseBody.setOtpIdentifierBytes(body.getOtpIdentifierBytes()); try { byte[] encodedMsg = msg.encode(); connection.sendPacket(encodedMsg); System.out.println("Successfully updated sentry file for machine authentication."); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException(e); } }); } public void registerEventHandler(EMsg eventMsg, EventHandler eventHandler) { EventListener eventListener = eventListeners.get(eventMsg); if (eventListener == null) { eventListener = new EventListener(); eventListeners.put(eventMsg, eventListener); } eventListener.registerHandler(eventHandler); } public TcpConnection getConnection() { return connection; } public EUniverse getConnectedUniverse() { return connectedUniverse; } public long getSteamId() { return steamId; } }
UniquePassive/JSteamKit
src/main/java/com/jsteamkit/steam/SteamClient.java
Java
apache-2.0
14,856
package org.arquillian.cube.kubernetes.api; import java.net.URL; import java.util.List; import java.util.Map; import io.fabric8.kubernetes.api.model.HasMetadata; public interface ResourceInstaller extends WithToImmutable<ResourceInstaller> { /** * Installs the resources found in the specified URL. * @param url The URL to read resources from. * @return The list with the created resources. */ List<HasMetadata> install(URL url); /** * Uninstalls the resources found in the specified URL. * @param url The URL to read resources from. * @return A map of the resources to their delete status. */ Map<HasMetadata, Boolean> uninstall(URL url); /** * Uninstalls the resources found in the specified list. * @param list The list with the resources. * @return A map of the resources to their delete status. */ Map<HasMetadata, Boolean> uninstall(List<HasMetadata> list); }
lordofthejars/arquillian-cube
kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/api/ResourceInstaller.java
Java
apache-2.0
985
/* * Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.datastore.id; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Collection; import java.util.Set; import org.junit.Test; import com.b2international.snowowl.core.terminology.ComponentCategory; import com.b2international.snowowl.snomed.cis.ISnomedIdentifierService; import com.b2international.snowowl.snomed.cis.domain.IdentifierStatus; import com.b2international.snowowl.snomed.cis.domain.SctId; import com.b2international.snowowl.snomed.common.SnomedConstants.Concepts; import com.google.common.collect.Sets; /** * @since 4.5 */ public abstract class AbstractIdentifierServiceTest { protected static final String B2I_NAMESPACE = Concepts.B2I_NAMESPACE; protected abstract ISnomedIdentifierService getIdentifierService(); @Test public void whenGeneratingIds_ThenItShouldReturnTheGeneratedIds() { final Set<String> componentIds = Sets.newHashSet(); try { componentIds.addAll(getIdentifierService().generate(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2)); assertTrue(String.format("Component IDs size is %d instead of 2.", componentIds.size()), componentIds.size() == 2); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be assigned", IdentifierStatus.ASSIGNED.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } finally { if (!componentIds.isEmpty()) getIdentifierService().release(componentIds); } } @Test public void whenReservingIds_ThenItShouldReturnTheReservedIds() { final Set<String> componentIds = Sets.newHashSet(); try { componentIds.addAll(getIdentifierService().reserve(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2)); assertTrue(String.format("Component IDs size is %d instead of 2.", componentIds.size()), componentIds.size() == 2); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be reserved", IdentifierStatus.RESERVED.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } finally { if (!componentIds.isEmpty()) getIdentifierService().release(componentIds); } } @Test public void whenRegisteringReservedIds_ThenTheyShouldBeRegistered() { final Set<String> componentIds = Sets.newHashSet(); try { componentIds.addAll(getIdentifierService().reserve(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2)); assertTrue(String.format("Component IDs size is %d instead of 2.", componentIds.size()), componentIds.size() == 2); getIdentifierService().register(componentIds); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be assigned", IdentifierStatus.ASSIGNED.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } finally { if (!componentIds.isEmpty()) getIdentifierService().release(componentIds); } } @Test public void whenReleasingReservedIds_ThenTheyShouldBeAvailable() { try { final Set<String> componentIds = getIdentifierService().reserve(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2); getIdentifierService().register(componentIds); getIdentifierService().release(componentIds); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be available", IdentifierStatus.AVAILABLE.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } } @Test public void whenPublishingAssignedIds_ThenTheyShouldBePublished() { try { final Set<String> componentIds = getIdentifierService().generate(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2); getIdentifierService().publish(componentIds); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be published", IdentifierStatus.PUBLISHED.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } } @Test public void whenDeprecatingAssignedIds_ThenTheyShouldBeDeprecated() { try { final Set<String> componentIds = getIdentifierService().generate(B2I_NAMESPACE, ComponentCategory.CONCEPT, 2); getIdentifierService().deprecate(componentIds); final Collection<SctId> sctIds = getIdentifierService().getSctIds(componentIds).values(); for (final SctId sctId : sctIds) { assertTrue("Status must be deprecated", IdentifierStatus.DEPRECATED.getSerializedName().equals(sctId.getStatus())); } } catch (Exception e) { fail(String.format("Unexpected exception was thrown: %s.", e.getMessage())); } } }
b2ihealthcare/snow-owl
snomed/com.b2international.snowowl.snomed.datastore.tests/src/com/b2international/snowowl/snomed/datastore/id/AbstractIdentifierServiceTest.java
Java
apache-2.0
5,868
package org.towerhawk.monitor.descriptors; import org.towerhawk.monitor.schedule.ScheduleCollector; public interface Schedulable { ScheduleCollector getScheduleCollector(); }
tower-hawk/tower-hawk
api/src/main/java/org/towerhawk/monitor/descriptors/Schedulable.java
Java
apache-2.0
179
/******************************************************************************* * * This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim> * for the latest version of iBioSim. * * Copyright (C) 2017 University of Utah * * This library is free software; you can redistribute it and/or modify it * under the terms of the Apache License. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online at <http://www.async.ece.utah.edu/ibiosim/License>. * *******************************************************************************/ package edu.utah.ece.async.lema.verification.platu.common; import java.util.*; import edu.utah.ece.async.lema.verification.platu.MDD.*; import edu.utah.ece.async.lema.verification.platu.main.Options; /** * * * @author * @author Chris Myers * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a> * @version %I% */ public class MddTable extends SetIntTuple { protected Mdd mddMgr = null; mddNode ReachSet; mddNode buffer; long nextMemUpBound; int Size; static boolean UseBuffer = true; static boolean MDDBUF_MODE = true; static int gcIntervalMin = 0; public MddTable(int TupleLength) { mddMgr = new Mdd(TupleLength*4); this.ReachSet = null; if (UseBuffer == true) this.buffer = Mdd.newNode(); else this.buffer = null; nextMemUpBound = 500000000; this.Size = 0; MddTable.MDDBUF_MODE = Options.getStateFormat() == "mddbuf"; } @Override public int add(int[] IntArray) { long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); //int[] byteVec = toByteArray(IntArray); int[] byteVec = MddTable.encode(IntArray); if(MddTable.UseBuffer == true && MddTable.MDDBUF_MODE==true) { mddMgr.add(this.buffer, byteVec, false); boolean overThreshold = (Options.getMemUpperBound() - curUsedMem / 1000000) < 200; if (overThreshold) { mddMgr.compress(this.buffer); if (this.ReachSet == null) this.ReachSet = this.buffer; else { mddNode newReachSet = mddMgr.union(this.ReachSet, this.buffer); if (newReachSet != this.ReachSet) { mddMgr.remove(this.ReachSet); this.ReachSet = newReachSet; } if (newReachSet != this.ReachSet) { mddMgr.remove(this.ReachSet); this.ReachSet = newReachSet; } } mddMgr.remove(this.buffer); this.buffer = Mdd.newNode(); Runtime.getRuntime().gc(); MddTable.UseBuffer = false; System.out.println("*** stop buffering"); } } else { if(this.ReachSet==null) this.ReachSet = Mdd.newNode(); mddMgr.add(this.ReachSet, byteVec, true); if((Options.getMemUpperBound() - curUsedMem / 1000000) > 400) MddTable.UseBuffer = true; } this.Size++; return 0; } @Override public boolean contains(int[] IntArray) { //int[] byteVec = toByteArray(IntArray); int[] byteVec = MddTable.encode(IntArray); boolean existing = Mdd.contains(this.ReachSet, byteVec); if (existing == true) return true; if (this.buffer != null) return Mdd.contains(this.buffer, byteVec); return false; } @Override public int size() { return this.Size; } @Override public String stats() { return "State count: " + this.Size + ", " + "MDD node count: " + this.mddMgr.nodeCnt(); } /* * Utilities for search functions */ private static int[] toIntArray(int i) { int[] charArray = new int[4]; int mask = 0x000000FF; for (int iter = 0; iter < 4; iter++) { charArray[3 - iter] = (i & mask); i = i >> 8; } return charArray; } @SuppressWarnings("unused") private static int[] toByteArray(int[] intVec) { //System.out.println(Arrays.toString(intVec)); int[] byteArray = new int[intVec.length*4]; int offset = intVec.length; int zeros = 0; for (int i = 0; i < intVec.length; i++) { int[] result = toIntArray(intVec[i]); byteArray[i] = result[0]; if(byteArray[i] == 0) zeros++; byteArray[offset+i] = result[1]; byteArray[offset*2 + i] = result[2]; byteArray[offset*3 + i] = result[3]; } int firstNonZero = 0; for(int i = 0; i < intVec.length*4; i++) if(byteArray[i] != 0) { firstNonZero = i; break; } int[] byteArray1 = byteArray; if(firstNonZero > 0) { int[] result = new int[intVec.length*4 - firstNonZero]; for(int i = 0; i < result.length; i++) result[i] = byteArray[i+firstNonZero]; byteArray1 = result; } //System.out.println(Arrays.toString(byteArray1)+"\n-----------------------------------------------"); return byteArray; } private static int[] encode(int[] intVec) { int[] codeArray = new int[intVec.length*2]; int offset = intVec.length; for (int i = 0; i < intVec.length; i++) { int remainder = intVec[i] & 0x000003FF; int quotient = intVec[i] >> 10; codeArray[i] = quotient; codeArray[offset+i] = remainder; } // System.out.println(Arrays.toString(intVec) + "\n--------------" + // Arrays.toString(codeArray)); return codeArray; } @SuppressWarnings("unused") private static HashSet<IntArrayObj> decompose(int[] IntArray) { HashSet<IntArrayObj> result = new HashSet<IntArrayObj>(); for (int i = 1; i < IntArray.length-1; i++) { for (int ii = i+1; ii < IntArray.length; ii++) { int[] tmp = new int[3]; tmp[0] = IntArray[0]; tmp[1] = IntArray[i]; tmp[2] = IntArray[ii]; result.add(new IntArrayObj(tmp)); } } return result; } }
MyersResearchGroup/iBioSim
verification/src/main/java/edu/utah/ece/async/lema/verification/platu/common/MddTable.java
Java
apache-2.0
5,548
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202202; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Lists all errors associated with performing actions on {@link Proposal} objects. * * * <p>Java class for ProposalActionError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ProposalActionError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202202}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v202202}ProposalActionError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProposalActionError", propOrder = { "reason" }) public class ProposalActionError extends ApiError { @XmlSchemaType(name = "string") protected ProposalActionErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link ProposalActionErrorReason } * */ public ProposalActionErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link ProposalActionErrorReason } * */ public void setReason(ProposalActionErrorReason value) { this.reason = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202202/ProposalActionError.java
Java
apache-2.0
2,335
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2014.03.23 at 01:49:06 PM CET // package org.sdmx.resources.sdmxml.schemas.v2_0.common; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * MemberValue specifies the value of the specified component, which must be a valid value as described in the appropriate structure definition (key family). * * <p>Java class for MemberValueType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MemberValueType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Value" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MemberValueType", propOrder = { "value" }) public class MemberValueType { @XmlElement(name = "Value", required = true) protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } }
culmat/sdmx
src/main/java/org/sdmx/resources/sdmxml/schemas/v2_0/common/MemberValueType.java
Java
apache-2.0
1,938
package fr.icam.emit.services.symbols; import java.sql.ResultSet; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import fr.icam.emit.entities.Symbol; public class Lister extends fr.icam.emit.services.commons.Lister<Symbol> { private static final long serialVersionUID = 201711161140001L; @Override protected List<Symbol> doMap(HttpServletRequest request, ResultSet resultSet) throws Exception { List<Symbol> items = new LinkedList<Symbol>(); while (resultSet.next()) { String name = resultSet.getString("name"); String html = resultSet.getString("html"); Symbol item = new Symbol(name, html); items.add(item); } return items; } }
JeromeRocheteau/emit
emit-monitoring/emit-services/src/main/java/fr/icam/emit/services/symbols/Lister.java
Java
apache-2.0
772
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.multimap; import com.hazelcast.config.MultiMapConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.internal.util.Clock; import com.hazelcast.map.LocalMapStats; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class LocalMultiMapStatsTest extends HazelcastTestSupport { private static final int OPERATION_COUNT = 10; private HazelcastInstance instance; private String mapName = "mapName"; private String mapNameSet = "mapNameSet"; @Before public void setUp() { MultiMapConfig multiMapConfig1 = new MultiMapConfig() .setName(mapName) .setValueCollectionType(MultiMapConfig.ValueCollectionType.LIST); MultiMapConfig multiMapConfig2 = new MultiMapConfig() .setName(mapNameSet) .setValueCollectionType(MultiMapConfig.ValueCollectionType.SET); instance = createHazelcastInstance(getConfig() .addMultiMapConfig(multiMapConfig1) .addMultiMapConfig(multiMapConfig2)); } protected LocalMultiMapStats getMultiMapStats() { return getMultiMapStats(mapName); } protected LocalMultiMapStats getMultiMapStats(String multiMapName) { return instance.getMultiMap(multiMapName).getLocalMultiMapStats(); } protected <K, V> MultiMap<K, V> getMultiMap() { return getMultiMap(mapName); } protected <K, V> MultiMap<K, V> getMultiMap(String multiMapName) { warmUpPartitions(instance); return instance.getMultiMap(multiMapName); } @Test public void testHitsGenerated() { MultiMap<Integer, Integer> map = getMultiMap(); for (int i = 0; i < 100; i++) { map.put(i, i); map.get(i); } LocalMapStats localMapStats = getMultiMapStats(); assertEquals(100, localMapStats.getHits()); } @Test public void testPutAndHitsGenerated() { MultiMap<Integer, Integer> map = getMultiMap(); for (int i = 0; i < 100; i++) { map.put(i, i); map.get(i); } LocalMapStats localMapStats = getMultiMapStats(); assertEquals(100, localMapStats.getPutOperationCount()); assertEquals(100, localMapStats.getHits()); } public void testPutAllAndHitsGeneratedTemplate(Map<Integer, Collection<? extends Integer>> expectedMultiMap, Consumer<MultiMap<Integer, Integer>> putAllOperation) { MultiMap<Integer, Integer> mmap1 = getMultiMap(); MultiMap<Integer, Integer> mmap2 = getMultiMap(mapNameSet); for (int i = 0; i < 100; i++) { expectedMultiMap.put(i, new ArrayList<>(Arrays.asList(1, 1, 1))); } putAllOperation.accept(mmap1); putAllOperation.accept(mmap2); for (int i = 0; i < 100; i++) { int index = i; assertTrueEventually(() -> assertTrue(mmap1.get(index).size() > 0)); assertTrueEventually(() -> assertTrue(mmap2.get(index).size() > 0)); } testPutAllAndHitsGeneratedTemplateVerify(); } public void testPutAllAndHitsGeneratedTemplateVerify() { LocalMapStats localMapStats1 = getMultiMapStats(); LocalMapStats localMapStats2 = getMultiMapStats(mapNameSet); assertEquals(300, localMapStats1.getOwnedEntryCount()); assertEquals(100, localMapStats1.getPutOperationCount()); assertEquals(100, localMapStats1.getHits()); assertEquals(100, localMapStats2.getOwnedEntryCount()); assertEquals(100, localMapStats2.getPutOperationCount()); assertEquals(100, localMapStats2.getHits()); } @Test public void testPutAllAndHitsGeneratedMap() { Map<Integer, Collection<? extends Integer>> expectedMultiMap = new HashMap<>(); testPutAllAndHitsGeneratedTemplate(expectedMultiMap, (o) -> { o.putAllAsync(expectedMultiMap); } ); } @Test public void testPutAllAndHitsGeneratedKey() { Map<Integer, Collection<? extends Integer>> expectedMultiMap = new HashMap<>(); testPutAllAndHitsGeneratedTemplate(expectedMultiMap, (o) -> { for (int i = 0; i < 100; ++i) { o.putAllAsync(i, expectedMultiMap.get(i)); } } ); } @Test public void testGetAndHitsGenerated() { MultiMap<Integer, Integer> map = getMultiMap(); for (int i = 0; i < 100; i++) { map.put(i, i); map.get(i); } LocalMapStats localMapStats = getMultiMapStats(); assertEquals(100, localMapStats.getGetOperationCount()); assertEquals(100, localMapStats.getHits()); } @Test public void testDelete() { MultiMap<Integer, Integer> map = getMultiMap(); for (int i = 0; i < 100; i++) { map.put(i, i); map.delete(i); } LocalMapStats localMapStats = getMultiMapStats(); assertEquals(100, localMapStats.getRemoveOperationCount()); } @Test public void testRemove() { MultiMap<Integer, Integer> map = getMultiMap(); for (int i = 0; i < 100; i++) { map.put(i, i); map.remove(i); } LocalMapStats localMapStats = getMultiMapStats(); assertEquals(100, localMapStats.getRemoveOperationCount()); } @Test public void testHitsGenerated_updatedConcurrently() { final MultiMap<Integer, Integer> map = getMultiMap(); final int actionCount = 100; for (int i = 0; i < actionCount; i++) { map.put(i, i); map.get(i); } final LocalMapStats localMapStats = getMultiMapStats(); final long initialHits = localMapStats.getHits(); new Thread(() -> { for (int i = 0; i < actionCount; i++) { map.get(i); } getMultiMapStats(); // causes the local stats object to update }).start(); assertEquals(actionCount, initialHits); assertTrueEventually(() -> assertEquals(actionCount * 2, localMapStats.getHits())); } @Test public void testLastAccessTime() throws InterruptedException { final long startTime = Clock.currentTimeMillis(); MultiMap<String, String> map = getMultiMap(); String key = "key"; map.put(key, "value"); map.get(key); long lastAccessTime = getMultiMapStats().getLastAccessTime(); assertTrue(lastAccessTime >= startTime); Thread.sleep(5); map.put(key, "value2"); long lastAccessTime2 = getMultiMapStats().getLastAccessTime(); assertTrue(lastAccessTime2 > lastAccessTime); } @Test public void testLastAccessTime_updatedConcurrently() { final long startTime = Clock.currentTimeMillis(); final MultiMap<String, String> map = getMultiMap(); final String key = "key"; map.put(key, "value"); map.put(key, "value"); final LocalMapStats localMapStats = getMultiMapStats(); final long lastUpdateTime = localMapStats.getLastUpdateTime(); new Thread(() -> { sleepAtLeastMillis(1); map.put(key, "value2"); getMultiMapStats(); // causes the local stats object to update }).start(); assertTrue(lastUpdateTime >= startTime); assertTrueEventually(() -> assertTrue(localMapStats.getLastUpdateTime() > lastUpdateTime)); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_containsKey() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.containsKey(i); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_entrySet() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.entrySet(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_keySet() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.keySet(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test public void testOtherOperationCount_localKeySet() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.localKeySet(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_values() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.values(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_clear() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.clear(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_containsValue() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.containsValue(1); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test @Ignore("GH issue 15307") public void testOtherOperationCount_size() { MultiMap map = getMultiMap(); for (int i = 0; i < OPERATION_COUNT; i++) { map.size(); } LocalMapStats stats = getMultiMapStats(); assertEquals(OPERATION_COUNT, stats.getOtherOperationCount()); } @Test public void testLockedEntryCount_emptyMultiMap() { MultiMap<String, String> map = getMultiMap(); map.lock("non-existent-key"); LocalMapStats stats = getMultiMapStats(); assertEquals(1, stats.getLockedEntryCount()); } @Test public void testLockedEntryCount_multiMapWithOneEntry() { MultiMap<String, String> map = getMultiMap(); map.put("key", "value"); map.lock("key"); map.lock("non-existent-key"); LocalMapStats stats = getMultiMapStats(); assertEquals(2, stats.getLockedEntryCount()); } }
emre-aydin/hazelcast
hazelcast/src/test/java/com/hazelcast/multimap/LocalMultiMapStatsTest.java
Java
apache-2.0
12,306
/* * Copyright 2012 Steve Chaloner * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers; import be.objectify.deadbolt.core.PatternType; import be.objectify.deadbolt.java.actions.Pattern; import play.libs.F; import play.mvc.Controller; import play.mvc.Result; import views.html.accessOk; /** * @author Steve Chaloner ([email protected]) */ public class PatternController extends Controller { @Pattern("printers.edit") public F.Promise<Result> editPrinter() { return F.Promise.promise(() -> ok(accessOk.render())); } @Pattern("printers.detonate") public F.Promise<Result> detonatePrinter() { return F.Promise.promise(() -> ok(accessOk.render())); } @Pattern(value = "(.)*\\.edit", patternType = PatternType.REGEX) public F.Promise<Result> editPrinterRegex() { return F.Promise.promise(() -> ok(accessOk.render())); } }
play2-maven-plugin/play2-maven-test-projects
play24/external-modules/deadbolt/java/app/controllers/PatternController.java
Java
apache-2.0
1,426
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.lang.properties.create; import com.intellij.icons.AllIcons; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.properties.*; import com.intellij.lang.properties.ResourceBundle; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.xml.XmlPropertiesFile; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.*; import com.intellij.ui.components.JBList; import com.intellij.util.NotNullFunction; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.event.*; import java.util.*; /** * @author Dmitry Batkovich */ public class CreateResourceBundleDialogComponent { private final static Logger LOG = Logger.getInstance(CreateResourceBundleDialogComponent.class); private static final Comparator<Locale> LOCALE_COMPARATOR = (l1, l2) -> { if (l1 == PropertiesUtil.DEFAULT_LOCALE) { return -1; } if (l2 == PropertiesUtil.DEFAULT_LOCALE) { return 1; } return l1.toString().compareTo(l2.toString()); }; private final Project myProject; private final PsiDirectory myDirectory; private final ResourceBundle myResourceBundle; private JPanel myPanel; private JTextField myResourceBundleBaseNameTextField; private JButton myAddLocaleFromExistButton; private JPanel myNewBundleLocalesPanel; private JPanel myProjectExistLocalesPanel; private JButton myAddAllButton; private JPanel myResourceBundleNamePanel; private JCheckBox myUseXMLBasedPropertiesCheckBox; private CollectionListModel<Locale> myLocalesModel; private final Map<Locale, String> myLocaleSuffixes; // java.util.Locale is case insensitive public CreateResourceBundleDialogComponent(@NotNull Project project, PsiDirectory directory, ResourceBundle resourceBundle) { myProject = project; myDirectory = directory; myResourceBundle = resourceBundle; myLocaleSuffixes = new THashMap<>(); if (resourceBundle != null) { myResourceBundleNamePanel.setVisible(false); myUseXMLBasedPropertiesCheckBox.setVisible(false); } else { final String checkBoxSelectedStateKey = getClass() + ".useXmlPropertiesFiles"; myUseXMLBasedPropertiesCheckBox.setSelected(PropertiesComponent.getInstance().getBoolean(checkBoxSelectedStateKey)); myUseXMLBasedPropertiesCheckBox.addContainerListener(new ContainerAdapter() { @Override public void componentRemoved(ContainerEvent e) { PropertiesComponent.getInstance().setValue(checkBoxSelectedStateKey, myUseXMLBasedPropertiesCheckBox.isSelected()); } }); } } public static class Dialog extends DialogWrapper { @NotNull private final PsiDirectory myDirectory; private final CreateResourceBundleDialogComponent myComponent; private PsiElement[] myCreatedFiles; protected Dialog(@NotNull Project project, @Nullable PsiDirectory directory, @Nullable ResourceBundle resourceBundle) { super(project); if (directory == null) { LOG.assertTrue(resourceBundle != null && getResourceBundlePlacementDirectory(resourceBundle) != null); } myDirectory = directory == null ? resourceBundle.getDefaultPropertiesFile().getContainingFile().getContainingDirectory() : directory; myComponent = new CreateResourceBundleDialogComponent(project, myDirectory, resourceBundle); init(); initValidation(); setTitle(resourceBundle == null ? "Create Resource Bundle" : "Add Locales to Resource Bundle " + resourceBundle.getBaseName()); } @Override protected void doOKAction() { final String errorString = myComponent.canCreateAllFilesForAllLocales(); if (errorString != null) { Messages.showErrorDialog(getContentPanel(), errorString); } else { final List<PsiFile> createFiles = myComponent.createPropertiesFiles(); myCreatedFiles = createFiles.toArray(PsiElement.EMPTY_ARRAY); super.doOKAction(); } } @Nullable @Override protected ValidationInfo doValidate() { for (String fileName : myComponent.getFileNamesToCreate()) { if (!PathUtil.isValidFileName(fileName)) { return new ValidationInfo(String.format("File name for properties file '%s' is invalid", fileName)); } else { if (myDirectory.findFile(fileName) != null) { return new ValidationInfo(String.format("File with name '%s' already exist", fileName)); } } } return null; } @Nullable @Override protected JComponent createCenterPanel() { return myComponent.getPanel(); } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myComponent.myResourceBundleBaseNameTextField; } public PsiElement[] getCreatedFiles() { return myCreatedFiles; } } private List<PsiFile> createPropertiesFiles() { final Set<String> fileNames = getFileNamesToCreate(); final List<PsiFile> createdFiles = WriteCommandAction.runWriteCommandAction(myProject, (Computable<List<PsiFile>>)() -> ReadAction.compute(() -> ContainerUtil.map(fileNames, n -> { final boolean isXml = myResourceBundle == null ? myUseXMLBasedPropertiesCheckBox.isSelected() : myResourceBundle.getDefaultPropertiesFile() instanceof XmlPropertiesFile; if (isXml) { FileTemplate template = FileTemplateManager.getInstance(myProject).getInternalTemplate("XML Properties File.xml"); try { return (PsiFile)FileTemplateUtil.createFromTemplate(template, n, null, myDirectory); } catch (Exception e) { throw new RuntimeException(e); } } else { return myDirectory.createFile(n); } }))); combineToResourceBundleIfNeeded(createdFiles); return createdFiles; } @NotNull private Set<String> getFileNamesToCreate() { final String name = getBaseName(); final String suffix = getPropertiesFileSuffix(); return ContainerUtil.map2Set(myLocalesModel.getItems(), locale -> name + (locale == PropertiesUtil.DEFAULT_LOCALE ? "" : ("_" + myLocaleSuffixes .getOrDefault(locale, locale.toString()))) + suffix); } private void combineToResourceBundleIfNeeded(Collection<PsiFile> files) { Collection<PropertiesFile> createdFiles = ContainerUtil.map(files, (NotNullFunction<PsiFile, PropertiesFile>)dom -> { final PropertiesFile file = PropertiesImplUtil.getPropertiesFile(dom); LOG.assertTrue(file != null, dom.getName()); return file; }); ResourceBundle mainBundle = myResourceBundle; final Set<ResourceBundle> allBundles = new HashSet<>(); if (mainBundle != null) { allBundles.add(mainBundle); } boolean needCombining = false; for (PropertiesFile file : createdFiles) { final ResourceBundle rb = file.getResourceBundle(); if (mainBundle == null) { mainBundle = rb; } else if (!mainBundle.equals(rb)) { needCombining = true; } allBundles.add(rb); } if (needCombining) { final List<PropertiesFile> toCombine = new ArrayList<>(createdFiles); final String baseName = getBaseName(); if (myResourceBundle != null) { toCombine.addAll(myResourceBundle.getPropertiesFiles()); } ResourceBundleManager manager = ResourceBundleManager.getInstance(mainBundle.getProject()); for (ResourceBundle bundle : allBundles) { manager.dissociateResourceBundle(bundle); } manager.combineToResourceBundle(toCombine, baseName); } } private String getBaseName() { return myResourceBundle == null ? myResourceBundleBaseNameTextField.getText() : myResourceBundle.getBaseName(); } private String canCreateAllFilesForAllLocales() { final String name = getBaseName(); if (name.isEmpty()) { return "Base name is empty"; } final Set<String> files = getFileNamesToCreate(); if (files.isEmpty()) { return "No locales added"; } for (PsiElement element : myDirectory.getChildren()) { if (element instanceof PsiFile) { if (element instanceof PropertiesFile) { PropertiesFile propertiesFile = (PropertiesFile)element; final String propertiesFileName = propertiesFile.getName(); if (files.contains(propertiesFileName)) { return "Some of files already exist"; } } } } return null; } private String getPropertiesFileSuffix() { if (myResourceBundle == null) { return myUseXMLBasedPropertiesCheckBox.isSelected() ? ".xml" : ".properties"; } return "." + myResourceBundle.getDefaultPropertiesFile().getContainingFile().getFileType().getDefaultExtension(); } public JPanel getPanel() { return myPanel; } @Nullable private static Map<Locale, String> extractLocalesFromString(final String rawLocales) { if (rawLocales.isEmpty()) { return Collections.emptyMap(); } final String[] splitRawLocales = rawLocales.split(","); final Map<Locale, String> locales = new THashMap<>(splitRawLocales.length); for (String rawLocale : splitRawLocales) { final Pair<Locale, String> localeAndSuffix = PropertiesUtil.getLocaleAndTrimmedSuffix("_" + rawLocale + ".properties"); if (localeAndSuffix.getFirst() == PropertiesUtil.DEFAULT_LOCALE) { return null; } locales.putIfAbsent(localeAndSuffix.getFirst(), localeAndSuffix.getSecond()); } return locales; } @SuppressWarnings("unchecked") private void createUIComponents() { final JBList<Locale> projectExistLocalesList = new JBList<>(); final MyExistLocalesListModel existLocalesListModel = new MyExistLocalesListModel(); projectExistLocalesList.setModel(existLocalesListModel); projectExistLocalesList.setCellRenderer(getLocaleRenderer()); myProjectExistLocalesPanel = ToolbarDecorator.createDecorator(projectExistLocalesList) .disableRemoveAction() .disableUpDownActions() .createPanel(); myProjectExistLocalesPanel.setBorder(IdeBorderFactory.createTitledBorder("Project locales", false)); final JBList localesToAddList = new JBList(); final List<Locale> locales; final List<Locale> restrictedLocales; if (myResourceBundle == null) { locales = Collections.singletonList(PropertiesUtil.DEFAULT_LOCALE); restrictedLocales = Collections.emptyList(); } else { locales = Collections.emptyList(); restrictedLocales = ContainerUtil.map(myResourceBundle.getPropertiesFiles(), PropertiesFile::getLocale); } myLocalesModel = new CollectionListModel<Locale>(locales) { @Override public void add(@NotNull List<? extends Locale> elements) { final List<Locale> currentItems = getItems(); elements = ContainerUtil.filter(elements, locale -> !restrictedLocales.contains(locale) && !currentItems.contains(locale)); super.add(elements); } }; localesToAddList.setModel(myLocalesModel); localesToAddList.setCellRenderer(getLocaleRenderer()); localesToAddList.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { projectExistLocalesList.clearSelection(); } }); projectExistLocalesList.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { localesToAddList.clearSelection(); } }); myNewBundleLocalesPanel = ToolbarDecorator.createDecorator(localesToAddList).setAddAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { final String rawAddedLocales = Messages.showInputDialog(myProject, PropertiesBundle.message("create.resource.bundle.dialog.add.locales.validator.message"), PropertiesBundle.message("create.resource.bundle.dialog.add.locales.validator.title"), null, null, new InputValidatorEx() { @Nullable @Override public String getErrorText(String inputString) { return checkInput(inputString) ? null : "Invalid locales"; } @Override public boolean checkInput(String inputString) { return extractLocalesFromString(inputString) != null; } @Override public boolean canClose(String inputString) { return checkInput(inputString); } }); if (rawAddedLocales != null) { final Map<Locale, String> locales = extractLocalesFromString(rawAddedLocales); LOG.assertTrue(locales != null); myLocaleSuffixes.putAll(locales); myLocalesModel.add(new ArrayList<>(locales.keySet())); } } }).setAddActionName("Add locales by suffix") .disableUpDownActions().createPanel(); myNewBundleLocalesPanel.setBorder(IdeBorderFactory.createTitledBorder("Locales to add", false)); myAddLocaleFromExistButton = new JButton(AllIcons.Actions.Forward); new ClickListener(){ @Override public boolean onClick(@NotNull MouseEvent event, int clickCount) { if (clickCount == 1) { myLocalesModel.add(projectExistLocalesList.getSelectedValuesList()); return true; } return false; } }.installOn(myAddLocaleFromExistButton); projectExistLocalesList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { final List<Locale> currentItems = myLocalesModel.getItems(); for (Locale l : projectExistLocalesList.getSelectedValuesList()) { if (!restrictedLocales.contains(l) && !currentItems.contains(l)) { myAddLocaleFromExistButton.setEnabled(true); return; } } myAddLocaleFromExistButton.setEnabled(false); } }); myAddLocaleFromExistButton.setEnabled(false); myAddAllButton = new JButton("Add All"); new ClickListener() { @Override public boolean onClick(@NotNull MouseEvent event, int clickCount) { if (clickCount == 1) { myLocalesModel.add(existLocalesListModel.getLocales()); } return false; } }.installOn(myAddAllButton); } @NotNull private ColoredListCellRenderer<Locale> getLocaleRenderer() { return new ColoredListCellRenderer<Locale>() { @Override protected void customizeCellRenderer(@NotNull JList list, Locale locale, int index, boolean selected, boolean hasFocus) { if (PropertiesUtil.DEFAULT_LOCALE == locale) { append("Default locale"); } else { append(myLocaleSuffixes.getOrDefault(locale, locale.toString())); append(PropertiesUtil.getPresentableLocale(locale), SimpleTextAttributes.GRAY_ATTRIBUTES); } } }; } private class MyExistLocalesListModel extends AbstractListModel { private final List<Locale> myLocales; private MyExistLocalesListModel() { myLocales = new ArrayList<>(); myLocales.add(PropertiesUtil.DEFAULT_LOCALE); PropertiesReferenceManager.getInstance(myProject).processPropertiesFiles(GlobalSearchScope.projectScope(myProject), (baseName, propertiesFile) -> { final Locale locale = propertiesFile.getLocale(); if (locale != PropertiesUtil.DEFAULT_LOCALE && !myLocales.contains(locale)) { myLocales.add(locale); } return true; }, BundleNameEvaluator.DEFAULT); Collections.sort(myLocales, LOCALE_COMPARATOR); } @Override public int getSize() { return myLocales.size(); } @Override public Locale getElementAt(int index) { return myLocales.get(index); } public List<Locale> getLocales() { return myLocales; } } @Nullable static PsiDirectory getResourceBundlePlacementDirectory(ResourceBundle resourceBundle) { PsiDirectory containingDirectory = null; for (PropertiesFile propertiesFile : resourceBundle.getPropertiesFiles()) { if (containingDirectory == null) { containingDirectory = propertiesFile.getContainingFile().getContainingDirectory(); } else if (!containingDirectory.isEquivalentTo(propertiesFile.getContainingFile().getContainingDirectory())) { return null; } } LOG.assertTrue(containingDirectory != null); return containingDirectory; } }
leafclick/intellij-community
plugins/properties/src/com/intellij/lang/properties/create/CreateResourceBundleDialogComponent.java
Java
apache-2.0
19,582
/** * Copyright 2015 Adrien PAILHES * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adioss.nessus.rest.api; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class App { public static final String NESSUS_URL = "http://url:port"; public static final String USERNAME = "USERNAME"; public static final String PASSWORD = "PASSWORD"; public static final String ACCESS_KEY = "ACCESS_KEY"; public static final String SECRET_KEY = "SECRET_KEY"; public static void main(String... args) throws IOException { getSession(); listScans(); } /** * Example request POST with parameters (passed in the body) * POST https://url:port/session HTTP/1.1 * Accept-Encoding: gzip,deflate * Content-Type: application/x-www-form-urlencoded * Content-Length: XXX * Host: url:port * Connection: Keep-Alive * User-Agent: Apache-HttpClient/4.1.1 (java 1.5) * * @throws IOException if URL can not be resolved */ private static void getSession() throws IOException { HttpURLConnection connection = null; try { URL url = new URL(NESSUS_URL + "/session"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // write body to query String body = "username=" + USERNAME + "&password=" + PASSWORD; OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(body); writer.flush(); writer.close(); os.close(); // connect connection.connect(); // result System.out.println(connection.getResponseCode()); String result = getResult(connection); System.out.println(result); } finally { if (connection != null) { connection.disconnect(); } } } /** * Example request GET with parameters (passed as headers) * GET https://url:port/scans HTTP/1.1 * Accept-Encoding: gzip,deflate * X-ApiKeys: accessKey=titi;secretKey=toto * Host: url:port * Connection: Keep-Alive * User-Agent: Apache-HttpClient/4.1.1 (java 1.5) * * @throws IOException if URL can not be resolved */ private static void listScans() throws IOException { HttpURLConnection connection = null; String apiKeys = "accessKey=" + ACCESS_KEY + ";" + "secretKey=" + SECRET_KEY; try { URL url = new URL(NESSUS_URL + "/scans"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.addRequestProperty("X-ApiKeys", apiKeys); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // connect connection.connect(); // result System.out.println(connection.getResponseCode()); String result = getResult(connection); System.out.println(result); } finally { if (connection != null) { connection.disconnect(); } } } private static String getResult(HttpURLConnection connection) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder results = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { results.append(line); } return results.toString(); } private App() { } }
adioss/NessusRestAPISamples
src/main/java/com/adioss/nessus/rest/api/App.java
Java
apache-2.0
4,760
package com.kircherelectronics.fsensor.sensor; import com.kircherelectronics.fsensor.observer.SensorSubject; /* * Copyright 2018, Kircher Electronics, LLC * * 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. */ public interface FSensor { void register(SensorSubject.SensorObserver sensorObserver); void unregister(SensorSubject.SensorObserver sensorObserver); void start(); void stop(); void reset(); }
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java
Java
apache-2.0
932
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2013.11.29 at 12:35:53 PM GMT // package org.mule.modules.hybris.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for openingDaiesDTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="openingDaiesDTO"> * &lt;complexContent> * &lt;extension base="{}abstractCollectionDTO"> * &lt;sequence> * &lt;element ref="{}openingday" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "openingDaiesDTO", propOrder = { "openingday" }) public class OpeningDaiesDTO extends AbstractCollectionDTO { protected List<OpeningDayDTO> openingday; /** * Gets the value of the openingday property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the openingday property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOpeningday().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OpeningDayDTO } * * */ public List<OpeningDayDTO> getOpeningday() { if (openingday == null) { openingday = new ArrayList<OpeningDayDTO>(); } return this.openingday; } }
ryandcarter/hybris-connector
src/main/java/org/mule/modules/hybris/model/OpeningDaiesDTO.java
Java
apache-2.0
2,131
package com.intellij.remoteServer.util; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.remoteServer.configuration.deployment.DeploymentSource; import org.jetbrains.annotations.NotNull; /** * @author michael.golubev */ public interface CloudDeploymentNameProvider { @NotNull String getDeploymentName(@NotNull DeploymentSource deploymentSource); CloudDeploymentNameProvider DEFAULT_NAME_PROVIDER = new CloudDeploymentNameProvider() { @NotNull @Override public String getDeploymentName(@NotNull DeploymentSource deploymentSource) { return StringUtil.toLowerCase(FileUtil.sanitizeFileName(deploymentSource.getPresentableName())); } }; }
leafclick/intellij-community
platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudDeploymentNameProvider.java
Java
apache-2.0
739
package controllers; import actors.UserParentActor; import akka.NotUsed; import akka.actor.ActorRef; import akka.stream.javadsl.Flow; import com.fasterxml.jackson.databind.JsonNode; import org.slf4j.Logger; import play.libs.F.Either; import play.mvc.*; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static akka.pattern.PatternsCS.ask; /** * The main web controller that handles returning the index page, setting up a WebSocket, and watching a stock. */ @Singleton public class HomeController extends Controller { private final Duration t = Duration.of(1, ChronoUnit.SECONDS); private final Logger logger = org.slf4j.LoggerFactory.getLogger("controllers.HomeController"); private final ActorRef userParentActor; @Inject public HomeController(@Named("userParentActor") ActorRef userParentActor) { this.userParentActor = userParentActor; } public Result index(Http.Request request) { return ok(views.html.index.render(request)); } public WebSocket ws() { return WebSocket.Json.acceptOrResult(request -> { if (sameOriginCheck(request)) { final CompletionStage<Flow<JsonNode, JsonNode, NotUsed>> future = wsFutureFlow(request); final CompletionStage<Either<Result, Flow<JsonNode, JsonNode, ?>>> stage = future.thenApply(Either::Right); return stage.exceptionally(this::logException); } else { return forbiddenResult(); } }); } @SuppressWarnings("unchecked") private CompletionStage<Flow<JsonNode, JsonNode, NotUsed>> wsFutureFlow(Http.RequestHeader request) { long id = request.asScala().id(); UserParentActor.Create create = new UserParentActor.Create(Long.toString(id)); return ask(userParentActor, create, t).thenApply((Object flow) -> { final Flow<JsonNode, JsonNode, NotUsed> f = (Flow<JsonNode, JsonNode, NotUsed>) flow; return f.named("websocket"); }); } private CompletionStage<Either<Result, Flow<JsonNode, JsonNode, ?>>> forbiddenResult() { final Result forbidden = Results.forbidden("forbidden"); final Either<Result, Flow<JsonNode, JsonNode, ?>> left = Either.Left(forbidden); return CompletableFuture.completedFuture(left); } private Either<Result, Flow<JsonNode, JsonNode, ?>> logException(Throwable throwable) { logger.error("Cannot create websocket", throwable); Result result = Results.internalServerError("error"); return Either.Left(result); } /** * Checks that the WebSocket comes from the same origin. This is necessary to protect * against Cross-Site WebSocket Hijacking as WebSocket does not implement Same Origin Policy. * <p> * See https://tools.ietf.org/html/rfc6455#section-1.3 and * http://blog.dewhurstsecurity.com/2013/08/30/security-testing-html5-websockets.html */ private boolean sameOriginCheck(Http.RequestHeader rh) { final Optional<String> origin = rh.header("Origin"); if (! origin.isPresent()) { logger.error("originCheck: rejecting request because no Origin header found"); return false; } else if (originMatches(origin.get())) { logger.debug("originCheck: originValue = " + origin); return true; } else { logger.error("originCheck: rejecting request because Origin header value " + origin + " is not in the same origin: " + String.join(", ", validOrigins)); return false; } } private List<String> validOrigins = Arrays.asList("localhost:9000", "localhost:19001"); private boolean originMatches(String actualOrigin) { return validOrigins.stream().anyMatch(actualOrigin::contains); } }
play2-maven-plugin/play2-maven-test-projects
play27/java/websocket-example-using-sbtweb/app/controllers/HomeController.java
Java
apache-2.0
4,114
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.core; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.BlockStoreException; import com.google.bitcoin.store.MemoryBlockStore; import org.junit.Before; import org.junit.Test; import java.math.BigInteger; import static com.google.bitcoin.core.TestUtils.createFakeBlock; import static com.google.bitcoin.core.TestUtils.createFakeTx; import static com.google.bitcoin.core.Utils.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class WalletTest { static final NetworkParameters params = NetworkParameters.unitTests(); private Address myAddress; private Wallet wallet; private BlockStore blockStore; private ECKey myKey; @Before public void setUp() throws Exception { myKey = new ECKey(); myAddress = myKey.toAddress(params); wallet = new Wallet(params); wallet.addKey(myKey); blockStore = new MemoryBlockStore(params); } @Test public void basicSpending() throws Exception { // We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change. BigInteger v1 = Utils.toNanoCoins(1, 0); Transaction t1 = createFakeTx(params, v1, myAddress); wallet.receive(t1, null, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(v1, wallet.getBalance()); ECKey k2 = new ECKey(); BigInteger v2 = toNanoCoins(0, 50); Transaction t2 = wallet.createSend(k2.toAddress(params), v2); // Do some basic sanity checks. assertEquals(1, t2.inputs.size()); assertEquals(myAddress, t2.inputs.get(0).getScriptSig().getFromAddress()); // We have NOT proven that the signature is correct! } @Test public void sideChain() throws Exception { // The wallet receives a coin on the main chain, then on a side chain. Only main chain counts towards balance. BigInteger v1 = Utils.toNanoCoins(1, 0); Transaction t1 = createFakeTx(params, v1, myAddress); wallet.receive(t1, null, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(v1, wallet.getBalance()); BigInteger v2 = toNanoCoins(0, 50); Transaction t2 = createFakeTx(params, v2, myAddress); wallet.receive(t2, null, BlockChain.NewBlockType.SIDE_CHAIN); assertEquals(v1, wallet.getBalance()); } @Test public void listeners() throws Exception { final Transaction fakeTx = createFakeTx(params, Utils.toNanoCoins(1, 0), myAddress); final boolean[] didRun = new boolean[1]; WalletEventListener listener = new WalletEventListener() { public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { assertTrue(prevBalance.equals(BigInteger.ZERO)); assertTrue(newBalance.equals(Utils.toNanoCoins(1, 0))); assertEquals(tx, fakeTx); // Same object. assertEquals(w, wallet); // Same object. didRun[0] = true; } }; wallet.addEventListener(listener); wallet.receive(fakeTx, null, BlockChain.NewBlockType.BEST_CHAIN); assertTrue(didRun[0]); } @Test public void balance() throws Exception { // Receive 5 coins then half a coin. BigInteger v1 = toNanoCoins(5, 0); BigInteger v2 = toNanoCoins(0, 50); Transaction t1 = createFakeTx(params, v1, myAddress); Transaction t2 = createFakeTx(params, v2, myAddress); StoredBlock b1 = createFakeBlock(params, blockStore, t1).storedBlock; StoredBlock b2 = createFakeBlock(params, blockStore, t2).storedBlock; BigInteger expected = toNanoCoins(5, 50); wallet.receive(t1, b1, BlockChain.NewBlockType.BEST_CHAIN); wallet.receive(t2, b2, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(expected, wallet.getBalance()); // Now spend one coin. BigInteger v3 = toNanoCoins(1, 0); Transaction spend = wallet.createSend(new ECKey().toAddress(params), v3); wallet.confirmSend(spend); // Available and estimated balances should not be the same. We don't check the exact available balance here // because it depends on the coin selection algorithm. assertEquals(toNanoCoins(4, 50), wallet.getBalance(Wallet.BalanceType.ESTIMATED)); assertFalse(wallet.getBalance(Wallet.BalanceType.AVAILABLE).equals( wallet.getBalance(Wallet.BalanceType.ESTIMATED))); // Now confirm the transaction by including it into a block. StoredBlock b3 = createFakeBlock(params, blockStore, spend).storedBlock; wallet.receive(spend, b3, BlockChain.NewBlockType.BEST_CHAIN); // Change is confirmed. We started with 5.50 so we should have 4.50 left. BigInteger v4 = toNanoCoins(4, 50); assertEquals(v4, wallet.getBalance(Wallet.BalanceType.AVAILABLE)); } // Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an // identical result to the official client. However the signatures are not deterministic - signing the same data // with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test // suite. @Test public void blockChainCatchup() throws Exception { Transaction tx1 = createFakeTx(params, Utils.toNanoCoins(1, 0), myAddress); StoredBlock b1 = createFakeBlock(params, blockStore, tx1).storedBlock; wallet.receive(tx1, b1, BlockChain.NewBlockType.BEST_CHAIN); // Send 0.10 to somebody else. Transaction send1 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 10), myAddress); // Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we // want to get back to our previous state. We can do this by just not confirming the transaction as // createSend is stateless. StoredBlock b2 = createFakeBlock(params, blockStore, send1).storedBlock; wallet.receive(send1, b2, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(bitcoinValueToFriendlyString(wallet.getBalance()), "0.90"); // And we do it again after the catchup. Transaction send2 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 10), myAddress); // What we'd really like to do is prove the official client would accept it .... no such luck unfortunately. wallet.confirmSend(send2); StoredBlock b3 = createFakeBlock(params, blockStore, send2).storedBlock; wallet.receive(send2, b3, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(bitcoinValueToFriendlyString(wallet.getBalance()), "0.80"); } @Test public void balances() throws Exception { BigInteger nanos = Utils.toNanoCoins(1, 0); Transaction tx1 = createFakeTx(params, nanos, myAddress); wallet.receive(tx1, null, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(nanos, tx1.getValueSentToMe(wallet, true)); // Send 0.10 to somebody else. Transaction send1 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 10), myAddress); // Reserialize. Transaction send2 = new Transaction(params, send1.bitcoinSerialize()); assertEquals(nanos, send2.getValueSentFromMe(wallet)); } @Test public void transactions() throws Exception { // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly. Transaction tx = createFakeTx(params, Utils.toNanoCoins(1, 0), myAddress); // Now add another output (ie, change) that goes to some other address. Address someOtherGuy = new ECKey().toAddress(params); TransactionOutput output = new TransactionOutput(params, tx, Utils.toNanoCoins(0, 5), someOtherGuy); tx.addOutput(output); // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all // transactions you can't check they add up. wallet.receive(tx, null, BlockChain.NewBlockType.BEST_CHAIN); // Now the other guy creates a transaction which spends that change. Transaction tx2 = new Transaction(params); tx2.addInput(output); tx2.addOutput(new TransactionOutput(params, tx2, Utils.toNanoCoins(0, 5), myAddress)); // tx2 doesn't send any coins from us, even though the output is in the wallet. assertEquals(Utils.toNanoCoins(0, 0), tx2.getValueSentFromMe(wallet)); } @Test public void bounce() throws Exception { // This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent // back to us, this isn't considered as a double spend. BigInteger coin1 = Utils.toNanoCoins(1, 0); BigInteger coinHalf = Utils.toNanoCoins(0, 50); // Start by giving us 1 coin. Transaction inbound1 = createFakeTx(params, coin1, myAddress); wallet.receive(inbound1, null, BlockChain.NewBlockType.BEST_CHAIN); // Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is // in the unspent pool, not pending or spent. Address someOtherGuy = new ECKey().toAddress(params); Transaction outbound1 = wallet.createSend(someOtherGuy, coinHalf); wallet.confirmSend(outbound1); wallet.receive(outbound1, null, BlockChain.NewBlockType.BEST_CHAIN); // That other guy gives us the coins right back. Transaction inbound2 = new Transaction(params); inbound2.addOutput(new TransactionOutput(params, inbound2, coinHalf, myAddress)); inbound2.addInput(outbound1.outputs.get(0)); wallet.receive(inbound2, null, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(coin1, wallet.getBalance()); } @Test public void finneyAttack() throws Exception { // A Finney attack is where a miner includes a transaction spending coins to themselves but does not // broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with // those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be // done by any miner for products that can be bought at a chosen time and very quickly (as every second you // withold your block means somebody else might find it first, invalidating your work). // // Test that we handle ourselves performing the attack correctly: a double spend on the chain moves // transactions from pending to dead. // // Note that the other way around, where a pending transaction sending us coins becomes dead, // isn't tested because today BitCoinJ only learns about such transactions when they appear in the chain. final Transaction[] eventDead = new Transaction[1]; final Transaction[] eventReplacement = new Transaction[1]; wallet.addEventListener(new WalletEventListener() { @Override public void onDeadTransaction(Transaction deadTx, Transaction replacementTx) { eventDead[0] = deadTx; eventReplacement[0] = replacementTx; } }); // Receive 1 BTC. BigInteger nanos = Utils.toNanoCoins(1, 0); Transaction t1 = createFakeTx(params, nanos, myAddress); wallet.receive(t1, null, BlockChain.NewBlockType.BEST_CHAIN); // Create a send to a merchant. Transaction send1 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 50)); // Create a double spend. Transaction send2 = wallet.createSend(new ECKey().toAddress(params), toNanoCoins(0, 50)); // Broadcast send1. wallet.confirmSend(send1); // Receive a block that overrides it. wallet.receive(send2, null, BlockChain.NewBlockType.BEST_CHAIN); assertEquals(send1, eventDead[0]); assertEquals(send2, eventReplacement[0]); } }
xmt/BitcoinJ
tests/com/google/bitcoin/core/WalletTest.java
Java
apache-2.0
12,969
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.projecteditor.client.forms; import javax.enterprise.context.Dependent; import javax.inject.Inject; import org.gwtbootstrap3.client.shared.event.ModalShownEvent; import org.gwtbootstrap3.client.shared.event.ModalShownHandler; import org.gwtbootstrap3.client.ui.ModalBody; import org.jboss.errai.ioc.client.api.AfterInitialization; import org.jboss.errai.ioc.client.container.IOC; import org.uberfire.client.mvp.LockRequiredEvent; import org.uberfire.ext.widgets.common.client.common.popups.BaseModal; import org.uberfire.mvp.ParameterizedCommand; @Dependent public class DependencySelectorPopupViewImpl extends BaseModal implements DependencySelectorPopupView { private DependencySelectorPresenter presenter; private DependencyListWidget dependencyPagedJarTable; @Inject private javax.enterprise.event.Event<LockRequiredEvent> lockRequired; @AfterInitialization public void init() { dependencyPagedJarTable = IOC.getBeanManager().lookupBean( DependencyListWidget.class ).getInstance(); dependencyPagedJarTable.addOnSelect( new ParameterizedCommand<String>() { @Override public void execute( String parameter ) { presenter.onPathSelection( parameter ); lockRequired.fire( new LockRequiredEvent() ); } } ); setTitle( "Artifacts" ); add( new ModalBody() {{ add( dependencyPagedJarTable ); }} ); setPixelSize( 800, 500 ); //Need to refresh the grid to load content after the popup is shown addShownHandler( new ModalShownHandler() { @Override public void onShown( final ModalShownEvent shownEvent ) { dependencyPagedJarTable.refresh(); } } ); } @Override public void init( final DependencySelectorPresenter presenter ) { this.presenter = presenter; } }
cristianonicolai/kie-wb-common
kie-wb-common-screens/kie-wb-common-project-editor/kie-wb-common-project-editor-client/src/main/java/org/kie/workbench/common/screens/projecteditor/client/forms/DependencySelectorPopupViewImpl.java
Java
apache-2.0
2,556
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 herddb.utils; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Key + Value * * @author enrico.olivelli */ @SuppressFBWarnings("EI2") public class KeyValue { public final byte[] key; public final byte[] value; public KeyValue(byte[] key, byte[] value) { this.key = key; this.value = value; } }
eolivelli/herddb
herddb-utils/src/main/java/herddb/utils/KeyValue.java
Java
apache-2.0
1,116
/******************************************************************************* * Copyright 2013 EMBL-EBI * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.sf.cram.ref; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.reference.ReferenceSequence; import htsjdk.samtools.reference.ReferenceSequenceFile; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class InMemoryReferenceSequenceFile implements ReferenceSequenceFile { private Map<Integer, byte[]> sequences = new HashMap<Integer, byte[]>(); private SAMSequenceDictionary dictionary = new SAMSequenceDictionary(); private int currentIndex = 0; public void addSequence(String name, byte[] bases) { SAMSequenceRecord r = new SAMSequenceRecord(name, bases.length); dictionary.addSequence(r); int index = getSequenceDictionary().getSequenceIndex(name); sequences.put(index, bases); } @Override public ReferenceSequence getSequence(String name) { int index = getSequenceDictionary().getSequenceIndex(name); return new ReferenceSequence(name, index, sequences.get(index)); } @Override public SAMSequenceDictionary getSequenceDictionary() { return dictionary; } @Override public ReferenceSequence getSubsequenceAt(String name, long start, long stop) { int index = getSequenceDictionary().getSequenceIndex(name); byte[] bases = Arrays.copyOfRange(sequences.get(index), (int) start, (int) stop + 1); return new ReferenceSequence(name, index, bases); } @Override public void close() throws IOException { sequences.clear(); } /** * @param name * @param start * inclusive * @param stop * inclusive * @return */ public ReferenceRegion getRegion(String name, long start, long stop) { int index = getSequenceDictionary().getSequenceIndex(name); if (!sequences.containsKey(index)) throw new RuntimeException("Sequence not found: " + name); ReferenceRegion region = new ReferenceRegion(sequences.get(index), index, name, start); return region; } @Override public boolean isIndexed() { return true; } @Override public ReferenceSequence nextSequence() { if (currentIndex >= dictionary.size()) return null; SAMSequenceRecord sequence = dictionary.getSequence(currentIndex++); return getSequence(sequence.getSequenceName()); } @Override public void reset() { currentIndex = 0; } }
enasequence/cramtools
src/main/java/net/sf/cram/ref/InMemoryReferenceSequenceFile.java
Java
apache-2.0
3,065
/* * Copyright 2007-2008 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.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. */ package org.kuali.rice.kns.datadictionary; import org.kuali.rice.krad.bo.BusinessObject; import java.util.List; @Deprecated public interface CollectionDefinitionI { public String getName(); public boolean getIncludeAddLine(); public List<? extends CollectionDefinitionI> getCollections(); public List<? extends FieldDefinitionI> getFields(); public String getSummaryTitle(); public Class<? extends BusinessObject> getBusinessObjectClass(); public boolean hasSummaryField(String key); public List<? extends FieldDefinitionI> getSummaryFields(); public boolean isAlwaysAllowCollectionDeletion(); }
sbower/kuali-rice-1
kns/src/main/java/org/kuali/rice/kns/datadictionary/CollectionDefinitionI.java
Java
apache-2.0
1,292
package org.osmdroid.tileprovider.modules; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import org.osmdroid.api.IMapView; import org.osmdroid.tileprovider.MapTile; import org.osmdroid.tileprovider.tilesource.ITileSource; public class ZipFileArchive implements IArchiveFile { private final ZipFile mZipFile; private ZipFileArchive(final ZipFile pZipFile) { mZipFile = pZipFile; } public static ZipFileArchive getZipFileArchive(final File pFile) throws ZipException, IOException { return new ZipFileArchive(new ZipFile(pFile)); } @Override public InputStream getInputStream(final ITileSource pTileSource, final MapTile pTile) { final String path = pTileSource.getTileRelativeFilenameString(pTile); try { final ZipEntry entry = mZipFile.getEntry(path); if (entry != null) { return mZipFile.getInputStream(entry); } } catch (final IOException e) { Log.w(IMapView.LOGTAG,"Error getting zip stream: " + pTile, e); } return null; } @Override public void close() { try { mZipFile.close(); } catch (IOException e) { } } @Override public String toString() { return "ZipFileArchive [mZipFile=" + mZipFile.getName() + "]"; } }
dozd/osmdroid
osmdroid-android/src/main/java/org/osmdroid/tileprovider/modules/ZipFileArchive.java
Java
apache-2.0
1,331
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.source.rtsp; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import android.net.Uri; import androidx.annotation.Nullable; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.source.rtsp.RtspMessageUtil.RtspAuthUserInfo; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; /** Unit test for {@link RtspMessageUtil}. */ @RunWith(AndroidJUnit4.class) public final class RtspMessageUtilTest { @Test public void parseRequest_withOptionsRequest_succeeds() { List<String> requestLines = Arrays.asList( "OPTIONS rtsp://localhost:554/foo.bar RTSP/1.0", "CSeq: 2", "User-Agent: LibVLC/3.0.11", ""); RtspRequest request = RtspMessageUtil.parseRequest(requestLines); assertThat(request.method).isEqualTo(RtspRequest.METHOD_OPTIONS); assertThat(request.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "2", RtspHeaders.USER_AGENT, "LibVLC/3.0.11"); assertThat(request.messageBody).isEmpty(); } @Test public void parseResponse_withOptionsResponse_succeeds() { List<String> responseLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 2", "Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER", ""); RtspResponse response = RtspMessageUtil.parseResponse(responseLines); assertThat(response.status).isEqualTo(200); assertThat(response.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "2", RtspHeaders.PUBLIC, "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER," + " SET_PARAMETER"); assertThat(response.messageBody).isEmpty(); } @Test public void parseRequest_withDescribeRequest_succeeds() { List<String> requestLines = Arrays.asList( "DESCRIBE rtsp://localhost:554/foo.bar RTSP/1.0", "CSeq: 3", "User-Agent: LibVLC/3.0.11", "Accept: application/sdp", ""); RtspRequest request = RtspMessageUtil.parseRequest(requestLines); assertThat(request.method).isEqualTo(RtspRequest.METHOD_DESCRIBE); assertThat(request.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "3", RtspHeaders.USER_AGENT, "LibVLC/3.0.11", RtspHeaders.ACCEPT, "application/sdp"); assertThat(request.messageBody).isEmpty(); } @Test public void parseResponse_withDescribeResponse_succeeds() { List<String> responseLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 3", "Content-Base: rtsp://127.0.0.1/test.mkv/", "Content-Type: application/sdp", "Content-Length: 707", "", "v=0", "o=- 1606776316530225 1 IN IP4 192.168.2.176", "i=imax.mkv", "m=video 0 RTP/AVP 96", "a=rtpmap:96 H264/90000", "a=control:track1", "m=audio 0 RTP/AVP 97", "a=rtpmap:97 AC3/48000", "a=control:track2"); RtspResponse response = RtspMessageUtil.parseResponse(responseLines); assertThat(response.status).isEqualTo(200); assertThat(response.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "3", RtspHeaders.CONTENT_BASE, "rtsp://127.0.0.1/test.mkv/", RtspHeaders.CONTENT_TYPE, "application/sdp", RtspHeaders.CONTENT_LENGTH, "707"); assertThat(response.messageBody) .isEqualTo( "v=0\r\n" + "o=- 1606776316530225 1 IN IP4 192.168.2.176\r\n" + "i=imax.mkv\r\n" + "m=video 0 RTP/AVP 96\r\n" + "a=rtpmap:96 H264/90000\r\n" + "a=control:track1\r\n" + "m=audio 0 RTP/AVP 97\r\n" + "a=rtpmap:97 AC3/48000\r\n" + "a=control:track2"); } @Test public void parseResponse_with401DescribeResponse_succeeds() { List<String> responseLines = Arrays.asList( "RTSP/1.0 401 Unauthorized", "CSeq: 3", "WWW-Authenticate: BASIC realm=\"wow\"", "WWW-Authenticate: DIGEST realm=\"wow\", nonce=\"nonce\"", ""); RtspResponse response = RtspMessageUtil.parseResponse(responseLines); ListMultimap<String, String> headersMap = response.headers.asMultiMap(); assertThat(response.status).isEqualTo(401); assertThat(headersMap.keySet()) .containsExactly(RtspHeaders.CSEQ, RtspHeaders.WWW_AUTHENTICATE) .inOrder(); assertThat(headersMap).valuesForKey(RtspHeaders.CSEQ).containsExactly("3"); assertThat(headersMap) .valuesForKey(RtspHeaders.WWW_AUTHENTICATE) .containsExactly("BASIC realm=\"wow\"", "DIGEST realm=\"wow\", nonce=\"nonce\"") .inOrder(); assertThat(response.messageBody).isEmpty(); } @Test public void parseRequest_withSetParameterRequest_succeeds() { List<String> requestLines = Arrays.asList( "SET_PARAMETER rtsp://localhost:554/foo.bar RTSP/1.0", "CSeq: 3", "User-Agent: LibVLC/3.0.11", "Content-Length: 20", "Content-Type: text/parameters", "", "param: stuff"); RtspRequest request = RtspMessageUtil.parseRequest(requestLines); assertThat(request.method).isEqualTo(RtspRequest.METHOD_SET_PARAMETER); assertThat(request.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "3", RtspHeaders.USER_AGENT, "LibVLC/3.0.11", RtspHeaders.CONTENT_LENGTH, "20", RtspHeaders.CONTENT_TYPE, "text/parameters"); assertThat(request.messageBody).isEqualTo("param: stuff"); } @Test public void parseResponse_withGetParameterResponse_succeeds() { List<String> responseLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 431", "Content-Length: 46", "Content-Type: text/parameters", "", "packets_received: 10", "jitter: 0.3838"); RtspResponse response = RtspMessageUtil.parseResponse(responseLines); assertThat(response.status).isEqualTo(200); assertThat(response.headers.asMultiMap()) .containsExactly( RtspHeaders.CSEQ, "431", RtspHeaders.CONTENT_LENGTH, "46", RtspHeaders.CONTENT_TYPE, "text/parameters"); assertThat(response.messageBody).isEqualTo("packets_received: 10\r\n" + "jitter: 0.3838"); } @Test public void serialize_setupRequest_succeeds() { RtspRequest request = new RtspRequest( Uri.parse("rtsp://127.0.0.1/test.mkv/track1"), RtspRequest.METHOD_SETUP, new RtspHeaders.Builder() .addAll( ImmutableMap.of( RtspHeaders.CSEQ, "4", RtspHeaders.TRANSPORT, "RTP/AVP;unicast;client_port=65458-65459")) .build(), /* messageBody= */ ""); List<String> messageLines = RtspMessageUtil.serializeRequest(request); List<String> expectedLines = Arrays.asList( "SETUP rtsp://127.0.0.1/test.mkv/track1 RTSP/1.0", "CSeq: 4", "Transport: RTP/AVP;unicast;client_port=65458-65459", "", ""); String expectedRtspMessage = "SETUP rtsp://127.0.0.1/test.mkv/track1 RTSP/1.0\r\n" + "CSeq: 4\r\n" + "Transport: RTP/AVP;unicast;client_port=65458-65459\r\n" + "\r\n"; assertThat(messageLines).isEqualTo(expectedLines); assertThat(RtspMessageUtil.convertMessageToByteArray(messageLines)) .isEqualTo(expectedRtspMessage.getBytes(RtspMessageChannel.CHARSET)); } @Test public void serialize_setupResponse_succeeds() { RtspResponse response = new RtspResponse( /* status= */ 200, new RtspHeaders.Builder() .addAll( ImmutableMap.of( RtspHeaders.CSEQ, "4", RtspHeaders.TRANSPORT, "RTP/AVP;unicast;client_port=65458-65459;server_port=5354-5355")) .build()); List<String> messageLines = RtspMessageUtil.serializeResponse(response); List<String> expectedLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 4", "Transport: RTP/AVP;unicast;client_port=65458-65459;server_port=5354-5355", "", ""); String expectedRtspMessage = "RTSP/1.0 200 OK\r\n" + "CSeq: 4\r\n" + "Transport: RTP/AVP;unicast;client_port=65458-65459;server_port=5354-5355\r\n" + "\r\n"; assertThat(messageLines).isEqualTo(expectedLines); assertThat(RtspMessageUtil.convertMessageToByteArray(messageLines)) .isEqualTo(expectedRtspMessage.getBytes(RtspMessageChannel.CHARSET)); } @Test public void serialize_describeResponse_succeeds() { RtspResponse response = new RtspResponse( /* status= */ 200, new RtspHeaders.Builder() .addAll( ImmutableMap.of( RtspHeaders.CSEQ, "4", RtspHeaders.CONTENT_BASE, "rtsp://127.0.0.1/test.mkv/", RtspHeaders.CONTENT_TYPE, "application/sdp", RtspHeaders.CONTENT_LENGTH, "707")) .build(), /* messageBody= */ "v=0\r\n" + "o=- 1606776316530225 1 IN IP4 192.168.2.176\r\n" + "i=test.mkv\r\n" + "m=video 0 RTP/AVP 96\r\n" + "a=rtpmap:96 H264/90000\r\n" + "a=control:track1\r\n" + "m=audio 0 RTP/AVP 97\r\n" + "a=rtpmap:97 AC3/48000\r\n" + "a=control:track2"); List<String> messageLines = RtspMessageUtil.serializeResponse(response); List<String> expectedLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 4", "Content-Base: rtsp://127.0.0.1/test.mkv/", "Content-Type: application/sdp", "Content-Length: 707", "", "v=0\r\n" + "o=- 1606776316530225 1 IN IP4 192.168.2.176\r\n" + "i=test.mkv\r\n" + "m=video 0 RTP/AVP 96\r\n" + "a=rtpmap:96 H264/90000\r\n" + "a=control:track1\r\n" + "m=audio 0 RTP/AVP 97\r\n" + "a=rtpmap:97 AC3/48000\r\n" + "a=control:track2"); String expectedRtspMessage = "RTSP/1.0 200 OK\r\n" + "CSeq: 4\r\n" + "Content-Base: rtsp://127.0.0.1/test.mkv/\r\n" + "Content-Type: application/sdp\r\n" + "Content-Length: 707\r\n" + "\r\n" + "v=0\r\n" + "o=- 1606776316530225 1 IN IP4 192.168.2.176\r\n" + "i=test.mkv\r\n" + "m=video 0 RTP/AVP 96\r\n" + "a=rtpmap:96 H264/90000\r\n" + "a=control:track1\r\n" + "m=audio 0 RTP/AVP 97\r\n" + "a=rtpmap:97 AC3/48000\r\n" + "a=control:track2"; assertThat(messageLines).isEqualTo(expectedLines); assertThat(RtspMessageUtil.convertMessageToByteArray(messageLines)) .isEqualTo(expectedRtspMessage.getBytes(RtspMessageChannel.CHARSET)); } @Test public void serialize_requestWithoutCseqHeader_throwsIllegalArgumentException() { RtspRequest request = new RtspRequest( Uri.parse("rtsp://127.0.0.1/test.mkv/track1"), RtspRequest.METHOD_OPTIONS, RtspHeaders.EMPTY, /* messageBody= */ ""); assertThrows(IllegalArgumentException.class, () -> RtspMessageUtil.serializeRequest(request)); } @Test public void serialize_responseWithoutCseqHeader_throwsIllegalArgumentException() { RtspResponse response = new RtspResponse(/* status= */ 200, RtspHeaders.EMPTY); assertThrows(IllegalArgumentException.class, () -> RtspMessageUtil.serializeResponse(response)); } @Test public void isRtspResponse_withSuccessfulRtspResponse_returnsTrue() { List<String> responseLines = Arrays.asList( "RTSP/1.0 200 OK", "CSeq: 2", "Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER", ""); assertThat(RtspMessageUtil.isRtspResponse(responseLines)).isTrue(); } @Test public void isRtspResponse_withUnsuccessfulRtspResponse_returnsTrue() { List<String> responseLines = Arrays.asList("RTSP/1.0 405 Method Not Allowed", "CSeq: 2", ""); assertThat(RtspMessageUtil.isRtspResponse(responseLines)).isTrue(); } @Test public void isRtspResponse_withRtspRequest_returnsFalse() { List<String> requestLines = Arrays.asList("OPTIONS rtsp://localhost:554/foo.bar RTSP/1.0", "CSeq: 2", ""); assertThat(RtspMessageUtil.isRtspResponse(requestLines)).isFalse(); } @Test public void serialize_failedResponse_succeeds() { RtspResponse response = new RtspResponse( /* status= */ 454, new RtspHeaders.Builder().add(RtspHeaders.CSEQ, "4").build()); List<String> messageLines = RtspMessageUtil.serializeResponse(response); List<String> expectedLines = Arrays.asList("RTSP/1.0 454 Session Not Found", "CSeq: 4", "", ""); String expectedRtspMessage = "RTSP/1.0 454 Session Not Found\r\n" + "CSeq: 4\r\n" + "\r\n"; assertThat(RtspMessageUtil.serializeResponse(response)).isEqualTo(expectedLines); assertThat(RtspMessageUtil.convertMessageToByteArray(messageLines)) .isEqualTo(expectedRtspMessage.getBytes(RtspMessageChannel.CHARSET)); } @Test public void parseSessionHeader_withSessionIdContainingSpecialCharacters_succeeds() throws Exception { String sessionHeaderString = "610a63df-9b57.4856_97ac$665f+56e9c04"; RtspMessageUtil.RtspSessionHeader sessionHeader = RtspMessageUtil.parseSessionHeader(sessionHeaderString); assertThat(sessionHeader.sessionId).isEqualTo("610a63df-9b57.4856_97ac$665f+56e9c04"); } @Test public void parseSessionHeader_withSessionIdContainingSpecialCharactersAndTimeout_succeeds() throws Exception { String sessionHeaderString = "610a63df-9b57.4856_97ac$665f+56e9c04;timeout=60"; RtspMessageUtil.RtspSessionHeader sessionHeader = RtspMessageUtil.parseSessionHeader(sessionHeaderString); assertThat(sessionHeader.sessionId).isEqualTo("610a63df-9b57.4856_97ac$665f+56e9c04"); assertThat(sessionHeader.timeoutMs).isEqualTo(60_000); } @Test public void removeUserInfo_withUserInfo() { Uri uri = Uri.parse("rtsp://user:[email protected]/foo.mkv"); assertThat(RtspMessageUtil.removeUserInfo(uri)).isEqualTo(Uri.parse("rtsp://foo.bar/foo.mkv")); } @Test public void removeUserInfo_withUserInfoAndPortNumber() { Uri uri = Uri.parse("rtsp://user:[email protected]:5050/foo.mkv"); assertThat(RtspMessageUtil.removeUserInfo(uri)) .isEqualTo(Uri.parse("rtsp://foo.bar:5050/foo.mkv")); } @Test public void removeUserInfo_withEmptyUserInfoAndPortNumber() { Uri uri = Uri.parse("rtsp://@foo.bar:5050/foo.mkv"); assertThat(RtspMessageUtil.removeUserInfo(uri)) .isEqualTo(Uri.parse("rtsp://foo.bar:5050/foo.mkv")); } @Test public void removeUserInfo_withNoUserInfo() { Uri uri = Uri.parse("rtsp://foo.bar:5050/foo.mkv"); assertThat(RtspMessageUtil.removeUserInfo(uri)) .isEqualTo(Uri.parse("rtsp://foo.bar:5050/foo.mkv")); } @Test public void parseContentLengthHeader_withContentLengthOver31Bits_succeeds() throws Exception { String line = "Content-Length: 1000000000000000"; long contentLength = RtspMessageUtil.parseContentLengthHeader(line); assertThat(contentLength).isEqualTo(1000000000000000L); } @Test public void isRtspStartLine_onValidRequestLine_succeeds() { assertThat(RtspMessageUtil.isRtspStartLine("OPTIONS rtsp://localhost/test RTSP/1.0")).isTrue(); } @Test public void isRtspStartLine_onValidResponseLine_succeeds() { assertThat(RtspMessageUtil.isRtspStartLine("RTSP/1.0 456 Header Field Not Valid for Resource")) .isTrue(); } @Test public void isRtspStartLine_onValidHeaderLine_succeeds() { assertThat(RtspMessageUtil.isRtspStartLine("Transport: RTP/AVP;unicast;client_port=1000-1001")) .isFalse(); } @Test public void extractUserInfo_withoutPassword_returnsNull() { @Nullable RtspAuthUserInfo authUserInfo = RtspMessageUtil.parseUserInfo(Uri.parse("rtsp://[email protected]/stream1")); assertThat(authUserInfo).isNull(); } @Test public void extractUserInfo_withoutUserInfo_returnsNull() { @Nullable RtspAuthUserInfo authUserInfo = RtspMessageUtil.parseUserInfo(Uri.parse("rtsp://mediaserver.com/stream1")); assertThat(authUserInfo).isNull(); } @Test public void extractUserInfo_withProperlyFormattedUri_succeeds() { @Nullable RtspAuthUserInfo authUserInfo = RtspMessageUtil.parseUserInfo( Uri.parse("rtsp://username:pass:[email protected]/stream1")); assertThat(authUserInfo).isNotNull(); assertThat(authUserInfo.username).isEqualTo("username"); assertThat(authUserInfo.password).isEqualTo("pass:word"); } @Test public void parseWWWAuthenticateHeader_withBasicAuthentication_succeeds() throws Exception { RtspAuthenticationInfo authenticationInfo = RtspMessageUtil.parseWwwAuthenticateHeader("Basic realm=\"Wally - World\""); assertThat(authenticationInfo.authenticationMechanism).isEqualTo(RtspAuthenticationInfo.BASIC); assertThat(authenticationInfo.nonce).isEmpty(); assertThat(authenticationInfo.realm).isEqualTo("Wally - World"); } @Test public void parseWWWAuthenticateHeader_withDigestAuthenticationWithDomain_succeeds() throws Exception { RtspAuthenticationInfo authenticationInfo = RtspMessageUtil.parseWwwAuthenticateHeader( "Digest realm=\"[email protected]\", domain=\"host.com\"," + " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", " + " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""); assertThat(authenticationInfo.authenticationMechanism).isEqualTo(RtspAuthenticationInfo.DIGEST); assertThat(authenticationInfo.nonce).isEqualTo("dcd98b7102dd2f0e8b11d0f600bfb0c093"); assertThat(authenticationInfo.realm).isEqualTo("[email protected]"); assertThat(authenticationInfo.opaque).isEmpty(); } @Test public void parseWWWAuthenticateHeader_withDigestAuthenticationWithOptionalParameters_succeeds() throws Exception { RtspAuthenticationInfo authenticationInfo = RtspMessageUtil.parseWwwAuthenticateHeader( "Digest realm=\"[email protected]\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\"," + " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", stale=\"stalev\"," + " algorithm=\"md5\""); assertThat(authenticationInfo.authenticationMechanism).isEqualTo(RtspAuthenticationInfo.DIGEST); assertThat(authenticationInfo.nonce).isEqualTo("dcd98b7102dd2f0e8b11d0f600bfb0c093"); assertThat(authenticationInfo.realm).isEqualTo("[email protected]"); assertThat(authenticationInfo.opaque).isEqualTo("5ccc069c403ebaf9f0171e9517f40e41"); } @Test public void parseWWWAuthenticateHeader_withDigestAuthentication_succeeds() throws Exception { RtspAuthenticationInfo authenticationInfo = RtspMessageUtil.parseWwwAuthenticateHeader( "Digest realm=\"RTSP server\", nonce=\"0cdfe9719e7373b7d5bb2913e2115f3f\""); assertThat(authenticationInfo.authenticationMechanism).isEqualTo(RtspAuthenticationInfo.DIGEST); assertThat(authenticationInfo.nonce).isEqualTo("0cdfe9719e7373b7d5bb2913e2115f3f"); assertThat(authenticationInfo.realm).isEqualTo("RTSP server"); assertThat(authenticationInfo.opaque).isEmpty(); } @Test public void splitRtspMessageBody_withCrLfLineTerminatorMessageBody_splitsMessageBody() { String[] lines = RtspMessageUtil.splitRtspMessageBody("line1\r\nline2\r\nline3"); assertThat(lines).asList().containsExactly("line1", "line2", "line3").inOrder(); } @Test public void splitRtspMessageBody_withLfLineTerminatorMessageBody_splitsMessageBody() { String[] lines = RtspMessageUtil.splitRtspMessageBody("line1\nline2\nline3"); assertThat(lines).asList().containsExactly("line1", "line2", "line3").inOrder(); } }
google/ExoPlayer
library/rtsp/src/test/java/com/google/android/exoplayer2/source/rtsp/RtspMessageUtilTest.java
Java
apache-2.0
21,560
package com.lerx.web.util; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.lerx.qa.dao.IQaItemDao; import com.lerx.qa.dao.IQaNavDao; import com.lerx.qa.util.QaItemUtil; import com.lerx.qa.util.QaNavUtil; import com.lerx.qa.vo.QaItem; import com.lerx.qa.vo.QaNav; import com.lerx.site.vo.SiteInfo; import com.lerx.style.qa.vo.QaStyle; import com.lerx.style.qa.vo.QaStyleSubElementInCommon; import com.lerx.sys.util.IpUtil; import com.lerx.sys.util.StringUtil; import com.lerx.sys.util.vo.FormatElements; import com.lerx.sys.util.vo.UserCookie; import com.lerx.web.util.camp.PubUtil; import com.lerx.web.util.camp.QaUtil; import com.lerx.web.vo.LoginCheckEl; import com.lerx.web.vo.WebElements; import com.opensymphony.xwork2.ActionSupport; public class WebThreadQa { public static String show(WebElements wel) throws IOException{ wel.setRefererRec(false); String staticHtmlRoot = wel.getAs().getText("lerx.htmlPath"); //从wel中取值,以防用过多的get方法 IQaNavDao qaNavDaoImp = wel.getQaNavDaoImp(); IQaItemDao qaItemDaoImp = wel.getQaItemDaoImp(); ActionSupport as=wel.getAs(); HttpServletRequest request=wel.getRequest(); SiteInfo site=wel.getSite(); QaStyle curQaStyle; long tid = wel.getTid(); long id = wel.getId(); String pwd = wel.getPwd(); if (tid == 0){ tid=id; } String location; QaItem qi=qaItemDaoImp.findById(tid); QaNav qn=qi.getQn(); if (qn!=null && qn.getStyle()!=null){ curQaStyle=qn.getStyle(); }else{ curQaStyle=wel.getCurQaStyle(); } if (qn==null){ return as.getText("lerx.err.parameter"); } wel.setTitleFormat(StringUtil.strReplace(wel.getTitleFormat(), "{$$app$$}", qn.getTitle())); //下面五行顺序不能错 QaStyleSubElementInCommon ec=curQaStyle.getItemStyle(); wel=QaUtil.init(wel,ec); FormatElements fel=wel.getFel(); LoginCheckEl lcel=PubUtil.logincheck(wel); wel.setCdm(lcel.getCdm()); wel.setUc(lcel.getUc()); wel.setUserLogined(lcel.isLogined()); String html; html=ec.getHtmlCode(); UserCookie uc=wel.getUc(); if (uc != null && QaUtil.checkUserOnQa(wel,qn)==1){ html=StringUtil.strReplace(html,"{$$replyArea$$}",curQaStyle.getReplyAreaCode()); }else{ html=StringUtil.strReplace(html,"{$$replyArea$$}",""); } if (uc!=null){ html=StringUtil.strReplace(html,"{$$remName$$}",StringUtil.nullFilter(uc.getRemName())); }else{ html=StringUtil.strReplace(html,"{$$remName$$}",""); } fel.setLf(html); html=QaItemUtil.formatHref(fel, qi); wel.setHtml(html); wel=QaUtil.endQaService(wel); String htmlTemplate = wel.getHtmlTemplate(); String locationSplitStr = wel.getLocationSplitStr(); boolean staticHtmlMode; // int stateMod; if (site.getStaticHtmlMode() == 2){ staticHtmlMode=true; }else{ staticHtmlMode=false; } List<QaNav> qnl; if (qn.getParentNav()==null){ qnl=qaNavDaoImp.findByParent(qn.getId(),1); }else{ qnl=qaNavDaoImp.findByParent(qn.getParentNav().getId(),1); //与上同 } String tmpAll="",lf; String navsLoopFormat; if (ec.getNavsLoopFormat()==null || ec.getNavsLoopFormat().trim().equals("")){ navsLoopFormat=curQaStyle.getPublicStyle().getNavsLoopFormat(); // fel.setLf(curQaStyle.getPublicStyle().getNavsLoopFormat()); }else{ navsLoopFormat=ec.getNavsLoopFormat(); // fel.setLf(ec.getNavsLoopFormat()); } fel.setLf(navsLoopFormat); if (qnl.size()>0){ for (QaNav n : qnl) { lf=QaNavUtil.formatHref(fel, n,staticHtmlMode,staticHtmlRoot); tmpAll+=lf; } } // 判断页面访问并保存 String curIP = IpUtil.getRealRemotIP(request).trim(); String lastViewIP = qi.getLastViewIp(); if (!as.getText("lerx.mode.realtime.byAjax").trim() .equalsIgnoreCase("true")) { boolean saveT = false; if (lastViewIP == null) { lastViewIP = ""; } if (as.getText("lerx.viewsUpdateByIp").trim().equals("true")){ if (!lastViewIP.trim().equals(curIP)) { qi.setLastViewIp(curIP); qi.setViews(qi.getViews() + 1); saveT = true; } }else{ qi.setViews(qi.getViews() + 1); saveT = true; } if (saveT) { qaItemDaoImp.modify(qi); } } boolean pwdRead; String pwdAtQi; pwdAtQi=qi.getPassword(); if (pwdAtQi==null){ pwdAtQi=""; } if (pwd==null){ pwd=""; } if (pwd.trim().equals("") || pwdAtQi.trim().equals("")){ pwdRead=false; }else{ if (pwd.trim().equalsIgnoreCase(pwdAtQi.trim())){ pwdRead=true; }else{ pwdRead=false; } } if (!qi.isOpen() && QaUtil.checkUserOnQa(wel,qn)!=1 && !pwdRead){ return as.getText("lerx.fail.power"); } if (qn.getParentNav()==null){ location=QaNavUtil.locationStr(fel, qn, staticHtmlMode); }else{ String l1,l2; l1=QaNavUtil.locationStr(fel, qn.getParentNav(), staticHtmlMode); l2=QaNavUtil.locationStr(fel, qn, staticHtmlMode); location=l1+locationSplitStr+l2; } htmlTemplate = StringUtil.strReplace(htmlTemplate, "{$$htmlBody$$}", html); htmlTemplate = StringUtil.strReplace(htmlTemplate, "{$$location$$}", location); htmlTemplate = StringUtil.strReplace(htmlTemplate, "{$$app$$}", qi.getTitle()); htmlTemplate=StringUtil.strReplace(htmlTemplate,"{$$navList$$}",tmpAll); return htmlTemplate; } }
chenxyzy/cms
src/com/lerx/web/util/WebThreadQa.java
Java
apache-2.0
5,342
/* * Copyright © WebServices pour l'Éducation, 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.wseduc.webutils.data; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; import java.io.StringWriter; public class XML { public static String format(String input, int indent) throws TransformerException { return format(input, indent, false); } public static String format(String input, int indent, boolean crlf) throws TransformerException { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(xmlInput, xmlOutput); final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlOutput.getWriter().toString(); return crlf ? xml.replaceAll("\\n", "\r\n") : xml; } }
web-education/web-utils
src/main/java/fr/wseduc/webutils/data/XML.java
Java
apache-2.0
1,798
package com.uxxu.konashi.lib.action; import android.bluetooth.BluetoothGattService; import com.uxxu.konashi.lib.KonashiUUID; import java.util.UUID; import info.izumin.android.bletia.action.ReadCharacteristicAction; /** * Created by izumin on 9/23/15. */ public class BatteryLevelReadAction extends ReadCharacteristicAction { private static final UUID UUID = KonashiUUID.BATTERY_LEVEL_UUID; public BatteryLevelReadAction(BluetoothGattService service) { super(service, UUID); } }
YUKAI/konashi-android-sdk
konashi-android-sdk/src/main/java/com/uxxu/konashi/lib/action/BatteryLevelReadAction.java
Java
apache-2.0
507
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.rabbitmq; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Envelope; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Suspendable; import org.apache.camel.support.DefaultConsumer; import org.apache.camel.support.service.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RabbitMQConsumer extends DefaultConsumer implements Suspendable { private static final Logger LOG = LoggerFactory.getLogger(RabbitMQConsumer.class); private ExecutorService executor; private Connection conn; private int closeTimeout = 30 * 1000; private final RabbitMQEndpoint endpoint; /** * Task in charge of starting consumer */ private StartConsumerCallable startConsumerCallable; /** * Running consumers */ private final List<RabbitConsumer> consumers = new ArrayList<>(); public RabbitMQConsumer(RabbitMQEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } @Override public RabbitMQEndpoint getEndpoint() { return (RabbitMQEndpoint) super.getEndpoint(); } /** * Open connection */ private void openConnection() throws IOException, TimeoutException { LOG.trace("Creating connection..."); this.conn = getEndpoint().connect(executor); LOG.debug("Created connection: {}", conn); } /** * Returns the exiting open connection or opens a new one */ protected synchronized Connection getConnection() throws IOException, TimeoutException { if (this.conn == null || !this.conn.isOpen()) { LOG.debug("The existing connection is closed or not opened yet."); openConnection(); return this.conn; } else { return this.conn; } } /** * Create the consumers but don't start yet */ private void createConsumers() { // Create consumers but don't start yet for (int i = 0; i < endpoint.getConcurrentConsumers(); i++) { createConsumer(); } } /** * Start the consumers (already created) */ private void startConsumers() { // Try starting consumers (which will fail if RabbitMQ can't connect) Throwable fail = null; // attempt to start all consumers if possible for (RabbitConsumer consumer : this.consumers) { try { ServiceHelper.startService(consumer); } catch (Exception e) { fail = e; } } if (fail != null) { LOG.info("Connection failed starting consumers, will start background thread to retry!", fail); reconnect(); } } /** * Add a consumer thread for given channel */ private void createConsumer() { RabbitConsumer consumer = new RabbitConsumer(this); this.consumers.add(consumer); } public Exchange createExchange(Envelope envelope, AMQP.BasicProperties properties, byte[] body) { Exchange exchange = createExchange(false); endpoint.getMessageConverter().populateRabbitExchange(exchange, envelope, properties, body, false, endpoint.isAllowMessageBodySerialization()); return exchange; } private synchronized void reconnect() { if (startConsumerCallable != null) { return; } // Open connection, and start message listener in background Integer networkRecoveryInterval = getEndpoint().getNetworkRecoveryInterval(); final long connectionRetryInterval = networkRecoveryInterval != null && networkRecoveryInterval > 0 ? networkRecoveryInterval : 100L; startConsumerCallable = new StartConsumerCallable(connectionRetryInterval); executor.submit(startConsumerCallable); } /** * If needed, close Connection and Channels */ private void closeConnectionAndChannel() throws IOException { if (startConsumerCallable != null) { startConsumerCallable.stop(); } for (RabbitConsumer consumer : this.consumers) { try { ServiceHelper.stopAndShutdownService(consumer); } catch (Exception e) { LOG.warn("Error occurred while stopping consumer. This exception is ignored", e); } } this.consumers.clear(); if (conn != null) { LOG.debug("Closing connection: {} with timeout: {} ms.", conn, closeTimeout); conn.close(closeTimeout); conn = null; } } @Override protected void doSuspend() throws Exception { closeConnectionAndChannel(); } @Override protected void doResume() throws Exception { createConsumers(); startConsumers(); } @Override protected void doStart() throws Exception { executor = endpoint.createExecutor(); LOG.debug("Using executor {}", executor); createConsumers(); startConsumers(); } @Override protected void doStop() throws Exception { closeConnectionAndChannel(); if (executor != null) { if (endpoint != null && endpoint.getCamelContext() != null) { endpoint.getCamelContext().getExecutorServiceManager().shutdownNow(executor); } else { executor.shutdownNow(); } executor = null; } } /** * Task in charge of opening connection and adding listener when consumer is started and broker is not available. */ private class StartConsumerCallable implements Callable<Void> { private final long connectionRetryInterval; private final AtomicBoolean running = new AtomicBoolean(true); StartConsumerCallable(long connectionRetryInterval) { this.connectionRetryInterval = connectionRetryInterval; } public void stop() { running.set(false); RabbitMQConsumer.this.startConsumerCallable = null; } @Override public Void call() throws Exception { boolean connectionFailed = true; // Reconnection loop while (running.get() && connectionFailed) { try { for (RabbitConsumer consumer : consumers) { consumer.reconnect(); } connectionFailed = false; } catch (Exception e) { LOG.info("Connection failed, will retry in {} ms", connectionRetryInterval, e); Thread.sleep(connectionRetryInterval); } } stop(); return null; } } }
tadayosi/camel
components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitMQConsumer.java
Java
apache-2.0
7,975
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.kernel.util; import com.google.common.collect.ImmutableSet; import org.sakaiproject.kernel.api.jcr.JCRConstants; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; /** * @author ieb */ public class JCRNodeMap extends HashMap<String, Object> { /** * */ private static final long serialVersionUID = -7045000748456348620L; private static final Set<String> IGNORE = ImmutableSet.of( "sakai:sha1-password-hash", "acl:acl"); /** * @throws RepositoryException */ public JCRNodeMap(Node n, int depth) throws RepositoryException { depth--; put("primaryNodeType", n.getPrimaryNodeType().getName()); put("mixinNodeType", getMixinTypes(n)); put("properties", getProperties(n)); put("name", n.getName()); NodeType nt = n.getPrimaryNodeType(); if (JCRConstants.NT_FILE.equals(nt.getName())) { addFile(n); } else { if (depth >= 0) { Map<String, Object> nodes = new HashMap<String, Object>(); NodeIterator ni = n.getNodes(); int i = 0; while (ni.hasNext()) { Node cn = ni.nextNode(); Map<String, Object> m = new JCRNodeMap(cn, depth); m.put("position", String.valueOf(i)); nodes.put(cn.getName(), m); i++; } put("nitems", nodes.size()); put("items", nodes); } } } /** * @param n * @throws RepositoryException */ private void addFile(Node n) throws RepositoryException { Node resource = n.getNode(JCRConstants.JCR_CONTENT); Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED); Property content = resource.getProperty(JCRConstants.JCR_DATA); put("lastModified", lastModified.getDate().getTime()); put("mimeType", resource.getProperty(JCRConstants.JCR_MIMETYPE).getString()); if (resource.hasProperty(JCRConstants.JCR_ENCODING)) { put("encoding", resource.getProperty(JCRConstants.JCR_ENCODING) .getString()); } put("length", String.valueOf(content.getLength())); } /** * @param n * @return * @throws RepositoryException */ private Map<String, Object> getProperties(Node n) throws RepositoryException { Map<String, Object> m = new HashMap<String, Object>(); for (PropertyIterator pi = n.getProperties(); pi.hasNext();) { Property p = pi.nextProperty(); String name = p.getName(); if (!IGNORE.contains(name)) { boolean multiValue = p.getDefinition().isMultiple(); if (multiValue) { Value[] v = p.getValues(); Object[] o = new String[v.length]; for (int i = 0; i < o.length; i++) { o[i] = formatType(v[i]); } m.put(name, o); } else { Value v = p.getValue(); m.put(name, formatType(v)); } } } if ( n.hasNode(JCRConstants.JCR_CONTENT) ) { Node content = n.getNode(JCRConstants.JCR_CONTENT); for (PropertyIterator pi = content.getProperties(); pi.hasNext();) { Property p = pi.nextProperty(); String name = p.getName(); if (!IGNORE.contains(name)) { boolean multiValue = p.getDefinition().isMultiple(); if (multiValue) { Value[] v = p.getValues(); Object[] o = new String[v.length]; for (int i = 0; i < o.length; i++) { o[i] = formatType(v[i]); } m.put(name, o); } else { Value v = p.getValue(); m.put(name, formatType(v)); } } } } return m; } /** * @param value * @return * @throws RepositoryException */ private Object formatType(Value value) throws RepositoryException { switch (value.getType()) { case PropertyType.BOOLEAN: return String.valueOf(value.getBoolean()); case PropertyType.BINARY: return "--binary--"; case PropertyType.DATE: return value.getDate().getTime(); case PropertyType.DOUBLE: return String.valueOf(value.getDouble()); case PropertyType.LONG: return String.valueOf(value.getLong()); case PropertyType.NAME: case PropertyType.PATH: case PropertyType.REFERENCE: case PropertyType.STRING: return value.getString(); default: return "--undefined--"; } } /** * @param n * @return * @throws RepositoryException */ private String[] getMixinTypes(Node n) throws RepositoryException { List<String> mixins = new ArrayList<String>(); for (NodeType nt : n.getMixinNodeTypes()) { mixins.add(nt.getName()); } return mixins.toArray(new String[0]); } }
sakai-mirror/k2
kernel/src/main/java/org/sakaiproject/kernel/util/JCRNodeMap.java
Java
apache-2.0
5,981
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.text.translate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Unit tests for {@link org.apache.commons.lang3.text.translate.NumericEntityUnescaper}. */ @Deprecated public class NumericEntityUnescaperTest { @Test public void testSupplementaryUnescaping() { final NumericEntityUnescaper neu = new NumericEntityUnescaper(); final String input = "&#68642;"; final String expected = "\uD803\uDC22"; final String result = neu.translate(input); assertEquals(expected, result, "Failed to unescape numeric entities supplementary characters"); } @Test public void testOutOfBounds() { final NumericEntityUnescaper neu = new NumericEntityUnescaper(); assertEquals("Test &", neu.translate("Test &"), "Failed to ignore when last character is &"); assertEquals("Test &#", neu.translate("Test &#"), "Failed to ignore when last character is &"); assertEquals("Test &#x", neu.translate("Test &#x"), "Failed to ignore when last character is &"); assertEquals("Test &#X", neu.translate("Test &#X"), "Failed to ignore when last character is &"); } @Test public void testUnfinishedEntity() { // parse it NumericEntityUnescaper neu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional); String input = "Test &#x30 not test"; String expected = "Test \u0030 not test"; String result = neu.translate(input); assertEquals(expected, result, "Failed to support unfinished entities (i.e. missing semi-colon)"); // ignore it neu = new NumericEntityUnescaper(); input = "Test &#x30 not test"; expected = input; result = neu.translate(input); assertEquals(expected, result, "Failed to ignore unfinished entities (i.e. missing semi-colon)"); // fail it final NumericEntityUnescaper failingNeu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon); final String failingInput = "Test &#x30 not test"; assertThrows(IllegalArgumentException.class, () -> failingNeu.translate(failingInput)); } }
MarkDacek/commons-lang
src/test/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaperTest.java
Java
apache-2.0
3,136
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2018 Fabian Prasser and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.gui.view.impl.common; /** * A progress provider * @author Fabian Prasser * */ public interface ComponentStatusLabelProgressProvider { /** May return a progress value between 0 and 100, or always 0.*/ public abstract int getProgress(); }
RaffaelBild/arx
src/gui/org/deidentifier/arx/gui/view/impl/common/ComponentStatusLabelProgressProvider.java
Java
apache-2.0
969
package org.fogbeam.experimental.blackboard.concurrencystuff.jtp.hyde.chapter7; public class FixedWrite { private String fName; private String lName; public synchronized void setNames( String firstName, String lastName ) { print( "entering setNames()" ); fName = firstName; // a Thread might be swapped out here and // may stay out for a varying amount of time // the different sleep times exaggerate this if( fName.length() < 5 ) { try { Thread.sleep( 1000 ); } catch( Exception e ) {} } else { try { Thread.sleep( 2000 ); } catch( Exception e ) {} } lName = lastName; print( "leaving setNames() - " + fName + ", " + lName ); } public static void print( String msg ) { String threadName = Thread.currentThread().getName(); System.out.println( threadName + ": " + msg ); } public static void main( String[] args ) { final FixedWrite fw = new FixedWrite(); Runnable runA = new Runnable() { public void run() { fw.setNames( "George", "Washington" ); } }; Thread threadA = new Thread( runA, "threadA" ); threadA.start(); try { Thread.sleep( 200 ); } catch( Exception e ) {} Runnable runB = new Runnable() { public void run() { fw.setNames( "Abe", "Lincoln" ); } }; Thread threadB = new Thread( runB, "threadB" ); threadB.start(); } }
mindcrime/AISandbox
blackboard/src/main/java/org/fogbeam/experimental/blackboard/concurrencystuff/jtp/hyde/chapter7/FixedWrite.java
Java
apache-2.0
1,370
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.streaming.udfs; import java.sql.Timestamp; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import com.huawei.streaming.config.StreamingConfig; import com.huawei.streaming.exception.StreamingException; import com.huawei.streaming.util.datatype.TimestampParser; /** * 数据类型转换函数 * */ @UDFAnnotation("totimestamp") public class ToTimeStamp extends UDF { private static final long serialVersionUID = -4516472038115224500L; private static final Logger LOG = LoggerFactory.getLogger(ToTimeStamp.class); private TimestampParser timestampParser = null; /** * <默认构造函数> */ public ToTimeStamp(Map<String, String> config) throws StreamingException { super(config); StreamingConfig conf = new StreamingConfig(); for(Map.Entry<String, String> et : config.entrySet()) { conf.put(et.getKey(), et.getValue()); } timestampParser = new TimestampParser(conf); } /** * 类型转换实现 */ public Timestamp evaluate(String s) { if (Strings.isNullOrEmpty(s)) { return null; } try { /** * 更改该函数默认行为和输入一致 */ return (Timestamp)timestampParser.createValue(s); } catch (StreamingException e) { LOG.warn(EVALUATE_IGNORE_MESSAGE); return null; } } }
HuaweiBigData/StreamCQL
streaming/src/main/java/com/huawei/streaming/udfs/ToTimeStamp.java
Java
apache-2.0
2,380
// as nums consists of n + 1 elements which is from 1 to n with at least one dup number. // we can use binary search: left half should contains at most n/2 elements which is bigger than mid, vice versa. // the one contains more means there is duplicates. eg: // 1,2,2,4,5,6,6, is 1....6, mid is 3, total have 3 elements are <= 3. then dup must be in right half. // 5,2,3,4,1,7,5,3, // 1) mid = (1 + 7) / 2 = 4 -> 5 , 5 > 4, right = mid - 1, dup -> 1, 3 (4 - 1) // 1,1,1,1,1,1,1,1 // (1 + 7) /2 -> mid = 4, count = 8, dup -> [1, 3] 3 -> 4 - 1 //1,2,2,4,5,7,6,6 // mid = 4, count = 3, dup -> [5, 7] // 3,3,3,3,5,5,5,5 // 1 + 7 /2 -> mid = 4, count = 5, dup -> [1,3] // mid = 2, count = 3, dup -> [1, 1] // mid = 1, count = 1, low -> [2, 1], return low -> 2 // 8,8,8,8,8,8,8,8 // public class FindTheDuplicateNumber { public int findDuplicate(int[] nums) { int low = 1, high = nums.length - 1; while(low <= high){ int mid = low + (high - low) / 2; int count = 0; for(int i : nums){ if(i <= mid) count++; } if(count > mid){ // low...mid count should have dup high = mid -1; }else{ low = mid + 1; } } return low; } }
zouzhiguang/practices
two_pointing/FindTheDuplicateNumber.java
Java
apache-2.0
1,340
package org.huberb.i18nvalidator.spi; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.WeakHashMap; import org.huberb.i18nvalidator.api.*; /** * * @author HuberB1 */ public abstract class AbstractVisitor { protected PropertyChangeSupport pcs; private WeakHashMap<Class,Method> methodMap; public static final String VISTING_PROP = "visiting"; public AbstractVisitor() { this.methodMap = new WeakHashMap<Class,Method>(); this.pcs = new PropertyChangeSupport(this); } //------------------------------------------------------------------------- public void visit(AbstractComponent ac) { //System.out.println("???visit???" + ac ); final Class acClass = ac.getClass(); Method m = methodMap.get( acClass ); if (m == null) { try { m = this.getClass().getMethod("_visit", acClass ); methodMap.put( acClass, m ); } catch (SecurityException ex) { ex.printStackTrace(); } catch (NoSuchMethodException ex) { ex.printStackTrace(); } } if (m != null) { try { pcs.firePropertyChange( VISTING_PROP, null, ac ); m.invoke( this, ac ); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } //------------------------------------------------------------------------- public void _visit(ContextComposite cc) { AbstractComponent ac = cc.getContext(); if (ac != null) { ac.accept( this ); } _visit( (AbstractComposite)cc ); } //---- public void _visit(AbstractComposite abstractComposite) { for (Iterator<AbstractComponent> i = abstractComposite.getItems().iterator(); i.hasNext(); ) { AbstractComponent ac = i.next(); ac.accept( this ); } } //---- public void _visit(FindInfoComposite fic) { _visit( (AbstractComposite)fic ); } public void _visit(SearchInfoComposite fic) { _visit( (AbstractComposite)fic ); } //------------------------------------------------------------------------- public void addPropertyChangeListener(PropertyChangeListener pcl) { this.pcs.addPropertyChangeListener(pcl); } public void addAllPropertyChangeListeners(PropertyChangeListener[] pcls) { for (int i = 0; i < pcls.length; i++ ) { this.pcs.addPropertyChangeListener( pcls[i] ); } } public void removePropertyChangeListener(PropertyChangeListener pcl) { this.pcs.removePropertyChangeListener(pcl); } public PropertyChangeListener[] getPropertyChangeListeners() { return this.pcs.getPropertyChangeListeners(); } }
bernhardhuber/netbeansplugins
nb-i18n-validator/src/org/huberb/i18nvalidator/spi/AbstractVisitor.java
Java
apache-2.0
3,300
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2013 * Contact : [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jrebirth.core.command; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.jrebirth.core.concurrent.RunType; import org.jrebirth.core.exception.CoreException; import org.jrebirth.core.wave.Wave; import org.jrebirth.core.wave.WaveBean; import org.jrebirth.core.wave.WaveBuilder; import org.jrebirth.core.wave.WaveGroup; import org.jrebirth.core.wave.WaveListener; /** * The class <strong>AbstractMultiCommand</strong>. * * The base multi command class for Internal commands. * * @author Sébastien Bordes * * @param <WB> The WaveBean type used for this command (by default you can use the WaveBean interface) */ public abstract class AbstractMultiCommand<WB extends WaveBean> extends AbstractBaseCommand<WB> implements MultiCommand<WB>, WaveListener { /** The command is running. */ private final AtomicBoolean running = new AtomicBoolean(false); /** The list of command that will be chained. */ private final List<Class<? extends Command>> commandList = new ArrayList<>(); /** Flag that indicate if commands must be run sequentially(true) or in parallel(false). */ private final boolean sequential; /** The index of the last command performed. */ private int commandRunIndex; /** The source wave that trigger this command. */ private Wave waveSource; /** * Default Constructor. * * @param runInto The run into thread type */ public AbstractMultiCommand(final RunType runInto) { this(runInto, true); } /** * Default Constructor. * * @param sequential indicate if commands must be run sequentially(true) or in parallel(false) */ public AbstractMultiCommand(final boolean sequential) { super(); this.sequential = sequential; } /** * Default Constructor. * * @param runInto The run into thread type * @param sequential indicate if commands must be run sequentially(true) or in parallel(false) */ public AbstractMultiCommand(final RunType runInto, final boolean sequential) { super(runInto); this.sequential = sequential; } /** * {@inheritDoc} */ @Override public void ready() throws CoreException { addSubCommand(); for (final Class<? extends Command> commandClass : this.commandList) { getLocalFacade().retrieve(commandClass); } } /** * This method must be used to add sub command. */ protected abstract void addSubCommand(); /** * {@inheritDoc} */ @Override public void preExecute(final Wave wave) { this.running.set(true); } /** * {@inheritDoc} */ @Override public void postExecute(final Wave wave) { // Nothing to do } /** * @return Returns the running. */ public boolean isRunning() { return this.running.get(); } /** * {@inheritDoc} */ @Override protected void execute(final Wave wave) { if (this.sequential) { // Store the wave when we are running the first command synchronized (this) { if (this.commandRunIndex == 0) { this.waveSource = wave; } if (this.commandList.size() > this.commandRunIndex) { final Wave subCommandWave = WaveBuilder.create() .waveGroup(WaveGroup.CALL_COMMAND) .relatedClass(this.commandList.get(this.commandRunIndex)) .build(); subCommandWave.linkWaveBean(wave.getWaveBean()); subCommandWave.addWaveListener(this); sendWave(subCommandWave); } } } else { // Launch all sub command in parallel for (final Class<? extends Command> commandClass : this.commandList) { getLocalFacade().retrieve(commandClass).run(); } } } /** * {@inheritDoc} */ @Override public void waveConsumed(final Wave wave) { if (this.sequential) { synchronized (this) { // Move the index to retrieve the next command to run this.commandRunIndex++; // Run next command if any if (this.commandList.size() > this.commandRunIndex) { execute(wave); } else { this.running.set(false); // No more command to run the MultiCommand is achieved fireConsumed(this.waveSource); } } } } /** * {@inheritDoc} */ @Override public void waveFailed(final Wave wave) { if (this.sequential) { synchronized (this) { // A sub command has failed fireFailed(this.waveSource); } } } /** * {@inheritDoc} */ @Override public void addCommandClass(final Class<? extends Command> commandClass) { this.commandList.add(commandClass); } }
amischler/JRebirth
org.jrebirth/core/src/main/java/org/jrebirth/core/command/AbstractMultiCommand.java
Java
apache-2.0
6,137
/** * Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.pay.response.parser; import com.amazon.pay.response.model.ListOrderReferenceByNextTokenResponse; import com.amazon.pay.response.model.OrderReference; import com.amazon.pay.response.model.OrderReferenceList; import java.io.Serializable; import java.util.List; /** * Response from ListOrderReferenceByNextToken service API, as returned by Amazon Pay */ public class ListOrderReferenceByNextTokenResponseData extends ResponseData implements Serializable { private String requestId; private OrderReferenceList orderReferenceList; private String nextPageToken; private List<OrderReference> orderReferences; /** * The requestID that uniquely identifies the service request * the caller made. * * @return The requestID that uniquely identifies the service request * the caller made. */ public String getRequestId() { return requestId; } /** * Returns a list of order reference objects which encapsulates details about an order. * * @return orderReferences */ public List<OrderReference> getOrderReferences() { return orderReferences; } /** * Returns the next page token. * * @return orderReferences */ public String getNextPageToken() { return nextPageToken; } public ListOrderReferenceByNextTokenResponseData(ListOrderReferenceByNextTokenResponse response, ResponseData rawResponse){ super(rawResponse); if (response!= null){ this.requestId = response.getResponseMetadata().getRequestId(); if (response.getListOrderReferenceByNextTokenResult()!= null){ orderReferenceList = response.getListOrderReferenceByNextTokenResult().getOrderReferenceList(); nextPageToken = response.getListOrderReferenceByNextTokenResult().getNextPageToken(); if (orderReferenceList != null) { orderReferences = orderReferenceList.getOrderReferences(); } } } } /** * Returns the string representation of ListOrderReferenceByNextTokenResponseData */ @Override public String toString() { return "ListOrderReferenceByNextTokenResponseData{" + "requestId=" + requestId + ", nextPageToken=" + nextPageToken + ", orderReferences=" + orderReferences.toString() + '}'; } }
amzn/login-and-pay-with-amazon-sdk-java
src/com/amazon/pay/response/parser/ListOrderReferenceByNextTokenResponseData.java
Java
apache-2.0
3,018
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glowroot.agent.weaving; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; import org.immutables.value.Value; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import static com.google.common.base.Preconditions.checkNotNull; import static org.objectweb.asm.Opcodes.ACC_BRIDGE; import static org.objectweb.asm.Opcodes.ASM9; class ThinClassVisitor extends ClassVisitor { private final ImmutableThinClass.Builder thinClassBuilder = ImmutableThinClass.builder(); private int majorVersion; private @Nullable ThinClass thinClass; private boolean constructorPointcut; ThinClassVisitor() { super(ASM9); } @Override public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String /*@Nullable*/ [] interfaces) { majorVersion = version & 0xFFFF; thinClassBuilder.access(access); thinClassBuilder.name(name); thinClassBuilder.superName(superName); if (interfaces != null) { thinClassBuilder.addInterfaces(interfaces); } } @Override public @Nullable AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { thinClassBuilder.addAnnotations(descriptor); if (descriptor.equals("Lorg/glowroot/agent/plugin/api/weaving/Pointcut;")) { return new PointcutAnnotationVisitor(); } else if (descriptor.equals("Ljavax/ejb/Remote;")) { return new RemoteAnnotationVisitor(); } else { return null; } } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String /*@Nullable*/ [] exceptions) { ImmutableThinMethod.Builder thinMethodBuilder = ImmutableThinMethod.builder(); thinMethodBuilder.access(access); thinMethodBuilder.name(name); thinMethodBuilder.descriptor(descriptor); thinMethodBuilder.signature(signature); if (exceptions != null) { thinMethodBuilder.addExceptions(exceptions); } return new AnnotationCaptureMethodVisitor(thinMethodBuilder); } @Override public void visitEnd() { thinClass = thinClassBuilder.build(); } int getMajorVersion() { return majorVersion; } ThinClass getThinClass() { return checkNotNull(thinClass); } boolean isConstructorPointcut() { return constructorPointcut; } @Value.Immutable interface ThinClass { int access(); String name(); @Nullable String superName(); List<String> interfaces(); List<String> annotations(); List<ThinMethod> nonBridgeMethods(); List<ThinMethod> bridgeMethods(); List<Type> ejbRemoteInterfaces(); } @Value.Immutable interface ThinMethod { int access(); String name(); String descriptor(); @Nullable String signature(); List<String> exceptions(); List<String> annotations(); } private class PointcutAnnotationVisitor extends AnnotationVisitor { private PointcutAnnotationVisitor() { super(ASM9); } @Override public void visit(@Nullable String name, Object value) { if ("methodName".equals(name) && "<init>".equals(value)) { constructorPointcut = true; } } } private class AnnotationCaptureMethodVisitor extends MethodVisitor { private final ImmutableThinMethod.Builder thinMethodBuilder; private AnnotationCaptureMethodVisitor(ImmutableThinMethod.Builder thinMethodBuilder) { super(ASM9); this.thinMethodBuilder = thinMethodBuilder; } @Override public @Nullable AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { thinMethodBuilder.addAnnotations(descriptor); return null; } @Override public void visitEnd() { ThinMethod thinMethod = thinMethodBuilder.build(); if ((thinMethod.access() & ACC_BRIDGE) != 0) { thinClassBuilder.addBridgeMethods(thinMethod); } else { thinClassBuilder.addNonBridgeMethods(thinMethod); } } } private class RemoteAnnotationVisitor extends AnnotationVisitor { private RemoteAnnotationVisitor() { super(ASM9); } @Override public @Nullable AnnotationVisitor visitArray(String name) { if (name.equals("value")) { return new ValueAnnotationVisitor(); } else { return null; } } } private class ValueAnnotationVisitor extends AnnotationVisitor { private ValueAnnotationVisitor() { super(ASM9); } @Override public void visit(@Nullable String name, Object value) { if (name == null && value instanceof Type) { thinClassBuilder.addEjbRemoteInterfaces((Type) value); } } } }
glowroot/glowroot
agent/core/src/main/java/org/glowroot/agent/weaving/ThinClassVisitor.java
Java
apache-2.0
5,933
/* * Copyright 2011, 2012 Thomas Amsler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thomasamsler.android.flashcards.fragment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.thomasamsler.android.flashcards.ActionBusListener; import org.thomasamsler.android.flashcards.AppConstants; import org.thomasamsler.android.flashcards.MainApplication; import org.thomasamsler.android.flashcards.R; import org.thomasamsler.android.flashcards.activity.MainActivity; import org.thomasamsler.android.flashcards.db.DataSource; import org.thomasamsler.android.flashcards.external.FlashCardExchangeData; import org.thomasamsler.android.flashcards.model.Card; import org.thomasamsler.android.flashcards.model.CardSet; import org.thomasamsler.android.flashcards.sample.WordSets; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.Html; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class CardSetsFragment extends ListFragment implements AppConstants, ActionBusListener, FlashCardExchangeData { private static final int MENU_ITEM_ADD = 1; private static final int MENU_ITEM_DELETE = 2; private List<CardSet> mCardSets; private ArrayAdapter<CardSet> mArrayAdapter; private ProgressBar mProgressBar; private DataSource mDataSource; private MainActivity mActivity; private MainApplication mMainApplication; @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mActivity = (MainActivity) getActivity(); mDataSource = mActivity.getDataSource(); mMainApplication = (MainApplication) mActivity.getApplication(); mMainApplication.registerAction(this, ACTION_DELETE_CARD_UPDATE_CARD_SET); registerForContextMenu(getListView()); mProgressBar = (ProgressBar) mActivity.findViewById(R.id.progressBar); if (null == mCardSets && null == mArrayAdapter) { mCardSets = new ArrayList<CardSet>(); mArrayAdapter = new ArrayAdapter<CardSet>(mActivity, android.R.layout.simple_list_item_1, mCardSets) { /* * Overwriting getView method to style the list item font. If * it's a remote item that hasn't been clicked on, we style it * bold */ @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView = (TextView) super.getView(position, convertView, parent); CardSet cardSet = mCardSets.get(position); switch (cardSet.getCardCount()) { case 0: textView.setText(Html.fromHtml(cardSet.getTitle() + "<br /><small><i><font color='#989898'>empty</font></i></small>")); break; case 1: textView.setText(Html.fromHtml(cardSet.getTitle() + "<br /><small><i><font color='#989898'>" + cardSet.getCardCount() + " card</font></i></small>")); break; default: textView.setText(Html.fromHtml(cardSet.getTitle() + "<br /><small><i><font color='#989898'>" + cardSet.getCardCount() + " cards</font></i></small>")); break; } if (mCardSets.get(position).isRemote()) { ((TextView) textView).setTypeface(Typeface.DEFAULT_BOLD); } else { ((TextView) textView).setTypeface(Typeface.DEFAULT); } return textView; } }; setListAdapter(mArrayAdapter); } else { mCardSets.clear(); mArrayAdapter.notifyDataSetChanged(); } mCardSets.addAll(mDataSource.getCardSets()); if (0 == mCardSets.size()) { SharedPreferences sharedPreferences = mActivity.getSharedPreferences(AppConstants.PREFERENCE_NAME, Context.MODE_PRIVATE); boolean showSample = sharedPreferences.getBoolean(AppConstants.PREFERENCE_SHOW_SAMPLE, AppConstants.PREFERENCE_SHOW_SAMPLE_DEFAULT); if (showSample) { createDefaultCardSets(); mCardSets.addAll(mDataSource.getCardSets()); } else { Toast.makeText(mMainApplication, R.string.list_no_card_sets_message, Toast.LENGTH_SHORT).show(); } } Collections.sort(mCardSets); mArrayAdapter.notifyDataSetChanged(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { CardSet cardSet = mCardSets.get(position); if (!cardSet.isRemote() && !cardSet.hasCards()) { Toast.makeText(mMainApplication, R.string.view_cards_emtpy_set_message, Toast.LENGTH_SHORT).show(); return; } if (cardSet.isRemote()) { mProgressBar.setVisibility(ProgressBar.VISIBLE); cardSet.setFragmentId(CardSet.CARDS_PAGER_FRAGMENT); if (hasConnectivity()) { GetExternalCardsTask getExternalCardsTask = new GetExternalCardsTask(cardSet); getExternalCardsTask.execute(); } else { mProgressBar.setVisibility(ProgressBar.GONE); Toast.makeText(mMainApplication, R.string.util_connectivity_error, Toast.LENGTH_SHORT).show(); } } else { mMainApplication.doAction(ACTION_SHOW_CARDS, cardSet); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(MENU_ITEM_ADD, MENU_ITEM_ADD, 1, R.string.list_menu_add); menu.add(MENU_ITEM_DELETE, MENU_ITEM_DELETE, 2, R.string.list_meanu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int listItemPosition = (int) getListAdapter().getItemId(info.position); switch (item.getGroupId()) { case MENU_ITEM_ADD: addCard(listItemPosition); break; case MENU_ITEM_DELETE: deleteCardSet(listItemPosition); break; default: Log.w(AppConstants.LOG_TAG, "List context menu selection not recognized."); } return false; } @Override public void onResume() { super.onResume(); mMainApplication.doAction(ACTION_SET_HELP_CONTEXT, HELP_CONTEXT_CARD_SET_LIST); } public void addCardSet(CardSet cardSet) { mCardSets.add(cardSet); Collections.sort(mCardSets); mArrayAdapter.notifyDataSetChanged(); } private void decrementCardCount(long cardSetId) { if (AppConstants.INVALID_CARD_SET_ID != cardSetId) { for (CardSet cardSet : mCardSets) { if (cardSet.getId() == cardSetId) { cardSet.setCardCount(cardSet.getCardCount() - 1); break; } } } } public void getFlashCardExchangeCardSets() { SharedPreferences preferences = mActivity.getSharedPreferences(AppConstants.PREFERENCE_NAME, Context.MODE_PRIVATE); String userName = preferences.getString(AppConstants.PREFERENCE_FCEX_USER_NAME, ""); if (null != userName && !"".equals(userName)) { mProgressBar.setVisibility(ProgressBar.VISIBLE); if (hasConnectivity()) { GetExternalCardSetsTask getExternalCardSetsTask = new GetExternalCardSetsTask(userName); getExternalCardSetsTask.execute(); } else { mProgressBar.setVisibility(ProgressBar.GONE); Toast.makeText(mMainApplication, R.string.util_connectivity_error, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(mMainApplication, R.string.setup_no_user_name_defined, Toast.LENGTH_SHORT).show(); mMainApplication.doAction(ACTION_SHOW_SETUP); } } private void addCard(int listItemPosition) { CardSet cardSet = mCardSets.get(listItemPosition); if (cardSet.isRemote()) { mProgressBar.setVisibility(ProgressBar.VISIBLE); cardSet.setFragmentId(CardSet.ADD_CARD_FRAGMENT); if (hasConnectivity()) { GetExternalCardsTask getExternalCardsTask = new GetExternalCardsTask(cardSet); getExternalCardsTask.execute(); } else { mProgressBar.setVisibility(ProgressBar.GONE); Toast.makeText(mMainApplication, R.string.util_connectivity_error, Toast.LENGTH_SHORT).show(); } } else { mMainApplication.doAction(ACTION_SHOW_ADD_CARD, cardSet); } } private void deleteCardSet(final int listItemPosition) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage(R.string.delete_card_set_dialog_message); builder.setCancelable(false); builder.setPositiveButton(R.string.delete_card_set_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { CardSet cardSet = mCardSets.get(listItemPosition); List<CardSet> cardSets = mDataSource.getCardSets(); if (cardSets.contains(cardSet)) { mDataSource.deleteCardSet(cardSet); } mCardSets.remove(listItemPosition); Collections.sort(mCardSets); mArrayAdapter.notifyDataSetChanged(); } }); builder.setNegativeButton(R.string.delete_card_set_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private void createDefaultCardSets() { List<CardSet> cardSets = mDataSource.getCardSets(); // Loading first sample CardSet CardSet sampleCardSet = new CardSet(); sampleCardSet.setTitle(WordSets.mWordSetNames.get(0)); if (!cardSets.contains(sampleCardSet)) { List<String> samples = new ArrayList<String>(Arrays.asList(getResources().getStringArray(WordSets.mWordSets.get(Integer.valueOf(0))))); sampleCardSet.setCardCount(samples.size()); mDataSource.createCardSet(sampleCardSet); int displayOrder = 1; for (String sample : samples) { String[] parts = sample.split(":"); Card newCard = new Card(); newCard.setQuestion(parts[0]); newCard.setAnswer(parts[1]); newCard.setCardSetId(sampleCardSet.getId()); newCard.setDisplayOrder(displayOrder); displayOrder += 1; mDataSource.createCard(newCard); } } // Loading second sample CardSet sampleCardSet = new CardSet(); sampleCardSet.setTitle(WordSets.mWordSetNames.get(1)); if (!cardSets.contains(sampleCardSet)) { List<String> samples = new ArrayList<String>(Arrays.asList(getResources().getStringArray(WordSets.mWordSets.get(Integer.valueOf(1))))); sampleCardSet.setCardCount(samples.size()); mDataSource.createCardSet(sampleCardSet); int displayOrder = 1; for (String sample : samples) { String[] parts = sample.split(":"); Card newCard = new Card(); newCard.setQuestion(parts[0]); newCard.setAnswer(parts[1]); newCard.setCardSetId(sampleCardSet.getId()); newCard.setDisplayOrder(displayOrder); displayOrder += 1; mDataSource.createCard(newCard); } } } /* * Helper method to check if there is network connectivity */ private boolean hasConnectivity() { return mActivity.hasConnectivity(); } private class GetExternalCardSetsTask extends AsyncTask<Void, Void, Void> { private String mUserName; private JSONObject mResult; private boolean hasError; public GetExternalCardSetsTask(String userName) { mUserName = userName.trim(); hasError = false; } @Override protected Void doInBackground(Void... params) { StringBuilder uriBuilder = new StringBuilder(); uriBuilder.append(API_GET_USER).append(mUserName).append(API_KEY); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = null; try { httpGet = new HttpGet(uriBuilder.toString()); } catch (IllegalArgumentException e) { Log.e(AppConstants.LOG_TAG, "IllegalArgumentException", e); } HttpResponse response; if (null == httpGet) { hasError = true; return null; } try { response = httpclient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { content.append(line); } } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); } finally { try { reader.close(); } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); } } mResult = new JSONObject(content.toString()); if (null == mResult) { hasError = true; return null; } String responseType = mResult.getString(FIELD_RESPONSE_TYPE); if (null == responseType || !RESPONSE_OK.equals(responseType)) { Toast.makeText(mMainApplication, R.string.util_flash_card_exchange_api_error, Toast.LENGTH_LONG).show(); return null; } JSONArray jsonArray = mResult.getJSONObject(FIELD_RESULT).getJSONArray(FILED_SETS); /* * Only add "new" cards to the list */ for (int i = 0; i < jsonArray.length(); i++) { JSONObject data = jsonArray.getJSONObject(i); CardSet newCardSet = new CardSet(); newCardSet.setTitle(data.getString(FIELD_TITLE)); newCardSet.setExternalId(data.getString(FIELD_CARD_SET_ID)); newCardSet.setCardCount(data.getInt(FIELD_FLASHCARD_COUNT)); if (!mCardSets.contains(newCardSet)) { mCardSets.add(newCardSet); } } /* * Sorting the list and refresh it */ Collections.sort(mCardSets); } } catch (ClientProtocolException e) { Log.e(AppConstants.LOG_TAG, "ClientProtocolException", e); hasError = true; } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); hasError = true; } catch (JSONException e) { Log.e(AppConstants.LOG_TAG, "JSONException", e); hasError = true; } catch (Exception e) { Log.e(AppConstants.LOG_TAG, "General Exception", e); hasError = true; } return null; } @Override protected void onPostExecute(Void arg) { mProgressBar.setVisibility(ProgressBar.GONE); mArrayAdapter.notifyDataSetChanged(); if (hasError) { Toast.makeText(mMainApplication, R.string.view_cards_fetch_remote_error, Toast.LENGTH_LONG).show(); } } } private class GetExternalCardsTask extends AsyncTask<Void, Void, Void> { private CardSet mCardSet; private JSONObject mResult; private boolean hasError; public GetExternalCardsTask(CardSet cardSet) { mCardSet = cardSet; hasError = false; } @Override protected Void doInBackground(Void... params) { StringBuilder uriBuilder = new StringBuilder(); uriBuilder.append(API_GET_CARD_SET).append(mCardSet.getExternalId()).append(API_KEY); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = null; try { httpGet = new HttpGet(uriBuilder.toString()); } catch (IllegalArgumentException e) { Log.e(AppConstants.LOG_TAG, "IllegalArgumentException", e); } HttpResponse response; if (null == httpGet) { hasError = true; return null; } try { response = httpclient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { content.append(line); } } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); } finally { try { reader.close(); } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); } } mResult = new JSONObject(content.toString()); // Check REST call response String responseType = mResult.getString(FIELD_RESPONSE_TYPE); if (null == responseType || !RESPONSE_OK.equals(responseType)) { hasError = true; return null; } // Card Set Cards JSONArray jsonArray = mResult.getJSONObject(FIELD_RESULT).getJSONArray(FIELD_FLASHCARDS); // Store the CardSet mCardSet.setExternalId(""); mDataSource.createCardSet(mCardSet); // Store all the Cards for (int i = 0; i < jsonArray.length(); i++) { JSONObject data = jsonArray.getJSONObject(i); Card card = new Card(); card.setId(data.getLong(FIELD_CARD_ID)); card.setExternalId(data.getString(FIELD_CARD_ID)); card.setQuestion(data.getString(FIELD_QUESTION)); card.setAnswer(data.getString(FIELD_ANSWER)); card.setDisplayOrder(data.getInt(FIELD_DISPLAY_ORDER)); card.setCardSetId(mCardSet.getId()); mDataSource.createCard(card); } /* * Now that we have the cards, we indicate that we don't * need to get them anymore, thus setting the card set's id * to an empty string */ int position = mCardSets.indexOf(mCardSet); mCardSets.get(position).setExternalId(""); mCardSets.get(position).setId(mCardSet.getId()); } } catch (ClientProtocolException e) { Log.e(AppConstants.LOG_TAG, "ClientProtocolException", e); } catch (IOException e) { Log.e(AppConstants.LOG_TAG, "IOException", e); } catch (Exception e) { Log.e(AppConstants.LOG_TAG, "General Exception", e); } return null; } @Override protected void onPostExecute(Void arg) { mProgressBar.setVisibility(View.GONE); mArrayAdapter.notifyDataSetChanged(); if (hasError) { Toast.makeText(mActivity.getApplicationContext(), R.string.util_flash_card_exchange_api_error, Toast.LENGTH_LONG).show(); } try { mProgressBar.setVisibility(ProgressBar.GONE); if (null == mResult) { Toast.makeText(mActivity.getApplicationContext(), R.string.view_cards_fetch_remote_error, Toast.LENGTH_LONG).show(); return; } if (null == mCardSet) { return; } switch (mCardSet.getFragmentId()) { case CardSet.ADD_CARD_FRAGMENT: mMainApplication.doAction(ACTION_SHOW_ADD_CARD, mCardSet); return; case CardSet.CARDS_PAGER_FRAGMENT: mMainApplication.doAction(ACTION_SHOW_CARDS, mCardSet); return; } } catch (Exception e) { Log.e(AppConstants.LOG_TAG, "General Exception", e); } } } public void doAction(Integer action, Object data) { switch (action) { case ACTION_DELETE_CARD_UPDATE_CARD_SET: decrementCardCount(((Long) data).longValue()); break; } } }
tamsler/android-flash-cards
src/org/thomasamsler/android/flashcards/fragment/CardSetsFragment.java
Java
apache-2.0
19,724
package natlab.backends.Fortran.codegen_simplified; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import natlab.backends.Fortran.codegen_simplified.FortranAST_simplified.StatementSection; import natlab.backends.Fortran.codegen_simplified.FortranAST_simplified.Subprogram; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRAbstractAssignToListStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRAbstractAssignToVarStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRArrayGetStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRArraySetStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRAssignLiteralStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRCommentStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRForStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRFunction; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRIfStmt; import natlab.backends.Fortran.codegen_simplified.astCaseHandler.HandleCaseTIRWhileStmt; import natlab.tame.tir.TIRAbstractAssignToListStmt; import natlab.tame.tir.TIRAbstractAssignToVarStmt; import natlab.tame.tir.TIRArrayGetStmt; import natlab.tame.tir.TIRArraySetStmt; import natlab.tame.tir.TIRAssignLiteralStmt; import natlab.tame.tir.TIRCommentStmt; import natlab.tame.tir.TIRForStmt; import natlab.tame.tir.TIRFunction; import natlab.tame.tir.TIRIfStmt; import natlab.tame.tir.TIRNode; import natlab.tame.tir.TIRWhileStmt; import natlab.tame.tir.analysis.TIRAbstractNodeCaseHandler; import natlab.tame.valueanalysis.ValueAnalysis; import natlab.tame.valueanalysis.ValueFlowMap; import natlab.tame.valueanalysis.ValueSet; import natlab.tame.valueanalysis.aggrvalue.AggrValue; import natlab.tame.valueanalysis.aggrvalue.CellValue; import natlab.tame.valueanalysis.basicmatrix.BasicMatrixValue; import ast.ASTNode; public class FortranCodeASTGenerator extends TIRAbstractNodeCaseHandler { static boolean Debug = false; // this currentOutSet is the out set at the end point of the program. public ValueFlowMap<AggrValue<BasicMatrixValue>> currentOutSet; public int callgraphSize; public String entryPointFile; // public Set<String> userDefinedFunctions; public Set<String> allSubprograms; public Subprogram subprogram; public StringBuffer buf; public StringBuffer buf2; public FortranMapping fortranMapping; public String functionName; public List<String> inArgs; public List<String> outRes; public boolean isInSubroutine; // used to back up input argument. public Set<String> inputHasChanged; public Set<String> arrayConvert; public int ifWhileForBlockNest; public StatementSection stmtSecForIfWhileForBlock; public int indentNum; public String standardIndent; /* * tmpVarAsArrayIndex, * K: the name of the temporary vector variable, * V: the range of those variables. */ public Map<String, ArrayList<String>> tempVectorAsArrayIndex; // temporary variables generated during McSAF or Tamer simplification. public Set<String> tempVarsBeforeF; // temporary variables generated in Fortran code generation. public Map<String, BasicMatrixValue> fortranTemporaries; // not support nested cell array. public Map<String, ArrayList<BasicMatrixValue>> forCellArr; public List<String> declaredCell; /** * private constructor, called by helper method generateFortran. * @param analysis * @param callgraphSize * @param index * @param entryPointFile */ private FortranCodeASTGenerator( ValueAnalysis<AggrValue<BasicMatrixValue>> analysis, int callgraphSize, int index, String entryPointFile, Set<String> userDefinedFunctions) { currentOutSet = analysis.getNodeList() .get(index).getAnalysis().getCurrentOutSet(); this.callgraphSize = callgraphSize; this.entryPointFile = entryPointFile; // this.userDefinedFunctions = userDefinedFunctions; allSubprograms = new HashSet<String>(); fortranMapping = new FortranMapping(); functionName = ""; subprogram = new Subprogram(); inArgs = new ArrayList<String>(); outRes = new ArrayList<String>(); isInSubroutine = false; inputHasChanged = new HashSet<String>(); arrayConvert = new HashSet<String>(); ifWhileForBlockNest = 0; stmtSecForIfWhileForBlock = new StatementSection(); indentNum = 0; standardIndent = " "; tempVectorAsArrayIndex = new HashMap<String, ArrayList<String>>(); tempVarsBeforeF = new HashSet<String>(); fortranTemporaries = new HashMap<String,BasicMatrixValue>(); forCellArr = new HashMap<String, ArrayList<BasicMatrixValue>>(); declaredCell = new ArrayList<String>(); ((TIRNode) analysis.getNodeList() .get(index).getFunction().getAst()).tirAnalyze(this); } // ******************************ast node override************************* @Override @SuppressWarnings("rawtypes") public void caseASTNode(ASTNode node) {} @Override public void caseTIRFunction(TIRFunction node) { HandleCaseTIRFunction functionStmt = new HandleCaseTIRFunction(); functionStmt.getFortran(this, node); } @Override public void caseTIRCommentStmt(TIRCommentStmt node) { HandleCaseTIRCommentStmt commentStmt = new HandleCaseTIRCommentStmt(); if (ifWhileForBlockNest!=0) stmtSecForIfWhileForBlock.addStatement( commentStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( commentStmt.getFortran(this, node)); } @Override public void caseTIRAssignLiteralStmt(TIRAssignLiteralStmt node) { /* * insert constant variable replacement check. */ String targetName = node.getTargetName().getVarName(); if (hasSingleton(targetName) && getMatrixValue(targetName).hasConstant() && !outRes.contains(targetName) && !inArgs.contains(targetName) && node.getTargetName().tmpVar) { tempVarsBeforeF.add(targetName); if (Debug) System.out.println(targetName + " has a constant value and safe to be replaced."); } else { HandleCaseTIRAssignLiteralStmt assignLiteralStmt = new HandleCaseTIRAssignLiteralStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( assignLiteralStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( assignLiteralStmt.getFortran(this, node)); } } @Override public void caseTIRAbstractAssignToVarStmt(TIRAbstractAssignToVarStmt node) { /* * insert constant variable replacement check. */ String targetName = node.getTargetName().getVarName(); if (!isCell(targetName) && hasSingleton(targetName) && getMatrixValue(targetName).hasConstant() && !this.outRes.contains(targetName) && node.getTargetName().tmpVar) { tempVarsBeforeF.add(targetName); if (Debug) System.out.println(targetName + " has a constant value and safe to be replaced."); } else { HandleCaseTIRAbstractAssignToVarStmt abstractAssignToVarStmt = new HandleCaseTIRAbstractAssignToVarStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( abstractAssignToVarStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( abstractAssignToVarStmt.getFortran(this, node)); } } @Override public void caseTIRAbstractAssignToListStmt(TIRAbstractAssignToListStmt node) { /* * insert constant variable replacement check. * p.s. need to check whether the expression is io expression, * because io expression doesn't have target variable * * one more problem, for this case, the lhs is a list of variable. * And because node.getTargetName().getVarName() can only return * the first variable, we need use node.getTargets().asNameList(). */ if (HandleCaseTIRAbstractAssignToListStmt .getRHSCaseNumber(this, node) != 6) { String targetName = node.getTargetName().getVarName(); if(!isCell(targetName) && hasSingleton(targetName) && getMatrixValue(targetName).hasConstant() && !outRes.contains(targetName) && node.getTargetName().tmpVar) { tempVarsBeforeF.add(targetName); if (Debug) System.out.println(targetName + " has a constant value and safe to be replaced."); } else { HandleCaseTIRAbstractAssignToListStmt abstractAssignToListStmt = new HandleCaseTIRAbstractAssignToListStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( abstractAssignToListStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( abstractAssignToListStmt.getFortran(this, node)); } } else { HandleCaseTIRAbstractAssignToListStmt abstractAssignToListStmt = new HandleCaseTIRAbstractAssignToListStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( abstractAssignToListStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( abstractAssignToListStmt.getFortran(this, node)); } } @Override public void caseTIRIfStmt(TIRIfStmt node) { HandleCaseTIRIfStmt ifStmt = new HandleCaseTIRIfStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( ifStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( ifStmt.getFortran(this, node)); } @Override public void caseTIRWhileStmt(TIRWhileStmt node) { HandleCaseTIRWhileStmt whileStmt = new HandleCaseTIRWhileStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( whileStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( whileStmt.getFortran(this, node)); } @Override public void caseTIRForStmt(TIRForStmt node) { HandleCaseTIRForStmt forStmt = new HandleCaseTIRForStmt(); if(ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( forStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( forStmt.getFortran(this, node)); } @Override public void caseTIRArrayGetStmt(TIRArrayGetStmt node) { HandleCaseTIRArrayGetStmt arrGetStmt = new HandleCaseTIRArrayGetStmt(); if(ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( arrGetStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( arrGetStmt.getFortran(this, node)); } @Override public void caseTIRArraySetStmt(TIRArraySetStmt node) { HandleCaseTIRArraySetStmt arrSetStmt = new HandleCaseTIRArraySetStmt(); if (ifWhileForBlockNest != 0) stmtSecForIfWhileForBlock.addStatement( arrSetStmt.getFortran(this, node)); else subprogram.getStatementSection().addStatement( arrSetStmt.getFortran(this, node)); } // ******************************helper methods**************************** public static Subprogram generateFortran( ValueAnalysis<AggrValue<BasicMatrixValue>> analysis, int callgraphSize, int index, String entryPointFile, Set<String> userDefinedFunctions) { return new FortranCodeASTGenerator( analysis, callgraphSize, index, entryPointFile, userDefinedFunctions).subprogram; } public void iterateStatements(ast.List<ast.Stmt> stmts) { for (ast.Stmt stmt : stmts) { ((TIRNode)stmt).tirAnalyze(this); } } public boolean hasArrayAsInput() { boolean result = false; for (String inArg : inArgs) { if (!getMatrixValue(inArg).getShape().isScalar()) result = true; } return result; } public ValueFlowMap<AggrValue<BasicMatrixValue>> getCurrentOutSet() { return currentOutSet; } public BasicMatrixValue getMatrixValue(String variable) { if (variable.indexOf("_copy") != -1) { int index = variable.indexOf("_copy"); String originalVar = variable.substring(0, index); return (BasicMatrixValue) currentOutSet.get(originalVar).getSingleton(); } else return (BasicMatrixValue) currentOutSet.get(variable).getSingleton(); } public boolean isCell(String variable) { if (currentOutSet.get(variable).getSingleton() instanceof CellValue) { return true; } else return false; } public boolean hasSingleton(String variable) { if (currentOutSet.get(variable).getSingleton() == null) return false; else return true; } @SuppressWarnings("rawtypes") public ValueSet getValueSet(String variable) { return currentOutSet.get(variable); } }
Sable/Mc2For
languages/Natlab/src/natlab/backends/Fortran/codegen_simplified/FortranCodeASTGenerator.java
Java
apache-2.0
12,590
/* * Copyright 2008-2009 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.store.routed; import static voldemort.FailureDetectorTestUtils.recordException; import static voldemort.FailureDetectorTestUtils.recordSuccess; import static voldemort.MutableStoreVerifier.create; import static voldemort.TestUtils.getClock; import static voldemort.VoldemortTestConstants.getNineNodeCluster; import static voldemort.cluster.failuredetector.FailureDetectorUtils.create; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import voldemort.ServerTestUtils; import voldemort.TestUtils; import voldemort.VoldemortException; import voldemort.VoldemortTestConstants; import voldemort.client.RoutingTier; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.cluster.failuredetector.BannagePeriodFailureDetector; import voldemort.cluster.failuredetector.FailureDetector; import voldemort.cluster.failuredetector.FailureDetectorConfig; import voldemort.routing.RoutingStrategyType; import voldemort.serialization.SerializerDefinition; import voldemort.store.AbstractByteArrayStoreTest; import voldemort.store.FailingReadsStore; import voldemort.store.FailingStore; import voldemort.store.InsufficientOperationalNodesException; import voldemort.store.SleepyStore; import voldemort.store.Store; import voldemort.store.StoreDefinition; import voldemort.store.StoreDefinitionBuilder; import voldemort.store.UnreachableStoreException; import voldemort.store.memory.InMemoryStorageEngine; import voldemort.store.stats.StatTrackingStore; import voldemort.store.stats.Tracked; import voldemort.store.versioned.InconsistencyResolvingStore; import voldemort.utils.ByteArray; import voldemort.utils.Utils; import voldemort.versioning.Occured; import voldemort.versioning.VectorClock; import voldemort.versioning.VectorClockInconsistencyResolver; import voldemort.versioning.Version; import voldemort.versioning.Versioned; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; /** * Basic tests for RoutedStore * * */ @RunWith(Parameterized.class) public class RoutedStoreTest extends AbstractByteArrayStoreTest { private Cluster cluster; private final ByteArray aKey = TestUtils.toByteArray("jay"); private final byte[] aValue = "kreps".getBytes(); private final Class<FailureDetector> failureDetectorClass; private FailureDetector failureDetector; public RoutedStoreTest(Class<FailureDetector> failureDetectorClass) { this.failureDetectorClass = failureDetectorClass; } @Override @Before public void setUp() throws Exception { super.setUp(); cluster = getNineNodeCluster(); } @Override @After public void tearDown() throws Exception { if(failureDetector != null) failureDetector.destroy(); } @Parameters public static Collection<Object[]> configs() { return Arrays.asList(new Object[][] { { BannagePeriodFailureDetector.class } }); } @Override public Store<ByteArray, byte[]> getStore() throws Exception { return new InconsistencyResolvingStore<ByteArray, byte[]>(getStore(cluster, cluster.getNumberOfNodes(), cluster.getNumberOfNodes(), 4, 0), new VectorClockInconsistencyResolver<byte[]>()); } private RoutedStore getStore(Cluster cluster, int reads, int writes, int threads, int failing) throws Exception { return getStore(cluster, reads, writes, threads, failing, 0, RoutingStrategyType.TO_ALL_STRATEGY, new VoldemortException()); } private RoutedStore getStore(Cluster cluster, int reads, int writes, int threads, int failing, int sleepy, String strategy, VoldemortException e) throws Exception { Map<Integer, Store<ByteArray, byte[]>> subStores = Maps.newHashMap(); int count = 0; for(Node n: cluster.getNodes()) { if(count >= cluster.getNumberOfNodes()) throw new IllegalArgumentException(failing + " failing nodes, " + sleepy + " sleepy nodes, but only " + cluster.getNumberOfNodes() + " nodes in the cluster."); else if(count < failing) subStores.put(n.getId(), new FailingStore<ByteArray, byte[]>("test", e)); else if(count < failing + sleepy) subStores.put(n.getId(), new SleepyStore<ByteArray, byte[]>(Long.MAX_VALUE, new InMemoryStorageEngine<ByteArray, byte[]>("test"))); else subStores.put(n.getId(), new InMemoryStorageEngine<ByteArray, byte[]>("test")); count += 1; } setFailureDetector(subStores); return new RoutedStore("test", subStores, cluster, ServerTestUtils.getStoreDef("test", reads + writes, reads, reads, writes, writes, strategy), threads, true, 1000L, failureDetector); } private int countOccurances(RoutedStore routedStore, ByteArray key, Versioned<byte[]> value) { int count = 0; for(Store<ByteArray, byte[]> store: routedStore.getInnerStores().values()) try { if(store.get(key).size() > 0 && Utils.deepEquals(store.get(key).get(0), value)) count += 1; } catch(VoldemortException e) { // This is normal for the failing store... } return count; } private void assertNEqual(RoutedStore routedStore, int expected, ByteArray key, Versioned<byte[]> value) { int count = countOccurances(routedStore, key, value); assertEquals("Expected " + expected + " occurances of '" + key + "' with value '" + value + "', but found " + count + ".", expected, count); } private void assertNOrMoreEqual(RoutedStore routedStore, int expected, ByteArray key, Versioned<byte[]> value) { int count = countOccurances(routedStore, key, value); assertTrue("Expected " + expected + " or more occurances of '" + key + "' with value '" + value + "', but found " + count + ".", expected <= count); } private void testBasicOperations(int reads, int writes, int failures, int threads) throws Exception { RoutedStore routedStore = getStore(cluster, reads, writes, threads, failures); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); VectorClock clock = getClock(1); Versioned<byte[]> versioned = new Versioned<byte[]>(aValue, clock); routedStore.put(aKey, versioned); assertNOrMoreEqual(routedStore, cluster.getNumberOfNodes() - failures, aKey, versioned); List<Versioned<byte[]>> found = store.get(aKey); assertEquals(1, found.size()); assertEquals(versioned, found.get(0)); assertNOrMoreEqual(routedStore, cluster.getNumberOfNodes() - failures, aKey, versioned); assertTrue(routedStore.delete(aKey, versioned.getVersion())); assertNEqual(routedStore, 0, aKey, versioned); assertTrue(!routedStore.delete(aKey, versioned.getVersion())); } @Test public void testBasicOperationsSingleThreaded() throws Exception { testBasicOperations(cluster.getNumberOfNodes(), cluster.getNumberOfNodes(), 0, 1); } @Test public void testBasicOperationsMultiThreaded() throws Exception { testBasicOperations(cluster.getNumberOfNodes(), cluster.getNumberOfNodes(), 0, 4); } @Test public void testBasicOperationsMultiThreadedWithFailures() throws Exception { testBasicOperations(cluster.getNumberOfNodes() - 2, cluster.getNumberOfNodes() - 2, 2, 4); } private void testBasicOperationFailure(int reads, int writes, int failures, int threads) throws Exception { VectorClock clock = getClock(1); Versioned<byte[]> versioned = new Versioned<byte[]>(aValue, clock); RoutedStore routedStore = getStore(cluster, reads, writes, threads, failures, 0, RoutingStrategyType.TO_ALL_STRATEGY, new UnreachableStoreException("no go")); try { routedStore.put(aKey, versioned); fail("Put succeeded with too few operational nodes."); } catch(InsufficientOperationalNodesException e) { // expected } try { routedStore.get(aKey); fail("Get succeeded with too few operational nodes."); } catch(InsufficientOperationalNodesException e) { // expected } try { routedStore.delete(aKey, versioned.getVersion()); fail("Get succeeded with too few operational nodes."); } catch(InsufficientOperationalNodesException e) { // expected } } @Test public void testBasicOperationFailureMultiThreaded() throws Exception { testBasicOperationFailure(cluster.getNumberOfNodes() - 2, cluster.getNumberOfNodes() - 2, 4, 4); } @Test public void testPutIncrementsVersion() throws Exception { Store<ByteArray, byte[]> store = getStore(); VectorClock clock = new VectorClock(); VectorClock copy = clock.clone(); store.put(aKey, new Versioned<byte[]>(getValue(), clock)); List<Versioned<byte[]>> found = store.get(aKey); assertEquals("Invalid number of items found.", 1, found.size()); assertEquals("Version not incremented properly", Occured.BEFORE, copy.compare(found.get(0).getVersion())); } @Test public void testObsoleteMasterFails() { // write me } @Test public void testOnlyNodeFailuresDisableNode() throws Exception { // test put cluster = getNineNodeCluster(); Store<ByteArray, byte[]> s1 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new VoldemortException()); try { s1.put(aKey, new Versioned<byte[]>(aValue)); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(9); cluster = getNineNodeCluster(); Store<ByteArray, byte[]> s2 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new UnreachableStoreException("no go")); try { s2.put(aKey, new Versioned<byte[]>(aValue)); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(0); // test get cluster = getNineNodeCluster(); s1 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new VoldemortException()); try { s1.get(aKey); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(9); cluster = getNineNodeCluster(); s2 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new UnreachableStoreException("no go")); try { s2.get(aKey); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(0); // test delete cluster = getNineNodeCluster(); s1 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new VoldemortException()); try { s1.delete(aKey, new VectorClock()); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(9); cluster = getNineNodeCluster(); s2 = getStore(cluster, 1, 9, 9, 9, 0, RoutingStrategyType.TO_ALL_STRATEGY, new UnreachableStoreException("no go")); try { s2.delete(aKey, new VectorClock()); fail("Failure is expected"); } catch(InsufficientOperationalNodesException e) { /* expected */ } assertOperationalNodes(0); } @Test public void testGetVersions2() throws Exception { List<ByteArray> keys = getKeys(2); ByteArray key = keys.get(0); byte[] value = getValue(); Store<ByteArray, byte[]> store = getStore(); store.put(key, Versioned.value(value)); List<Versioned<byte[]>> versioneds = store.get(key); List<Version> versions = store.getVersions(key); assertEquals(1, versioneds.size()); assertEquals(9, versions.size()); for(int i = 0; i < versions.size(); i++) assertEquals(versioneds.get(0).getVersion(), versions.get(i)); assertEquals(0, store.getVersions(keys.get(1)).size()); } /** * Tests that getAll works correctly with a node down in a two node cluster. */ @Test public void testGetAllWithNodeDown() throws Exception { cluster = VoldemortTestConstants.getTwoNodeCluster(); RoutedStore routedStore = getStore(cluster, 1, 2, 1, 0); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); Map<ByteArray, byte[]> expectedValues = Maps.newHashMap(); for(byte i = 1; i < 11; ++i) { ByteArray key = new ByteArray(new byte[] { i }); byte[] value = new byte[] { (byte) (i + 50) }; store.put(key, Versioned.value(value)); expectedValues.put(key, value); } recordException(failureDetector, cluster.getNodes().iterator().next()); Map<ByteArray, List<Versioned<byte[]>>> all = store.getAll(expectedValues.keySet()); assertEquals(expectedValues.size(), all.size()); for(Map.Entry<ByteArray, List<Versioned<byte[]>>> mapEntry: all.entrySet()) { byte[] value = expectedValues.get(mapEntry.getKey()); assertEquals(new ByteArray(value), new ByteArray(mapEntry.getValue().get(0).getValue())); } } @Test public void testGetAllWithFailingStore() throws Exception { cluster = VoldemortTestConstants.getTwoNodeCluster(); StoreDefinition storeDef = ServerTestUtils.getStoreDef("test", 2, 1, 1, 2, 2, RoutingStrategyType.CONSISTENT_STRATEGY); Map<Integer, Store<ByteArray, byte[]>> subStores = Maps.newHashMap(); subStores.put(Iterables.get(cluster.getNodes(), 0).getId(), new InMemoryStorageEngine<ByteArray, byte[]>("test")); subStores.put(Iterables.get(cluster.getNodes(), 1).getId(), new FailingReadsStore<ByteArray, byte[]>("test")); setFailureDetector(subStores); RoutedStore routedStore = new RoutedStore("test", subStores, cluster, storeDef, 1, true, 1000L, failureDetector); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); Map<ByteArray, byte[]> expectedValues = Maps.newHashMap(); for(byte i = 1; i < 11; ++i) { ByteArray key = new ByteArray(new byte[] { i }); byte[] value = new byte[] { (byte) (i + 50) }; store.put(key, Versioned.value(value)); expectedValues.put(key, value); } Map<ByteArray, List<Versioned<byte[]>>> all = store.getAll(expectedValues.keySet()); assertEquals(expectedValues.size(), all.size()); for(Map.Entry<ByteArray, List<Versioned<byte[]>>> mapEntry: all.entrySet()) { byte[] value = expectedValues.get(mapEntry.getKey()); assertEquals(new ByteArray(value), new ByteArray(mapEntry.getValue().get(0).getValue())); } } /** * One node up, two preferred reads and one required read. See: * * http://github.com/voldemort/voldemort/issues#issue/18 */ @Test public void testGetAllWithMorePreferredReadsThanNodes() throws Exception { cluster = VoldemortTestConstants.getTwoNodeCluster(); StoreDefinition storeDef = ServerTestUtils.getStoreDef("test", 2, 2, 1, 2, 2, RoutingStrategyType.CONSISTENT_STRATEGY); Map<Integer, Store<ByteArray, byte[]>> subStores = Maps.newHashMap(); subStores.put(Iterables.get(cluster.getNodes(), 0).getId(), new InMemoryStorageEngine<ByteArray, byte[]>("test")); subStores.put(Iterables.get(cluster.getNodes(), 1).getId(), new InMemoryStorageEngine<ByteArray, byte[]>("test")); setFailureDetector(subStores); RoutedStore routedStore = new RoutedStore("test", subStores, cluster, storeDef, 1, true, 1000L, failureDetector); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); store.put(aKey, Versioned.value(aValue)); recordException(failureDetector, cluster.getNodes().iterator().next()); Map<ByteArray, List<Versioned<byte[]>>> all = store.getAll(Arrays.asList(aKey)); assertEquals(1, all.size()); assertTrue(Arrays.equals(aValue, all.values().iterator().next().get(0).getValue())); } /** * See Issue #89: Sequential retrieval in RoutedStore.get doesn't consider * repairReads. */ @Test public void testReadRepairWithFailures() throws Exception { cluster = getNineNodeCluster(); RoutedStore routedStore = getStore(cluster, cluster.getNumberOfNodes() - 1, cluster.getNumberOfNodes() - 1, 1, 0); // Disable node 1 so that the first put also goes to the last node recordException(failureDetector, Iterables.get(cluster.getNodes(), 1)); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); store.put(aKey, new Versioned<byte[]>(aValue)); byte[] anotherValue = "john".getBytes(); // Disable the last node and enable node 1 to prevent the last node from // getting the new version recordException(failureDetector, Iterables.getLast(cluster.getNodes())); recordSuccess(failureDetector, Iterables.get(cluster.getNodes(), 1)); VectorClock clock = getClock(1); store.put(aKey, new Versioned<byte[]>(anotherValue, clock)); // Enable last node and disable node 1, the following get should cause a // read repair on the last node in the code path that is only executed // if there are failures. recordException(failureDetector, Iterables.get(cluster.getNodes(), 1)); recordSuccess(failureDetector, Iterables.getLast(cluster.getNodes())); List<Versioned<byte[]>> versioneds = store.get(aKey); assertEquals(1, versioneds.size()); assertEquals(new ByteArray(anotherValue), new ByteArray(versioneds.get(0).getValue())); // Read repairs are done asynchronously, so we sleep for a short period. // It may be a good idea to use a synchronous executor service. Thread.sleep(100); for(Store<ByteArray, byte[]> innerStore: routedStore.getInnerStores().values()) { List<Versioned<byte[]>> innerVersioneds = innerStore.get(aKey); assertEquals(1, versioneds.size()); assertEquals(new ByteArray(anotherValue), new ByteArray(innerVersioneds.get(0) .getValue())); } } /** * See issue #134: RoutedStore put() doesn't wait for enough attempts to * succeed * * This issue would only happen with one node down and another that was slow * to respond. */ @Test public void testPutWithOneNodeDownAndOneNodeSlow() throws Exception { cluster = VoldemortTestConstants.getThreeNodeCluster(); StoreDefinition storeDef = ServerTestUtils.getStoreDef("test", 3, 2, 2, 2, 2, RoutingStrategyType.CONSISTENT_STRATEGY); /* The key used causes the nodes selected for writing to be [2, 0, 1] */ Map<Integer, Store<ByteArray, byte[]>> subStores = Maps.newHashMap(); subStores.put(Iterables.get(cluster.getNodes(), 2).getId(), new InMemoryStorageEngine<ByteArray, byte[]>("test")); subStores.put(Iterables.get(cluster.getNodes(), 0).getId(), new FailingStore<ByteArray, byte[]>("test")); /* * The bug would only show itself if the second successful required * write was slow (but still within the timeout). */ subStores.put(Iterables.get(cluster.getNodes(), 1).getId(), new SleepyStore<ByteArray, byte[]>(100, new InMemoryStorageEngine<ByteArray, byte[]>("test"))); setFailureDetector(subStores); RoutedStore routedStore = new RoutedStore("test", subStores, cluster, storeDef, 1, true, 1000L, failureDetector); Store<ByteArray, byte[]> store = new InconsistencyResolvingStore<ByteArray, byte[]>(routedStore, new VectorClockInconsistencyResolver<byte[]>()); store.put(aKey, new Versioned<byte[]>(aValue)); } @Test public void testPutTimeout() throws Exception { int timeout = 50; StoreDefinition definition = new StoreDefinitionBuilder().setName("test") .setType("foo") .setKeySerializer(new SerializerDefinition("test")) .setValueSerializer(new SerializerDefinition("test")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.CONSISTENT_STRATEGY) .setReplicationFactor(3) .setPreferredReads(3) .setRequiredReads(3) .setPreferredWrites(3) .setRequiredWrites(3) .build(); Map<Integer, Store<ByteArray, byte[]>> stores = new HashMap<Integer, Store<ByteArray, byte[]>>(); List<Node> nodes = new ArrayList<Node>(); int totalDelay = 0; for(int i = 0; i < 3; i++) { int delay = 4 + i * timeout; totalDelay += delay; stores.put(i, new SleepyStore<ByteArray, byte[]>(delay, new InMemoryStorageEngine<ByteArray, byte[]>("test"))); List<Integer> partitions = Arrays.asList(i); nodes.add(new Node(i, "none", 0, 0, 0, partitions)); } setFailureDetector(stores); RoutedStore routedStore = new RoutedStore("test", stores, new Cluster("test", nodes), definition, 3, false, timeout, failureDetector); long start = System.currentTimeMillis(); try { routedStore.put(new ByteArray("test".getBytes()), new Versioned<byte[]>(new byte[] { 1 })); fail("Should have thrown"); } catch(InsufficientOperationalNodesException e) { long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed + " < " + totalDelay, elapsed < totalDelay); } } /** * See Issue #211: Unnecessary read repairs during getAll with more than one * key */ @Test public void testNoReadRepair() throws Exception { cluster = VoldemortTestConstants.getThreeNodeCluster(); StoreDefinition storeDef = ServerTestUtils.getStoreDef("test", 3, 2, 1, 3, 2, RoutingStrategyType.CONSISTENT_STRATEGY); Map<Integer, Store<ByteArray, byte[]>> subStores = Maps.newHashMap(); /* We just need to keep a store from one node */ StatTrackingStore<ByteArray, byte[]> statTrackingStore = null; for(int i = 0; i < 3; ++i) { statTrackingStore = new StatTrackingStore<ByteArray, byte[]>(new InMemoryStorageEngine<ByteArray, byte[]>("test"), null); subStores.put(Iterables.get(cluster.getNodes(), i).getId(), statTrackingStore); } setFailureDetector(subStores); RoutedStore routedStore = new RoutedStore("test", subStores, cluster, storeDef, 1, true, 1000L, failureDetector); ByteArray key1 = aKey; routedStore.put(key1, Versioned.value("value1".getBytes())); ByteArray key2 = TestUtils.toByteArray("voldemort"); routedStore.put(key2, Versioned.value("value2".getBytes())); long putCount = statTrackingStore.getStats().getCount(Tracked.PUT); routedStore.getAll(Arrays.asList(key1, key2)); /* Read repair happens asynchronously, so we wait a bit */ Thread.sleep(500); assertEquals("put count should remain the same if there are no read repairs", putCount, statTrackingStore.getStats().getCount(Tracked.PUT)); } private void assertOperationalNodes(int expected) { int found = 0; for(Node n: cluster.getNodes()) if(failureDetector.isAvailable(n)) found++; assertEquals("Number of operational nodes not what was expected.", expected, found); } private void setFailureDetector(Map<Integer, Store<ByteArray, byte[]>> subStores) throws Exception { // Destroy any previous failure detector before creating the next one // (the final one is destroyed in tearDown). if(failureDetector != null) failureDetector.destroy(); FailureDetectorConfig failureDetectorConfig = new FailureDetectorConfig().setImplementationClassName(failureDetectorClass.getName()) .setBannagePeriod(1000) .setNodes(cluster.getNodes()) .setStoreVerifier(create(subStores)); failureDetector = create(failureDetectorConfig, false); } }
netbear/CloudAnts
test/unit/voldemort/store/routed/RoutedStoreTest.java
Java
apache-2.0
34,864
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.cp.internal.datastructures.atomiclong.client; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.AtomicLongGetCodec; import com.hazelcast.cp.internal.RaftService; import com.hazelcast.cp.internal.client.AbstractCPMessageTask; import com.hazelcast.cp.internal.datastructures.atomiclong.AtomicLongService; import com.hazelcast.cp.internal.datastructures.atomiclong.operation.GetAndAddOp; import com.hazelcast.instance.impl.Node; import com.hazelcast.internal.nio.Connection; import com.hazelcast.security.permission.ActionConstants; import com.hazelcast.security.permission.AtomicLongPermission; import java.security.Permission; import static com.hazelcast.cp.internal.raft.QueryPolicy.LINEARIZABLE; /** * Client message task for {@link GetAndAddOp} */ public class GetMessageTask extends AbstractCPMessageTask<AtomicLongGetCodec.RequestParameters> { public GetMessageTask(ClientMessage clientMessage, Node node, Connection connection) { super(clientMessage, node, connection); } @Override protected void processMessage() { RaftService service = nodeEngine.getService(RaftService.SERVICE_NAME); service.getInvocationManager() .<Long>query(parameters.groupId, new GetAndAddOp(parameters.name, 0), LINEARIZABLE) .whenCompleteAsync(this); } @Override protected AtomicLongGetCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) { return AtomicLongGetCodec.decodeRequest(clientMessage); } @Override protected ClientMessage encodeResponse(Object response) { return AtomicLongGetCodec.encodeResponse((Long) response); } @Override public String getServiceName() { return AtomicLongService.SERVICE_NAME; } @Override public Permission getRequiredPermission() { return new AtomicLongPermission(parameters.name, ActionConstants.ACTION_READ); } @Override public String getDistributedObjectName() { return parameters.name; } @Override public String getMethodName() { return "get"; } public Object[] getParameters() { return new Object[0]; } }
mesutcelik/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/atomiclong/client/GetMessageTask.java
Java
apache-2.0
2,875
package org.apache.helix.messaging; /* * 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. */ import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.Mocks; import org.apache.helix.NotificationContext; import org.apache.helix.messaging.AsyncCallback; import org.apache.helix.messaging.handling.AsyncCallbackService; import org.apache.helix.messaging.handling.MessageHandler; import org.apache.helix.messaging.handling.TestHelixTaskExecutor.MockClusterManager; import org.apache.helix.model.Message; import org.testng.annotations.Test; import org.testng.AssertJUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; import org.testng.Assert; import org.testng.annotations.Test; public class TestAsyncCallbackSvc { class MockHelixManager extends Mocks.MockManager { public String getSessionId() { return "123"; } } class TestAsyncCallback extends AsyncCallback { HashSet<String> _repliedMessageId = new HashSet<String>(); @Override public void onTimeOut() { // TODO Auto-generated method stub } @Override public void onReplyMessage(Message message) { // TODO Auto-generated method stub _repliedMessageId.add(message.getMsgId()); } } @Test(groups = { "unitTest" }) public void testAsyncCallbackSvc() throws Exception { AsyncCallbackService svc = new AsyncCallbackService(); HelixManager manager = new MockHelixManager(); NotificationContext changeContext = new NotificationContext(manager); Message msg = new Message(svc.getMessageType(), UUID.randomUUID().toString()); msg.setTgtSessionId(manager.getSessionId()); try { MessageHandler aHandler = svc.createHandler(msg, changeContext); } catch(HelixException e) { AssertJUnit.assertTrue(e.getMessage().indexOf(msg.getMsgId())!= -1); } Message msg2 = new Message("RandomType", UUID.randomUUID().toString()); msg2.setTgtSessionId(manager.getSessionId()); try { MessageHandler aHandler = svc.createHandler(msg2, changeContext); } catch(HelixException e) { AssertJUnit.assertTrue(e.getMessage().indexOf(msg2.getMsgId())!= -1); } Message msg3 = new Message(svc.getMessageType(), UUID.randomUUID().toString()); msg3.setTgtSessionId(manager.getSessionId()); msg3.setCorrelationId("wfwegw"); try { MessageHandler aHandler = svc.createHandler(msg3, changeContext); } catch(HelixException e) { AssertJUnit.assertTrue(e.getMessage().indexOf(msg3.getMsgId())!= -1); } TestAsyncCallback callback = new TestAsyncCallback(); String corrId = UUID.randomUUID().toString(); svc.registerAsyncCallback(corrId, new TestAsyncCallback()); svc.registerAsyncCallback(corrId, callback); List<Message> msgSent = new ArrayList<Message>(); msgSent.add(new Message("Test", UUID.randomUUID().toString())); callback.setMessagesSent(msgSent); msg = new Message(svc.getMessageType(), UUID.randomUUID().toString()); msg.setTgtSessionId("*"); msg.setCorrelationId(corrId); MessageHandler aHandler = svc.createHandler(msg, changeContext); Map<String, String> resultMap = new HashMap<String, String>(); aHandler.handleMessage(); AssertJUnit.assertTrue(callback.isDone()); AssertJUnit.assertTrue(callback._repliedMessageId.contains(msg.getMsgId())); } }
kishoreg/incubator-helix
helix-core/src/test/java/org/apache/helix/messaging/TestAsyncCallbackSvc.java
Java
apache-2.0
4,310
/* * Copyright 2011 Takumi IINO * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.troter.seasar.extension.jdbc.manager; import java.util.List; import javax.sql.DataSource; import jp.troter.seasar.extension.jdbc.SelectableJdbcManagerFactory; import org.seasar.extension.jdbc.AutoBatchDelete; import org.seasar.extension.jdbc.AutoBatchInsert; import org.seasar.extension.jdbc.AutoBatchUpdate; import org.seasar.extension.jdbc.AutoDelete; import org.seasar.extension.jdbc.AutoFunctionCall; import org.seasar.extension.jdbc.AutoInsert; import org.seasar.extension.jdbc.AutoProcedureCall; import org.seasar.extension.jdbc.AutoSelect; import org.seasar.extension.jdbc.AutoUpdate; import org.seasar.extension.jdbc.DbmsDialect; import org.seasar.extension.jdbc.EntityMetaFactory; import org.seasar.extension.jdbc.JdbcContext; import org.seasar.extension.jdbc.JdbcManager; import org.seasar.extension.jdbc.SqlBatchUpdate; import org.seasar.extension.jdbc.SqlFileBatchUpdate; import org.seasar.extension.jdbc.SqlFileFunctionCall; import org.seasar.extension.jdbc.SqlFileProcedureCall; import org.seasar.extension.jdbc.SqlFileSelect; import org.seasar.extension.jdbc.SqlFileUpdate; import org.seasar.extension.jdbc.SqlFunctionCall; import org.seasar.extension.jdbc.SqlProcedureCall; import org.seasar.extension.jdbc.SqlSelect; import org.seasar.extension.jdbc.SqlUpdate; import org.seasar.extension.jdbc.manager.JdbcManagerImplementor; import org.seasar.framework.container.S2Container; import org.seasar.framework.convention.PersistenceConvention; public class SelectableJdbcManagerProxy implements JdbcManager, JdbcManagerImplementor { /** * S2コンテナです。 */ protected S2Container container; /** * <code>SelectableJdbcManagerFactory</code>のコンポーネント名です。 */ protected String selectableJdbcManagerFactoryName; /** * <code>SelectableJdbcManagerFactory</code>のコンポーネント名を設定します。 * @param name */ public void setSelectableJdbcManagerFactoryName(String name) { this.selectableJdbcManagerFactoryName = name; } /** * @return S2コンテナ */ public S2Container getContainer() { return container; } /** * @param container * S2コンテナ */ public void setContainer(S2Container container) { this.container = container; } /** * 選択可能な<code>JdbcManager</code>のファクトリを取得します。 */ protected SelectableJdbcManagerFactory getSelectableJdbcManagerFactory() { return (SelectableJdbcManagerFactory)container.getRoot().getComponent(selectableJdbcManagerFactoryName); } /** * <code>JdbcManager</code>を取得します。 * @return <code>JdbcManager</code> */ protected JdbcManager getJdbcManager() { return getSelectableJdbcManagerFactory().getJdbcManager(); } @Override public <T> AutoSelect<T> from(Class<T> baseClass) { return getJdbcManager().from(baseClass); } @Override public <T> SqlSelect<T> selectBySql(Class<T> baseClass, String sql, Object... params) { return getJdbcManager().selectBySql(baseClass, sql, params); } @Override public long getCountBySql(String sql, Object... params) { return getJdbcManager().getCountBySql(sql, params); } @Override public <T> SqlFileSelect<T> selectBySqlFile(Class<T> baseClass, String path) { return getJdbcManager().selectBySqlFile(baseClass, path); } @Override public <T> SqlFileSelect<T> selectBySqlFile(Class<T> baseClass, String path, Object parameter) { return getJdbcManager().selectBySqlFile(baseClass, path, parameter); } @Override public long getCountBySqlFile(String path) { return getJdbcManager().getCountBySqlFile(path); } @Override public long getCountBySqlFile(String path, Object parameter) { return getJdbcManager().getCountBySqlFile(path, parameter); } @Override public <T> AutoInsert<T> insert(T entity) { return getJdbcManager().insert(entity); } @Override public <T> AutoBatchInsert<T> insertBatch(T... entities) { return getJdbcManager().insertBatch(entities); } @Override public <T> AutoBatchInsert<T> insertBatch(List<T> entities) { return getJdbcManager().insertBatch(entities); } @Override public <T> AutoUpdate<T> update(T entity) { return getJdbcManager().update(entity); } @Override public <T> AutoBatchUpdate<T> updateBatch(T... entities) { return getJdbcManager().updateBatch(entities); } @Override public <T> AutoBatchUpdate<T> updateBatch(List<T> entities) { return getJdbcManager().updateBatch(entities); } @Override public SqlUpdate updateBySql(String sql, Class<?>... paramClasses) { return getJdbcManager().updateBySql(sql, paramClasses); } @Override public SqlBatchUpdate updateBatchBySql(String sql, Class<?>... paramClasses) { return getJdbcManager().updateBatchBySql(sql, paramClasses); } @Override public SqlFileUpdate updateBySqlFile(String path) { return getJdbcManager().updateBySqlFile(path); } @Override public SqlFileUpdate updateBySqlFile(String path, Object parameter) { return getJdbcManager().updateBySqlFile(path, parameter); } @Override public <T> SqlFileBatchUpdate<T> updateBatchBySqlFile(String path, T... params) { return getJdbcManager().updateBatchBySqlFile(path, params); } @Override public <T> SqlFileBatchUpdate<T> updateBatchBySqlFile(String path, List<T> params) { return getJdbcManager().updateBatchBySqlFile(path, params); } @Override public <T> AutoDelete<T> delete(T entity) { return getJdbcManager().delete(entity); } @Override public <T> AutoBatchDelete<T> deleteBatch(T... entities) { return getJdbcManager().deleteBatch(entities); } @Override public <T> AutoBatchDelete<T> deleteBatch(List<T> entities) { return getJdbcManager().deleteBatch(entities); } @Override public AutoProcedureCall call(String procedureName) { return getJdbcManager().call(procedureName); } @Override public AutoProcedureCall call(String procedureName, Object parameter) { return getJdbcManager().call(procedureName, parameter); } @Override public SqlProcedureCall callBySql(String sql) { return getJdbcManager().callBySql(sql); } @Override public SqlProcedureCall callBySql(String sql, Object parameter) { return getJdbcManager().callBySql(sql, parameter); } @Override public SqlFileProcedureCall callBySqlFile(String path) { return getJdbcManager().callBySqlFile(path); } @Override public SqlFileProcedureCall callBySqlFile(String path, Object parameter) { return getJdbcManager().callBySqlFile(path, parameter); } @Override public <T> AutoFunctionCall<T> call(Class<T> resultClass, String functionName) { return getJdbcManager().call(resultClass, functionName); } @Override public <T> AutoFunctionCall<T> call(Class<T> resultClass, String functionName, Object parameter) { return getJdbcManager().call(resultClass, functionName, parameter); } @Override public <T> SqlFunctionCall<T> callBySql(Class<T> resultClass, String sql) { return getJdbcManager().callBySql(resultClass, sql); } @Override public <T> SqlFunctionCall<T> callBySql(Class<T> resultClass, String sql, Object parameter) { return getJdbcManager().callBySql(resultClass, sql, parameter); } @Override public <T> SqlFileFunctionCall<T> callBySqlFile(Class<T> resultClass, String path) { return getJdbcManager().callBySqlFile(resultClass, path); } @Override public <T> SqlFileFunctionCall<T> callBySqlFile(Class<T> resultClass, String path, Object parameter) { return getJdbcManager().callBySqlFile(resultClass, path, parameter); } @Override public JdbcContext getJdbcContext() { return Methods.implementor(getJdbcManager()).getJdbcContext(); } @Override public DataSource getDataSource() { return Methods.implementor(getJdbcManager()).getDataSource(); } @Override public String getSelectableDataSourceName() { return Methods.implementor(getJdbcManager()).getSelectableDataSourceName(); } @Override public DbmsDialect getDialect() { return Methods.implementor(getJdbcManager()).getDialect(); } @Override public EntityMetaFactory getEntityMetaFactory() { return Methods.implementor(getJdbcManager()).getEntityMetaFactory(); } @Override public PersistenceConvention getPersistenceConvention() { return Methods.implementor(getJdbcManager()).getPersistenceConvention(); } @Override public boolean isAllowVariableSqlForBatchUpdate() { return Methods.implementor(getJdbcManager()).isAllowVariableSqlForBatchUpdate(); } public static class Methods { public static JdbcManagerImplementor implementor(JdbcManager jdbcManager) { if (jdbcManager instanceof JdbcManagerImplementor) { return ((JdbcManagerImplementor)jdbcManager); } throw new UnsupportedOperationException(); } } }
troter/s2jdbc-selectable
s2jdbc-selectable/src/main/java/jp/troter/seasar/extension/jdbc/manager/SelectableJdbcManagerProxy.java
Java
apache-2.0
10,187
/** * ConversionEvent.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201311; public class ConversionEvent implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected ConversionEvent(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _CREATIVE_VIEW = "CREATIVE_VIEW"; public static final java.lang.String _START = "START"; public static final java.lang.String _SKIP_SHOWN = "SKIP_SHOWN"; public static final java.lang.String _FIRST_QUARTILE = "FIRST_QUARTILE"; public static final java.lang.String _MIDPOINT = "MIDPOINT"; public static final java.lang.String _THIRD_QUARTILE = "THIRD_QUARTILE"; public static final java.lang.String _ENGAGED_VIEW = "ENGAGED_VIEW"; public static final java.lang.String _COMPLETE = "COMPLETE"; public static final java.lang.String _MUTE = "MUTE"; public static final java.lang.String _UNMUTE = "UNMUTE"; public static final java.lang.String _PAUSE = "PAUSE"; public static final java.lang.String _REWIND = "REWIND"; public static final java.lang.String _RESUME = "RESUME"; public static final java.lang.String _SKIPPED = "SKIPPED"; public static final java.lang.String _FULLSCREEN = "FULLSCREEN"; public static final java.lang.String _EXPAND = "EXPAND"; public static final java.lang.String _COLLAPSE = "COLLAPSE"; public static final java.lang.String _ACCEPT_INVITATION = "ACCEPT_INVITATION"; public static final java.lang.String _CLOSE = "CLOSE"; public static final java.lang.String _CLICK_TRACKING = "CLICK_TRACKING"; public static final java.lang.String _SURVEY = "SURVEY"; public static final java.lang.String _CUSTOM_CLICK = "CUSTOM_CLICK"; public static final ConversionEvent CREATIVE_VIEW = new ConversionEvent(_CREATIVE_VIEW); public static final ConversionEvent START = new ConversionEvent(_START); public static final ConversionEvent SKIP_SHOWN = new ConversionEvent(_SKIP_SHOWN); public static final ConversionEvent FIRST_QUARTILE = new ConversionEvent(_FIRST_QUARTILE); public static final ConversionEvent MIDPOINT = new ConversionEvent(_MIDPOINT); public static final ConversionEvent THIRD_QUARTILE = new ConversionEvent(_THIRD_QUARTILE); public static final ConversionEvent ENGAGED_VIEW = new ConversionEvent(_ENGAGED_VIEW); public static final ConversionEvent COMPLETE = new ConversionEvent(_COMPLETE); public static final ConversionEvent MUTE = new ConversionEvent(_MUTE); public static final ConversionEvent UNMUTE = new ConversionEvent(_UNMUTE); public static final ConversionEvent PAUSE = new ConversionEvent(_PAUSE); public static final ConversionEvent REWIND = new ConversionEvent(_REWIND); public static final ConversionEvent RESUME = new ConversionEvent(_RESUME); public static final ConversionEvent SKIPPED = new ConversionEvent(_SKIPPED); public static final ConversionEvent FULLSCREEN = new ConversionEvent(_FULLSCREEN); public static final ConversionEvent EXPAND = new ConversionEvent(_EXPAND); public static final ConversionEvent COLLAPSE = new ConversionEvent(_COLLAPSE); public static final ConversionEvent ACCEPT_INVITATION = new ConversionEvent(_ACCEPT_INVITATION); public static final ConversionEvent CLOSE = new ConversionEvent(_CLOSE); public static final ConversionEvent CLICK_TRACKING = new ConversionEvent(_CLICK_TRACKING); public static final ConversionEvent SURVEY = new ConversionEvent(_SURVEY); public static final ConversionEvent CUSTOM_CLICK = new ConversionEvent(_CUSTOM_CLICK); public java.lang.String getValue() { return _value_;} public static ConversionEvent fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { ConversionEvent enumeration = (ConversionEvent) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static ConversionEvent fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ConversionEvent.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "ConversionEvent")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201311/ConversionEvent.java
Java
apache-2.0
5,789
/* * Copyright 2011 The Netty Project * * The Netty Project licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.yammer.httptunnel.client; import java.net.InetSocketAddress; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelFuture; /** * Interface which is used by the send and poll "worker" channels to notify the * virtual tunnel channel of key events, and to get access to higher level * information required for correct operation. * * @author The Netty Project ([email protected]) * @author Iain McGinniss ([email protected]) * @author Jamie Furness ([email protected]) * @author OneDrum Ltd. */ interface HttpTunnelClientWorkerOwner { /** * The HTTP tunnel client sink invokes this when the application code * requests the connection of an HTTP tunnel to the specified remote * address. */ public void onConnectRequest(ChannelFuture connectFuture, InetSocketAddress remoteAddress); /** * The HTTP tunnel is being shut down. */ public void onDisconnectRequest(ChannelFuture connectFuture); /** * The send channel handler calls this method when the server accepts the * open tunnel request, returning a unique tunnel ID. * * @param tunnelId * the server allocated tunnel ID */ public void onTunnelOpened(String tunnelId); /** * The poll channel handler calls this method when the poll channel is * connected, indicating that full duplex communications are now possible. */ public void fullyEstablished(); /** * Called by both the send channel handler and poll channel handler if the * underlying channel fails. */ public void underlyingChannelFailed(); /** * The poll handler calls this method when some data is received and decoded * from the server. * * @param content * the data received from the server */ public void onMessageReceived(ChannelBuffer content); /** * @return the name of the server with whom we are communicating with - this * is used within the HOST HTTP header for all requests. This is * particularly important for operation behind a proxy, where the * HOST string is used to route the request. */ public String getServerHostName(); public String getUserAgent(); public boolean isConnecting(); public boolean isConnected(); }
reines/httptunnel
src/main/java/com/yammer/httptunnel/client/HttpTunnelClientWorkerOwner.java
Java
apache-2.0
2,876
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.launcher; import vanadis.common.io.Location; import vanadis.common.io.Probe; import vanadis.core.system.VM; class LocationHelper { private static final int portStart = 10000; private static int portRange = portStart; private static final int portEnd = 64000; static Location verifiedBindable(Location location) { if (bindable(location)) { return location; } throw new StartupException("Invalid location: " + location); } static boolean bindable(Location location) { return !(Probe.detectedActivity(location)); } static Location tmpLocation() { int attemptsLeft = 50; while (true) { try { Location location = new Location(VM.HOST, portRange); if (bindable(location)) { return location; } else { attemptsLeft--; if (attemptsLeft == 0) { throw new IllegalStateException("Unable to find a suitable location"); } } } finally { portRange += 960; if (portRange >= portEnd) { portRange= portStart; } } } } static Location resolveLocation(Location location) { return location != null ? verifiedBindable(location) : tmpLocation(); } }
kjetilv/vanadis
launcher/src/main/java/vanadis/launcher/LocationHelper.java
Java
apache-2.0
2,059
/** * Copyright (C) 2013 phloc systems * http://www.phloc.com * office[at]phloc[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phloc.schematron.pure.model; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import com.phloc.commons.annotations.ReturnsMutableCopy; import com.phloc.commons.collections.ContainerHelper; import com.phloc.commons.log.InMemoryLogger; import com.phloc.commons.microdom.IMicroElement; import com.phloc.commons.microdom.impl.MicroElement; import com.phloc.commons.string.StringHelper; import com.phloc.commons.string.ToStringGenerator; import com.phloc.schematron.CSchematron; import com.phloc.schematron.CSchematronXML; /** * A single Schematron rule-element.<br> * A list of assertions tested within the context specified by the required * context attribute. The context attribute specifies the rule context * expression.<br> * NOTE: It is not an error if a rule never fires in a document. In order to * test that a document always has some context, a new pattern should be created * from the context of the document, with an assertion requiring the element or * attribute.<br> * The icon, see and fpi attributes allow rich interfaces and documentation.<br> * The flag attribute allows more detailed outcomes.<br> * The role and subject attributes allow explicit identification of some part of * a pattern as part of the validation outcome.<br> * When the rule element has the attribute abstract with a value true, then the * rule is an abstract rule. An abstract rule shall not have a context * attribute. An abstract rule is a list of assertions that will be invoked by * other rules belonging to the same pattern using the extends element. Abstract * rules provide a mechanism for reducing schema size. * * @author Philip Helger */ @NotThreadSafe public class PSRule implements IPSElement, IPSHasID, IPSHasFlag, IPSHasForeignElements, IPSHasIncludes, IPSHasLets, IPSHasRichGroup, IPSHasLinkableGroup { public static final boolean DEFAULT_ABSTRACT = false; private String m_sFlag; private PSRichGroup m_aRich; private PSLinkableGroup m_aLinkable; private boolean m_bAbstract = DEFAULT_ABSTRACT; private String m_sContext; private String m_sID; private final List <PSInclude> m_aIncludes = new ArrayList <PSInclude> (); private final List <PSLet> m_aLets = new ArrayList <PSLet> (); private final List <IPSElement> m_aContent = new ArrayList <IPSElement> (); private Map <String, String> m_aForeignAttrs; private List <IMicroElement> m_aForeignElements; public PSRule () {} public boolean isValid (@Nonnull final InMemoryLogger aLogger) { // abstract rules need an ID if (m_bAbstract && StringHelper.hasNoText (m_sID)) { aLogger.error ("abstract <rule> has no 'id'"); return false; } // abstract rules may not have a context if (m_bAbstract && StringHelper.hasText (m_sContext)) { aLogger.error ("abstract <rule> may not have a 'context'"); return false; } // Non-abstract rules need a context if (!m_bAbstract && StringHelper.hasNoText (m_sContext)) { aLogger.error ("<rule> must have a 'context'"); return false; } // At least one assert, report or extends must be present if (m_aContent.isEmpty ()) { aLogger.error ("<rule> has no content"); return false; } for (final PSInclude aInclude : m_aIncludes) if (!aInclude.isValid (aLogger)) return false; for (final PSLet aLet : m_aLets) if (!aLet.isValid (aLogger)) return false; for (final IPSElement aContent : m_aContent) if (!aContent.isValid (aLogger)) return false; return true; } public boolean isMinimal () { for (final PSInclude aInclude : m_aIncludes) if (!aInclude.isMinimal ()) return false; for (final PSLet aLet : m_aLets) if (!aLet.isMinimal ()) return false; for (final IPSElement aContent : m_aContent) if (!aContent.isMinimal ()) return false; return true; } public void addForeignElement (@Nonnull final IMicroElement aForeignElement) { if (aForeignElement == null) throw new NullPointerException ("ForeignElement"); if (aForeignElement.hasParent ()) throw new IllegalArgumentException ("ForeignElement already has a parent!"); if (m_aForeignElements == null) m_aForeignElements = new ArrayList <IMicroElement> (); m_aForeignElements.add (aForeignElement); } public void addForeignElements (@Nonnull final List <IMicroElement> aForeignElements) { if (aForeignElements == null) throw new NullPointerException ("ForeignElements"); for (final IMicroElement aForeignElement : aForeignElements) addForeignElement (aForeignElement); } public boolean hasForeignElements () { return m_aForeignElements != null && !m_aForeignElements.isEmpty (); } @Nonnull @ReturnsMutableCopy public List <IMicroElement> getAllForeignElements () { return ContainerHelper.newList (m_aForeignElements); } public void addForeignAttribute (@Nonnull final String sAttrName, @Nonnull final String sAttrValue) { if (sAttrName == null) throw new NullPointerException ("AttrName"); if (sAttrValue == null) throw new NullPointerException ("AttrValue"); if (m_aForeignAttrs == null) m_aForeignAttrs = new LinkedHashMap <String, String> (); m_aForeignAttrs.put (sAttrName, sAttrValue); } public void addForeignAttributes (@Nonnull final Map <String, String> aForeignAttrs) { if (aForeignAttrs == null) throw new NullPointerException ("foreignAttrs"); for (final Map.Entry <String, String> aEntry : aForeignAttrs.entrySet ()) addForeignAttribute (aEntry.getKey (), aEntry.getValue ()); } public boolean hasForeignAttributes () { return m_aForeignAttrs != null && !m_aForeignAttrs.isEmpty (); } @Nonnull @ReturnsMutableCopy public Map <String, String> getAllForeignAttributes () { return ContainerHelper.newOrderedMap (m_aForeignAttrs); } public void setFlag (@Nullable final String sFlag) { m_sFlag = sFlag; } @Nullable public String getFlag () { return m_sFlag; } public void setRich (@Nullable final PSRichGroup aRich) { m_aRich = aRich; } public boolean hasRich () { return m_aRich != null; } @Nullable public PSRichGroup getRich () { return m_aRich; } @Nullable public PSRichGroup getRichClone () { return m_aRich == null ? null : m_aRich.getClone (); } public void setLinkable (@Nullable final PSLinkableGroup aLinkable) { m_aLinkable = aLinkable; } public boolean hasLinkable () { return m_aLinkable != null; } @Nullable public PSLinkableGroup getLinkable () { return m_aLinkable; } @Nullable public PSLinkableGroup getLinkableClone () { return m_aLinkable == null ? null : m_aLinkable.getClone (); } /** * @param bAbstract * The abstract state of this rule. */ public void setAbstract (final boolean bAbstract) { m_bAbstract = bAbstract; } /** * @return <code>true</code> if this rule is abstract, <code>false</code> * otherwise. Default is {@value #DEFAULT_ABSTRACT}. */ public boolean isAbstract () { return m_bAbstract; } public void setContext (@Nullable final String sContext) { m_sContext = sContext; } @Nullable public String getContext () { return m_sContext; } public void setID (@Nullable final String sID) { m_sID = sID; } public boolean hasID () { return m_sID != null; } @Nullable public String getID () { return m_sID; } public void addInclude (@Nonnull final PSInclude aInclude) { if (aInclude == null) throw new NullPointerException ("Include"); m_aIncludes.add (aInclude); } public boolean hasAnyInclude () { return !m_aIncludes.isEmpty (); } @Nonnull @ReturnsMutableCopy public List <PSInclude> getAllIncludes () { return ContainerHelper.newList (m_aIncludes); } public void addLet (@Nonnull final PSLet aLet) { if (aLet == null) throw new NullPointerException ("Let"); m_aLets.add (aLet); } public boolean hasAnyLet () { return !m_aLets.isEmpty (); } @Nonnull @ReturnsMutableCopy public List <PSLet> getAllLets () { return ContainerHelper.newList (m_aLets); } @Nonnull @ReturnsMutableCopy public Map <String, String> getAllLetsAsMap () { final Map <String, String> ret = new LinkedHashMap <String, String> (); for (final PSLet aLet : m_aLets) ret.put (aLet.getName (), aLet.getValue ()); return ret; } public void addAssertReport (@Nonnull final PSAssertReport aAssertReport) { if (aAssertReport == null) throw new NullPointerException ("AssertReport"); m_aContent.add (aAssertReport); } @Nonnull @ReturnsMutableCopy public List <PSAssertReport> getAllAssertReports () { final List <PSAssertReport> ret = new ArrayList <PSAssertReport> (); for (final IPSElement aElement : m_aContent) if (aElement instanceof PSAssertReport) ret.add ((PSAssertReport) aElement); return ret; } public void addExtends (@Nonnull final PSExtends aExtends) { if (aExtends == null) throw new NullPointerException ("Extends"); m_aContent.add (aExtends); } @Nonnull @ReturnsMutableCopy public List <PSExtends> getAllExtends () { final List <PSExtends> ret = new ArrayList <PSExtends> (); for (final IPSElement aElement : m_aContent) if (aElement instanceof PSExtends) ret.add ((PSExtends) aElement); return ret; } @Nonnegative public int getExtendsCount () { int ret = 0; for (final IPSElement aElement : m_aContent) if (aElement instanceof PSExtends) ++ret; return ret; } public boolean hasAnyExtends () { for (final IPSElement aElement : m_aContent) if (aElement instanceof PSExtends) return true; return false; } /** * @return A list consisting of {@link PSAssertReport} and {@link PSExtends} * parameters */ @Nonnull @ReturnsMutableCopy public List <IPSElement> getAllContentElements () { return ContainerHelper.newList (m_aContent); } @Nonnull public IMicroElement getAsMicroElement () { final IMicroElement ret = new MicroElement (CSchematron.NAMESPACE_SCHEMATRON, CSchematronXML.ELEMENT_RULE); ret.setAttribute (CSchematronXML.ATTR_FLAG, m_sFlag); if (m_bAbstract) ret.setAttribute (CSchematronXML.ATTR_ABSTRACT, "true"); ret.setAttribute (CSchematronXML.ATTR_CONTEXT, m_sContext); ret.setAttribute (CSchematronXML.ATTR_ID, m_sID); if (m_aRich != null) m_aRich.fillMicroElement (ret); if (m_aLinkable != null) m_aLinkable.fillMicroElement (ret); if (m_aForeignElements != null) for (final IMicroElement aForeignElement : m_aForeignElements) ret.appendChild (aForeignElement.getClone ()); for (final PSInclude aInclude : m_aIncludes) ret.appendChild (aInclude.getAsMicroElement ()); for (final PSLet aLet : m_aLets) ret.appendChild (aLet.getAsMicroElement ()); for (final IPSElement aContent : m_aContent) ret.appendChild (aContent.getAsMicroElement ()); if (m_aForeignAttrs != null) for (final Map.Entry <String, String> aEntry : m_aForeignAttrs.entrySet ()) ret.setAttribute (aEntry.getKey (), aEntry.getValue ()); return ret; } @Override public String toString () { return new ToStringGenerator (this).appendIfNotNull ("flag", m_sFlag) .appendIfNotNull ("rich", m_aRich) .appendIfNotNull ("linkable", m_aLinkable) .append ("abstract", m_bAbstract) .appendIfNotNull ("context", m_sContext) .appendIfNotNull ("id", m_sID) .append ("includes", m_aIncludes) .append ("lets", m_aLets) .append ("content", m_aContent) .appendIfNotNull ("foreignAttrs", m_aForeignAttrs) .appendIfNotNull ("foreignElements", m_aForeignElements) .toString (); } }
lsimons/phloc-schematron-standalone
phloc-schematron/phloc-schematron/src/main/java/com/phloc/schematron/pure/model/PSRule.java
Java
apache-2.0
13,284
/* * 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.psalgs.prog; /** * https://www.geeksforgeeks.org/recursive-program-to-generate-power-set/ * * @author djoshi */ public class GenerateSubSet { private static void powerSet(String str, int index, String curr) { int n = str.length(); // base cases; if (index == n) { System.out.println(curr); return; } powerSet(str, index + 1, curr + str.charAt(index)); powerSet(str, index + 1, curr); } public static void main(String args[]) { String str = "abc"; int index = 0; String curr = ""; powerSet(str, index, curr); } } // // 1] abc, 1, a x // abc, 1, "" x // // 2] abc, 2, ab x // abc, 2, a x // // 3] abc, 3, abc x // abc, 3, ab x // // print abc // print ab // // 4] abc, 3, ac x // abc, 3, a x // // print ac // print a // // 5] abc, 2, b x // abc, 2, "" x // // 6] abc, 3, bc x // abc, 3, b x // // print bc // print b // // 7] abc, 3, c x // abc, 3, "" x // // print c // print "" //
dhaval0129/PSAlgs
src/main/java/com/psalgs/prog/GenerateSubSet.java
Java
apache-2.0
1,310
/* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codecentric.boot.admin.server; import java.net.URI; import java.time.Duration; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.http.codec.json.Jackson2JsonEncoder; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.client.ExchangeStrategies; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import de.codecentric.boot.admin.server.domain.values.Registration; import static org.assertj.core.api.Assertions.assertThat; public abstract class AbstractAdminApplicationTest { private WebTestClient webClient; private int port; public void setUp(int port) { this.port = port; this.webClient = createWebClient(port); } @Test public void lifecycle() { AtomicReference<URI> location = new AtomicReference<>(); StepVerifier.create(getEventStream().log()).expectSubscription().then(() -> { listEmptyInstances(); location.set(registerInstance()); }).assertNext((event) -> assertThat(event.opt("type")).isEqualTo("REGISTERED")) .assertNext((event) -> assertThat(event.opt("type")).isEqualTo("STATUS_CHANGED")) .assertNext((event) -> assertThat(event.opt("type")).isEqualTo("ENDPOINTS_DETECTED")) .assertNext((event) -> assertThat(event.opt("type")).isEqualTo("INFO_CHANGED")).then(() -> { getInstance(location.get()); listInstances(); deregisterInstance(location.get()); }).assertNext((event) -> assertThat(event.opt("type")).isEqualTo("DEREGISTERED")) .then(this::listEmptyInstances).thenCancel().verify(Duration.ofSeconds(120)); } protected Flux<JSONObject> getEventStream() { //@formatter:off return this.webClient.get().uri("/instances/events") .accept(MediaType.TEXT_EVENT_STREAM) .exchange() .expectStatus().isOk() .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) .returnResult(JSONObject.class).getResponseBody(); //@formatter:on } protected URI registerInstance() { //@formatter:off return this.webClient.post().uri("/instances") .contentType(MediaType.APPLICATION_JSON) .bodyValue(createRegistration()) .exchange() .expectStatus().isCreated() .expectHeader().valueMatches("location", "^http://localhost:" + this.port + "/instances/[a-f0-9]+$") .returnResult(Void.class).getResponseHeaders().getLocation(); //@formatter:on } protected void getInstance(URI uri) { //@formatter:off this.webClient.get().uri(uri) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$.registration.name").isEqualTo("Test-Instance") .jsonPath("$.statusInfo.status").isEqualTo("UP") .jsonPath("$.info.test").isEqualTo("foobar"); //@formatter:on } protected void listInstances() { //@formatter:off this.webClient.get().uri("/instances") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$[0].registration.name").isEqualTo("Test-Instance") .jsonPath("$[0].statusInfo.status").isEqualTo("UP") .jsonPath("$[0].info.test").isEqualTo("foobar"); //@formatter:on } protected void listEmptyInstances() { //@formatter:off this.webClient.get().uri("/instances") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().json("[]"); //@formatter:on } protected void deregisterInstance(URI uri) { this.webClient.delete().uri(uri).exchange().expectStatus().isNoContent(); } private Registration createRegistration() { return Registration.builder().name("Test-Instance").healthUrl("http://localhost:" + this.port + "/mgmt/health") .managementUrl("http://localhost:" + this.port + "/mgmt").serviceUrl("http://localhost:" + this.port) .build(); } protected WebTestClient createWebClient(int port) { ObjectMapper mapper = new ObjectMapper().registerModule(new JsonOrgModule()); return WebTestClient.bindToServer().baseUrl("http://localhost:" + port) .exchangeStrategies(ExchangeStrategies.builder().codecs((configurer) -> { configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper)); configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper)); }).build()).build(); } public int getPort() { return this.port; } public WebTestClient getWebClient() { return this.webClient; } }
codecentric/spring-boot-admin
spring-boot-admin-server/src/test/java/de/codecentric/boot/admin/server/AbstractAdminApplicationTest.java
Java
apache-2.0
5,378
package com.intellij.vcs.log.data; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.LowMemoryWatcher; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcs.log.VcsFullCommitDetails; import com.intellij.vcs.log.VcsLogProvider; import com.intellij.vcs.log.data.index.VcsLogIndex; import com.intellij.vcs.log.util.VcsLogUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; /** * The CommitDetailsGetter is responsible for getting {@link VcsFullCommitDetails complete commit details} from the cache or from the VCS. */ public class CommitDetailsGetter extends AbstractDataGetter<VcsFullCommitDetails> { CommitDetailsGetter(@NotNull VcsLogStorage storage, @NotNull Map<VirtualFile, VcsLogProvider> logProviders, @NotNull VcsLogIndex index, @NotNull Disposable parentDisposable) { super(storage, logProviders, new VcsCommitCache<>(), index, parentDisposable); LowMemoryWatcher.register(() -> clear(), this); } @Nullable @Override protected VcsFullCommitDetails getFromAdditionalCache(int commitId) { return null; } @NotNull @Override protected List<? extends VcsFullCommitDetails> readDetails(@NotNull VcsLogProvider logProvider, @NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { return VcsLogUtil.getDetails(logProvider, root, hashes); } }
leafclick/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/CommitDetailsGetter.java
Java
apache-2.0
1,603
/* * Copyright 2017 Young Digital Planet S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.ydp.empiria.player.client.util.dom.drag.emulate; import com.google.gwt.dom.client.DataTransfer; import com.google.gwt.event.dom.client.DragEndHandler; import com.google.gwt.event.dom.client.DragStartHandler; import com.google.gwtmockito.GwtMockitoTestRunner; import com.google.web.bindery.event.shared.HandlerRegistration; import eu.ydp.empiria.player.client.overlaytypes.OverlayTypesParserMock; import eu.ydp.empiria.player.client.util.dom.drag.emulate.DragStartEndHandlerWrapper.DragEndEventWrapper; import eu.ydp.empiria.player.client.util.dom.drag.emulate.DragStartEndHandlerWrapper.DragStartEventWrapper; import gwtquery.plugins.draggable.client.events.DragStartEvent; import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler; import gwtquery.plugins.draggable.client.events.DragStopEvent; import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler; import gwtquery.plugins.draggable.client.gwt.DraggableWidget; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.Mockito.*; @RunWith(GwtMockitoTestRunner.class) public class DragStartEndHandlerWrapperTest { DraggableWidget<?> draggableWidget; private DragStartEndHandlerWrapper instance; @Before public void before() { AbstractHTML5DragDropWrapper.parser = new OverlayTypesParserMock(); draggableWidget = mock(DraggableWidget.class); instance = spy(new DragStartEndHandlerWrapper(draggableWidget)); when(instance.getDataTransfer()).then(new Answer<DataTransfer>() { @Override public DataTransfer answer(InvocationOnMock invocation) throws Throwable { DataTransfer dataTransfer = mock(DataTransfer.class); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { instance.setData((String) invocation.getArguments()[0], (String) invocation.getArguments()[1]); return null; } }).when(dataTransfer).setData(Matchers.anyString(), Matchers.anyString()); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { instance.getData((String) invocation.getArguments()[0]); return null; } }).when(dataTransfer).getData(Matchers.anyString()); return dataTransfer; } }); } @Test public void wrapDragStartHandlerTest() { DragStartHandler startHandler = mock(DragStartHandler.class); instance.wrap(startHandler); verify(draggableWidget).addDragStartHandler(Matchers.any(DragStartEventHandler.class)); } @Test public void wrapDragEndHandlerTest() { DragEndHandler endHandler = mock(DragEndHandler.class); instance.wrap(endHandler); verify(draggableWidget).addDragStopHandler(Matchers.any(DragStopEventHandler.class)); } DragStartEventHandler startHandler; @Test public void dragStartHandlerTest() { DragStartHandler dragStartHandler = mock(DragStartHandler.class); ArgumentCaptor<DragStartEventWrapper> captor = ArgumentCaptor.forClass(DragStartEventWrapper.class); when(draggableWidget.addDragStartHandler(Matchers.any(DragStartEventHandler.class))).then(new Answer<HandlerRegistration>() { @Override public HandlerRegistration answer(InvocationOnMock invocation) throws Throwable { startHandler = (DragStartEventHandler) invocation.getArguments()[0]; return null; } }); doNothing().when(instance).setData(Matchers.anyString(), Matchers.anyString()); doReturn(null).when(instance).getData(Matchers.anyString()); instance.wrap(dragStartHandler); startHandler.onDragStart(Mockito.mock(DragStartEvent.class)); verify(dragStartHandler).onDragStart(captor.capture()); DragStartEventWrapper event = captor.getValue(); event.setData("text", "text"); event.getData("text"); verify(instance).setData(Matchers.eq("text"), Matchers.eq("text")); verify(instance).getData(Matchers.eq("text")); } DragStopEventHandler stopHandler; @Test public void dragEndHandlerTest() { DragEndHandler endHandler = mock(DragEndHandler.class); ArgumentCaptor<DragEndEventWrapper> captor = ArgumentCaptor.forClass(DragEndEventWrapper.class); when(draggableWidget.addDragStopHandler(Matchers.any(DragStopEventHandler.class))).then(new Answer<HandlerRegistration>() { @Override public HandlerRegistration answer(InvocationOnMock invocation) throws Throwable { stopHandler = (DragStopEventHandler) invocation.getArguments()[0]; return null; } }); doNothing().when(instance).setData(Matchers.anyString(), Matchers.anyString()); doReturn(null).when(instance).getData(Matchers.anyString()); instance.wrap(endHandler); stopHandler.onDragStop(mock(DragStopEvent.class)); verify(endHandler).onDragEnd(captor.capture()); DragEndEventWrapper event = captor.getValue(); event.setData("text", "text"); event.getData("text"); verify(instance).setData(Matchers.eq("text"), Matchers.eq("text")); verify(instance).getData(Matchers.eq("text")); } }
YoungDigitalPlanet/empiria.player
src/test/java/eu/ydp/empiria/player/client/util/dom/drag/emulate/DragStartEndHandlerWrapperTest.java
Java
apache-2.0
6,597
package solucao; public class Date { public static String toISO(String dateBr) { return dateBr.split("/")[2] + "-" + dateBr.split("/")[1] + "-" + dateBr.split("/")[0]; } }
marciojrtorres/tecnicas-praticas-codificacao
problema-dos-nomes/src/solucao/Date.java
Java
apache-2.0
200
/** * AdScheduleTarget.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201406.cm; /** * Immutable structure to hold an ad schedule target. */ public class AdScheduleTarget extends com.google.api.ads.adwords.axis.v201406.cm.Target implements java.io.Serializable { /* Day of the week the schedule applies to. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ private com.google.api.ads.adwords.axis.v201406.cm.DayOfWeek dayOfWeek; /* Starting hour in 24 hour time. * <span class="constraint InRange">This field must * be between 0 and 23, inclusive.</span> */ private java.lang.Integer startHour; /* Interval starts these minutes after the starting hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ private com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour startMinute; /* Ending hour in 24 hour time; <code>24</code> signifies end * of the day. * <span class="constraint InRange">This field must * be between 0 and 24, inclusive.</span> */ private java.lang.Integer endHour; /* Interval ends these minutes after the ending hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ private com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour endMinute; /* Multiplying factor for bids during this specified time interval. */ private java.lang.Double bidMultiplier; public AdScheduleTarget() { } public AdScheduleTarget( java.lang.String targetType, com.google.api.ads.adwords.axis.v201406.cm.DayOfWeek dayOfWeek, java.lang.Integer startHour, com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour startMinute, java.lang.Integer endHour, com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour endMinute, java.lang.Double bidMultiplier) { super( targetType); this.dayOfWeek = dayOfWeek; this.startHour = startHour; this.startMinute = startMinute; this.endHour = endHour; this.endMinute = endMinute; this.bidMultiplier = bidMultiplier; } /** * Gets the dayOfWeek value for this AdScheduleTarget. * * @return dayOfWeek * Day of the week the schedule applies to. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public com.google.api.ads.adwords.axis.v201406.cm.DayOfWeek getDayOfWeek() { return dayOfWeek; } /** * Sets the dayOfWeek value for this AdScheduleTarget. * * @param dayOfWeek * Day of the week the schedule applies to. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public void setDayOfWeek(com.google.api.ads.adwords.axis.v201406.cm.DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; } /** * Gets the startHour value for this AdScheduleTarget. * * @return startHour * Starting hour in 24 hour time. * <span class="constraint InRange">This field must * be between 0 and 23, inclusive.</span> */ public java.lang.Integer getStartHour() { return startHour; } /** * Sets the startHour value for this AdScheduleTarget. * * @param startHour * Starting hour in 24 hour time. * <span class="constraint InRange">This field must * be between 0 and 23, inclusive.</span> */ public void setStartHour(java.lang.Integer startHour) { this.startHour = startHour; } /** * Gets the startMinute value for this AdScheduleTarget. * * @return startMinute * Interval starts these minutes after the starting hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour getStartMinute() { return startMinute; } /** * Sets the startMinute value for this AdScheduleTarget. * * @param startMinute * Interval starts these minutes after the starting hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public void setStartMinute(com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour startMinute) { this.startMinute = startMinute; } /** * Gets the endHour value for this AdScheduleTarget. * * @return endHour * Ending hour in 24 hour time; <code>24</code> signifies end * of the day. * <span class="constraint InRange">This field must * be between 0 and 24, inclusive.</span> */ public java.lang.Integer getEndHour() { return endHour; } /** * Sets the endHour value for this AdScheduleTarget. * * @param endHour * Ending hour in 24 hour time; <code>24</code> signifies end * of the day. * <span class="constraint InRange">This field must * be between 0 and 24, inclusive.</span> */ public void setEndHour(java.lang.Integer endHour) { this.endHour = endHour; } /** * Gets the endMinute value for this AdScheduleTarget. * * @return endMinute * Interval ends these minutes after the ending hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour getEndMinute() { return endMinute; } /** * Sets the endMinute value for this AdScheduleTarget. * * @param endMinute * Interval ends these minutes after the ending hour. * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public void setEndMinute(com.google.api.ads.adwords.axis.v201406.cm.MinuteOfHour endMinute) { this.endMinute = endMinute; } /** * Gets the bidMultiplier value for this AdScheduleTarget. * * @return bidMultiplier * Multiplying factor for bids during this specified time interval. */ public java.lang.Double getBidMultiplier() { return bidMultiplier; } /** * Sets the bidMultiplier value for this AdScheduleTarget. * * @param bidMultiplier * Multiplying factor for bids during this specified time interval. */ public void setBidMultiplier(java.lang.Double bidMultiplier) { this.bidMultiplier = bidMultiplier; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof AdScheduleTarget)) return false; AdScheduleTarget other = (AdScheduleTarget) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.dayOfWeek==null && other.getDayOfWeek()==null) || (this.dayOfWeek!=null && this.dayOfWeek.equals(other.getDayOfWeek()))) && ((this.startHour==null && other.getStartHour()==null) || (this.startHour!=null && this.startHour.equals(other.getStartHour()))) && ((this.startMinute==null && other.getStartMinute()==null) || (this.startMinute!=null && this.startMinute.equals(other.getStartMinute()))) && ((this.endHour==null && other.getEndHour()==null) || (this.endHour!=null && this.endHour.equals(other.getEndHour()))) && ((this.endMinute==null && other.getEndMinute()==null) || (this.endMinute!=null && this.endMinute.equals(other.getEndMinute()))) && ((this.bidMultiplier==null && other.getBidMultiplier()==null) || (this.bidMultiplier!=null && this.bidMultiplier.equals(other.getBidMultiplier()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getDayOfWeek() != null) { _hashCode += getDayOfWeek().hashCode(); } if (getStartHour() != null) { _hashCode += getStartHour().hashCode(); } if (getStartMinute() != null) { _hashCode += getStartMinute().hashCode(); } if (getEndHour() != null) { _hashCode += getEndHour().hashCode(); } if (getEndMinute() != null) { _hashCode += getEndMinute().hashCode(); } if (getBidMultiplier() != null) { _hashCode += getBidMultiplier().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AdScheduleTarget.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "AdScheduleTarget")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("dayOfWeek"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "dayOfWeek")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "DayOfWeek")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("startHour"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "startHour")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("startMinute"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "startMinute")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "MinuteOfHour")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("endHour"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "endHour")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("endMinute"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "endMinute")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "MinuteOfHour")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("bidMultiplier"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201406", "bidMultiplier")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
nafae/developer
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201406/cm/AdScheduleTarget.java
Java
apache-2.0
13,705
package com.erakk.lnreader.UI.activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.StringRes; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import com.erakk.lnreader.Constants; import com.erakk.lnreader.R; import com.erakk.lnreader.UI.fragment.BookmarkFragment; import com.erakk.lnreader.UI.fragment.DownloadFragment; import com.erakk.lnreader.UI.fragment.SearchFragment; import com.erakk.lnreader.UI.fragment.UpdateInfoFragment; import com.erakk.lnreader.UIHelper; public class BaseActivity extends AppCompatActivity { private static final String TAG = BaseActivity.class.toString(); private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UIHelper.setLanguage(this); //setContentView(R.layout.fragactivity_framework); } @Override public void setTitle(CharSequence title) { super.setTitle(title); ActionBar t = getSupportActionBar(); if (t != null) t.setTitle(title); } @Override public void setTitle(@StringRes int titleId) { super.setTitle(titleId); ActionBar t = getSupportActionBar(); if (t != null) t.setTitle(titleId); } @Override public void onResume() { super.onResume(); UIHelper.CheckScreenRotation(this); UIHelper.CheckKeepAwake(this); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. if (mDrawerToggle != null) mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggle if (mDrawerToggle != null) mDrawerToggle.onConfigurationChanged(newConfig); } // region drawer onClick Handler public void openNovelList(MenuItem view) { mDrawerLayout.closeDrawers(); UIHelper.openNovelList(this); } public void openWatchList(MenuItem item) { mDrawerLayout.closeDrawers(); UIHelper.openWatchList(this); } public void openLastRead(MenuItem item) { mDrawerLayout.closeDrawers(); UIHelper.openLastRead(this); } public void openAltNovelList(MenuItem item) { mDrawerLayout.closeDrawers(); UIHelper.selectAlternativeLanguage(this); } public void openSettings(MenuItem view) { mDrawerLayout.closeDrawers(); Intent intent = new Intent(this, DisplaySettingsActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); // FOR TESTING // resetFirstRun(); } public void openDownloadsList(MenuItem view) { mDrawerLayout.closeDrawers(); View f = findViewById(R.id.mainFrame); if (f != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(getLeftFrame(), new DownloadFragment()) .setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left) .addToBackStack(DownloadFragment.class.toString()) .commit(); } else { Intent i = new Intent(this, MainActivity.class); i.putExtra(Constants.EXTRA_INITIAL_FRAGMENT, DownloadFragment.class.toString()); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } } public void openUpdatesList(MenuItem view) { mDrawerLayout.closeDrawers(); View f = findViewById(R.id.mainFrame); if (f != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(getLeftFrame(), new UpdateInfoFragment()) .setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left) .addToBackStack(UpdateInfoFragment.class.toString()) .commit(); } else { Intent i = new Intent(this, MainActivity.class); i.putExtra(Constants.EXTRA_INITIAL_FRAGMENT, UpdateInfoFragment.class.toString()); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } } public void openBookmarks(MenuItem view) { mDrawerLayout.closeDrawers(); View f = findViewById(R.id.mainFrame); if (f != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(getLeftFrame(), new BookmarkFragment()) .setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left) .addToBackStack(BookmarkFragment.class.toString()) .commit(); } else { Intent i = new Intent(this, MainActivity.class); i.putExtra(Constants.EXTRA_INITIAL_FRAGMENT, BookmarkFragment.class.toString()); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } } public void openSearch(MenuItem view) { mDrawerLayout.closeDrawers(); View f = findViewById(R.id.mainFrame); if (f != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(getLeftFrame(), new SearchFragment()) .setCustomAnimations(R.anim.abc_fade_in, R.anim.slide_out_left, R.anim.abc_fade_in, R.anim.slide_out_left) .addToBackStack(SearchFragment.class.toString()) .commit(); } else { Intent i = new Intent(this, MainActivity.class); i.putExtra(Constants.EXTRA_INITIAL_FRAGMENT, SearchFragment.class.toString()); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } } // endregion protected int getLeftFrame() { View v = findViewById(R.id.rightFragment); if (v != null) return R.id.rightFragment; else return R.id.mainFrame; } @Override public void setContentView(@LayoutRes int layout) { super.setContentView(layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { toolbar.setTitle(R.string.app_name); setSupportActionBar(toolbar); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open_chapter_title, R.string.open_chapter_title) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); //getActionBar().setTitle(mTitle); //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); //getActionBar().setTitle(mDrawerTitle); //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } else { Log.w(TAG, "No toolbar detected!"); } } }
SandroHc/LNReader-Android
app/src/main/java/com/erakk/lnreader/UI/activity/BaseActivity.java
Java
apache-2.0
8,516
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2010 - 2014 Board of Regents of the University of * Wisconsin-Madison. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 HOLDERS 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. * #L% */ package imagej.workflow; import imagej.workflow.plugin.IPlugin; import imagej.workflow.plugin.annotations.Input; import imagej.workflow.plugin.annotations.Item; import imagej.workflow.plugin.annotations.Output; import imagej.workflow.util.xmllight.XMLException; import imagej.workflow.util.xmllight.XMLParser; import imagej.workflow.util.xmllight.XMLTag; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.prefs.Preferences; import net.java.sezpoz.Index; import net.java.sezpoz.IndexItem; /** * * @author aivar */ public class WorkflowManager implements IWorkflowManager { private static final String WORKFLOWS = "workflows"; private static String s_xml = ""; private static WorkflowManager s_instance = null; private enum Type { INPUT, OUTPUT }; private Preferences m_prefs = Preferences.userNodeForPackage(getClass()); private Map<String, IWorkflowInfo> m_workflows; private Map<String, IModuleInfo> m_plugins; /** * Gets singleton instance. * * @return */ public static synchronized WorkflowManager getInstance() { if (null == s_instance) { s_instance = new WorkflowManager(); } return s_instance; } /** * Private constructor. */ private WorkflowManager() { m_workflows = parseWorkflows(m_prefs.get(WORKFLOWS, s_xml)); m_plugins = discoverPlugins(); } /** * Adds a new workflow or replaces previous. * * @param workflow */ public void addWorkflow(IWorkflow workflow) { m_workflows.put(workflow.getName(), new WorkflowInfo(workflow.toXML())); //TODO going to XML and back is odd } /** * Deletes a named workflow. * * @param name */ public void deleteWorkflow(String name) { m_workflows.remove(name); } /** * Saves all workflows. */ public void saveAllWorkflows() { StringBuilder builder = new StringBuilder(); for (IWorkflowInfo workflow : m_workflows.values()) { builder.append(workflow.toXML()); } String xml = builder.toString(); if (xml.length() > Preferences.MAX_VALUE_LENGTH) { System.out.println("Workflows string exceeds " + Preferences.MAX_VALUE_LENGTH); } m_prefs.put(WORKFLOWS, xml); } /** * Gets an array of module infos. May be workflows and/or plugins. * * @return */ public IModuleInfo[] getModuleInfos() { List<IModuleInfo> moduleList = new ArrayList<IModuleInfo>(); moduleList.addAll(m_plugins.values()); moduleList.addAll(m_workflows.values()); //Collections.sort(moduleList); //TODO get "cannot find symbol sort(java.util.List<IModuleInfo>)"; should compile but give a generics warning return moduleList.toArray(new IModuleInfo[0]); } /** * Gets an array of workflow infos. * * @return */ public IWorkflowInfo[] getWorkflowInfos() { return m_workflows.values().toArray(new IWorkflowInfo[0]); } /** * Given the module information, creates an instance of the * module. Works for workflows and plugins. * * @param moduleInfo * @return */ public IModule createInstance(IModuleInfo moduleInfo) { return createInstance(moduleInfo, null); } /** * Given the module information and an instance identifider, * creates an instance of the module. Works for workflows and plugins. * * @param moduleInfo * @param instanceId * @return */ public IModule createInstance(IModuleInfo moduleInfo, String instanceId) { String xml = moduleInfo.toXML(); IModule module = null; try { module = ModuleFactory.getInstance().create(xml, instanceId); } catch (XMLException e) { System.out.println("internal XML problem " + e.getMessage()); } return module; } /** * Parses XML string to get workflow infos. * * @param xml * @return map of name to workflow info */ private Map<String, IWorkflowInfo> parseWorkflows(String xml) { if (!xml.isEmpty()) { System.out.println("Parsing workflow XML>" + xml + "<"); } Map<String, IWorkflowInfo> map = new HashMap<String, IWorkflowInfo>(); XMLParser xmlHelper = new XMLParser(); try { while (!xml.isEmpty()) { // look for workflow tag XMLTag tag = xmlHelper.getNextTag(xml); if (!Workflow.WORKFLOW.equals(tag.getName())) { throw new XMLException("Missing <workflow> tag"); } IWorkflowInfo workflowInfo = new WorkflowInfo(xml); map.put(workflowInfo.getName(), workflowInfo); xml = tag.getRemainder(); } } catch (XMLException e) { System.out.println("Internal XML Error " + e.getMessage()); } return map; } /** * Plugin discovery mechanism using SezPoz. * * @return map of name to plugin info */ private Map<String, IModuleInfo> discoverPlugins() { Map<String, IModuleInfo> pluginInfos = new HashMap<String, IModuleInfo>(); // Currently IPlugins are annotated with either Input or Output // annotations. Most will have both but its not required. // look for IPlugins with Input annotation for (final IndexItem<Input, IPlugin> indexItem : Index.load(Input.class, IPlugin.class)) { PluginModuleInfo pluginInfo = getPluginInfo( null, Type.INPUT, indexItem.className(), indexItem.annotation().value()); pluginInfos.put(pluginInfo.getName(), pluginInfo); } // look for IPlugins with Output annotation for (final IndexItem<Output, IPlugin> indexItem : Index.load(Output.class, IPlugin.class)) { String fullName = indexItem.className(); PluginModuleInfo pluginInfo = getPluginInfo( (PluginModuleInfo) pluginInfos.get(PluginModuleInfo.getName(fullName)), Type.OUTPUT, fullName, indexItem.annotation().value()); pluginInfos.put(pluginInfo.getName(), pluginInfo); }; return pluginInfos; } /** * Creates plugin info from full name and image names. This is called for both * input and output annotations. * * @param info existing plugin info or null * @param inputOrOutput whether input or output annotation * @param fullName full package and class name * @param items array of Item annotations * @return info */ private PluginModuleInfo getPluginInfo(PluginModuleInfo info, Type inputOrOutput, String fullName, Item[] items) { if (null == info) { info = new PluginModuleInfo(fullName); } // build list of item information List<IItemInfo> itemInfos = new ArrayList<IItemInfo>(); if (0 == items.length) { String name = Type.INPUT == inputOrOutput ? Input.DEFAULT : Output.DEFAULT; itemInfos.add(new ItemInfo(name, IItemInfo.Type.IMAGE, null)); } else { for (Item item : items) { String name = item.name(); IItemInfo.Type type = null; Object value = null; switch (item.type()) { case STRING: type = IItemInfo.Type.STRING; value = item.string(); break; case INTEGER: type = IItemInfo.Type.INTEGER; value = item.integer(); break; case FLOATING: type = IItemInfo.Type.FLOATING; value = item.floating(); break; case URL: type = IItemInfo.Type.URL; value = item.url(); break; case IMAGE: type = IItemInfo.Type.IMAGE; value = item.image(); break; } itemInfos.add(new ItemInfo(name, type, value)); } } if (Type.INPUT == inputOrOutput) { info.setInputItemInfos(itemInfos.toArray(new IItemInfo[0])); } else { info.setOutputItemInfos(itemInfos.toArray(new IItemInfo[0])); } return info; } }
imagej/workflow
src/main/java/imagej/workflow/WorkflowManager.java
Java
bsd-2-clause
10,258
package com.ocean.rpc.ipc; public class Call { private int callid; private String param; private Object o; private String error; private boolean isdone; public int getCallid() { return callid; } public void setCallid(int callid) { this.callid = callid; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } public Object getO() { return o; } public void setO(Object o) { this.o = o; } public String getError() { return error; } public void setError(String error) { this.error = error; } public boolean isIsdone() { return isdone; } public void setIsdone(boolean isdone) { this.isdone = isdone; } }
jayfans3/example
servcie/src/main/java/com/ocean/rpc/ipc/Call.java
Java
bsd-2-clause
718
package org.jcodec.containers.mp4.boxes; import java.nio.ByteBuffer; import org.jcodec.containers.mp4.boxes.Box.LeafBox; import org.junit.Assert; import org.junit.Test; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public class EditsBoxTest { @Test public void testShit() { LeafBox box = new LeafBox(Header.createHeader("free", 0), ByteBuffer.wrap(new byte[] { 0, 0, 0, 16, 'e', 'l', 's', 't', 0, 0, 0, 0, 0, 0, 0, 50, 0 })); Assert.assertFalse(EditsBox.isLookingLikeEdits(box)); } }
jcodec/jcodec
src/test/java/org/jcodec/containers/mp4/boxes/EditsBoxTest.java
Java
bsd-2-clause
637
package org.pm4j.core.xml.visibleState.beans; import javax.xml.bind.annotation.XmlRootElement; /** * Visible PM state XML report bean. * * @author Olaf Boede */ @XmlRootElement(name="cmd") public class XmlPmCommand extends XmlPmObject { }
pm4j/org.pm4j
pm4j-core/src/main/java/org/pm4j/core/xml/visibleState/beans/XmlPmCommand.java
Java
bsd-2-clause
246
package echowand.net; /** * コネクションのインタフェース * @author ymakino */ public interface Connection { /** * この接続のローカルノード情報を表すNodeInfoを返す。 * @return ローカルノード情報 */ public NodeInfo getLocalNodeInfo(); /** * この接続のリモートノード情報を表すNodeInfoを返す。 * @return リモートノード情報 */ public NodeInfo getRemoteNodeInfo(); /** * この接続が切断されているかどうかを返す。 * @return 接続が切断されていればtrue、接続中の場合にはfalse */ public boolean isClosed(); /** * この接続を切断する。 * @throws NetworkException エラーが発生した場合 */ public void close() throws NetworkException; /** * この接続を利用したフレームの送信を行う。 * @param commonFrame 送信するフレーム * @throws NetworkException 送信に失敗した場合 */ public void send(CommonFrame commonFrame) throws NetworkException; /** * この接続を利用したフレームの受信を行う。 * @return 受信したフレーム * @throws NetworkException 受信に失敗した場合 */ public CommonFrame receive() throws NetworkException; }
ymakino/echowand
src/echowand/net/Connection.java
Java
bsd-2-clause
1,389
package org.pm4j.core.sample.admin.user.service; import org.pm4j.core.pm.PmConversation; import org.pm4j.core.pm.impl.PmConversationImpl; import org.pm4j.core.sample.admin.user.UserEditPm; public class UserTestDataFactory { public static UserEditPm makeUserEditPm() { return new UserEditPm(makeSessionPm(), new User()); } public static PmConversation makeSessionPm() { PmConversation s = new PmConversationImpl(); s.setPmNamedObject("userService", new UserService()); return s; } }
pm4j/org.pm4j
pm4j-core-sample/src/main/java/org/pm4j/core/sample/admin/user/service/UserTestDataFactory.java
Java
bsd-2-clause
515
package de.lessvoid.nifty.examples.messagebox; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.MessageBox; import de.lessvoid.nifty.examples.NiftyExample; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; /** * The screen controller for the message box example. * * @author Martin Karing &lt;[email protected]&gt; */ public class MessageBoxStartScreen implements ScreenController, NiftyExample { private Screen screen; public void bind(final Nifty newNifty, final Screen screenParam) { screen = screenParam; } public void onStartScreen() { } public void onEndScreen() { } public void changeMessageBoxType(final String newType) { final MessageBox msgBox = screen.findNiftyControl("messagebox", MessageBox.class); msgBox.setMessageType(newType); msgBox.getElement().getParent().layoutElements(); } @Override public String getStartScreen() { return "start"; } @Override public String getMainXML() { return "messagebox/messagebox.xml"; } @Override public String getTitle() { return "Nifty MessageBox Example"; } @Override public void prepareStart(Nifty nifty) { // nothing to do } }
xranby/nifty-gui
nifty-examples/src/main/java/de/lessvoid/nifty/examples/messagebox/MessageBoxStartScreen.java
Java
bsd-2-clause
1,285
/* * 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 se.chalmers.dcs.bapic.concurrentKDTree.KDTrees; import edu.wlu.cs.levy.CG.KDTree; import edu.wlu.cs.levy.CG.KeyDuplicateException; import edu.wlu.cs.levy.CG.KeyMissingException; import edu.wlu.cs.levy.CG.KeySizeException; import java.util.logging.Level; import java.util.logging.Logger; import se.chalmers.dcs.bapic.concurrentKDTree.utils.*; /** * * @author Ivan Walulya * @param <K> * @param <V> */ public class LevyKDTreeWrapper<V> implements KDTreeADT<V> { KDTree<V> kd; int DIM; public LevyKDTreeWrapper(int dim) { kd = new KDTree<>(dim); this.DIM = dim; } @Override public boolean contains(double[] key) throws DimensionLimitException { try { return (kd.search(key) != null); } catch (KeySizeException ex) { Logger.getLogger(LevyKDTreeWrapper.class.getName()).log(Level.SEVERE, null, ex); } return false; } @Override public boolean add(double[] key, V value) throws DimensionLimitException { try { kd.insert(key, value); } catch (KeySizeException | KeyDuplicateException ex) { return false;//Logger.getLogger(LevyKDTreeWrapper.class.getName()).log(Level.SEVERE, null, ex); } return true; } @Override public boolean remove(double[] key) throws DimensionLimitException { try { kd.delete(key); return true; } catch (KeySizeException ex) { Logger.getLogger(LevyKDTreeWrapper.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyMissingException ex) { return false;//Logger.getLogger(LevyKDTreeWrapper.class.getName()).log(Level.SEVERE, null, ex); } return false; } @Override public V nearest(double[] key, boolean linearizable) { try { return kd.nearest(key); } catch (KeySizeException | IllegalArgumentException ex) { Logger.getLogger(LevyKDTreeWrapper.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
bapi/ConcurrentKDTree
src/se/chalmers/dcs/bapic/concurrentKDTree/KDTrees/LevyKDTreeWrapper.java
Java
bsd-2-clause
2,313
/* * Copyright (c) 2009-2012 jMonkeyEngine * 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 'jMonkeyEngine' 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 com.jme3.texture; import com.jme3.asset.AssetKey; import com.jme3.asset.AssetProcessor; import com.jme3.asset.TextureKey; import java.nio.ByteBuffer; public class TextureProcessor implements AssetProcessor { public Object postProcess(AssetKey key, Object obj) { TextureKey texKey = (TextureKey) key; Image img = (Image) obj; if (img == null) { return null; } Texture tex; if (texKey.isAsCube()) { if (texKey.isFlipY()) { // also flip -y and +y image in cubemap ByteBuffer pos_y = img.getData(2); img.setData(2, img.getData(3)); img.setData(3, pos_y); } tex = new TextureCubeMap(); } else if (texKey.isAsTexture3D()) { tex = new Texture3D(); } else { tex = new Texture2D(); } // enable mipmaps if image has them // or generate them if requested by user if (img.hasMipmaps() || texKey.isGenerateMips()) { tex.setMinFilter(Texture.MinFilter.Trilinear); } tex.setAnisotropicFilter(texKey.getAnisotropy()); tex.setName(texKey.getName()); tex.setImage(img); return tex; } public Object createClone(Object obj) { Texture tex = (Texture) obj; return tex.clone(); } }
chototsu/MikuMikuStudio
engine/src/core/com/jme3/texture/TextureProcessor.java
Java
bsd-2-clause
3,053
/** * Copyright (c) 2014, dector ([email protected]) * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.github.dector.sokoban.util; public class Audio { public enum Sounds { MENU_ITEM_MOVED("assets/sounds/menu_item_move.wav"), MENU_ITEM_SELECTED("assets/sounds/menu_item_select.wav"); public final String file; Sounds(String file) { this.file = file; } } public enum Music { MENU("assets/music/menu.mp3"), GAME("assets/music/game.mp3"); public final String file; Music(String file) { this.file = file; } } }
dector/sokoban
src/io/github/dector/sokoban/util/Audio.java
Java
bsd-2-clause
1,911
package com.sanluan.common.tools; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.ModelMap; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class FreeMarkerUtils { private static Logger log = LoggerFactory.getLogger(FreeMarkerUtils.class); public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config, Map<String, Object> model) throws IOException, TemplateException { makeFileByFile(templateFilePath, destFilePath, config, model, true, false); } public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config, Map<String, Object> model, boolean override) throws IOException, TemplateException { makeFileByFile(templateFilePath, destFilePath, config, model, override, false); } public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config, Map<String, Object> model, boolean override, boolean append) throws IOException, TemplateException { Template t = config.getTemplate(templateFilePath); File destFile = new File(destFilePath); if (override || append || !destFile.exists()) { File parent = destFile.getParentFile(); if (parent != null) { parent.mkdirs(); } Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile, append), "utf-8")); t.process(model, out); out.close(); log.info(destFilePath + " saved!"); } else { log.error(destFilePath + " already exists!"); } } public String makeStringByFile(String template, Configuration configuration) { return makeStringByFile(template, configuration, new ModelMap()); } public String makeStringByFile(String template, Configuration configuration, ModelMap model) { try { Template tpl = configuration.getTemplate(template); return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model); } catch (Exception e) { log.error(e.getMessage()); return ""; } } public static String makeStringByString(String templateContent, Configuration config, Map<String, Object> model) throws IOException, TemplateException { Template t = new Template(String.valueOf(templateContent.hashCode()), templateContent, config); return FreeMarkerTemplateUtils.processTemplateIntoString(t, model); } }
858888/PublicCMS
src/com/sanluan/common/tools/FreeMarkerUtils.java
Java
bsd-2-clause
2,660
package org.mapfish.print.processor.map; import org.junit.Test; import org.mapfish.print.AbstractMapfishSpringTest; import org.mapfish.print.TestHttpClientFactory; import org.mapfish.print.config.Configuration; import org.mapfish.print.config.ConfigurationFactory; import org.mapfish.print.config.Template; import org.mapfish.print.output.Values; import org.mapfish.print.test.util.ImageSimilarity; import org.mapfish.print.wrapper.json.PJsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import static org.junit.Assert.assertEquals; /** * Basic test of the Map processor. * <p></p> * Created by Jesse on 3/26/14. */ public class CreateMapProcessorGridFixedNumlinesPointAltLabelProjTest extends AbstractMapfishSpringTest { public static final String BASE_DIR = "grid_numlines_points_fixedscale_alt_label_proj/"; @Autowired private ConfigurationFactory configurationFactory; @Autowired private TestHttpClientFactory requestFactory; @Autowired private ForkJoinPool forkJoinPool; private static PJsonObject loadJsonRequestData() throws IOException { return parseJSONObjectFromFile(CreateMapProcessorFlexibleScaleCenterTiledWmsTest.class, BASE_DIR + "requestData.json"); } @Test @DirtiesContext public void testExecute() throws Exception { final String host = "grid_numlines_points_fixedscale_alt_label_proj"; TiledWMSUtil.registerTiledWmsHandler(requestFactory, host); final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml")); final Template template = config.getTemplate("A4 landscape"); PJsonObject requestData = loadJsonRequestData(); Values values = new Values("test", requestData, template, getTaskDirectory(), this.requestFactory, new File(".")); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit( template.getProcessorGraph().createTask(values)); taskFuture.get(); @SuppressWarnings("unchecked") List<URI> layerGraphics = (List<URI>) values.getObject("layerGraphics", List.class); assertEquals(1, layerGraphics.size()); String imageName = getExpectedImageName("", BASE_DIR); new ImageSimilarity(getFile(BASE_DIR + imageName)) .assertSimilarity(layerGraphics, 780, 330, 20); } }
marcjansen/mapfish-print
core/src/test/java/org/mapfish/print/processor/map/CreateMapProcessorGridFixedNumlinesPointAltLabelProjTest.java
Java
bsd-2-clause
2,679
/** * */ package org.kfm.camel.response; import java.io.Serializable; import java.util.Date; import org.kfm.camel.util.Utils; import com.livescribe.framework.orm.consumer.Authorization; import com.livescribe.framework.web.response.ResponseCode; import com.livescribe.framework.web.response.ServiceResponse; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * <p></p> * * @author <a href="mailto:[email protected]">Kevin F. Murdoff</a> * @version 1.0 */ @XStreamAlias("response") public class AuthorizationResponse implements Serializable { @XStreamAlias("responseCode") private ResponseCode responseCode; @XStreamAlias("authorized") private Boolean authorized; @XStreamAlias("authorizationId") private Long authorizationId; @XStreamAlias("user") private UserInfoResponse user; @XStreamAlias("enUsername") private String enUsername; @XStreamAlias("oauthAccessToken") private String oauthAccessToken; @XStreamAlias("provider") private String provider; @XStreamAlias("enShardId") private String enShardId; @XStreamAlias("expiration") private Date expiration; @XStreamAlias("created") private Date created; @XStreamAlias("lastModified") private Date lastModified; @XStreamAlias("lastModifiedBy") private String lastModifiedBy; @XStreamAlias("enUserId") private Long enUserId; @XStreamAlias("uid") private String uid; @XStreamAlias("isPrimary") private Boolean isPrimary; /** * <p></p> * */ public AuthorizationResponse() { } /** * <p></p> * * @param code */ public AuthorizationResponse(ResponseCode code) { this(code, null); } /** * <p></p> * @param Authorization authorization */ public AuthorizationResponse(Authorization authorization) { this(null, authorization); } /** * <p></p> * @param ResponseCode code * @param Authorization authorization */ public AuthorizationResponse(ResponseCode code, Authorization authorization) { super(); if(code != null) { this.setResponseCode(code); } this.authorized = null; if (authorization != null) { this.authorizationId = authorization.getAuthorizationId(); this.user = new UserInfoResponse(authorization.getUser()); this.enUsername = authorization.getEnUsername(); this.oauthAccessToken = authorization.getOauthAccessToken(); this.provider = authorization.getProvider(); this.enShardId = authorization.getEnShardId(); this.expiration = authorization.getExpiration(); this.created = authorization.getCreated(); this.lastModified = authorization.getLastModified(); this.lastModifiedBy = authorization.getLastModifiedBy(); this.isPrimary = authorization.getIsPrimary(); this.enUserId = authorization.getEnUserId(); if (this.user != null) { this.uid = this.user.getUid(); } } } /** * @return the authorized */ public Boolean isAuthorized() { return authorized; } /** * @param authorized the authorized to set */ public void setAuthorized(Boolean authorized) { this.authorized = authorized; } /** * @return */ public Long getAuthorizationId() { return authorizationId; } /** * @param evernoteUserId */ public void setAuthorizationId(Long authorizationId) { this.authorizationId = authorizationId; } public Boolean getIsPrimary() { return isPrimary; } public void setIsPrimary(Boolean isPrimary) { this.isPrimary = isPrimary; } /** * @return the user */ public UserInfoResponse getUser() { return user; } /** * @param user the user to set */ public void setUser(UserInfoResponse user) { this.user = user; } /** * @return Evernote user name */ public String getEnUsername() { return enUsername; } /** * @param enUserName The Evernote user name */ public void setEnUsername(String enUsername) { this.enUsername = enUsername; } /** * @return the authorizationToken */ public String getOauthAccessToken() { return oauthAccessToken; } /** * @param authorizationToken the authorizationToken to set */ public void setOauthAccessToken(String oauthAccessToken) { this.oauthAccessToken = oauthAccessToken; } /** * @return the provider */ public String getProvider() { return provider; } /** * @param provider the provider to set */ public void setProvider(String provider) { this.provider = provider; } /** * * @return */ public String getEnShardId() { return enShardId; } /** * * @param evernoteShardId */ public void setEnShardId(String enShardId) { this.enShardId = enShardId; } /** * @return the expiration */ public Date getExpiration() { return expiration; } /** * @param expiration the expiration to set */ public void setExpiration(Date expiration) { this.expiration = expiration; } /** * @return the created */ public Date getCreated() { return created; } /** * @param created the created to set */ public void setCreated(Date created) { this.created = created; } /** * @return the lastModified */ public Date getLastModified() { return lastModified; } /** * @param lastModified the lastModified to set */ public void setLastModified(Date lastModified) { this.lastModified = lastModified; } /** * @return the lastModifiedBy */ public String getLastModifiedBy() { return lastModifiedBy; } /** * @param lastModifiedBy the lastModifiedBy to set */ public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } /** * @return */ public Long getEnUserId() { return enUserId; } /** * @param evernoteUserId */ public void setEnUserId(Long enUserId) { this.enUserId = enUserId; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AuthorizationResponse <authorized = ").append(authorized); builder.append(", user = ").append(user); builder.append(", enUsername = ").append(enUsername); builder.append(", oauthAccessToken = ").append(Utils.obfuscateOAuthToken(oauthAccessToken)); builder.append(", provider = ").append(provider); builder.append(", enShardId = ").append(enShardId); builder.append(", expiration = ").append(expiration); builder.append(", created = ").append(created); builder.append(", lastModified = ").append(lastModified); builder.append(", lastModifiedBy = ").append(lastModifiedBy); builder.append(", enUserId = ").append(enUserId); builder.append(", isPrimary = ").append(isPrimary); builder.append(", authorizationId = ").append(authorizationId); builder.append(", uid = ").append(uid).append(">"); return builder.toString(); } /** * <p></p> * * @return the uid */ public String getUid() { return uid; } /** * <p></p> * * @param uid the uid to set */ public void setUid(String uid) { this.uid = uid; } /** * <p></p> * * @return the responseCode */ public ResponseCode getResponseCode() { return responseCode; } /** * <p></p> * * @param responseCode the responseCode to set */ public void setResponseCode(ResponseCode responseCode) { this.responseCode = responseCode; } }
jackstraw66/web
camel-scratch/src/main/java/org/kfm/camel/response/AuthorizationResponse.java
Java
bsd-2-clause
7,242
package example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class AppController { private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class); private final HystrixEnabledService service; @Autowired public AppController(HystrixEnabledService service) { this.service = service; } @RequestMapping(value = "/", produces = "application/json") public String something(@RequestParam(value = "wait", defaultValue = "4") int wait) { LOGGER.info("received request"); return service.request(wait); } }
ericdahl/hello-hystrix
src/main/java/example/AppController.java
Java
bsd-2-clause
863
/* * Copyright (c) 2017, Seth <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 net.runelite.api; import java.util.HashMap; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; /** * Enumeration of message types that can be received in the chat. */ @AllArgsConstructor @Getter public enum ChatMessageType { /** * A normal game message. */ GAMEMESSAGE(0), /** * A message in the public chat from a moderator */ MODCHAT(1), /** * A message in the public chat. */ PUBLICCHAT(2), /** * A private message from another player. */ PRIVATECHAT(3), /** * A message that the game engine sends. */ ENGINE(4), /** * A message received when a friend logs in or out. */ LOGINLOGOUTNOTIFICATION(5), /** * A private message sent to another player. */ PRIVATECHATOUT(6), /** * A private message received from a moderator. */ MODPRIVATECHAT(7), /** * A message received in clan chat. */ FRIENDSCHAT(9), /** * A message received with information about the current clan chat. */ FRIENDSCHATNOTIFICATION(11), /** * A trade request being sent. */ TRADE_SENT(12), /** * A game broadcast. */ BROADCAST(14), /** * An abuse report submitted. */ SNAPSHOTFEEDBACK(26), /** * Examine item description. */ ITEM_EXAMINE(27), /** * Examine NPC description. */ NPC_EXAMINE(28), /** * Examine object description. */ OBJECT_EXAMINE(29), /** * Adding player to friend list. */ FRIENDNOTIFICATION(30), /** * Adding player to ignore list. */ IGNORENOTIFICATION(31), /** * An autotyper message from a player. */ AUTOTYPER(90), /** * An autotyper message from a mod. */ MODAUTOTYPER(91), /** * A game message (ie. when a setting is changed). */ CONSOLE(99), /** * A message received when somebody sends a trade offer. */ TRADEREQ(101), /** * A message received when completing a trade or a duel */ TRADE(102), /** * A message received when somebody sends a duel offer. */ CHALREQ_TRADE(103), /** * A message received when someone sends a clan challenge offer. */ CHALREQ_FRIENDSCHAT(104), /** * A message that was filtered. */ SPAM(105), /** * A message that is relating to the player. */ PLAYERRELATED(106), /** * A message that times out after 10 seconds. */ TENSECTIMEOUT(107), /** * An unknown message type. */ UNKNOWN(-1); private final int type; private static final Map<Integer, ChatMessageType> CHAT_MESSAGE_TYPES = new HashMap<>(); static { for (ChatMessageType chatMessageType : values()) { CHAT_MESSAGE_TYPES.put(chatMessageType.type, chatMessageType); } } /** * Utility method that maps the type value to its respective * {@link ChatMessageType} value. * * @param type the raw type * @return appropriate message type, or {@link #UNKNOWN} */ public static ChatMessageType of(int type) { return CHAT_MESSAGE_TYPES.getOrDefault(type, UNKNOWN); } }
abelbriggs1/runelite
runelite-api/src/main/java/net/runelite/api/ChatMessageType.java
Java
bsd-2-clause
4,267
package me.lcw.utils; /* * Base64.java * * Brazil project web application toolkit, * export version: 2.0 * Copyright (c) 2000-2002 Sun Microsystems, Inc. * * Sun Public License Notice * * The contents of this file are subject to the Sun Public License * Version 1.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is included as * the file "license.terms", and also available at * http://www.sun.com/ * * The Original Code is from: * Brazil project web application toolkit release 2.0. * The Initial Developer of the Original Code is: cstevens. * Portions created by cstevens are Copyright (C) Sun Microsystems, * Inc. All Rights Reserved. * * Contributor(s): cstevens, suhler. * * Version: 1.9 * Created by cstevens on 00/04/17 * Last modified by suhler on 02/07/24 10:49:48 */ /** * Utility to base64 encode and decode a string. * @author Stephen Uhler * @version 1.9, 02/07/24 */ public class Base64 { private static byte[] encodeData; private static String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static { encodeData = new byte[64]; for (int i = 0; i < 64; i++) { byte c = (byte) charSet.charAt(i); encodeData[i] = c; } } private Base64() {} public static String encode(String s) { return encode(s.getBytes()); } public static String encode(byte[] src) { return encode(src, 0, src.length); } public static String encode(byte[] src, int start, int length) { byte[] dst = new byte[(length+2)/3 * 4 ]; int x = 0; int dstIndex = 0; int state = 0; // which char in pattern int old = 0; // previous byte int len = 0; // length decoded so far int max = length + start; for (int srcIndex = start; srcIndex<max; srcIndex++) { x = src[srcIndex]; switch (++state) { case 1: dst[dstIndex++] = encodeData[(x>>2) & 0x3f]; break; case 2: dst[dstIndex++] = encodeData[((old<<4)&0x30) | ((x>>4)&0xf)]; break; case 3: dst[dstIndex++] = encodeData[((old<<2)&0x3C) | ((x>>6)&0x3)]; dst[dstIndex++] = encodeData[x&0x3F]; state = 0; break; default: break; } old = x; } // now clean up the end bytes switch (state) { case 1: { dst[dstIndex++] = encodeData[(old<<4) & 0x30]; dst[dstIndex++] = (byte) '='; dst[dstIndex++] = (byte) '='; } break; case 2: { dst[dstIndex++] = encodeData[(old<<2) & 0x3c]; dst[dstIndex++] = (byte) '='; } break; } return new String(dst); } public static byte[] decode(String s) { int end = 0; // end state if (s.endsWith("=")) { end++; } if (s.endsWith("==")) { end++; } int len = (s.length() + 3)/4 * 3 - end; byte[] result = new byte[len]; int dst = 0; try { for(int src = 0; src< s.length(); src++) { int code = charSet.indexOf(s.charAt(src)); if (code == -1) { break; } switch (src%4) { case 0: result[dst] = (byte) (code<<2); break; case 1: result[dst++] |= (byte) ((code>>4) & 0x3); result[dst] = (byte) (code<<4); break; case 2: result[dst++] |= (byte) ((code>>2) & 0xf); result[dst] = (byte) (code<<6); break; case 3: result[dst++] |= (byte) (code & 0x3f); break; default: break; } } } catch (ArrayIndexOutOfBoundsException e) {} return result; } }
lwahlmeier/oggHeaderParser
src/main/java/me/lcw/utils/Base64.java
Java
bsd-2-clause
3,662
package adf.communication; import java.util.List; abstract public class MessageBundle { abstract public List<Class<? extends CommunicationMessage>> getMessageClassList(); }
tkmnet/RCRS-ADF
modules/core/src/main/java/adf/communication/MessageBundle.java
Java
bsd-2-clause
179
package org.protobee.gnutella.file; import com.google.inject.AbstractModule; import com.google.inject.Singleton; public class FileGuiceModule extends AbstractModule { protected void configure() { bind(ShareFileManager.class).to(NoOpShareFileManager.class).in(Singleton.class); } }
dmurph/protobee
gnutella6/src/main/java/org/protobee/gnutella/file/FileGuiceModule.java
Java
bsd-2-clause
303
/* * Copyright (c) 2017, 7u83 <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package opensesim.trader.ManTrader; import opensesim.gui.OpenOrdersList; import opensesim.old_sesim.Exchange; import opensesim.old_sesim.Order; import opensesim.old_sesim.Order.OrderType; /** * * @author 7u83 <[email protected]> */ public class ManTraderConsole extends javax.swing.JPanel { public ManTrader trader; public OpenOrdersList getOrderListPanel(){ return this.ordersList; } /** * Creates new form ManTraderConsole */ public ManTraderConsole() { initComponents(); // this.ordersList1.account=trader.getAccount(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { limitSpinner = new javax.swing.JSpinner(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); volumeSpinner = new javax.swing.JSpinner(); buyButton = new javax.swing.JButton(); sellButton = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); moneyText = new javax.swing.JLabel(); stopLossButton = new javax.swing.JButton(); jTabbedPane1 = new javax.swing.JTabbedPane(); ordersList = new opensesim.gui.OpenOrdersList(); limitSpinner.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, null, 1.0d)); jLabel1.setText("Limit:"); jLabel2.setText("Volume:"); volumeSpinner.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, null, 1.0d)); buyButton.setText("Buy"); buyButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buyButtonActionPerformed(evt); } }); sellButton.setText("Sell"); sellButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sellButtonActionPerformed(evt); } }); jLabel3.setText("Money:"); moneyText.setText("jLabel4"); stopLossButton.setText("StopLoss"); stopLossButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopLossButtonActionPerformed(evt); } }); jTabbedPane1.addTab("Open Orders", ordersList); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(buyButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sellButton, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(stopLossButton)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(44, 44, 44) .addComponent(volumeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(limitSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(moneyText, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(moneyText)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(limitSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(volumeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(buyButton, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addComponent(sellButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(stopLossButton) .addGap(20, 20, 20)))) ); }// </editor-fold>//GEN-END:initComponents private void buyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buyButtonActionPerformed Double limit = (Double)this.limitSpinner.getValue(); Double volume = (Double)this.volumeSpinner.getValue(); System.out.printf("Should buy: %f %f\n",volume,limit); Order createOrder = trader.getSE().createOrder(trader.getAccount().getID(), trader.getSE().getDefaultStockSymbol(), OrderType.BUYLIMIT, volume, limit); System.out.printf("The retval is %d",createOrder); // this.ordersList.account=this.trader.getAccount(); // this.ordersList.updateModel(); }//GEN-LAST:event_buyButtonActionPerformed private void sellButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sellButtonActionPerformed Double limit = (Double)this.limitSpinner.getValue(); Double volume = (Double)this.volumeSpinner.getValue(); System.out.printf("Should sell: %f %f\n",volume,limit); Order createOrder = trader.getSE().createOrder(trader.getAccount().getID(), trader.getSE().getDefaultStockSymbol(), OrderType.SELLLIMIT, volume, limit); System.out.printf("The retval is %d",createOrder); }//GEN-LAST:event_sellButtonActionPerformed private void stopLossButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopLossButtonActionPerformed Double limit = (Double)this.limitSpinner.getValue(); Double volume = (Double)this.volumeSpinner.getValue(); System.out.printf("Should stoploss: %f %f\n",volume,limit); Order createOrder = trader.getSE().createOrder(trader.getAccount().getID(), trader.getSE().getDefaultStockSymbol(), OrderType.STOPLOSS, volume, limit); System.out.printf("The retval is %d",createOrder); }//GEN-LAST:event_stopLossButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buyButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JSpinner limitSpinner; private javax.swing.JLabel moneyText; private opensesim.gui.OpenOrdersList ordersList; private javax.swing.JButton sellButton; private javax.swing.JButton stopLossButton; private javax.swing.JSpinner volumeSpinner; // End of variables declaration//GEN-END:variables }
7u83/SeSim
src/opensesim/trader/ManTrader/ManTraderConsole.java
Java
bsd-2-clause
11,526
package com.epicgames.ue4; public class JavaBuildSettings { public enum PackageType {AMAZON, GOOGLE, DEVELOPMENT}; public static final PackageType PACKAGING = PackageType.DEVELOPMENT; }
PopCap/GameIdea
Engine/Build/Android/Java/src/com/epicgames/ue4/JavaBuildSettings.java
Java
bsd-2-clause
188
package cola.machine.game.myblocks.engine.subsystem; import cola.machine.game.myblocks.config.Config; import cola.machine.game.myblocks.engine.modes.GameState; public interface EngineSubsystem { void preInitialise(); void postInitialise(Config config); void preUpdate(GameState currentState,float delta); void postUpdate(GameState currentState,float delta); void shutdown(Config config); void dispose(); //void registerSystems(ComponentSystemManager componentSystemManager); }
ColaMachine/MyBlock
src/main/java/cola/machine/game/myblocks/engine/subsystem/EngineSubsystem.java
Java
bsd-2-clause
498
package blang.core; /** * A factor in a factor graph. * * * @author Alexandre Bouchard ([email protected]) * */ public interface Factor extends ModelComponent { }
UBC-Stat-ML/blangDSL
ca.ubc.stat.blang.parent/ca.ubc.stat.blang/src/blang/core/Factor.java
Java
bsd-2-clause
183
/*- * #%L * PropertiesFramework :: Core * %% * Copyright (C) 2017 LeanFrameworks * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 HOLDERS 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. * #L% */ package com.github.leanframeworks.propertiesframework.base.transform.collection; import com.github.leanframeworks.propertiesframework.api.transform.Transformer; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import static org.junit.Assert.assertEquals; /** * @see GetCollectionSizeTransformer */ public class GetCollectionSizeTransformerTest { @Test public void testNonNull() { Transformer<Collection<?>, Integer> transformer = new GetCollectionSizeTransformer(); Collection<String> collection = new ArrayList<>(); assertEquals(Integer.valueOf(0), transformer.transform(collection)); collection.add("One"); assertEquals(Integer.valueOf(1), transformer.transform(collection)); collection.add("Two"); assertEquals(Integer.valueOf(2), transformer.transform(collection)); collection.add("Three"); assertEquals(Integer.valueOf(3), transformer.transform(collection)); collection.clear(); assertEquals(Integer.valueOf(0), transformer.transform(collection)); } }
LeanFrameworks/PropertiesFramework
propertiesframework-core/src/test/java/com/github/leanframeworks/propertiesframework/base/transform/collection/GetCollectionSizeTransformerTest.java
Java
bsd-2-clause
2,508
package cfvbaibai.cardfantasy.web.beans; public class OfficialSkillTypeInfo { private String name; private String firstSkillId; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstSkillId() { return firstSkillId; } public void setFirstSkillId(String firstSkillId) { this.firstSkillId = firstSkillId; } public OfficialSkillTypeInfo(String name, String firstSkillId) { this.name = name; this.firstSkillId = firstSkillId; } }
cfvbaibai/CardFantasy
workspace/mkhx/src/cfvbaibai/cardfantasy/web/beans/OfficialSkillTypeInfo.java
Java
bsd-2-clause
586
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.petite.proxy.example1.impl; import jodd.petite.meta.PetiteBean; import jodd.petite.proxy.Logged; import jodd.petite.proxy.example1.ISubPetiteBean; import jodd.petite.scope.ProtoScope; @PetiteBean (scope = ProtoScope.class) public class SubPetiteBean implements ISubPetiteBean { @Override @Logged public void execute_sub() { System.out.println("Executing " + this.getClass().getCanonicalName()); } }
vilmospapp/jodd
jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/SubPetiteBean.java
Java
bsd-2-clause
1,823
import java.applet.Applet; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("bs") public class class57 { @ObfuscatedName("o") static Applet field674; @ObfuscatedName("k") public static String field667; @ObfuscatedName("u") @ObfuscatedSignature( signature = "[Lll;" ) @Export("titlemuteSprite") static IndexedSprite[] titlemuteSprite; static { field674 = null; field667 = ""; } @ObfuscatedName("o") @ObfuscatedSignature( signature = "(ILjava/lang/String;Ljava/lang/String;S)V", garbageValue = "304" ) @Export("sendGameMessage") static void sendGameMessage(int var0, String var1, String var2) { class20.addChatMessage(var0, var1, var2, (String)null); } @ObfuscatedName("k") @ObfuscatedSignature( signature = "(Ljava/lang/CharSequence;Llh;I)Ljava/lang/String;", garbageValue = "879307111" ) public static String method861(CharSequence var0, JagexLoginType var1) { if(var0 == null) { return null; } else { int var2 = 0; int var3; for(var3 = var0.length(); var2 < var3 && WorldMapDecoration.method315(var0.charAt(var2)); ++var2) { ; } while(var3 > var2 && WorldMapDecoration.method315(var0.charAt(var3 - 1))) { --var3; } int var4 = var3 - var2; if(var4 >= 1) { byte var6; if(var1 == null) { var6 = 12; } else { switch(var1.field4073) { case 6: var6 = 20; break; default: var6 = 12; } } if(var4 <= var6) { StringBuilder var13 = new StringBuilder(var4); for(int var14 = var2; var14 < var3; ++var14) { char var7 = var0.charAt(var14); boolean var8; if(Character.isISOControl(var7)) { var8 = false; } else { boolean var9 = var7 >= '0' && var7 <= '9' || var7 >= 'A' && var7 <= 'Z' || var7 >= 'a' && var7 <= 'z'; if(var9) { var8 = true; } else { char[] var10 = class315.field3920; int var11 = 0; label96: while(true) { char var12; if(var11 >= var10.length) { var10 = class315.field3922; for(var11 = 0; var11 < var10.length; ++var11) { var12 = var10[var11]; if(var12 == var7) { var8 = true; break label96; } } var8 = false; break; } var12 = var10[var11]; if(var7 == var12) { var8 = true; break; } ++var11; } } } if(var8) { char var15 = ClanMember.method5259(var7); if(var15 != 0) { var13.append(var15); } } } if(var13.length() == 0) { return null; } return var13.toString(); } } return null; } } @ObfuscatedName("u") @ObfuscatedSignature( signature = "([BI)Lki;", garbageValue = "-1528138480" ) static Font method868(byte[] var0) { if(var0 == null) { return null; } else { Font var1 = new Font(var0, class332.indexedSpriteOffsetXs, FileSystem.indexedSpriteOffsetYs, WorldMapDecoration.indexSpriteWidths, class332.indexedSpriteHeights, class332.indexedSpritePalette, class332.spritePixels); class36.method541(); return var1; } } @ObfuscatedName("ge") @ObfuscatedSignature( signature = "(Lgj;I)V", garbageValue = "233468918" ) static final void method869(class183 var0) { PacketBuffer var1 = Client.field957.packetBuffer; int var2; int var3; int var5; int var6; int var7; int var8; int var37; int var39; int var43; if(class183.field2492 == var0) { var2 = var1.readUnsignedByte(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.readUnsignedShortOb1(); var6 = var5 >> 2; var7 = var5 & 3; var8 = Client.field929[var6]; var39 = var1.method3553(); if(var3 >= 0 && var37 >= 0 && var3 < 103 && var37 < 103) { if(var8 == 0) { WallObject var10 = class255.region.method2874(BoundingBox3DDrawMode.plane, var3, var37); if(var10 != null) { var43 = var10.hash >> 14 & 32767; if(var6 == 2) { var10.renderable1 = new DynamicObject(var43, 2, var7 + 4, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var10.renderable1); var10.renderable2 = new DynamicObject(var43, 2, var7 + 1 & 3, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var10.renderable2); } else { var10.renderable1 = new DynamicObject(var43, var6, var7, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var10.renderable1); } } } if(var8 == 1) { DecorativeObject var40 = class255.region.method2928(BoundingBox3DDrawMode.plane, var3, var37); if(var40 != null) { var43 = var40.hash >> 14 & 32767; if(var6 != 4 && var6 != 5) { if(var6 == 6) { var40.renderable1 = new DynamicObject(var43, 4, var7 + 4, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var40.renderable1); } else if(var6 == 7) { var40.renderable1 = new DynamicObject(var43, 4, (var7 + 2 & 3) + 4, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var40.renderable1); } else if(var6 == 8) { var40.renderable1 = new DynamicObject(var43, 4, var7 + 4, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var40.renderable1); var40.renderable2 = new DynamicObject(var43, 4, (var7 + 2 & 3) + 4, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var40.renderable2); } } else { var40.renderable1 = new DynamicObject(var43, 4, var7, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var40.renderable1); } } } if(var8 == 2) { GameObject var41 = class255.region.method2876(BoundingBox3DDrawMode.plane, var3, var37); if(var6 == 11) { var6 = 10; } if(var41 != null) { var41.renderable = new DynamicObject(var41.hash >> 14 & 32767, var6, var7, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var41.renderable); } } if(var8 == 3) { GroundObject var42 = class255.region.getFloorDecoration(BoundingBox3DDrawMode.plane, var3, var37); if(var42 != null) { var42.renderable = new DynamicObject(var42.hash >> 14 & 32767, 22, var7, BoundingBox3DDrawMode.plane, var3, var37, var39, false, var42.renderable); } } } } else { byte var11; int var12; int var13; int var14; int var44; if(class183.field2491 == var0) { var2 = var1.readUnsignedShortOb1() * 4; byte var38 = var1.method3725(); var37 = var1.method3555(); var5 = var1.readUnsignedByte(); var6 = var1.method3553(); var7 = var1.readUnsignedShort(); var8 = var1.method3556(); var39 = var1.readUnsignedByte(); var44 = var1.readUnsignedShortOb1() * 4; var11 = var1.readByte(); var12 = var1.readUnsignedByte(); var13 = (var12 >> 4 & 7) + WidgetNode.field794; var14 = (var12 & 7) + class278.field3551; var3 = var38 + var13; var43 = var11 + var14; if(var13 >= 0 && var14 >= 0 && var13 < 104 && var14 < 104 && var3 >= 0 && var43 >= 0 && var3 < 104 && var43 < 104 && var6 != 65535) { var13 = var13 * 128 + 64; var14 = var14 * 128 + 64; var3 = var3 * 128 + 64; var43 = var43 * 128 + 64; Projectile var15 = new Projectile(var6, BoundingBox3DDrawMode.plane, var13, var14, class265.getTileHeight(var13, var14, BoundingBox3DDrawMode.plane) - var2, var7 + Client.gameCycle, var37 + Client.gameCycle, var5, var39, var8, var44); var15.moveProjectile(var3, var43, class265.getTileHeight(var3, var43, BoundingBox3DDrawMode.plane) - var44, var7 + Client.gameCycle); Client.projectiles.addFront(var15); } } else { if(class183.field2501 == var0) { var2 = var1.method3553(); var3 = var1.method3553(); byte var4 = var1.readByte(); var5 = var1.readUnsignedByte(); var6 = (var5 >> 4 & 7) + WidgetNode.field794; var7 = (var5 & 7) + class278.field3551; var8 = var1.readUnsignedShort(); byte var9 = var1.method3634(); byte var31 = var1.method3548(); var11 = var1.method3725(); var12 = var1.method3553(); var13 = var1.readUnsignedShortOb1(); var14 = var13 >> 2; int var32 = var13 & 3; int var16 = Client.field929[var14]; Player var17; if(var8 == Client.localInteractingIndex) { var17 = SoundTaskDataProvider.localPlayer; } else { var17 = Client.cachedPlayers[var8]; } if(var17 != null) { ObjectComposition var18 = GameCanvas.getObjectDefinition(var12); int var19; int var20; if(var32 != 1 && var32 != 3) { var19 = var18.width; var20 = var18.length; } else { var19 = var18.length; var20 = var18.width; } int var21 = var6 + (var19 >> 1); int var22 = var6 + (var19 + 1 >> 1); int var23 = var7 + (var20 >> 1); int var24 = var7 + (var20 + 1 >> 1); int[][] var25 = class62.tileHeights[BoundingBox3DDrawMode.plane]; int var26 = var25[var22][var23] + var25[var21][var23] + var25[var21][var24] + var25[var22][var24] >> 2; int var27 = (var6 << 7) + (var19 << 6); int var28 = (var7 << 7) + (var20 << 6); Model var29 = var18.method4999(var14, var32, var25, var27, var26, var28); if(var29 != null) { class264.method4683(BoundingBox3DDrawMode.plane, var6, var7, var16, -1, 0, 0, var3 + 1, var2 + 1); var17.animationCycleStart = var3 + Client.gameCycle; var17.animationCycleEnd = var2 + Client.gameCycle; var17.model = var29; var17.field845 = var6 * 128 + var19 * 64; var17.field843 = var7 * 128 + var20 * 64; var17.field858 = var26; byte var30; if(var4 > var31) { var30 = var4; var4 = var31; var31 = var30; } if(var11 > var9) { var30 = var11; var11 = var9; var9 = var30; } var17.field849 = var4 + var6; var17.field851 = var31 + var6; var17.field850 = var7 + var11; var17.field852 = var9 + var7; } } } if(class183.field2489 == var0) { var2 = var1.method3636(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.method3636(); var6 = var5 >> 2; var7 = var5 & 3; var8 = Client.field929[var6]; if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { class264.method4683(BoundingBox3DDrawMode.plane, var3, var37, var8, -1, var6, var7, 0, -1); } } else if(class183.field2490 == var0) { var2 = var1.method3555(); var3 = var1.readUnsignedByte(); var37 = (var3 >> 4 & 7) + WidgetNode.field794; var5 = (var3 & 7) + class278.field3551; var6 = var1.method3555(); var7 = var1.method3554(); if(var37 >= 0 && var5 >= 0 && var37 < 104 && var5 < 104) { Deque var45 = Client.groundItemDeque[BoundingBox3DDrawMode.plane][var37][var5]; if(var45 != null) { for(Item var34 = (Item)var45.getFront(); var34 != null; var34 = (Item)var45.getNext()) { if((var7 & 32767) == var34.id && var6 == var34.quantity) { var34.quantity = var2; break; } } class18.groundItemSpawned(var37, var5); } } } else if(class183.field2497 == var0) { var2 = var1.method3538(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.method3553(); var6 = var1.method3636(); var7 = var1.method3554(); if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { var3 = var3 * 128 + 64; var37 = var37 * 128 + 64; GraphicsObject var33 = new GraphicsObject(var7, BoundingBox3DDrawMode.plane, var3, var37, class265.getTileHeight(var3, var37, BoundingBox3DDrawMode.plane) - var6, var5, Client.gameCycle); Client.graphicsObjectDeque.addFront(var33); } } else { if(class183.field2495 == var0) { var2 = var1.readUnsignedShortOb1(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.method3636(); var6 = var5 >> 4 & 15; var7 = var5 & 7; var8 = var1.readUnsignedByte(); var39 = var1.method3554(); if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { var44 = var6 + 1; if(SoundTaskDataProvider.localPlayer.pathX[0] >= var3 - var44 && SoundTaskDataProvider.localPlayer.pathX[0] <= var3 + var44 && SoundTaskDataProvider.localPlayer.pathY[0] >= var37 - var44 && SoundTaskDataProvider.localPlayer.pathY[0] <= var37 + var44 && Client.field951 != 0 && var7 > 0 && Client.queuedSoundEffectCount < 50) { Client.queuedSoundEffectIDs[Client.queuedSoundEffectCount] = var39; Client.unknownSoundValues1[Client.queuedSoundEffectCount] = var7; Client.unknownSoundValues2[Client.queuedSoundEffectCount] = var8; Client.audioEffects[Client.queuedSoundEffectCount] = null; Client.soundLocations[Client.queuedSoundEffectCount] = var6 + (var37 << 8) + (var3 << 16); ++Client.queuedSoundEffectCount; } } } Item var35; if(class183.field2494 == var0) { var2 = var1.method3636(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.method3553(); var6 = var1.method3555(); if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { var35 = new Item(); var35.id = var5; var35.quantity = var6; if(Client.groundItemDeque[BoundingBox3DDrawMode.plane][var3][var37] == null) { Client.groundItemDeque[BoundingBox3DDrawMode.plane][var3][var37] = new Deque(); } Client.groundItemDeque[BoundingBox3DDrawMode.plane][var3][var37].addFront(var35); class18.groundItemSpawned(var3, var37); } } else if(class183.field2498 == var0) { var2 = var1.readUnsignedByte(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.method3553(); var6 = var1.readUnsignedShortOb1(); var7 = var6 >> 2; var8 = var6 & 3; var39 = Client.field929[var7]; if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { class264.method4683(BoundingBox3DDrawMode.plane, var3, var37, var39, var5, var7, var8, 0, -1); } } else if(class183.field2493 == var0) { var2 = var1.readUnsignedByte(); var3 = (var2 >> 4 & 7) + WidgetNode.field794; var37 = (var2 & 7) + class278.field3551; var5 = var1.readUnsignedShort(); if(var3 >= 0 && var37 >= 0 && var3 < 104 && var37 < 104) { Deque var36 = Client.groundItemDeque[BoundingBox3DDrawMode.plane][var3][var37]; if(var36 != null) { for(var35 = (Item)var36.getFront(); var35 != null; var35 = (Item)var36.getNext()) { if((var5 & 32767) == var35.id) { var35.unlink(); break; } } if(var36.getFront() == null) { Client.groundItemDeque[BoundingBox3DDrawMode.plane][var3][var37] = null; } class18.groundItemSpawned(var3, var37); } } } } } } } @ObfuscatedName("jb") @ObfuscatedSignature( signature = "(Lbt;ZB)V", garbageValue = "0" ) @Export("closeWidget") static final void closeWidget(WidgetNode var0, boolean var1) { int var2 = var0.id; int var3 = (int)var0.hash; var0.unlink(); if(var1 && var2 != -1 && class154.validInterfaces[var2]) { UrlRequest.widgetIndex.method4543(var2); if(MouseRecorder.widgets[var2] != null) { boolean var6 = true; for(int var5 = 0; var5 < MouseRecorder.widgets[var2].length; ++var5) { if(MouseRecorder.widgets[var2][var5] != null) { if(MouseRecorder.widgets[var2][var5].type != 2) { MouseRecorder.widgets[var2][var5] = null; } else { var6 = false; } } } if(var6) { MouseRecorder.widgets[var2] = null; } class154.validInterfaces[var2] = false; } } for(IntegerNode var4 = (IntegerNode)Client.widgetFlags.first(); var4 != null; var4 = (IntegerNode)Client.widgetFlags.next()) { if((var4.hash >> 48 & 65535L) == (long)var2) { var4.unlink(); } } Widget var7 = class44.getWidget(var3); if(var7 != null) { FontName.method5490(var7); } ScriptState.method1109(); if(Client.widgetRoot != -1) { DynamicObject.method2026(Client.widgetRoot, 1); } } }
UniquePassive/runelite
runescape-client/src/main/java/class57.java
Java
bsd-2-clause
21,067
/******************************************************************************* * Copyright (c) 2012, Daniel Murphy and Deanna Surma * 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. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package org.protobee.guice.multiscopes; import java.util.Map; import com.google.common.collect.MapMaker; import com.google.inject.Key; public final class MultiscopeUtils { private MultiscopeUtils() {} /** * Creates a default scope map with concurrency level of 8 and initial capacity of 100. */ public static Map<Key<?>, Object> createDefaultScopeMap() { return new MapMaker().concurrencyLevel(8).initialCapacity(100).makeMap(); } }
dmurph/guice-multiscopes
src/main/java/org/protobee/guice/multiscopes/MultiscopeUtils.java
Java
bsd-2-clause
1,980
/** * */ package org.jhove2.module.format.utf8; import static org.junit.Assert.assertTrue; import java.util.Set; import javax.annotation.Resource; import org.jhove2.module.format.utf8.unicode.CodeBlock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author mstrong * */ @RunWith(SpringJUnit4ClassRunner.class) public class UTF8CodeBlockTest extends UTF8ModuleTestBase { private String codeBlockTestFile; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { super.setUp(); parse(codeBlockTestFile); } /** * Test method for UTF8 Parser */ @Test public void testCodeBlock() { int st = 0xFE70; int en = 0xFEFF; String name = "Arabic Presentation Forms-B"; CodeBlock block = new CodeBlock(st, en, name); Set<CodeBlock> codeBlocks = testUtf8Module.getCodeBlocks(); assertTrue("CodeBlock does not contain " + block.toString(), codeBlocks.contains(block)); } @After public void tearDown() { display(); } public String getCodeBlockTestFile() { return codeBlockTestFile; } @Resource public void setCodeBlockTestFile(String codeBlockTestFile) { this.codeBlockTestFile = codeBlockTestFile; } }
opf-labs/jhove2
src/test/java/org/jhove2/module/format/utf8/UTF8CodeBlockTest.java
Java
bsd-2-clause
1,521
/** * Pubdesc_num_type0.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene; /** * Pubdesc_num_type0 bean class */ @SuppressWarnings({"unchecked","unused"}) public class Pubdesc_num_type0 implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = Pubdesc_num_type0 Namespace URI = http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene Namespace Prefix = ns1 */ /** * field for Numbering */ protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.Numbering_type0 localNumbering ; /** * Auto generated getter method * @return gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.Numbering_type0 */ public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.Numbering_type0 getNumbering(){ return localNumbering; } /** * Auto generated setter method * @param param Numbering */ public void setNumbering(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.Numbering_type0 param){ this.localNumbering=param; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName); return factory.createOMElement(dataSource,parentQName); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":Pubdesc_num_type0", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "Pubdesc_num_type0", xmlWriter); } } if (localNumbering==null){ throw new org.apache.axis2.databinding.ADBException("Numbering cannot be null!!"); } localNumbering.serialize(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Numbering"), xmlWriter); xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "Numbering")); if (localNumbering==null){ throw new org.apache.axis2.databinding.ADBException("Numbering cannot be null!!"); } elementList.add(localNumbering); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static Pubdesc_num_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ Pubdesc_num_type0 object = new Pubdesc_num_type0(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"Pubdesc_num_type0".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (Pubdesc_num_type0)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Numbering").equals(reader.getName())){ object.setNumbering(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.Numbering_type0.Factory.parse(reader)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
milot-mirdita/GeMuDB
Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/Pubdesc_num_type0.java
Java
bsd-2-clause
18,968
/* * @lc app=leetcode id=106 lang=java * * [106] Construct Binary Tree from Inorder and Postorder Traversal * * https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ * * algorithms * Medium (48.79%) * Total Accepted: 268.8K * Total Submissions: 550.8K * Testcase Example: '[9,3,15,20,7]\n[9,15,7,20,3]' * * Given inorder and postorder traversal of a tree, construct the binary tree. * * Note: * You may assume that duplicates do not exist in the tree. * * For example, given * * * inorder = [9,3,15,20,7] * postorder = [9,15,7,20,3] * * Return the following binary tree: * * * ⁠ 3 * ⁠ / \ * ⁠ 9 20 * ⁠ / \ * ⁠ 15 7 * * */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length-1); } TreeNode buildTree(int[] inorder, int il, int ir, int[] postorder, int pl, int pr) { if (il > ir || pl > pr) return null; TreeNode node = new TreeNode(postorder[pr]); int m = il; while (inorder[m] != node.val) { m++; } node.left = buildTree(inorder, il, m-1, postorder, pl, pl + (m-1-il)); node.right = buildTree(inorder, m+1, ir, postorder, pl + (m-1-il) + 1,pr-1); return node; } }
lang010/acit
leetcode/106.construct-binary-tree-from-inorder-and-postorder-traversal.310091534.ac.java
Java
bsd-3-clause
1,586
/************************************************************************************** * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, * * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************/ package fi.uta.fsd.metka.ddi.reader; import codebook25.CodeBookType; import codebook25.OtherMatType; import fi.uta.fsd.metka.enums.Language; import fi.uta.fsd.metka.model.access.enums.StatusCode; import fi.uta.fsd.metka.model.configuration.Configuration; import fi.uta.fsd.metka.model.data.RevisionData; import fi.uta.fsd.metka.model.data.change.Change; import fi.uta.fsd.metka.model.data.container.ContainerDataField; import fi.uta.fsd.metka.model.data.container.DataRow; import fi.uta.fsd.metka.model.general.DateTimeUserPair; import fi.uta.fsd.metka.names.Fields; import fi.uta.fsd.metka.storage.repository.enums.ReturnResult; import org.apache.commons.lang3.tuple.Pair; import org.springframework.util.StringUtils; import java.util.Map; class DDIReadOtherMaterialDescription extends DDIReadSectionBase { DDIReadOtherMaterialDescription(RevisionData revision, Language language, CodeBookType codeBook, DateTimeUserPair info, Configuration configuration) { super(revision, language, codeBook, info, configuration); } @Override ReturnResult read() { /* * We know that language has to be DEFAULT and that description tab should be clear so we can just insert the new data in */ if(!hasContent(codeBook.getOtherMatArray())) { return ReturnResult.OPERATION_SUCCESSFUL; } Pair<ReturnResult, Pair<ContainerDataField, Map<String, Change>>> containerResult = getContainer(Fields.OTHERMATERIALS); if(containerResult.getLeft() != ReturnResult.OPERATION_SUCCESSFUL) { return containerResult.getLeft(); } Pair<ContainerDataField, Map<String, Change>> container = containerResult.getRight(); for(OtherMatType other : codeBook.getOtherMatArray()) { Pair<StatusCode, DataRow> row = container.getLeft().insertNewDataRow(language, container.getRight()); if(row.getLeft() != StatusCode.ROW_INSERT) { continue; } if(StringUtils.hasText(other.getURI())) { valueSet(row.getRight(), Fields.OTHERMATERIALURI, other.getURI()); } if(hasContent(other.getTxtArray()) && StringUtils.hasText(getText(other.getTxtArray(0)))) { valueSet(row.getRight(), Fields.OTHERMATERIALTEXT, getText(other.getTxtArray(0))); } if(hasContent(other.getLablArray()) && StringUtils.hasText(getText(other.getLablArray(0)))) { valueSet(row.getRight(), Fields.OTHERMATERIALLABEL, getText(other.getLablArray(0))); } if(hasContent(other.getLablArray()) && StringUtils.hasText(getText(other.getLablArray(0)))) { valueSet(row.getRight(), Fields.OTHERMATERIALLEVEL, other.getLevel()); } } return ReturnResult.OPERATION_SUCCESSFUL; } }
Tietoarkisto/metka
metka/src/main/java/fi/uta/fsd/metka/ddi/reader/DDIReadOtherMaterialDescription.java
Java
bsd-3-clause
5,225
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/stats-analysis/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.dto.view; import gov.nih.nci.caintegrator.dto.de.DomainElementClass; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * @author BhattarR */ /** * * */ abstract public class View implements Viewable,Serializable{ /** * IMPORTANT! This class requires a clone method! This requires that any new * data field that is added to this class also be cloneable and be added to * clone calls in the clone method.If you do not do this, you will not * seperate the references of at least one data field when we generate a * copy of this object.This means that if the data field ever changes in one * copy or the other it will affect both instances... this will be hell to * track down if you aren't ultra familiar with the code base, so add those * methods now! (Not necesary for primitives.) */ Collection selectedDomainElements; ViewType viewType; public Collection getSelectedElements() { return selectedDomainElements; } public void setSelectedElements(Collection selectedElems) { selectedDomainElements = selectedElems; } /** * Compares the class names to determine if the passed view is * of the same type as this view * @param view * @return */ public boolean equals(View view) { if(view!=null) { if((view.getClass()).getName().equals(this.getClass().getName())) { return true; } } return false; } public Object clone() { View myClone = null; try { myClone = (View)super.clone(); myClone.selectedDomainElements = new ArrayList(); if(selectedDomainElements != null){ for(Iterator i = selectedDomainElements.iterator();i.hasNext(); ) { myClone.selectedDomainElements.add(i.next()); } } if(viewType != null){ myClone.viewType = (ViewType)viewType.clone(); } } catch (CloneNotSupportedException e) { //This will never happen } return myClone; } }
NCIP/stats-analysis
src/gov/nih/nci/caintegrator/dto/view/View.java
Java
bsd-3-clause
2,248
package uk.ac.lkl.server; import uk.ac.lkl.client.composer.MicroBehaviourEnhancement; import uk.ac.lkl.server.persistent.BehaviourCode; import uk.ac.lkl.server.persistent.DataStore; import uk.ac.lkl.server.persistent.MacroBehaviourData; import uk.ac.lkl.server.persistent.MicroBehaviourData; import uk.ac.lkl.server.persistent.MicroBehaviourURLCopy; import uk.ac.lkl.server.persistent.NetLogoNameSerialNumber; import uk.ac.lkl.shared.CommonUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; public class MicroBehaviour { protected String behaviourCode; protected String originalBehaviourCode; protected String transformedBehaviourCode; protected String behaviourURL = null; // protected String behaviourName = null; protected String behaviourDescription; // above can be used within NetLogo while the following preserves rich text formatting protected String behaviourDescriptionAndNameHTML; protected ArrayList<MicroBehaviour> referencedMicroBehaviours = new ArrayList<MicroBehaviour>(); protected ResourcePageServiceImpl resourcePageServiceImpl = null; protected NetLogoModel netLogoModel; // use a hash map rather than an array since the values can come in any order // and don't know here the full size protected HashMap<Integer, String> textAreaValues = new HashMap<Integer, String>(); protected ArrayList<String> textAreaElements = null; protected List<MicroBehaviourEnhancement> enhancements = new ArrayList<MicroBehaviourEnhancement>(); protected ArrayList<MacroBehaviour> macroBehaviours; // to avoid infinite recursions when // a micro-behaviour refers to itself private boolean gettingBehaviourCode = false; // micro-behaviour may be shared so client state shouldn't be // protected ClientState clientState; private MicroBehaviourData microBehaviourData; private boolean enhancementsInstalled = false; private String netLogoName = null; private static int unnamedCounter = 1; protected static String[] operationsExpectingABracketedExpression = { "do-now", "do-every", "do-every-dynamic", "do-after", "do-with-probability", "do-with-probabilities", "do-repeatedly", "do-for-n", "do-at-time", "do-at-setup", "do-after-setup", "do-if", "do-if-else", "ask-every-patch", "when", "whenever", "anyone-is", "anyone-who-is", "all-who-are", "create-objects", "create-agents", "create-agents-from-data"}; protected static String[] operationsExpectingASecondBracketedExpression = // above is a superset of this list { "when", "whenever", "anyone-who-is", "all-who-are", "do-if-else", "do-every-dynamic"}; protected static String[] operationsExpectingBracketedExpressionAsFirstArgument = // used to produce warnings if first argument is not a square bracket { "do-now", "do-at-setup", "do-after-setup", "do-with-probabilities", "when", "whenever", "anyone-who-is", "all-who-are", "do-every-dynamic" }; protected static String[] topLevelNetLogoPrimitives = { "to", "to-report", "extensions", "globals"}; //public static Pattern operationExpectingSquareBracketedExpression = Pattern.compile( // "\bdo-now\b|\bdo-every\b|\bdo-after\b|\bdo-with-probability\b|\bdo-repeatedly\b|\bdo-for-n\b|\bdo-at-time\b|\bdo-after-setup\b|\bdo-if\b|\bask-every-patch\b"); protected static int commandNumber = 1; protected static int totalMicroBehaviourCount = 0; public static final Pattern askSelfPattern = Pattern.compile("ask(\\s)+self(\\s)+", Pattern.CASE_INSENSITIVE); public static final Pattern askPatchesPattern = Pattern.compile("ask(\\s)+patches(\\s)*\\[", Pattern.CASE_INSENSITIVE); private static final boolean NETLOGO_5 = true; // private static ArrayList<String> debugURLs = new ArrayList<String>(); public MicroBehaviour(String behaviourDescriptionHTML, String behaviourCode, String url, ResourcePageServiceImpl resourcePageServiceImpl, NetLogoModel netLogoModel, ClientState clientState, ArrayList<String> textAreaElements, List<MicroBehaviourEnhancement> enhancements, ArrayList<MacroBehaviour> macroBehaviours, boolean addToDataBase) { if (behaviourCode == null) { Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).severe( "Micro behaviour created with null code. Constructor 1"); } this.textAreaElements = textAreaElements; if (enhancements != null) { this.enhancements = enhancements; // } else { // System.err.println("Server micro-behaviour has a null value for enhancement rather than an empty list."); } this.macroBehaviours = macroBehaviours; this.netLogoModel = netLogoModel; setBehaviourURL(url); // this.clientState = clientState; String updatedNameHTML = resourcePageServiceImpl.fetchUpdatedNameHTML(url, clientState); setBehaviourCode(behaviourCode); // above used to call CommonUtils.removeHTMLMarkup(behaviourCode); // but the HTML mark-up is now removed by getTextContent() // and the above misbehaved if < or > was in the code (e.g. less than) if (updatedNameHTML == null) { setBehaviourDescriptionAndNameHTML(CommonUtils.removePTags(behaviourDescriptionHTML)); } else { setBehaviourDescriptionAndNameHTML(CommonUtils.decode(updatedNameHTML)); } HashMap<Integer, String> fetchedTextAreaValues = resourcePageServiceImpl.fetchTextAreaValues(url, clientState); if (fetchedTextAreaValues != null) { textAreaValues = fetchedTextAreaValues; } if (textAreaElements != null) { int size = textAreaElements.size(); int index = 0; for (int i = 1; i < size; i += 2) { // every other is a value if (textAreaValues.get(index) == null) { // has no value so give it the default one // is wrapped in HTML so remove that textAreaValues.put(index, CommonUtils.removeHTMLMarkup(textAreaElements.get(i))); index++; } } } setBehaviourDescription(); this.resourcePageServiceImpl = resourcePageServiceImpl; if (url != null) { if (addToDataBase) { createMicroBehaviourDataIfNeeded(); } resourcePageServiceImpl.rememberMicroBehaviour(this, url); } // else should be a required micro-behaviour which will set this } public MicroBehaviour( String behaviourDescriptionHTML, String behaviourCode, String behaviourURL, ResourcePageServiceImpl resourcePageServiceImpl, NetLogoModel netLogoModel, ArrayList<String> textAreaElements, List<MicroBehaviourEnhancement> enhancements, ArrayList<MacroBehaviour> macroBehaviours, boolean addToDataBase) { this(behaviourDescriptionHTML, behaviourCode, behaviourURL, resourcePageServiceImpl, netLogoModel, netLogoModel.getClientState(), textAreaElements, enhancements, macroBehaviours, addToDataBase); } public MicroBehaviour( MicroBehaviourData microBehaviourData, String behaviourDescriptionAndNameHTML, String behaviourCode, String url, ArrayList<String> textAreaElements, HashMap<Integer, String> textAreaValues, List<MicroBehaviourEnhancement> enhancements, ArrayList<MacroBehaviour> macroBehaviours, ResourcePageServiceImpl resourcePageServiceImpl) { if (behaviourCode == null) { Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).severe( "Micro behaviour created with null code. Constructor 2"); } // constructor used to reconstruct a micro-behaviour from the database this.microBehaviourData = microBehaviourData; if (behaviourDescriptionAndNameHTML == null) { ServerUtils.logError("No name or description given to micro behaviour: " + url); } setBehaviourDescriptionAndNameHTML(behaviourDescriptionAndNameHTML); this.behaviourCode = behaviourCode; this.originalBehaviourCode = behaviourCode; this.resourcePageServiceImpl = resourcePageServiceImpl; if (resourcePageServiceImpl != null) { this.netLogoModel = resourcePageServiceImpl.getNetLogoModel(); } // following only used while transforming the code this.textAreaElements = textAreaElements; this.textAreaValues = textAreaValues == null ? new HashMap<Integer, String>() : textAreaValues; if (enhancements != null) { this.enhancements = enhancements; // } else { // System.err.println("Server micro-behaviour has a null value for enhancement rather than an empty list."); } this.macroBehaviours = macroBehaviours; setBehaviourDescription(); setBehaviourURL(url); } public MicroBehaviour() { // only used by dummyMicroBehaviour and MacroBehaviourAsMicroBehaviour } protected void updateMicroBehaviourData() { // similar to createDeltaPage except discovered while running a model // resourcePageServiceImpl.removeMicroBehaviourCache(behaviourURL); DataStore.begin().delete(MicroBehaviourURLCopy.class, behaviourURL); // String guid = ServerUtils.generateGUIDString(); String guid = ServerUtils.generateUniqueIdWithProcedureName(behaviourURL, getName()); String oldURL = behaviourURL; behaviourURL = CommonUtils.addAttributeOrHashAttributeToURL(behaviourURL, "changes", guid); if (netLogoModel != null) { netLogoModel.microBehaviourRenamed(oldURL, behaviourURL); } createMicroBehaviourData(); resourcePageServiceImpl.addListsOfMicroBehavioursToCopy(guid, listOfListOfMicroBehaviours(macroBehaviours)); resourcePageServiceImpl.rememberMicroBehaviour(this, behaviourURL); } public static ArrayList<ArrayList<String>> listOfListOfMicroBehaviours(ArrayList<MacroBehaviour> macroBehaviours) { if (macroBehaviours == null) { return null; } ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(macroBehaviours.size()); for (MacroBehaviour macroBehaviour : macroBehaviours) { List<MicroBehaviour> microBehaviours = macroBehaviour.getMicroBehaviours(); if (!microBehaviours.isEmpty()) { String name = macroBehaviour.getNameHTML(); ArrayList<String> nameAndUrls = new ArrayList<String>(microBehaviours.size()+1); result.add(nameAndUrls); nameAndUrls.add(name); for (MicroBehaviour microBehaviour : microBehaviours) { String url = microBehaviour.getBehaviourURL(); // String activeSign = microBehaviour.isActive() ? "" : "-"; nameAndUrls.add(url); } } } return result; } public void createMicroBehaviourDataIfNeeded() { if (microBehaviourData == null && CommonUtils.hasChangesGuid(behaviourURL)) { createMicroBehaviourData(); } } public void updateMicroBehaviourDataIfNeeded(HashMap<Integer, String> textAreaKeysAndValues) { if (microBehaviourData != null) { // if (!behaviourCode.equals(microBehaviourData.getBehaviourCode())) { //// microBehaviourData.setBehaviourCode(behaviourCode); //// ServerUtils.persist(microBehaviourData); // setBehaviourCode(behaviourCode); // String url = getBehaviourURL(); // BehaviourCode.update(url, behaviourCode); // resourcePageServiceImpl.behaviourCodeChanged(url, behaviourCode); // } if (textAreaKeysAndValues != null && !textAreaKeysAndValues.equals(microBehaviourData.getTextAreaValues())) { microBehaviourData.setTextAreaValues(textAreaKeysAndValues); } } } public void createMicroBehaviourData() { ArrayList<MacroBehaviourData> macroBehaviourData = new ArrayList<MacroBehaviourData>(); if (macroBehaviours != null) { for (MacroBehaviour macroBehaviour : macroBehaviours) { macroBehaviourData.add(macroBehaviour.getMacroBehaviourData()); } } String url = CommonUtils.firstURL(behaviourURL); BehaviourCode.update(url, this.originalBehaviourCode, this.textAreaElements); microBehaviourData = MicroBehaviourData.persistMicroBehaviourData( url, this.behaviourDescriptionAndNameHTML, this.textAreaValues, this.enhancements, macroBehaviourData); } public MicroBehaviour copy(ArrayList<MacroBehaviour> macroBehavioursCopiesSoFar) { String guid = ServerUtils.generateUniqueIdWithProcedureName(behaviourURL, CommonUtils.getNameHTML(behaviourDescriptionAndNameHTML)); String newURL = ServerUtils.createURLCopy(behaviourURL, guid); return new MicroBehaviour( null, behaviourDescriptionAndNameHTML, originalBehaviourCode, newURL, textAreaElements, textAreaValues, enhancements, copyMacroBehaviours(macroBehavioursCopiesSoFar), resourcePageServiceImpl); } public ArrayList<MacroBehaviour> copyMacroBehaviours(ArrayList<MacroBehaviour> macroBehavioursCopiesSoFar) { if (macroBehaviours == null) { return null; } else { ArrayList<MacroBehaviour> macroBehavioursCopy = new ArrayList<MacroBehaviour>(); for (MacroBehaviour macroBehaviour : macroBehaviours) { if (macroBehavioursCopiesSoFar != null && macroBehaviour.isCopyOfElementOf(macroBehavioursCopiesSoFar)) { macroBehavioursCopy.add(macroBehaviour); } else { if (macroBehavioursCopiesSoFar == null) { macroBehavioursCopiesSoFar = new ArrayList<MacroBehaviour>(); } MacroBehaviour copy = macroBehaviour.copy(macroBehavioursCopiesSoFar); macroBehavioursCopy.add(copy); } } return macroBehavioursCopy; } } public MicroBehaviour copy( String newURL, HashMap<Integer, String> newTextAreaValues, List<MicroBehaviourEnhancement> newEnhancements) { return new MicroBehaviour( null, behaviourDescriptionAndNameHTML, originalBehaviourCode, newURL, textAreaElements, CommonUtils.transferTextAreaValues(newTextAreaValues, textAreaValues), newEnhancements, copyMacroBehaviours(null), resourcePageServiceImpl); } protected void setBehaviourDescription() { String behaviourDescriptionWithoutHTML = CommonUtils.removeHTMLMarkup(behaviourDescriptionAndNameHTML); // behaviourDescription = CommonUtils.onlyValidNetLogoCharacters(behaviourDescriptionWithoutHTML.trim(), "-"); behaviourDescription = behaviourDescriptionWithoutHTML.trim(); if (behaviourDescription.isEmpty()) { behaviourDescription = "UnNamed-" + unnamedCounter ++; } } protected boolean isRawNetLogoCode() { if (gettingBehaviourCode) { // if recursively referred to can't be raw NetLogo code return false; } try { gettingBehaviourCode = true; String code = getTransformedBehaviourCode(); gettingBehaviourCode = false; if (code == null) { if (this == resourcePageServiceImpl.getDummyMicroBehaviour()) { netLogoModel.warn("Dummy micro behaviour asked for its code."); return true; } else { netLogoModel.warn("isRawNetLogoCode called on null code. Name = " + CommonUtils.getName(behaviourDescription) + "; URL = " + behaviourURL + ". This behaviour is being ignored during compilation. Open it and make any change to work around this problem."); } // seen this is logs -- better to recover than throw an exception later code = ""; if (behaviourURL == null) { behaviourURL = ""; } return true; // kinda } if (code.length() < 10) { return false; } ArrayList<String> parts = CommonUtils.splitIntoNonEmptyLinesWithoutNetLogoComments(code); if (parts.isEmpty()) { return false; } String firstLineParts[] = CommonUtils.splitByFirstWhiteSpace(parts.get(0)); if (firstLineParts.length == 0) { // can never happen. right? return false; } String operation = firstLineParts[0]; for (String topLevelNetLogoPrimitive : topLevelNetLogoPrimitives) { if (operation.equalsIgnoreCase(topLevelNetLogoPrimitive)) { return true; } } return false; } catch (Exception e) { netLogoModel.logException(e, "In getBehaviourCode "); gettingBehaviourCode = false; return false; } } protected String generateNetLogo(NetLogoModel netLogoModel, boolean prototypeActive) throws NetLogoException { this.netLogoModel = netLogoModel; if (behaviourCode == null) { netLogoModel.warn("Micro behaviour has null code."); if (this == resourcePageServiceImpl.getDummyMicroBehaviour()) { System.err.println("generateNetLogo called on dummy micro behaviour"); } return ""; } if (isRawNetLogoCode()) { String netLogoCode = getBehaviourCode(); netLogoModel.findAllKindsOfVariables(netLogoCode); return netLogoCode + "\n"; // no need to do any of the following } updateVariables(netLogoModel); updateRequiredBehaviours(netLogoModel); String code = getTransformedBehaviourCode().trim(); String body = transformCode(code, getBehaviourName(false), prototypeActive, netLogoModel, netLogoModel.getClientState()); body = CommonUtils.removeAlreadyProcessedMarkers(body); if (body.contains("output-") || body.contains("log-attributes") || body.contains("log-patch-attributes")) { netLogoModel.setOutputAreaNeeded(); } if (body.isEmpty() || CommonUtils.splitIntoNonEmptyLinesWithoutNetLogoComments(body).isEmpty()) { netLogoModel.addUnneededCommands(getBehaviourName(false)); return ""; } // just the first occurrence (if there is one) if (body.contains("just-created-agents")) { if (body.startsWith("set just-created-agents nobody")) { // change 'set' to 'let' body = "l" + body.substring(1); } else { body = "let just-created-agents nobody\n" + body; } } // following is one for each occurrence of a "procedure body" StringBuilder behaviourCommand = new StringBuilder(); behaviourCommand.append("to "); behaviourCommand.append(getBehaviourName(false)); behaviourCommand.append('\n'); behaviourCommand.append(body); if (body.charAt(body.length()-1) != '\n') { behaviourCommand.append('\n'); } behaviourCommand.append("end"); netLogoModel.getGeneratedCommands().add(behaviourCommand.toString()); return ""; } protected String transformCode( String originalCode, String behaviourName, boolean prototypeActive, NetLogoModel netLogoModel, ClientState clientState) { String phase1 = transformCodePhase1(originalCode, null, behaviourName, prototypeActive, netLogoModel, clientState); if (phase1.isEmpty()) { return phase1; } // add-behaviours and add-behaviours-to were optimised away on 2 June 2010 String phase2 = replaceObsoleteAddBehaviours(phase1); String proceduresRequiringQuotedMicroBehaviours[] = {"remove-behaviours", "remove-behaviours-from", "add-copies", "add-copy-of-another", "add-copies-of-another", "add-link-behaviours-after"}; for (String procedure : proceduresRequiringQuotedMicroBehaviours) { // need to ensure there is white space after each procedure // otherwise "remove-behaviours" will be found in "remove-behaviours-from" String[] pieces = phase2.split(procedure + "(\\s)+"); if (pieces.length > 1) { StringBuffer phase3 = new StringBuffer(pieces[0]); for (int i = 1; i < pieces.length; i++) { String piece = pieces[i]; if (!piece.trim().isEmpty()) { phase3.append(procedure); phase3.append(' '); if (procedure.equals("remove-behaviours-from") || procedure.equals("remove-behaviours")) { // this is special since really using name to remove matching behaviours phase3.append(CommonUtils.quoteContentsOfNextBracket(piece)); } else { phase3.append(CommonUtils.taskifyContentsOfNextBracket(piece)); } } } phase2 = phase3.toString(); } } return workaroundAskPatchesLimitation(optimiseAwayAskSelf(phase2)); } public static String replaceObsoleteAddBehaviours(String code) { return code.replaceAll("add-behaviours-to(\\s)+", "ask ") .replaceAll("add-behaviours(\\s)+", "ask self ") .replaceAll("add-behaviour(\\s)+", ""); } protected String optimiseAwayAskSelf(String code) { // optimise ask self [...] to ... String[] split = askSelfPattern.split(code, 2); if (split.length == 2) { String[] splitByOpenBracket = split[1].split("\\[", 2); StringBuffer rest = new StringBuffer(); if (splitByOpenBracket.length == 2) { int closingBracket = CommonUtils.closeBracket(splitByOpenBracket[1], 0); if (closingBracket > 0) { // don't include the final ] since optimising away the entire [] rest.append(splitByOpenBracket[1].substring(0, closingBracket-1)); rest.append("\n"); rest.append(splitByOpenBracket[1].substring(closingBracket+1)); } else if (closingBracket == 0) { // if ask self [] following will be empty code rest.append("\n"); rest.append(splitByOpenBracket[1].substring(closingBracket+1)); } else { return code; } } else { return code; } return optimiseAwayAskSelf(split[0] + rest.toString()); } return code; } protected String workaroundAskPatchesLimitation(String code) { // NetLogo complains about ask patches [...] but not ask patches with [true] [...] String[] parts = askPatchesPattern.split(code); if (parts.length == 1) { return code; } StringBuilder result = new StringBuilder(parts[0]); for (int i = 1; i < parts.length; i++) { result.append("ask patches with [true] [ "); result.append(parts[i]); } return result.toString(); } protected String transformCodePhase1( String originalCode, String comment, String behaviourName, boolean prototypeActive, NetLogoModel netLogoModel, ClientState clientState) { // TODO: rewrite this to use the tokenizer String alreadyProcessed = ""; String code = originalCode; while (true) { // remove blank lines // while (!code.isEmpty() && (code.charAt(0) == '\n' || code.charAt(0) == ' ')) { // code = code.substring(1); // } if (code.isEmpty()) { return alreadyProcessed + code; } if (code.startsWith("\"")) { int quotedStringEnd = CommonUtils.endQuoteIndex(code); if (quotedStringEnd < 0) { netLogoModel.warn(CommonUtils.emphasiseError("The code of " + behaviourName + " has mismatching quotes. Please fix and try again.")); return ""; } return alreadyProcessed + code.substring(0, quotedStringEnd+1) + transformCode(code.substring(quotedStringEnd+1), behaviourName, prototypeActive, netLogoModel, netLogoModel.getClientState()); } if (code.startsWith("constant-list")) { // this is a workaround for dealing with large lists that otherwise cause server to // run out of memory or overflow the stack int openBracket = code.indexOf('['); int dataEnd = CommonUtils.closeBracket(code, openBracket+1); if (dataEnd >= 0) { return alreadyProcessed + code.substring(openBracket, dataEnd+1) + transformCode(code.substring(dataEnd+1), behaviourName, prototypeActive, netLogoModel, netLogoModel.getClientState()); } } int operationIndex = indexOfFirstOperationExpectingABracketedExpression(code); if (operationIndex >= 0) { // spit out the code before the operator and transform the rest String remainingCode = code.substring(operationIndex); String operation = CommonUtils.firstWord(remainingCode); String beforeActionAfter[]; if (remainingCode.startsWith("create-agents-from-data")) { beforeActionAfter = new String[3]; beforeActionAfter[0] = remainingCode; // special handler for create-agents-from-data will take care of this beforeActionAfter[1] = ""; beforeActionAfter[2] = ""; } else { beforeActionAfter = splitOnSquareBrackets(remainingCode, operation, clientState); } if (beforeActionAfter != null) { StringBuilder behaviourBody = new StringBuilder(code.substring(0, operationIndex)); transformBody(beforeActionAfter, operation, behaviourName, prototypeActive, netLogoModel, code, behaviourBody, clientState); return alreadyProcessed + behaviourBody.toString(); } } String[] operationAndBody = code.split("\n", 2); // new line String operation = operationAndBody[0]; operationAndBody = code.split("(\\s)+", 2); // any white space if (code.startsWith("\n")) { alreadyProcessed += "\n"; } boolean newLineAfterOperation = operation.equals(operationAndBody[0]); if (operationAndBody.length < 2) { // too small to care about if it doesn't have a second word return alreadyProcessed + code; } while (operationAndBody[0].isEmpty()) { // white space operationAndBody = CommonUtils.splitByFirstWhiteSpace(operationAndBody[1]); if (operationAndBody.length < 2) { // too small to care about if it doesn't have a second word return alreadyProcessed + code; } } operation = operationAndBody[0]; if (operation.charAt(0) == '[') { String beforeActionAfter[] = splitOnSquareBrackets(code, null, clientState); if (beforeActionAfter != null && !beforeActionAfter[1].trim().isEmpty()) { // beforeActionAfter[0] should be the empty string or white space return alreadyProcessed + "[ " + transformCodePhase1(beforeActionAfter[1], comment, behaviourName, prototypeActive, netLogoModel, clientState) + " ]" + transformCodePhase1(beforeActionAfter[2], comment, behaviourName, prototypeActive, netLogoModel, clientState); } } if (operation.charAt(0) == ';') { // is a comment int commentEnd = code.indexOf('\n'); if (commentEnd < 0) { return alreadyProcessed + code + "\n"; } String localComment = code.substring(0, commentEnd+1); String remainingCode = code.substring(commentEnd+1); return alreadyProcessed + localComment + transformCodePhase1(remainingCode, localComment, behaviourName, prototypeActive, netLogoModel, netLogoModel.getClientState()); } String prefix = ""; if (operation.startsWith("[")) { prefix = "["; operation = operation.substring(1); } if (operation.startsWith("(")) { prefix = "("; operation = operation.substring(1); } String body = operationAndBody[1].trim(); if (body.isEmpty()) { return alreadyProcessed + code; } if (body.startsWith("]") && prefix.equals("[")) { // empty list alreadyProcessed += "[]"; prefix = ""; body = body.substring(1); } int indexOfOperation = code.indexOf(operation); boolean operationOnNewLine = code.lastIndexOf('\n', indexOfOperation) >= 0; int indexOfBody = code.indexOf(body); boolean bodyOnNewLine = code.lastIndexOf('\n', indexOfBody) >= 0; alreadyProcessed += prefix; // if (operation.isEmpty()) { // alreadyProcessed += body; // } if (!prototypeActive) { continue; } if (operation.equalsIgnoreCase("define-parameter")) { // nothing follows a define-parameter call return alreadyProcessed + defineParameter(body, comment, netLogoModel, clientState); } else if (operation.equalsIgnoreCase("create-plot") || operation.equalsIgnoreCase("create-histogram")) { // ArrayList<String> lines = CommonUtils.splitIntoNonEmptyLinesWithoutNetLogoComments(body); // int argumentCount = lines.size(); boolean histogram = operation.equalsIgnoreCase("create-histogram"); // String quoted[] = lines.get(0).split("\""); // boolean includesCorners = (quoted.length > 3); // create the NetLogo plot widget ArrayList<String> plotData = netLogoModel.createPlot(body, histogram); if (plotData == null) { // ignore broken call to plot return alreadyProcessed; } return alreadyProcessed + generateNetLogoPlottingCode(plotData, operation); } else if (operation.equalsIgnoreCase("set-world-size")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 4 || bodyParts.length == 6) { try { netLogoModel.setMinPxcor(Integer.valueOf(bodyParts[0])); netLogoModel.setMaxPxcor(Integer.valueOf(bodyParts[1])); netLogoModel.setMinPycor(Integer.valueOf(bodyParts[2])); netLogoModel.setMaxPycor(Integer.valueOf(bodyParts[3])); if (bodyParts.length == 6) { netLogoModel.setMinPzcor(Integer.valueOf(bodyParts[4])); netLogoModel.setMaxPzcor(Integer.valueOf(bodyParts[5])); netLogoModel.setDimensions(3); } } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-world-location")) { // can only be set via the API not from within NetLogo if (prototypeActive) { ArrayList<String> bodyParts = CommonUtils.removeEmptyLines(body.split("(\\s)+")); // split by white space // TODO: rewrite this and the like to use CommonUtils.splitIntoNonEmptyLinesWithoutNetLogoComments(body); // but need to be backwards compatible // TODO: get rid of urx and ury if (bodyParts.size() == 4) { try { Integer llx = Integer.valueOf(bodyParts.get(0)); netLogoModel.setWorldLLX(llx); Integer lly = Integer.valueOf(bodyParts.get(1)); netLogoModel.setWorldLLY(lly); Integer urx = Integer.valueOf(bodyParts.get(2)); netLogoModel.setWorldURX(urx); Integer ury = Integer.valueOf(bodyParts.get(3)); netLogoModel.setWorldURY(ury); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-patch-size")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setPatchSize(Double.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-label-font-size")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setLabelFontSize(Integer.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-world-geometry")) { if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setWorldGeometry(Integer.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); // ServerUtils.logException(e, getServletContext().getRealPath("/")); e.printStackTrace(); } } } // NetLogo needs to know this too if (operationOnNewLine) { operation = "\n" + operation; } if (bodyOnNewLine) { alreadyProcessed += operation + "\n" + body; } else { alreadyProcessed += operation + " " + body; } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-tick-based-view-update-policy")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setTickBasedUpdates(Boolean.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-frame-rate")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setFrameRate(Double.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-tick-counter-label")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setTickLabel(bodyParts[0]); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("set-tick-counter-visible")) { // can only be set via the API not from within NetLogo if (prototypeActive) { String bodyParts[] = body.split("(\\s)+"); // split by white space if (bodyParts.length == 1) { try { netLogoModel.setShowTickCounter(Boolean.valueOf(bodyParts[0])); } catch (Exception e) { netLogoModel.warn("Error " + e.toString() + " interpreting: " + operation + " " + body); e.printStackTrace(); } } } return alreadyProcessed; } else if (operation.equalsIgnoreCase("add-declaration")) { netLogoModel.addDeclaration(body); return alreadyProcessed; } else { String extensionAndName[] = operation.split(":", 2); if (extensionAndName.length == 2) { netLogoModel.extensionUsed(extensionAndName[0]); } if (!body.equals("")) { if (operation.equalsIgnoreCase("create-slider")) { if (prototypeActive) netLogoModel.createSlider(body); // create the NetLogo slider widget return alreadyProcessed; } else if (operation.equalsIgnoreCase("create-button")) { // create the NetLogo button widget // old style if (prototypeActive) { netLogoModel.createButton(body, true, false); } return alreadyProcessed; } else if (operation.equalsIgnoreCase("add-button")) { if (prototypeActive) netLogoModel.createButton(body, false, false); // create the NetLogo button widget -- using behaviours return alreadyProcessed; } else if (operation.equalsIgnoreCase("add-netlogo-button")) { if (prototypeActive) netLogoModel.createButton(body, false, true); // create the NetLogo button widget - using NetLogo code return alreadyProcessed; } else if (operation.equalsIgnoreCase("create-monitor")) { if (prototypeActive) netLogoModel.createMonitor(body); // create the NetLogo monitor widget return alreadyProcessed; } else if (operation.equalsIgnoreCase("create-chooser")) { if (prototypeActive) netLogoModel.createChooser(body); // create the NetLogo chooser widget return alreadyProcessed; } else if (operation.equalsIgnoreCase("create-switch")) { if (prototypeActive) netLogoModel.createSwitch(body); // create the NetLogo switch widget return alreadyProcessed; } else if (operation.equalsIgnoreCase("create-text")) { if (prototypeActive) netLogoModel.createText(body, false); // create the NetLogo text widget continue; } else if (operation.equalsIgnoreCase("create-color-text")) { if (prototypeActive) netLogoModel.createText(body, true); // create the NetLogo text widget return alreadyProcessed; } } if (operation.equalsIgnoreCase("create-output-area")) { if (prototypeActive) netLogoModel.createOutputArea(body); // create the NetLogo output widget return alreadyProcessed;// no need to add this to the NetLogo code } String[] newOperationAndBody; try { newOperationAndBody = expandSetMyNext(operation, operationOnNewLine, body, bodyOnNewLine, false); alreadyProcessed += newOperationAndBody[0]; if (newLineAfterOperation) { alreadyProcessed += "\n"; } code = newOperationAndBody[1]; } catch (Exception e) { netLogoModel.warn(e.getMessage() + " in " + getBehaviourDescription() + " (" + getBehaviourURL() + ")"); e.printStackTrace(); return alreadyProcessed + code; } } } } private String generateNetLogoPlottingCode(ArrayList<String> plotData, String operation) { String name = getName().trim(); String newCommandName1 = name.replace(' ', '-') + "-" + commandNumber++; generateReporter(plotData.get(3), newCommandName1, netLogoModel); String newCommandName2 = name.replace(' ', '-') + "-" + commandNumber++; generateReporter(plotData.get(4), newCommandName2, netLogoModel); return operation + " " + plotData.get(0) + "\n" + plotData.get(1) + "\n" + plotData.get(2) + "\n" + "task [" + newCommandName1 + "]\n" + "task [" + newCommandName2 + "]\n"; } protected void transformBody( String beforeActionAfter[], String operation, String behaviourName, boolean prototypeActive, NetLogoModel netLogoModel, String originalCode, StringBuilder behaviourBody, ClientState clientState) { if (beforeActionAfter == null) { netLogoModel.warn("Error: missing matched square brackets of " + behaviourURL + " (" + behaviourDescription + ") " + " in<br>" + originalCode); return; } // removed call to addUpdateTurtlePositionIfNeeded since my-x/xcor etc handled differently now String transformedBracketedCode = transformCode(beforeActionAfter[1], behaviourName, prototypeActive, netLogoModel, clientState); boolean operationExpectingASecondBracketedExpression = isOperationExpectingASecondBracketedExpression(operation); if (operation.equals("do-now") || operation.equals("do-at-setup")) { // no need to do anything at run-time behaviourBody.append(transformedBracketedCode); } else if (operation.equals("do-with-probability")) { behaviourBody.append("if "); String[] parts = beforeActionAfter[0].split("(\\s)+", 2); behaviourBody.append(" random-float 1.0 <= "); behaviourBody.append(parts[1].trim()); behaviourBody.append("\n["); behaviourBody.append(transformedBracketedCode.trim()); // need to go to a new line in case the above ended with a comment behaviourBody.append("\n]"); } else if (operation.equals("do-with-probabilities")) { behaviourBody.append("let random-fraction random-float 1.0"); String oddsAndBehaviours = beforeActionAfter[1].trim(); int index = 0; float odds = 0.0f; float newOdds; boolean first = true; int closeBracketsNeeded = 0; while (true) { int openBracketIndex = oddsAndBehaviours.indexOf("[", index); if (openBracketIndex < 0) { behaviourBody.append("[]"); // last else branch break; } String oddsString = oddsAndBehaviours.substring(index, openBracketIndex); try { newOdds = Float.parseFloat(oddsString); } catch (NumberFormatException e) { netLogoModel.warn("Expected the following to be a floating point number: " + oddsString); netLogoModel.warn("In " + originalCode); return; } index = openBracketIndex; int closeBracketIndex = oddsAndBehaviours.indexOf("]", index); if (closeBracketIndex < 0) { netLogoModel.warn("Missing close bracket in " + originalCode); return; } String behaviours = oddsAndBehaviours.substring(index, closeBracketIndex+1); index = closeBracketIndex+1; if (newOdds > 0.0f) { odds += newOdds; if (odds < 1.0) { if (!first) { behaviourBody.append("["); // for else branches closeBracketsNeeded++; } behaviourBody.append("\nif-else random-fraction <= "); behaviourBody.append(odds); } behaviourBody.append(CommonUtils.removeQuotesAndAddNewLines(behaviours)); if (odds >= 1.0) { if (odds > 1.0) { netLogoModel.warn("Probabilities add up to more than 1.0 in " + originalCode); } break; } } first = false; } if (closeBracketsNeeded > 0) { behaviourBody.append('\n'); // in case the last line was a comment } while (closeBracketsNeeded > 0) { behaviourBody.append(']'); closeBracketsNeeded--; } } else if (operation.equals("do-if") || operation.equals("do-if-else")) { // no need to do anything at run-time -- but remove the "do-" part // except that do-if implicitly checked if predicate was equal to true // otherwise uninitialised variables will trigger an error that 0 is not true/false // first strip off the "do-" part String conditional; conditional = beforeActionAfter[0].substring(3); // why this new line code? int newLineIndex = conditional.indexOf('\n'); String firstPart; if (newLineIndex > 0) { firstPart = conditional.substring(0, newLineIndex); } else { firstPart = conditional; } behaviourBody.append(firstPart); if (!beforeActionAfter[0].trim().equals("do-if") && !containsNetLogoPredicate(beforeActionAfter[0])) { behaviourBody.append(" = true"); } if (newLineIndex > 0) { behaviourBody.append(conditional.substring(newLineIndex)); } behaviourBody.append('['); behaviourBody.append(transformedBracketedCode); // need to go to a new line in case the above ended with a comment behaviourBody.append("\n]"); if (operationExpectingASecondBracketedExpression) { ArrayList<String> beforeContentsAndAfter = CommonUtils.beforeContentsAndAfter(beforeActionAfter[2]); if (beforeContentsAndAfter == null) { return; // TODO: produce warning } String transformedElseCode = transformCode(addUpdateTurtlePositionIfNeeded(beforeContentsAndAfter.get(1)), behaviourName, prototypeActive, netLogoModel, clientState); // put brackets back behaviourBody.append(beforeContentsAndAfter.get(0)); behaviourBody.append(transformedElseCode); behaviourBody.append(beforeContentsAndAfter.get(2)); // taken care of second command return; } } else if (operation.equals("create-agents") || // older name -- kept for backwards compatibility operation.equals("create-objects")) { // need to remove kind-name and // insert "initialise-instance-of-" kind-name into command list // first one will be changed to 'let' behaviourBody.append("; The following code was generated by a call to create-agent.\n"); behaviourBody.append(" set just-created-agents nobody\n"); // patch pxcor pycor works whether is a patch or turtle unlike patch-here behaviourBody.append("ask patch pxcor pycor"); if (netLogoModel.getDimensions() == 3) { behaviourBody.append(" zcor"); } behaviourBody.append(" [sprout-objects "); String[] arguments = beforeActionAfter[0].split("(\\s)+", 3); behaviourBody.append(arguments[1]); // number of agents String kindNameExpression = arguments[2]; // String kindName = kindNameExpression.replace("\"", "").trim(); behaviourBody.append(" [\n set just-created-agents (turtle-set self just-created-agents)\n set kind " + kindNameExpression + "]]"); // String initialisationBehaviours = ""; // MacroBehaviour macroBehaviour = netLogoModel.getMacroBehaviourNamed(kindName); // if (macroBehaviour != null) { // String behaviourNames = macroBehaviour.getBehaviourNames(); // if (behaviourNames != null && !behaviourNames.isEmpty()) { // initialisationBehaviours = behaviourNames; // } // } else { // clientState.warn("Unable to find a prototype named " + kindName + ".\nCode is: " + originalCode); // } // the following used to be just be called from within sprout-objects but then can't reference myself, etc. // initialise my-x and my-y since sprouted where 'myself' is // initialise them all before running any behaviours behaviourBody.append("\nask just-created-agents [\n set my-x xcor\n set my-y ycor\n initialise-object\n initialise-previous-state\n]"); // if (!initialisationBehaviours.isEmpty()) { behaviourBody.append("\nask just-created-agents [\n " + "kind-initialisation " + kindNameExpression + "]\n"); // } if (transformedBracketedCode != null) { behaviourBody.append("\nask just-created-agents [\n " + transformedBracketedCode + "\n ]"); } } else if (operation.equals("create-agents-from-data")) { behaviourBody.append("; The following code was generated by a call to create-agents-from-data.\n"); // would like to split the code into 5 pieces but can only rely upon new line for the first ones since // data can have new lines in it String[] arguments = beforeActionAfter[0].split("\n", 4); String kindNameExpression = arguments[1]; String attributeString = arguments[2].trim(); attributeString = attributeString.substring(1, attributeString.length()-1); // remove [ and ] String[] attributes = attributeString.split("\\s"); int attributesCount = attributes.length; int dataEndIndex = arguments[3].indexOf("]\n"); String dataString = arguments[3].substring(0, dataEndIndex+1); String additionalBehaviours = arguments[3].substring(dataEndIndex+2).trim(); behaviourBody.append("let data " + dataString + "\n"); behaviourBody.append("let data-count length data\n"); behaviourBody.append("; Following is used to ignore any extra data at the end.\n"); behaviourBody.append("let last-index " + attributesCount + " * floor (data-count / " + attributesCount + ")\n"); behaviourBody.append("let index 0\n"); behaviourBody.append("while [index < last-index]\n"); // patch pxcor pycor works whether is a patch or turtle unlike patch-here behaviourBody.append("[ask patch pxcor pycor"); if (netLogoModel.getDimensions() == 3) { behaviourBody.append(" zcor"); } behaviourBody.append("\n[sprout-objects 1 \n"); behaviourBody.append("[\n"); behaviourBody.append("set kind " + kindNameExpression + "\n"); for (int i = 0; i < attributesCount; i++) { if (!attributes[i].equals("\"\"")) { // ignore "" behaviourBody.append("set " + attributes[i] + " item index data\n"); } behaviourBody.append("set index index + 1\n"); } behaviourBody.append("initialise-object\n"); behaviourBody.append("kind-initialisation " + kindNameExpression + "\n"); behaviourBody.append(additionalBehaviours.substring(1,additionalBehaviours.length()-1) + "\n ]"); // remove [ and ] behaviourBody.append("]]\n"); } else if (CommonUtils.isTrivialCode(transformedBracketedCode)) { // use a task even though the body is trivial since // relied upon by remove-behaviours // and perhaps task [foo] is faster to run than "foo" // when and whenever may be referring to free variables behaviourBody.append(beforeActionAfter[0]); behaviourBody.append(" task ["); behaviourBody.append(transformedBracketedCode); behaviourBody.append("] "); } else if (NETLOGO_5) { behaviourBody.append(beforeActionAfter[0]); if (operationExpectingASecondBracketedExpression) { behaviourBody.append(" task ["); behaviourBody.append(CommonUtils.addNewLineIfLastLineIsComment(beforeActionAfter[1])); behaviourBody.append("]"); behaviourBody.append("\n task "); behaviourBody.append(transformCodePhase1(beforeActionAfter[2], null, behaviourName, prototypeActive, netLogoModel,clientState)); } else { behaviourBody.append(" task ["); behaviourBody.append(CommonUtils.addNewLineIfLastLineIsComment(transformedBracketedCode)); behaviourBody.append("]"); String transformedAfter = transformCode(addUpdateTurtlePositionIfNeeded(beforeActionAfter[2]), behaviourName, prototypeActive, netLogoModel, clientState); behaviourBody.append(transformedAfter); // might be some closing square brackets for example } return; // netLogoModel.associateWithProcedureName(getBehaviourName(true), body); } else { behaviourBody.append(beforeActionAfter[0]); String newCommandNameBase = CommonUtils.replaceAllNonLetterOrDigit(getName().trim(), '-'); String newCommandName = newCommandNameBase + "-" + commandNumber++; char firstCharacter = newCommandName.charAt(0); if (!Character.isLetter(firstCharacter)) { // NetLogo can't handle procedures that begin with a non-letter newCommandName = "c" + newCommandName; // System.out.println(CommonUtils.decode(behaviourDescription)); } StringBuilder newCommand = new StringBuilder(); newCommand.append("to"); if (operationExpectingASecondBracketedExpression) { // assumes the first one is a reporter -- e.g. when and whenever newCommand.append("-report"); } newCommand.append(' '); newCommand.append(newCommandName); newCommand.append('\n'); if (operationExpectingASecondBracketedExpression) { newCommand.append("report "); } newCommand.append(transformedBracketedCode); newCommand.append('\n'); newCommand.append("end"); netLogoModel.getGeneratedCommands().add(newCommand.toString()); // netLogoModel.associateWithProcedureName(getBehaviourName(true), CommonUtils.quote(newCommandNameBase)); behaviourBody.append(' '); behaviourBody.append(CommonUtils.quote(newCommandName)); behaviourBody.append(' '); } if (operationExpectingASecondBracketedExpression) { transformBody(splitOnSquareBrackets(beforeActionAfter[2], operation, clientState), "", behaviourName, prototypeActive, netLogoModel, originalCode, behaviourBody, clientState); } else { String transformedAfter = transformCode(addUpdateTurtlePositionIfNeeded(beforeActionAfter[2]), behaviourName, prototypeActive, netLogoModel, clientState); behaviourBody.append(transformedAfter); } } private static boolean containsNetLogoPredicate(String code) { if (code.contains("and")) return true; if (code.contains("or")) return true; if (code.contains("=")) return true; if (code.contains("?")) return true; // predicates end in ? if (code.contains(">")) return true; if (code.contains("<")) return true; // might miss a few but worst case // you end up with (predicate) = true rather than just (predicate) return false; } public static boolean isOperationExpectingASecondBracketedExpression(String operation) { for (String operationExpectingASecondBracketedExpression : operationsExpectingASecondBracketedExpression) { if (operation.equals(operationExpectingASecondBracketedExpression)) { return true; } } return false; } public static int indexOfFirstOperationExpectingABracketedExpression(String code) { int bestIndex = -1; for (String operationExpectingABracketedExpression : operationsExpectingABracketedExpression) { int index = CommonUtils.indexOfNetLogoCodeOnly(operationExpectingABracketedExpression, code, 0); if (index >= 0) { if (bestIndex < 0 || index < bestIndex) { bestIndex = index; } } } return bestIndex; } protected String defineParameter(String body, String comment, NetLogoModel netLogoModel, ClientState clientState) { // supports (controlled by a slider), (controlled by an input box), // and no interface (just set and declare) String tokensNewVersion[] = {"name: ", "initial value: ", "upper left corner: ", "lower right corner: ", "minimum value: ", "maximum value: ", "increment: ", "units: ", "horizontal: ", "Type check: ", "Multi-line: ", "\n"}; String tokensOldVersion[] = {"name: ", "initial value: ", "lower left corner: ", "upper right corner: ", "minimum value: ", "maximum value: ", "increment: ", "units: ", "horizontal: ", "Type check: ", "Multi-line: ", "\n"}; String tokens[]; if (body.contains(tokensOldVersion[2])) { tokens = tokensOldVersion; } else { tokens = tokensNewVersion; } int startEnd[] = {0, 0}; if (!ServerUtils.extractValue(tokens[0], tokens[1], body, startEnd, clientState)) { return ""; } String variableName = body.substring(startEnd[0], startEnd[1]).trim(); if (!ServerUtils.extractValue(tokens[1], tokens[2], body, startEnd, clientState)) { return ""; } String interfaceType = null; String initialValue = body.substring(startEnd[0], startEnd[1]).trim(); int sliderStart = variableName.indexOf(" (controlled by a slider)"); int inputBoxStart = -1; int switchStart = -1; if (sliderStart > 0) { variableName = variableName.substring(0, sliderStart); interfaceType = "slider"; try { Double.parseDouble(initialValue); } catch (NumberFormatException e) { clientState.warn("Initial value of a slider (define-parameter) is not a proper number: " + initialValue); } } else { inputBoxStart = variableName.indexOf(" (controlled by an input box)"); if (inputBoxStart > 0) { variableName = variableName.substring(0, inputBoxStart); interfaceType = "input box"; } else { switchStart = variableName.indexOf(" (controlled by a switch)"); if (switchStart > 0) { variableName = variableName.substring(0, switchStart); interfaceType = "switch"; // no need to check if it is a correct boolean value since Boolean.parseBoolean // just checks if the value is "true" } } } // if (variableName.equalsIgnoreCase("clocked")) { // netLogoModel.doNotAddClockedSwitch(); // } else if (variableName.equalsIgnoreCase("the-default-buttons-should-not-be-added")) { netLogoModel.doNotAddDefaultButtons(); return ""; } if (comment == null || !comment.equals("; Define a new parameter (optionally controlled by a slider or input box). \n")) { netLogoModel.associateCommentWithGlobal(variableName, comment, interfaceType); } if (interfaceType != null) { // if has interface then the new lines should be 'quoted' in the NetLogo file initialValue = initialValue.replaceAll("\n", "\\\\n"); } if (!netLogoModel.addExtraGlobalVariable(variableName, interfaceType == null, false)) { // no need to warn since can have multiple interfaces for the same variable // and if it has no interface OK to set it multiple times... // clientState.warn("Warning. Parameter " + variableName + " is defined more than once."); } if (interfaceType != null) { // both use same location parameters // older versions used lower left if (!ServerUtils.extractValue(tokens[2], tokens[3], body, startEnd, null)) { // don't warn return ""; } String upperLeftCorner = body.substring(startEnd[0], startEnd[1]).trim(); // older versions used upper right if (!ServerUtils.extractValue(tokens[3], tokens[4], body, startEnd, null)) { // don't warn{ return ""; } String lowerRightCorner = body.substring(startEnd[0], startEnd[1]).trim(); int llx, lly, urx, ury; String[] point = upperLeftCorner.split(" ", 2); if (point.length < 2) { clientState.warn("Upper left corner (in define-parameter) should be two numbers separated by a space. Not '" + upperLeftCorner + "' in " + behaviourDescription + " " + behaviourURL); return ""; } llx = ServerUtils.parseInt(point[0], "defineParameter", clientState); lly = ServerUtils.parseInt(point[1], "defineParameter", clientState); point = lowerRightCorner.split(" ", 2); if (point.length < 2) { clientState.warn("Lower right corner (in define-parameter) should be two numbers separated by a space. Not '" + lowerRightCorner + "'" + "' in " + behaviourDescription + " " + behaviourURL); return ""; } urx = ServerUtils.parseInt(point[0], "defineParameter", clientState); ury = ServerUtils.parseInt(point[1], "defineParameter", clientState); if (sliderStart > 0) { if (!ServerUtils.extractValue(tokens[4], tokens[5], body, startEnd, clientState)) { return ""; } String minimumValue = body.substring(startEnd[0], startEnd[1]).trim(); try { Double.parseDouble(minimumValue); } catch (NumberFormatException e) { clientState.warn("Minimum value of slider (in define-parameter) is not a number: " + minimumValue); } if (!ServerUtils.extractValue(tokens[5], tokens[6], body, startEnd, clientState)) { return ""; } String maximumValue = body.substring(startEnd[0], startEnd[1]).trim(); try { Double.parseDouble(maximumValue); } catch (NumberFormatException e) { clientState.warn("Maximum value of slider (in define-parameter) is not a number: " + maximumValue); } if (!ServerUtils.extractValue(tokens[6], tokens[7], body, startEnd, clientState)) { return ""; } String increment = body.substring(startEnd[0], startEnd[1]).trim(); try { Double.parseDouble(increment); } catch (NumberFormatException e) { clientState.warn("Increment value of slider (in define-parameter) is not a number: " + increment); } String units = "NIL"; // none by default // don't pass in clientState since no warnings since // older version of micro-behaviour didn't have this and next feature if (ServerUtils.extractValue(tokens[7], "Units displayed on the slider", body, startEnd, null)) { units = body.substring(startEnd[0], startEnd[1]).trim(); if (units.isEmpty()) { units = "NIL"; } } boolean horizontal = true; if (ServerUtils.extractValue(tokens[8], "Displayed horizontally rather than vertically (true or false)", body, startEnd, null)) { horizontal = !body.substring(startEnd[0], startEnd[1]).trim().equalsIgnoreCase("false"); } netLogoModel.addCommandToAddSlider(variableName, llx, lly, urx, ury, minimumValue, maximumValue, increment, initialValue, units, horizontal); return ""; } else if (switchStart > 0) { netLogoModel.addCommandToAddSwitch(variableName, llx, lly, urx, ury, initialValue); } else { if (!ServerUtils.extractValue(tokens[9], tokens[10], body, startEnd, clientState)) { return ""; } String typeString = body.substring(startEnd[0], startEnd[1]).trim(); String[] typeAndComment = typeString.split("\n", 2); if (typeAndComment.length == 2) { typeString = typeAndComment[0].trim(); } // valid types: Number, String, Color, String (reporter), String (commands) if (!typeString.equals("Number") && !typeString.equals("String") && !typeString.equals("Color") && !typeString.equals("String (reporter)") && !typeString.equals("String (commands)")) { clientState.warn("Input box type: '" + typeString + "' should be Number, String, Color, String (reporter), or String (commands) in input box in define-parameter."); typeString = "Number"; // good default? } if (!ServerUtils.extractValue(tokens[10], tokens[11], body, startEnd, clientState)) { return ""; } String multiLineString = body.substring(startEnd[0], startEnd[1]).trim(); boolean multiLine = multiLineString.startsWith("1"); netLogoModel.addCommandToAddInputBox(variableName, llx, lly, urx, ury, initialValue, multiLine, typeString); } return ""; } String initialiseVariable = "if not member? \"" + variableName + "\" globals-not-to-be-initialised\n" + " [set " + variableName + " " + initialValue + "\n ]"; // ] on new line in case initialValue ends with a comment netLogoModel.addGlobalInitialisation(initialiseVariable); return ""; } protected void generateReporter(String body2, String newCommandName, NetLogoModel netLogoModel) { StringBuilder newReporter = new StringBuilder(); newReporter.append("to-report "); newReporter.append(newCommandName); newReporter.append('\n'); newReporter.append("report "); newReporter.append(body2); if (body2.charAt(body2.length()-1) != '\n') { newReporter.append('\n'); } newReporter.append("end"); netLogoModel.getGeneratedCommands().add(newReporter.toString()); } protected static String addUpdateTurtlePositionIfNeeded(String body) { if (body.indexOf("set my-x ") >= 0 || body.indexOf("set my-y ") >= 0) { return body + "\nupdate-turtle-position"; } else { return body; } } protected static String[] expandSetMyNext(String operation, boolean operationOnNewLine, String body, boolean bodyOnNewLine, boolean keepToOneLine) throws Exception { String[] result = new String[2]; // operation (with white space) and body boolean operationIsSet = operation.equalsIgnoreCase("set"); result[0] = bodyOnNewLine & !keepToOneLine && !operationIsSet ? operation + "\n" : operation + " "; result[1] = body; if (operationOnNewLine && !keepToOneLine) { result[0] = "\n" + result[0]; } if (!operationIsSet) { return result; } String setPrefix = operationOnNewLine && !keepToOneLine ? "\n" : ""; String setPostfix = " "; // following just broke up set statements and looked bad // String setPostfix = bodyOnNewLine & !keepToOneLine ? "\n" : " "; final String variable = CommonUtils.firstWord(body); if (variable == null) { throw new Exception("Error. The following code contains 'set' without a value expression: " + body); } int index = variable.indexOf("my-next-"); if (index >= 0) { if (variable.endsWith("-set")) { return result; // already processed } String setSet = setPrefix + "set" + setPostfix + variable + "-set true"; if (!keepToOneLine && !result[0].startsWith("\n")) { setSet = setSet + "\n"; } result[0] = setSet + " " + result[0]; return result; } int setNextIndex = variable.indexOf("next-"); if (setNextIndex >= 0) { int ofPatchIndex = variable.indexOf("-of-patch"); if (ofPatchIndex >= 0) { if (variable.endsWith("-the")) { return result; // already processed } String setSet = setPrefix + "set" + setPostfix + variable + "-set true"; if (!keepToOneLine && !result[0].startsWith("\n")) { setSet = setSet + "\n"; } result[0] = setSet + " " + result[0]; return result; } } return result; } protected static String removeComment(String line) { int commentStart = line.indexOf(';'); if (commentStart < 0) { return line; } int quoteEnd = line.indexOf('\"', commentStart); if (quoteEnd < 0) { return line.substring(0, commentStart); } int quoteStart = line.indexOf('\"'); if (quoteStart > commentStart) { return line.substring(0, commentStart); } // in principle could be foo " ... " ; " ... " which this misses return line; } protected void updateRequiredBehaviours(NetLogoModel netLogoModel) throws NetLogoException { if (referencedMicroBehaviours.size() > 0) { for (MicroBehaviour referencedMicroBehaviour : referencedMicroBehaviours) { netLogoModel.addRequiredMicroBehaviour(referencedMicroBehaviour); } return; // already did all this or already know the answer } if (transformedBehaviourCode != null) { return; // already transformed } String code = getBehaviourCode(); boolean alreadyProcessed = ServerUtils.extraNameIndex(code) >= 0; if (alreadyProcessed) { // processed code ended up in database -- rework this? return; } StringBuilder newCode = new StringBuilder(code); for (int i = 0; i < NetLogoModel.proceduresWithOneBehaviourArgument.length; i++) { int location = code.indexOf(NetLogoModel.proceduresWithOneBehaviourArgument[i], 0); if (location >= 0) { int procedureNameLength = NetLogoModel.proceduresWithOneBehaviourArgument[i].length(); char ch; if (code.length() <= location + procedureNameLength) { ch = ' '; } else { ch = code.charAt(location + procedureNameLength); } if (ch == ' ' || ch == '\n') { // otherwise is just part of the name while (location >= 0) { int argumentStart = location + procedureNameLength; String behaviour[] = code.substring(argumentStart).split("\"", 3); if (behaviour.length == 3) { String fullBehaviourName = behaviour[1]; int extraNameIndex = ServerUtils.extraNameIndex(fullBehaviourName); if (extraNameIndex > 0) { fullBehaviourName = fullBehaviourName.substring(0, extraNameIndex); } processRequiredBehaviour(netLogoModel, newCode, fullBehaviourName); } location = code.indexOf(NetLogoModel.proceduresWithOneBehaviourArgument[i], argumentStart); } } } } // TODO: determine if this is still needed: for (int i = 0; i < NetLogoModel.proceduresWithBehaviourArguments.length; i++) { int location = code.indexOf(NetLogoModel.proceduresWithBehaviourArguments[i], 0); if (location >= 0) { int procedureNameLength = NetLogoModel.proceduresWithBehaviourArguments[i].length(); char ch; if (code.length() <= location + procedureNameLength) { ch = ' '; } else { ch = code.charAt(location + procedureNameLength); } if (ch == ' ' || ch == '\n') { // otherwise is just part of the name while (location >= 0) { String remainingCode = code.substring(location + procedureNameLength); int argumentStart = remainingCode.indexOf('['); if (argumentStart < 0) { netLogoModel.warn("Expected to find a list with square brackets in " + code); return; } remainingCode = remainingCode.substring(argumentStart); int argumentStop = remainingCode.indexOf(']'); if (argumentStop < 0) { netLogoModel.warn("Expected to find a list with square brackets in " + code); return; } String behavioursString = remainingCode.substring(1, argumentStop); StringBuilder behaviourDescriptions = new StringBuilder(); // old BehaviourComposer 1.0 quoted names String behaviour[] = behavioursString.split("\""); for (int j = 1; j < behaviour.length; j += 2) { processRequiredBehaviour(netLogoModel, newCode, behaviour[j]); behaviourDescriptions.append(behaviour[j]); behaviourDescriptions.append(' '); } // int newArgumentStop = newCode.indexOf("]"); // comments not needed now that micro-behaviour names do the same job better // // add a comment for clarity of the NetLogo code // newCode.insert(newArgumentStop, "\n; " + behaviourDescriptions.toString() + "\n"); remainingCode = remainingCode.substring(argumentStop + 1); location = remainingCode.indexOf(NetLogoModel.proceduresWithBehaviourArguments[i], argumentStop + 1); } } } } // since don't want to transform twice store the result // Also make sure no non-breaking spaces remain (either as HTML or as UTF-8) transformedBehaviourCode = CommonUtils.replaceNonBreakingSpaces(newCode.toString().replaceAll("&nbsp;", " ")); } private void processRequiredBehaviour(NetLogoModel netLogoModel, StringBuilder newCode, String requiredBehaviourName) throws NetLogoException { MicroBehaviour referencedMicroBehaviour = netLogoModel.addRequiredBehaviourName(requiredBehaviourName, null, this); if (referencedMicroBehaviour != null) { referencedMicroBehaviours.add(referencedMicroBehaviour); int nameStart = newCode.indexOf(requiredBehaviourName); if (nameStart >= 0) { int nameEnd = nameStart+requiredBehaviourName.length(); if (referencedMicroBehaviour.isRawNetLogoCode()) { // no need to add this at run-time so remove it from the code newCode.replace(nameStart, nameEnd, ""); } else { String referencedBehaviourName = referencedMicroBehaviour.getBehaviourName(false); // if (addComment) { // // a comment for clarity // // replace the existing closing quote // // in order to add comment afterwards // referencedBehaviourName += "\"\n; " + requiredBehaviourName + "\n"; // nameEnd++; // to add comment replace " as well // } newCode.replace(nameStart, nameEnd, referencedBehaviourName); } } } } protected void updateVariables(NetLogoModel netLogoModel) throws NetLogoException { netLogoModel.findAllKindsOfVariables(getTransformedBehaviourCode()); } protected void updateBreedVariables(NetLogoModel netLogoModel) throws NetLogoException { netLogoModel.findBreedVariables(getTransformedBehaviourCode()); } protected void updateGlobalVariables(NetLogoModel netLogoModel) throws NetLogoException { netLogoModel.findGlobalVariables(getTransformedBehaviourCode()); } protected void updatePatchVariables(NetLogoModel netLogoModel) throws NetLogoException { netLogoModel.findPatchVariables(getTransformedBehaviourCode()); } protected void updateLinkVariables(NetLogoModel netLogoModel) throws NetLogoException { netLogoModel.findLinkVariables(getTransformedBehaviourCode()); } protected String getBehaviourCodeUnprocessed() { return behaviourCode; } protected String getBehaviourCode() throws NetLogoException { // throws Exception since subclass does // some callers don't have a netLogoModel if (behaviourCode == null) { Level level = getBehaviourURL() == null ? Level.WARNING : Level.SEVERE; Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).log( level, "getBehaviourCode called but behaviourCode is null. Url is " + getBehaviourURL()); return null; } if (!enhancementsInstalled && enhancements != null && !enhancements.isEmpty()) { int originalTextAreasCount = textAreaElements == null ? 0 : textAreaElements.size()/2; installEnhancements(originalTextAreasCount); } String description = CommonUtils.getDescription(getBehaviourDescription()); String result; if (!description.isEmpty()) { String comment = CommonUtils.comment(description); result = comment + "\n" + behaviourCode; } else { result = behaviourCode; } Set<Entry<Integer, String>> textAreaValuesEntrySet = textAreaValues.entrySet(); for (Entry<Integer, String> entry : textAreaValuesEntrySet) { Integer index = entry.getKey(); if (index >= 0) { // ignore name changes here String replacement = entry.getValue(); if (replacement != null) { if (!CommonUtils.TOKEN_FOR_REMOVED_TEXT_AREA.equals(replacement)) { result = result.replace(ServerUtils.textAreaPlaceHolder(index), replacement.trim()); } } else { Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).severe( "Replacement of a text area #" + index + " is null. " + result + " url=" + getBehaviourURL()); } } } if (macroBehaviours != null) { for (MacroBehaviour macroBehaviour : macroBehaviours) { String name = macroBehaviour.getObjectName(); String placeHolder = ServerUtils.macroBehaviourPlaceHolder(name); ArrayList<MicroBehaviour> microBehaviours = macroBehaviour.getMicroBehaviours(); StringBuffer microBehaviourList = new StringBuffer("["); for (MicroBehaviour microBehaviour : microBehaviours) { if (!microBehaviour.isRawNetLogoCode() && macroBehaviour.isActive(microBehaviour)) { microBehaviourList.append(microBehaviour.getBehaviourName(false)); microBehaviourList.append("\n "); // the space is so the code isn't at the left edge } } microBehaviourList.append(']'); result = result.replace(placeHolder, microBehaviourList.toString()); } } // make sure there are no non-breaking spaces to interfere with NetLogo // not sure how the 160 (non-breaking space got there but this gets rid of it) transformedBehaviourCode = CommonUtils.replaceNonBreakingSpaces(result.replaceAll("&nbsp;", " ")).replace((char) 160, (char) 32); return transformedBehaviourCode; } private void installEnhancements(int nextTextAreaIndex) { for (MicroBehaviourEnhancement enhancement : enhancements) { nextTextAreaIndex = enhanceCode(enhancement, nextTextAreaIndex); } } public void updateTextArea(String newContents, int index) { if (newContents == null) { Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).severe( "Updating text area#" + index + " with null. url=" + this.getBehaviourURL()); } textAreaValues.put(index, newContents); transformedBehaviourCode = null; // no longer valid if (index == -1) { setBehaviourDescriptionAndNameHTML(newContents); setBehaviourDescription(); } } public String getTransformedBehaviourCode() throws NetLogoException { if (transformedBehaviourCode != null) { return transformedBehaviourCode; } return getBehaviourCode(); } protected void setBehaviourCode(String newCode) { if (newCode != null) { // replace UTF-8 encoding of non-breaking space and the like with ASCII space behaviourCode = CommonUtils.replaceNonBreakingSpaces(newCode); originalBehaviourCode = behaviourCode; } else { behaviourCode = null; System.err.println("behaviourCode set to null"); } } protected static String[] splitOnSquareBrackets(String s, String operation, ClientState clientState) { // returns 3 strings: // before square bracketed code, contents of square brackets, after square bracketed code // or null if no square brackets return splitOnSquareBracketsInternal(s, 0, operation, clientState); } private static String[] splitOnSquareBracketsInternal( String s, int earliestOpenSquareBracket, String operation, ClientState clientState) { // if it begins with parentheses then don't consider square brackets inside if (operation != null) { int openParenthesis = CommonUtils.indexOfNetLogoCodeOnly('(', s, earliestOpenSquareBracket); // List<String> conditionals = Arrays.asList("if", "ifelse", "if-else", "if-else-value", "while"); // if (openParenthesis < 0 && conditionals.contains(operation.toLowerCase())) { // TODO: act as if the conditional was in parentheses. // } if (openParenthesis >= 0) { String beforeParenthesis = s.substring(operation.length(), openParenthesis).trim(); if (beforeParenthesis.isEmpty()) { int closeParenthesis = CommonUtils.indexOfNetLogoCodeOnly(')', s, openParenthesis); if (closeParenthesis >= 0) { earliestOpenSquareBracket = closeParenthesis+1; } } } } int openBracket = CommonUtils.indexOfNetLogoCodeOnly('[', s, earliestOpenSquareBracket); if (openBracket < 0) { return null; } String beforeOpenBracket = s.substring(0, openBracket); String lastWord = CommonUtils.lastWord(beforeOpenBracket); if (operation != null && lastWord != null && !lastWord.equals(operation)) { for (int i = 0; i < operationsExpectingBracketedExpressionAsFirstArgument.length; i++) { if (operationsExpectingBracketedExpressionAsFirstArgument[i].equals(operation)) { clientState.warn("Ignored everything between " + operation + " and [ in " + s); break; } } } if (isNetLogoPrimitiveRequiringSquareBracketsAfter(lastWord)) { return splitOnSquareBracketsInternal(s, openBracket+1, operation, clientState); } int closeBracket = CommonUtils.closeBracket(s, openBracket+1); if (closeBracket < 0) { clientState.warn("Could not find ] to match [ in " + s); return null; } // following caused Issue 739 // seemed to be support for the older NetLogo set [x] of y z // String firstWord = CommonUtils.firstWord(s.substring(closeBracket+1)); // if (isNetLogoPrimitiveRequiringSquareBracketsBefore(firstWord)) { // return splitOnSquareBracketsInternal(s, closeBracket+1, operation, clientState); // } String pieces[] = new String[3]; pieces[0] = beforeOpenBracket; pieces[1] = s.substring(openBracket+1, closeBracket); // remove brackets pieces[2] = s.substring(closeBracket+1); return pieces; } protected static boolean isNetLogoPrimitiveRequiringSquareBracketsAfter(String word) { if (word == null) return false; return word.equalsIgnoreCase("with"); // what else? } protected static boolean isNetLogoPrimitiveRequiringSquareBracketsBefore(String word) { if (word == null) return false; return word.equalsIgnoreCase("of") || word.equalsIgnoreCase("set"); // what else? } protected static String[] splitOnLineContaining(String[] separators, String s) { int earliestSeparatorIndex = Integer.MAX_VALUE; String earliestSeparator = null; for (int i = 0; i < separators.length; i++) { int index = s.indexOf(separators[i]); if (index >= 0 && index < earliestSeparatorIndex) { earliestSeparatorIndex = index; earliestSeparator = separators[i]; } } if (earliestSeparator == null) { return null; } else { String pieces[] = new String[2]; pieces[0] = s.substring(0, earliestSeparatorIndex).trim(); pieces[1] = s.substring(earliestSeparatorIndex).trim(); return pieces; } } protected static String[] splitOnLineContainingOnly(String separator, String s) { String lines[] = s.split("\n", 0); // all of them for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith(separator)) { // was equalsIgnoreCase(separator) but need do-after 5 kind of thing String answer[] = new String[3]; answer[0] = ""; answer[1] = lines[i]; answer[2] = ""; for (int j = 0; j < i; j++) { answer[0] = answer[0] + " " + lines[j].trim() + "\n"; } for (int j = i + 1; j < lines.length; j++) { answer[2] = answer[2] + " " + lines[j].trim() + "\n"; } return answer; } } return null; } public String getBehaviourName(boolean quote) { return getBehaviourName(quote, null); } public String getBehaviourName(boolean quote, ArrayList<MicroBehaviour> visitedMicroBehaviours) { if (behaviourURL == null) { return null; } String name = getNetLogoName(); if (quote) { return "\"" + name + "\""; } else { return name; } } public int enhanceCode(MicroBehaviourEnhancement enhancement, int textAreaIndex) { switch (enhancement) { case DO_EVERY: behaviourCode = "do-every (" + textAreaValues.get(textAreaIndex++) + ")\n [" + behaviourCode + "]"; break; case DO_AFTER: behaviourCode = "do-after (" + textAreaValues.get(textAreaIndex++) + ")\n [" + behaviourCode + "]"; break; case DO_AT_TIME: behaviourCode = "do-at-time (" + textAreaValues.get(textAreaIndex++) + ")\n [" + behaviourCode + "]"; break; case DO_WITH_PROBABILITY: behaviourCode = "do-with-probability (" + textAreaValues.get(textAreaIndex++) + ")\n [" + behaviourCode + "]"; break; case DO_IF: behaviourCode = "do-if (" + textAreaValues.get(textAreaIndex++) + ")\n [" + behaviourCode + "]"; break; case DO_WHEN: behaviourCode = "when [" + textAreaValues.get(textAreaIndex++) + "]\n [" + behaviourCode + "]"; break; case DO_WHENEVER: behaviourCode = "whenever [" + textAreaValues.get(textAreaIndex++) + "]\n [" + behaviourCode + "]"; break; case ADD_VARIABLE: behaviourCode = "let " + addParenthesesToValue(textAreaValues.get(textAreaIndex++).trim()) + "\n " + behaviourCode; break; case ADD_COMMENT: behaviourCode = textAreaValues.get(textAreaIndex++) + "\n" + behaviourCode; break; } enhancementsInstalled = true; transformedBehaviourCode = null; // no longer valid return textAreaIndex; } private String addParenthesesToValue(String nameAndValue) { // changes name value to name (value) // otherwise can't parse edits inside of BC2NetLogo String[] parts = nameAndValue.split("(\\s)+", 2); if (parts.length < 2) { return nameAndValue; } else { return parts[0] + " ( " + parts[1] + " ) "; } } protected MicroBehaviour getReferringMicroBehaviour() { return null; } public String getBehaviourURL() { return behaviourURL; } protected void setBehaviourURL(String behaviourURL) { if (behaviourURL == null) { ServerUtils.logError("Warning. URL of a micro-behaviour is null."); } this.behaviourURL = behaviourURL; // the URL is the true identity so make sure the names are unique // computed on demand now -- not enough is always known at the time this is called // if (behaviourURL != null) { // behaviourName = ServerUtils.convertURLToNetLogoName(behaviourURL, behaviourDescription); // } } protected ArrayList<MicroBehaviour> getReferencedMicroBehaviours() { return referencedMicroBehaviours; } protected void setReferencedMicroBehaviours(ArrayList<MicroBehaviour> referencedMicroBehaviours) { this.referencedMicroBehaviours = referencedMicroBehaviours; } public String getBehaviourDescription() { return behaviourDescription; } public String getBehaviourDescriptionHTML() { return behaviourDescriptionAndNameHTML; } public String getName() { return CommonUtils.getName(behaviourDescriptionAndNameHTML); } public HashMap<Integer, String> getTextAreaValues() { return textAreaValues; } /** * @return a list alternating between names and text area HTML elements or NULL */ public ArrayList<String> getTextAreaElements() { return textAreaElements; } protected void setTextAreaElements(ArrayList<String> textAreaElements) { this.textAreaElements = textAreaElements; } public ArrayList<MacroBehaviour> getMacroBehaviours() { return macroBehaviours; } public void addMacroBehaviour(MacroBehaviour macroBehaviour) { transformedBehaviourCodeInvalid(); if (macroBehaviours == null) { macroBehaviours = new ArrayList<MacroBehaviour>(); } macroBehaviours.add(macroBehaviour); } // // public void removeMacroBehaviour(MacroBehaviour macroBehaviour) { // transformedBehaviourCodeInvalid(); // macroBehaviours.remove(macroBehaviour); // } public void resetMacroBehaviours() { if (macroBehaviours != null) { transformedBehaviourCodeInvalid(); macroBehaviours.clear(); } } private void transformedBehaviourCodeInvalid() { transformedBehaviourCode = null; } protected void setMacroBehaviours(ArrayList<MacroBehaviour> macroBehaviours) { this.macroBehaviours = macroBehaviours; } public boolean isMacroBehaviourAsMicroBehaviour() { return false; } public NetLogoModel getNetLogoModel() { return netLogoModel; } public void setNetLogoModel(NetLogoModel netLogoModel) { this.netLogoModel = netLogoModel; } public MicroBehaviourData getMicroBehaviourData() { // should be up to date -- no need to do this // createOrUpdateMicroBehaviourData(false); return microBehaviourData; } public List<MicroBehaviourEnhancement> getEnhancements() { return enhancements; } public void resetEnhancements() { enhancements.clear(); behaviourCode = originalBehaviourCode; transformedBehaviourCode = null; // no longer valid } public void addEnhancement(MicroBehaviourEnhancement enhancement) { enhancements.add(enhancement); } public boolean isEnhancementsInstalled() { return enhancementsInstalled; } public static String getNextSerialNumber(String nameWithoutSerialNumber) { // return serial number as string with preceding zeros to have a fixed length // equivalent-micro-behaviour? in NLS auxiliary file expects 5 digits // in order to work backwards from procedure name to micro-behaviour URL // we need to be sure that the NetLogo names are globally unique // hence maintaining the serial number in the data store NetLogoNameSerialNumber lastSerialNumber = DataStore.begin().find(NetLogoNameSerialNumber.class, nameWithoutSerialNumber); if (lastSerialNumber == null) { lastSerialNumber = new NetLogoNameSerialNumber(nameWithoutSerialNumber, 1); } else { lastSerialNumber.incrementSerialNumber(); } DataStore.begin().put(lastSerialNumber); return Integer.toString(100000 + lastSerialNumber.getSerialNumber()).substring(1); } public String getNetLogoName() { if (netLogoName == null) { netLogoName = ServerUtils.convertURLToNetLogoName(behaviourURL, CommonUtils.getName(behaviourDescriptionAndNameHTML)); } return netLogoName; } public String getBehaviourDescriptionAndNameHTML() { return behaviourDescriptionAndNameHTML; } public void setBehaviourDescriptionAndNameHTML(String behaviourDescriptionAndNameHTML) { if (behaviourDescriptionAndNameHTML == null) { Logger.getLogger(ResourcePageServiceImpl.RESOURCE_SERVICE_LOGGER_NAME).severe( "MicroBehaviour's setBehaviourDescriptionAndNameHTML called with null name."); } else { this.behaviourDescriptionAndNameHTML = behaviourDescriptionAndNameHTML.replaceAll("&nbsp;", " ").replaceAll("&NBSP;", " "); } } }
ToonTalk/behaviour-composer
BC/src/uk/ac/lkl/server/MicroBehaviour.java
Java
bsd-3-clause
85,783
package org.datagr4m.drawing.model.items; public enum ItemShape { CIRCLE, RECTANGLE }
datagr4m/org.datagr4m
datagr4m-drawing/src/main/java/org/datagr4m/drawing/model/items/ItemShape.java
Java
bsd-3-clause
95
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.payments; import androidx.test.filters.MediumTest; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.payments.PaymentRequestTestRule.AppPresence; import org.chromium.chrome.browser.payments.PaymentRequestTestRule.FactorySpeed; import org.chromium.chrome.browser.payments.PaymentRequestTestRule.MainActivityStartCallback; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.components.payments.Event; import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.ui.test.util.DisableAnimationsTestRule; import java.util.concurrent.TimeoutException; /** * A payment integration test to validate the logging of Payment Request metrics. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class PaymentRequestJourneyLoggerTest implements MainActivityStartCallback { // Disable animations to reduce flakiness. @ClassRule public static DisableAnimationsTestRule sNoAnimationsRule = new DisableAnimationsTestRule(); @Rule public PaymentRequestTestRule mPaymentRequestTestRule = new PaymentRequestTestRule("payment_request_metrics_test.html", this); @Override public void onMainActivityStarted() {} private void createTestData() throws TimeoutException { AutofillTestHelper mHelper = new AutofillTestHelper(); // The user has a shipping address and a credit card associated with that address on disk. String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "[email protected]", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "4111111111111111", "1111", "12", "2050", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); // The user also has an incomplete address and an incomplete card saved. String mIncompleteAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "In Complete", "Google", "344 Main St", "CA", "", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "", "4111111111111111", "1111", "18", "2075", "visa", R.drawable.visa_card, mIncompleteAddressId, "" /* serverId */)); } /** * Expect that the number of shipping address suggestions was logged properly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testNumberOfSuggestionsShown_ShippingAddress_Completed() throws TimeoutException { createTestData(); // Complete a Payment Request with a credit card. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait( R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); Assert.assertEquals(1, RecordHistogram.getHistogramTotalCountForTesting( "PaymentRequest.TimeToCheckout.Completed")); Assert.assertEquals(1, RecordHistogram.getHistogramTotalCountForTesting( "PaymentRequest.TimeToCheckout.Completed.Shown")); Assert.assertEquals(1, RecordHistogram.getHistogramTotalCountForTesting( "PaymentRequest.TimeToCheckout.Completed.Shown.BasicCard")); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2)); } /** * Expect that the number of shipping address suggestions was logged properly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testNumberOfSuggestionsShown_ShippingAddress_AbortedByUser() throws InterruptedException, TimeoutException { createTestData(); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); // Wait for the histograms to be logged. Thread.sleep(200); Assert.assertEquals(1, RecordHistogram.getHistogramTotalCountForTesting( "PaymentRequest.TimeToCheckout.UserAborted")); Assert.assertEquals(1, RecordHistogram.getHistogramTotalCountForTesting( "PaymentRequest.TimeToCheckout.UserAborted.Shown")); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2)); } /** * Expect that the number of payment method suggestions was logged properly. */ @Test @MediumTest @Feature({"Payments"}) public void testNumberOfSuggestionsShown_PaymentMethod_Completed() throws TimeoutException { // Add two credit cards. createTestData(); // Add a complete payment app. mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); // Complete a Payment Request with the payment app. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"https://bobpay.com", "\"transaction\"", "1337"}); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.Completed", 3)); } /** * Expect that the number of payment method suggestions was logged properly. */ @Test @MediumTest @Feature({"Payments"}) public void testNumberOfSuggestionsShown_PaymentMethod_AbortedByUser() throws InterruptedException, TimeoutException { // Add two credit cards. createTestData(); // Add a complete payment app. mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); // Wait for the histograms to be logged. Thread.sleep(200); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.UserAborted", 3)); } /** * Expect that an incomplete payment app is not suggested to the user. */ @Test @MediumTest @Feature({"Payments"}) public void testNumberOfSuggestionsShown_PaymentMethod_InvalidPaymentApp() throws InterruptedException, TimeoutException { // Add two credit cards. createTestData(); // Add an incomplete payment app. mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.NO_APPS, FactorySpeed.FAST_FACTORY); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); Thread.sleep(200); // Make sure only the two credit card suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.UserAborted", 2)); } /** * Expect that the number of contact info suggestions was logged properly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testNumberOfSuggestionsShown_ContactInfo_Completed() throws TimeoutException { createTestData(); // Complete a Payment Request with a credit card. mPaymentRequestTestRule.triggerUIAndWait( "contactInfoBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait( R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2)); } /** * Expect that the number of contact info suggestions was logged properly. */ @Test @MediumTest @Feature({"Payments"}) @FlakyTest(message = "https://crbug.com/1197578") public void testNumberOfSuggestionsShown_ContactInfo_AbortedByUser() throws InterruptedException, TimeoutException { createTestData(); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "contactInfoBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); // Wait for the histograms to be logged. Thread.sleep(200); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 2)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserHadCompleteSuggestions_ShippingAndPayment() throws TimeoutException { // Add two addresses and two cards. createTestData(); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.AVAILABLE_METHOD_BASIC_CARD; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserDidNotHaveCompleteSuggestions_ShippingAndPayment_IncompleteShipping() throws TimeoutException { // Add a card and an incomplete address (no region). AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", /*region=*/"", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "4111111111111111", "1111", "12", "2050", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "ccBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. Since the added credit card is using the same // incomplete profile for billing address, NEEDS_COMPLETION_PAYMENT is also set. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.AVAILABLE_METHOD_BASIC_CARD | Event.NEEDS_COMPLETION_PAYMENT | Event.NEEDS_COMPLETION_SHIPPING; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserDidNotHaveCompleteSuggestions_ShippingAndPayment_IncompleteCard() throws TimeoutException { // Add an incomplete card (no exp date) and an complete address. AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, /*cardholderName=*/"", "4111111111111111", "1111", "10", "2021", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "ccBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.AVAILABLE_METHOD_BASIC_CARD | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) @CommandLineFlags.Add("disable-features=StrictHasEnrolledAutofillInstrument") public void testUserDidNotHaveCompleteSuggestions_ShippingAndPayment_UnsupportedCard() throws TimeoutException { // Add an unsupported card (mastercard) and an complete address. AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "5187654321098765", "8765", "10", "2021", "mastercard", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "ccBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) @CommandLineFlags.Add("disable-features=StrictHasEnrolledAutofillInstrument") public void testUserDidNotHaveCompleteSuggestions_ShippingAndPayment_OnlyPaymentApp() throws TimeoutException { // Add a complete address and a working payment app. AutofillTestHelper mHelper = new AutofillTestHelper(); mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "ccBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @Feature({"Payments"}) @CommandLineFlags.Add("disable-features=StrictHasEnrolledAutofillInstrument") public void testUserDidNotHaveCompleteSuggestions_PaymentApp_NoApps() throws TimeoutException { // Add an address and a factory without apps. AutofillTestHelper mHelper = new AutofillTestHelper(); mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.NO_APPS, FactorySpeed.FAST_FACTORY); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @Feature({"Payments"}) public void testUserHadCompleteSuggestions_PaymentApp_HasValidPaymentApp() throws TimeoutException { // Add an address and a payment app on file. AutofillTestHelper mHelper = new AutofillTestHelper(); mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.AVAILABLE_METHOD_OTHER; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the metric that records whether the user had complete suggestions for the * requested information is logged correctly. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserHadCompleteSuggestions_ShippingAndPaymentApp_HasInvalidShipping() throws TimeoutException { // Add a card and an incomplete address (no region). AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", /*region=*/"", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "4111111111111111", "1111", "12", "2050", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); // Cancel the payment request. mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. Since the added credit card is using the same // incomplete profile, NEEDS_COMPLETION_PAYMENT is also set. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.NEEDS_COMPLETION_PAYMENT | Event.AVAILABLE_METHOD_BASIC_CARD | Event.NEEDS_COMPLETION_SHIPPING; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the UserHadCompleteSuggestions histogram gets logged properly when the user has * at least one credit card on file. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserHadCompleteSuggestions_AcceptsCardsAndApps_UserHasOnlyCard() throws TimeoutException { // Add an address and a credit card on file. AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "4111111111111111", "1111", "12", "2050", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); // The user cancels the Payment Request (trigger the logs). mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.AVAILABLE_METHOD_BASIC_CARD; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the UserHadCompleteSuggestions histogram gets logged properly when the user has * at least one payment app on file. */ @Test @MediumTest @Feature({"Payments"}) public void testUserHadCompleteSuggestions_AcceptsCardsAndApps_UserHasOnlyPaymentApp() throws TimeoutException { // Add an address and a payment app on file. AutofillTestHelper mHelper = new AutofillTestHelper(); mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); // The user cancels the Payment Request (trigger the logs). mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.AVAILABLE_METHOD_OTHER; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the UserHadCompleteSuggestions histogram gets logged properly when the user has * at both a card and a payment app on file. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testUserHadCompleteSuggestions_AcceptsCardsAndApps_UserHasCardAndPaymentApp() throws TimeoutException { // Add an address, a credit card and a payment app on file. AutofillTestHelper mHelper = new AutofillTestHelper(); String mBillingAddressId = mHelper.setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mHelper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Jon Doe", "4111111111111111", "1111", "12", "2050", "visa", R.drawable.visa_card, mBillingAddressId, "" /* serverId */)); mPaymentRequestTestRule.addPaymentAppFactory( AppPresence.HAVE_APPS, FactorySpeed.FAST_FACTORY); mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyToPay()); // The user cancels the Payment Request (trigger the logs). mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.AVAILABLE_METHOD_BASIC_CARD | Event.AVAILABLE_METHOD_OTHER; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that the UserDidNotHaveInitialFormOfPayment histogram gets logged properly when the * user has no form of payment on file. */ @Test @MediumTest @Feature({"Payments"}) @CommandLineFlags.Add("disable-features=StrictHasEnrolledAutofillInstrument") public void testUserDidNotHaveCompleteSuggestions_AcceptsCardsAndApps_NoCardOrPaymentApp() throws TimeoutException { // Add an address on file. new AutofillTestHelper().setProfile(new AutofillProfile("", "https://example.com", true, "" /* honorific prefix */, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", "US", "650-253-0000", "", "en-US")); mPaymentRequestTestRule.triggerUIAndWait( "cardsAndBobPayBuy", mPaymentRequestTestRule.getReadyForInput()); // The user cancels the Payment Request (trigger the logs). mPaymentRequestTestRule.clickAndWait( R.id.close_button, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains( new String[] {"User closed the Payment Request UI."}); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.USER_ABORTED | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.REQUEST_METHOD_OTHER | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that no metric for contact info has been logged. */ @Test @MediumTest @FlakyTest(message = "crbug.com/1182234") @Feature({"Payments"}) public void testNoContactInfoHistogram() throws TimeoutException { createTestData(); // Complete a Payment Request with a credit card. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait( R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); // Make sure nothing was logged for contact info. Assert.assertEquals(0, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2)); } /** * Expect that that the journey metrics are logged correctly on a second consecutive payment * request. */ @Test @MediumTest @Feature({"Payments"}) public void testTwoTimes() throws TimeoutException { createTestData(); // Complete a Payment Request with a credit card. mPaymentRequestTestRule.triggerUIAndWait("ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait( R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); // Make sure the right number of suggestions were logged. Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2)); // Complete a second Payment Request with a credit card. mPaymentRequestTestRule.reTriggerUIAndWait( "ccBuy", mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput()); mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait( R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); // Make sure the right number of suggestions were logged. Assert.assertEquals(2, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2)); // Make sure the events were logged correctly. int expectedSample = Event.SHOWN | Event.COMPLETED | Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_BASIC_CARD | Event.HAD_INITIAL_FORM_OF_PAYMENT | Event.HAD_NECESSARY_COMPLETE_SUGGESTIONS | Event.RECEIVED_INSTRUMENT_DETAILS | Event.PAY_CLICKED | Event.AVAILABLE_METHOD_BASIC_CARD | Event.SELECTED_CREDIT_CARD; Assert.assertEquals(2, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); } /** * Expect that only some journey metrics are logged if the payment request was not shown to the * user. */ @Test @MediumTest @Feature({"Payments"}) public void testNoShow() throws TimeoutException { // Android Pay has a factory but it does not return an app. mPaymentRequestTestRule.addPaymentAppFactory( "https://android.com/pay", AppPresence.NO_APPS, FactorySpeed.SLOW_FACTORY); mPaymentRequestTestRule.openPageAndClickNodeAndWait( "androidPayBuy", mPaymentRequestTestRule.getShowFailed()); mPaymentRequestTestRule.expectResultContains( new String[] {"The payment method", "not supported"}); // Make sure that no journey metrics were logged. Assert.assertEquals(0, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2)); Assert.assertEquals(0, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.OtherAborted", 2)); Assert.assertEquals(0, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2)); } }
nwjs/chromium.src
chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java
Java
bsd-3-clause
39,574
package com.xxmicloxx.znetworklib.packet.ext; import com.xxmicloxx.znetworklib.codec.CodecResult; import com.xxmicloxx.znetworklib.codec.PacketReader; import com.xxmicloxx.znetworklib.codec.PacketWriter; import com.xxmicloxx.znetworklib.codec.Request; /** * Created by ml on 04.07.14. */ public class GetChildServersRequest implements Request { private String nameMatcher; private String typeMatcher; public String getNameMatcher() { return nameMatcher; } public void setNameMatcher(String nameMatcher) { this.nameMatcher = nameMatcher; } public String getTypeMatcher() { return typeMatcher; } public void setTypeMatcher(String typeMatcher) { this.typeMatcher = typeMatcher; } @Override public com.xxmicloxx.znetworklib.codec.CodecResult write(PacketWriter writer) { writer.writeString(nameMatcher); writer.writeString(typeMatcher); return CodecResult.OK; } @Override public com.xxmicloxx.znetworklib.codec.CodecResult read(PacketReader reader) { nameMatcher = reader.readString(); typeMatcher = reader.readString(); return CodecResult.OK; } }
FuseMCNetwork/ZNetwork
ZNetworkLib/src/main/java/com/xxmicloxx/znetworklib/packet/ext/GetChildServersRequest.java
Java
bsd-3-clause
1,198
/* * BSD License (http://lemurproject.org/galago-license) */ package org.lemurproject.galago.utility; import org.junit.Assert; import org.junit.Test; import org.lemurproject.galago.utility.json.JSONUtil; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.*; import static org.junit.Assert.*; /** * * @author irmarc */ public class ParametersTest { @Test public void testCreation() { Parameters p = Parameters.create(); assertNotNull(p); } @Test public void testNumberInput() throws IOException { Parameters input = Parameters.parseString("{\"a\": +17, \"b\": -17, \"c\": +14.0, \"d\": -14.0}"); assertEquals(17, input.getInt("a")); assertEquals(-17, input.getInt("b")); assertEquals(14.0, input.getDouble("c"), 1e-7); assertEquals(-14.0, input.getDouble("d"), 1e-7); } @Test public void testGetAsDouble() throws IOException { Parameters input = Parameters.parseString("{\"a\": \"NaN\", \"b\": \"-Infinity\", \"c\": \"-17.7\"}"); assertTrue(Double.isNaN(input.getAsDouble("a"))); assertTrue(Double.isInfinite(input.getAsDouble("b"))); assertTrue(input.getAsDouble("b")<0.0); assertEquals(-17.7, input.getAsDouble("c"), 1e-7); assertEquals("-17.7", input.getString("c")); } @Test public void testAddSimpleData() { Parameters p = Parameters.create(); // add boolean data p.set("testa", false); assertTrue(p.isBoolean("testa")); assertFalse(p.getBoolean("testa")); p.setIfMissing("testa", true); assertTrue(p.isBoolean("testa")); assertFalse(p.getBoolean("testa")); // remove p.remove("testa"); assertFalse(p.isBoolean("testa")); // add long data p.set("t3", 50); assertTrue(p.isLong("t3")); assertEquals(50L, p.getLong("t3")); assertEquals(50, (int) p.getLong("t3")); // add double data p.set("tf", Math.PI); assertTrue(p.isDouble("tf")); assertFalse(p.isLong("tf")); assertFalse(p.isMap("tf")); assertEquals(Math.PI, p.getDouble("tf"), 0.001); // add String data p.set("str", "TestString"); assertTrue(p.isString("str")); assertFalse(p.isLong("str")); assertEquals("TestString", p.getString("str")); } @Test public void testPutIfNotNull() { Parameters p = Parameters.create(); p.putIfNotNull("abcd", null); assertEquals(0, p.size()); assertFalse(p.containsKey("abcd")); p.putIfNotNull(null, "foo"); assertEquals(0, p.size()); p.putIfNotNull("foo", "bar"); assertEquals("bar", p.getString("foo")); } @Test public void testAddLists() throws Exception { ArrayList<String> a = new ArrayList<>(); a.add("woot"); a.add("yeah"); Parameters p = Parameters.create(); p.set("list", a); assertTrue(p.isList("list")); assertTrue(p.isList("list", String.class)); assertFalse(p.isList("list", Parameters.class)); List<String> recv = p.getList("list", String.class); assertEquals("woot", recv.get(0)); assertEquals("yeah", recv.get(1)); p.remove("list"); assertFalse(p.isList("list")); } @Test public void testAddParameters() throws Exception { Parameters inner = Parameters.create(); inner.set("ib", true); inner.set("ii", 5L); assertEquals(true, inner.getBoolean("ib")); assertEquals(5L, inner.getLong("ii")); Parameters outer = Parameters.create(); outer.set("inside", inner); assertTrue(outer.isMap("inside")); Parameters recv = outer.getMap("inside"); assertEquals(true, recv.getBoolean("ib")); } @Test public void testWritingAndReading() throws IOException { File tempPath = null; try { Parameters tokenizer = Parameters.create(); Parameters formats = Parameters.create(); formats.set("title", "string"); formats.set("date", "date"); formats.set("version", "int"); tokenizer.set("formats", formats); String[] fields = {"title", "date", "version"}; tokenizer.set("fields", Arrays.asList(fields)); Parameters params = Parameters.create(); // MCZ 3/21/2014 - made platform independent params.set("filename", "fictional" + File.separatorChar + "path"); params.set("tokenizer", tokenizer); tempPath = File.createTempFile("parametersTest", ".json"); params.write(tempPath.getAbsolutePath() ); // Now read it in. Parameters newParams = Parameters.parseFile(tempPath); assertEquals(params.toString(), newParams.toString()); assertEquals(params, newParams); Parameters fromStringPath = Parameters.parseFile(tempPath.getAbsolutePath()); assertEquals(params.toString(), fromStringPath.toString()); assertEquals(params, fromStringPath); } finally { if (tempPath != null) { Assert.assertTrue(tempPath.delete()); } } } @Test public void testParseAndGenerateParameters() throws Exception { StringBuilder json = new StringBuilder(); json.append("{ \"inner\" : { \"inner1\" : 1 , \"inner2\" : \"jackal\" } "); json.append(", \"key1\" : true "); json.append(", \"key2\" : false , \"key3\" : null "); json.append(", \"key4\" : [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] , \"key5\" : -4.56 }"); Parameters p = Parameters.parseString(json.toString()); assertTrue(p.isBoolean("key1")); assertTrue(p.getBoolean("key1")); assertTrue(p.isBoolean("key2")); assertFalse(p.getBoolean("key2")); assertTrue(p.getString("key3") == null); assertTrue(p.isList("key4")); List l = p.getList("key4"); for (int i = 0; i < l.size(); i++) { assertEquals((long) i, ((Long) l.get(i)).longValue()); } String output = p.toString(); assertEquals(output, json.toString()); Parameters clone = p.clone(); assertEquals(p.toString(), clone.toString()); } @Test public void testPrettyPrinter() throws Exception { Parameters tokenizer = Parameters.create(); Parameters formats = Parameters.create(); formats.set("title", "string"); formats.set("date", "date"); formats.set("version", "int"); tokenizer.set("formats", formats); String[] fields = {"title", "date", "version"}; tokenizer.set("fields", Arrays.asList(fields)); ArrayList<Parameters> pList = new ArrayList<>(); pList.add(Parameters.parseString("{\"text\":\"query text one\", \"number\":\"10\"}")); pList.add(Parameters.parseString("{\"text\":\"query text two\", \"number\":\"11\"}")); Parameters params = Parameters.create(); params.set("filename", "fictional/path"); params.set("tokenizer", tokenizer); params.set("paramList", pList); String prettyString = params.toPrettyString(); Parameters reParsed = Parameters.parseString(prettyString); assert (reParsed.equals(params)); } @Test public void testInHashMap() { assertEquals(Parameters.parseArray("key", 1), Parameters.parseArray("key", 1)); assertNotEquals(Parameters.parseArray("key", 2), Parameters.parseArray("key", 1)); assertNotEquals(Parameters.parseArray("key2", 1), Parameters.parseArray("key", 1)); HashMap<Parameters, Integer> counts = new HashMap<>(); for (int item : Arrays.asList(10, 20, 30, 10, 20, 40)) { Parameters key = Parameters.create(); key.put("key", item); int prev = counts.getOrDefault(key, 0); counts.put(key, prev+1); } System.out.println(counts); assertEquals(2, counts.getOrDefault(Parameters.parseArray("key", 10), -1).intValue()); assertEquals(2, counts.getOrDefault(Parameters.parseArray("key", 20), -1).intValue()); assertEquals(1, counts.getOrDefault(Parameters.parseArray("key", 30), -1).intValue()); assertEquals(1, counts.getOrDefault(Parameters.parseArray("key", 40), -1).intValue()); } @Test public void testTrailingCommas() throws Exception { Parameters test = Parameters.parseString(" { \"foo\" : [1, 2,3,\t],\n}"); assertTrue(test.isList("foo")); assertEquals(3, test.getList("foo").size()); } @Test public void testParseMap() { Map<String,String> data = new HashMap<>(); data.put("keyA", "0"); data.put("keyB", "1"); Parameters test = Parameters.parseMap(data); assertEquals(0, test.getLong("keyA")); assertEquals(1, test.getLong("keyB")); assertEquals("0", test.getAsString("keyA")); assertEquals("1", test.getAsString("keyB")); assertEquals(data.size(), test.size()); } @Test public void testWriteAndRead() throws IOException { Parameters truth = complicated(); Parameters same0 = Parameters.parseReader(new StringReader(truth.toString())); assertEquals(truth.toString(), same0.toString()); assertEquals(truth, same0); Parameters same1 = Parameters.parseString(same0.toString()); assertEquals(truth.toString(), same1.toString()); assertEquals(truth, same1); } @Test public void testCopyTo() throws IOException { Parameters truth = complicated(); Parameters newP = Parameters.create(); truth.copyTo(newP); assertEquals(truth.toString(), newP.toString()); assertEquals(truth, newP); } @Test public void testEscaping() throws IOException { Parameters truth = Parameters.create(); truth.set("withAQuote!", "here it comes \" to wreck the day..."); truth.set("withANewline!", "here it comes \n to wreck the day..."); truth.set("withABackslash!", "here it comes \\ to wreck the day..."); truth.set("too much!", "\\\r\n\t\b\f \\hmm\\ \f\b\n\r\\"); truth.set("C:\\", "busted keys \f\b\n\r\\"); Parameters same = Parameters.parseString(truth.toString()); for(String key : truth.keySet()) { assertEquals(truth.get(key), same.get(key)); } } @Test public void testBackoff() { Parameters theBack = complicated(); Parameters theFront = Parameters.create(); theFront.setBackoff(theBack); assertEquals(theBack.toString(), theFront.toString()); assertEquals(theFront.getBackoff(), theBack); assertSame(theFront.getBackoff(), theBack); } @Test public void testENotation() throws IOException { Parameters test = Parameters.parseString("{ \"foo\": -1.0E-10 }"); assertNotNull(test); assertEquals(test.getDouble("foo"), -1.0e-10, 1e-12); } @Test public void testVarargs() { Parameters p = Parameters.parseArray("foo", 17, "bar", true, "baz", Arrays.asList(1L,2L,3L,4L)); assertNotNull(p); assertEquals(17, p.getLong("foo")); assertEquals(true, p.getBoolean("bar")); List<Long> baz = p.getList("baz", Long.class); assertEquals(4, baz.size()); assertEquals(1, baz.get(0).longValue()); assertEquals(2, baz.get(1).longValue()); assertEquals(3, baz.get(2).longValue()); assertEquals(4, baz.get(3).longValue()); } @Test public void testUnicode() throws IOException { String testShort = "Eating a piece of \u03c0 (pi)"; assertEquals("Eating a piece of \\u03c0 (pi)", JSONUtil.escape(testShort)); String testLong = "I stole this guy from wikipedia: \ud83d\ude02"; // emoji "face with tears of joy" assertEquals("I stole this guy from wikipedia: \\ud83d\\ude02", JSONUtil.escape(testLong)); Parameters p = Parameters.create(); p.set("short", testShort); p.set("long", testLong); Parameters p2 = Parameters.parseString(p.toString()); assertEquals(p.getString("short"), p2.getString("short")); assertEquals(p.getString("long"), p2.getString("long")); } public static Parameters complicated() { Parameters p = Parameters.create(); p.set("bool-t", true); p.set("bool-f", false); p.set("long-a", 120L); p.set("long-b", 0xdeadbeefL); p.set("double-pi", Math.PI); p.set("double-neg-e", -Math.exp(1)); p.set("list-a", Arrays.asList(true, false, "bar", "foo", Math.PI, -Math.exp(1), p.clone())); p.set("list-b", Collections.EMPTY_LIST); p.set("map-a", p.clone()); p.set("map-b", Parameters.create()); assertEquals(p, p.clone()); assertEquals(p.hashCode(), p.clone().hashCode()); return p; } @Test public void testPrettyPrint() { Parameters test = Parameters.parseArray("foo", Parameters.parseArray("bar", "baz")); String data = test.toPrettyString("#"); String expected = "#{\n" + "# \"foo\" : {\n" + "# \"bar\" : \"baz\"\n" + "# }\n" + "#}"; assertEquals(expected, data); } @Test public void unfinishedStr() throws IOException { try { Parameters.parseString("{\"ids\":[\"where's my ending quote? - used to cause an Out of Memory error!"); fail("Expected error."); } catch (IOException e) { assertNotNull(e); } } }
jjfiv/galago-git
utility/src/test/java/org/lemurproject/galago/utility/ParametersTest.java
Java
bsd-3-clause
12,669