lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
501e05f1a1225dfbcc16bf4d2c0d86e55d4a928e
0
gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger
/* * 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.ranger.solr; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.apache.log4j.Logger; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SortField; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SolrUtil { private static final Logger logger = Logger.getLogger(SolrUtil.class); @Autowired RESTErrorUtil restErrorUtil; @Autowired StringUtil stringUtil; SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); public SolrUtil() { String timeZone = PropertiesUtil.getProperty("xa.solr.timezone"); if (timeZone != null) { logger.info("Setting timezone to " + timeZone); try { dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); } catch (Throwable t) { logger.error("Error setting timezone. TimeZone = " + timeZone); } } } public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) throws Throwable { if (solrQuery != null) { QueryResponse response = null; try { response = solrClient.query(solrQuery, METHOD.POST); return response; } catch (Throwable e) { logger.error("Error from Solr server. ", e); throw e; } } return null; } public QueryResponse searchResources(SearchCriteria searchCriteria, List<SearchField> searchFields, List<SortField> sortFieldList, SolrClient solrClient) { SolrQuery query = new SolrQuery(); query.setQuery("*:*"); if (searchCriteria.getParamList() != null) { // For now assuming there is only date field where range query will // be done. If we there are more than one, then we should create a // hashmap for each field name Date fromDate = null; Date toDate = null; String dateFieldName = null; for (SearchField searchField : searchFields) { Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); if (paramValue == null || paramValue.toString().isEmpty()) { continue; } String fieldName = searchField.getFieldName(); if (paramValue instanceof Collection) { String fq = orList(fieldName, (Collection<?>) paramValue); if (fq != null) { query.addFilterQuery(fq); } } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { if (!(paramValue instanceof Date)) { logger.error("Search field is not a Java Date Object, paramValue = " + paramValue); } else { if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { fromDate = (Date) paramValue; dateFieldName = fieldName; } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { toDate = (Date) paramValue; dateFieldName = fieldName; } } } else if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { //NOPMD // TODO: Need to handle range here } else { String fq = setField(fieldName, paramValue); if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { fq = setFieldForPartialSearch(fieldName, paramValue); } if (fq != null) { query.addFilterQuery(fq); } } } if (fromDate != null || toDate != null) { String fq = setDateRange(dateFieldName, fromDate, toDate); if (fq != null) { query.addFilterQuery(fq); } } } setSortClause(searchCriteria, sortFieldList, query); query.setStart(searchCriteria.getStartIndex()); query.setRows(searchCriteria.getMaxRows()); // Fields to get // query.setFields("myClassType", "id", "score", "globalId"); if (logger.isDebugEnabled()) { logger.debug("SOLR QUERY = " + query); } QueryResponse response = null; try { response = runQuery(solrClient, query); } catch (Throwable e) { logger.error("Error running solr query. Query = " + query + ", response = " + response); throw restErrorUtil.createRESTException( "Error running solr query, please check solr configs. " + e.getMessage(), MessageEnums.ERROR_SYSTEM); } if (response == null || response.getStatus() != 0) { logger.error("Error running solr query. Query = " + query + ", response = " + response); throw restErrorUtil.createRESTException( "Unable to connect to Audit store !!", MessageEnums.ERROR_SYSTEM); } return response; } private String setFieldForPartialSearch(String fieldName, Object value) { if (value == null || value.toString().trim().length() == 0) { return null; } return fieldName + ":*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*"; } public String setField(String fieldName, Object value) { if (value == null || value.toString().trim().length() == 0) { return null; } return fieldName + ":" + ClientUtils.escapeQueryChars(value.toString().trim() .toLowerCase()); } public String setDateRange(String fieldName, Date fromDate, Date toDate) { String fromStr = "*"; String toStr = "NOW"; if (fromDate != null) { fromStr = dateFormat.format(fromDate); } if (toDate != null) { toStr = dateFormat.format(toDate); } return fieldName + ":[" + fromStr + " TO " + toStr + "]"; } public String orList(String fieldName, Collection<?> valueList) { if (valueList == null || valueList.isEmpty()) { return null; } String expr = ""; int count = -1; for (Object value : valueList) { count++; if (count > 0) { expr += " OR "; } expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString() .toLowerCase()); } if (valueList.isEmpty()) { return expr; } else { return "(" + expr + ")"; } } public String andList(String fieldName, Collection<?> valueList) { if (valueList == null || valueList.isEmpty()) { return null; } String expr = ""; int count = -1; for (Object value : valueList) { count++; if (count > 0) { expr += " AND "; } expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString() .toLowerCase()); } if (valueList.isEmpty()) { return expr; } else { return "(" + expr + ")"; } } public void setSortClause(SearchCriteria searchCriteria, List<SortField> sortFields, SolrQuery query) { // TODO: We are supporting single sort field only for now String sortBy = searchCriteria.getSortBy(); String querySortBy = null; if (!stringUtil.isEmpty(sortBy)) { sortBy = sortBy.trim(); for (SortField sortField : sortFields) { if (sortBy.equalsIgnoreCase(sortField.getParamName())) { querySortBy = sortField.getFieldName(); // Override the sortBy using the normalized value searchCriteria.setSortBy(sortField.getParamName()); break; } } } if (querySortBy == null) { for (SortField sortField : sortFields) { if (sortField.isDefault()) { querySortBy = sortField.getFieldName(); // Override the sortBy using the default value searchCriteria.setSortBy(sortField.getParamName()); searchCriteria.setSortType(sortField.getDefaultOrder() .name()); break; } } } if (querySortBy != null) { // Add sort type String sortType = searchCriteria.getSortType(); ORDER order = ORDER.asc; if (sortType != null && "desc".equalsIgnoreCase(sortType)) { order = ORDER.desc; } query.addSort(querySortBy, order); } } // Utility methods public int toInt(Object value) { if (value == null) { return 0; } if (value instanceof Integer) { return (Integer) value; } if (value.toString().isEmpty()) { return 0; } try { return Integer.valueOf(value.toString()); } catch (Throwable t) { logger.error("Error converting value to integer. Value = " + value, t); } return 0; } public long toLong(Object value) { if (value == null) { return 0; } if (value instanceof Long) { return (Long) value; } if (value.toString().isEmpty()) { return 0; } try { return Long.valueOf(value.toString()); } catch (Throwable t) { logger.error("Error converting value to long. Value = " + value, t); } return 0; } public Date toDate(Object value) { if (value == null) { return null; } if (value instanceof Date) { return (Date) value; } try { // TODO: Do proper parsing based on Solr response value return new Date(value.toString()); } catch (Throwable t) { logger.error("Error converting value to date. Value = " + value, t); } return null; } }
security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ranger.solr; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.apache.log4j.Logger; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SortField; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SolrUtil { private static final Logger logger = Logger.getLogger(SolrUtil.class); @Autowired RESTErrorUtil restErrorUtil; @Autowired StringUtil stringUtil; SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); public SolrUtil() { String timeZone = PropertiesUtil.getProperty("xa.solr.timezone"); if (timeZone != null) { logger.info("Setting timezone to " + timeZone); try { dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); } catch (Throwable t) { logger.error("Error setting timezone. timeZone=" + timeZone); } } } public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) { if (solrQuery != null) { QueryResponse response; try { response = solrClient.query(solrQuery, METHOD.POST); return response; } catch (Throwable e) { logger.error("Error from Solr server.", e); } } return null; } public QueryResponse searchResources(SearchCriteria searchCriteria, List<SearchField> searchFields, List<SortField> sortFieldList, SolrClient solrClient) { SolrQuery query = new SolrQuery(); query.setQuery("*:*"); if (searchCriteria.getParamList() != null) { // For now assuming there is only date field where range query will // be done. If we there are more than one, then we should create a // hashmap for each field name Date fromDate = null; Date toDate = null; String dateFieldName = null; for (SearchField searchField : searchFields) { Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); if (paramValue == null || paramValue.toString().isEmpty()) { continue; } String fieldName = searchField.getFieldName(); if (paramValue instanceof Collection) { String fq = orList(fieldName, (Collection<?>) paramValue); if (fq != null) { query.addFilterQuery(fq); } } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { if (!(paramValue instanceof Date)) { logger.error("Search field is not a Java Date Object, paramValue=" + paramValue); } else { if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { fromDate = (Date) paramValue; dateFieldName = fieldName; } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { toDate = (Date) paramValue; dateFieldName = fieldName; } } } else if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { //NOPMD // TODO: Need to handle range here } else { String fq = setField(fieldName, paramValue); if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { fq = setFieldForPartialSearch(fieldName, paramValue); } if (fq != null) { query.addFilterQuery(fq); } } } if (fromDate != null || toDate != null) { String fq = setDateRange(dateFieldName, fromDate, toDate); if (fq != null) { query.addFilterQuery(fq); } } } setSortClause(searchCriteria, sortFieldList, query); query.setStart(searchCriteria.getStartIndex()); query.setRows(searchCriteria.getMaxRows()); // Fields to get // query.setFields("myClassType", "id", "score", "globalId"); if (logger.isDebugEnabled()) { logger.debug("SOLR QUERY=" + query); } QueryResponse response = runQuery(solrClient, query); if (response == null || response.getStatus() != 0) { logger.error("Unable to connect to Audit store!! Error running query. query=" + query + ", response=" + response); throw restErrorUtil.createRESTException("Unable to connect to Audit store !!", MessageEnums.ERROR_SYSTEM); } return response; } private String setFieldForPartialSearch(String fieldName, Object value) { if (value == null || value.toString().trim().length() == 0) { return null; } return fieldName + ":*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*"; } public String setField(String fieldName, Object value) { if (value == null || value.toString().trim().length() == 0) { return null; } return fieldName + ":" + ClientUtils.escapeQueryChars(value.toString().trim() .toLowerCase()); } public String setDateRange(String fieldName, Date fromDate, Date toDate) { String fromStr = "*"; String toStr = "NOW"; if (fromDate != null) { fromStr = dateFormat.format(fromDate); } if (toDate != null) { toStr = dateFormat.format(toDate); } return fieldName + ":[" + fromStr + " TO " + toStr + "]"; } public String orList(String fieldName, Collection<?> valueList) { if (valueList == null || valueList.isEmpty()) { return null; } String expr = ""; int count = -1; for (Object value : valueList) { count++; if (count > 0) { expr += " OR "; } expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString() .toLowerCase()); } if (valueList.isEmpty()) { return expr; } else { return "(" + expr + ")"; } } public String andList(String fieldName, Collection<?> valueList) { if (valueList == null || valueList.isEmpty()) { return null; } String expr = ""; int count = -1; for (Object value : valueList) { count++; if (count > 0) { expr += " AND "; } expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString() .toLowerCase()); } if (valueList.isEmpty()) { return expr; } else { return "(" + expr + ")"; } } public void setSortClause(SearchCriteria searchCriteria, List<SortField> sortFields, SolrQuery query) { // TODO: We are supporting single sort field only for now String sortBy = searchCriteria.getSortBy(); String querySortBy = null; if (!stringUtil.isEmpty(sortBy)) { sortBy = sortBy.trim(); for (SortField sortField : sortFields) { if (sortBy.equalsIgnoreCase(sortField.getParamName())) { querySortBy = sortField.getFieldName(); // Override the sortBy using the normalized value searchCriteria.setSortBy(sortField.getParamName()); break; } } } if (querySortBy == null) { for (SortField sortField : sortFields) { if (sortField.isDefault()) { querySortBy = sortField.getFieldName(); // Override the sortBy using the default value searchCriteria.setSortBy(sortField.getParamName()); searchCriteria.setSortType(sortField.getDefaultOrder() .name()); break; } } } if (querySortBy != null) { // Add sort type String sortType = searchCriteria.getSortType(); ORDER order = ORDER.asc; if (sortType != null && "desc".equalsIgnoreCase(sortType)) { order = ORDER.desc; } query.addSort(querySortBy, order); } } // Utility methods public int toInt(Object value) { if (value == null) { return 0; } if (value instanceof Integer) { return (Integer) value; } if (value.toString().isEmpty()) { return 0; } try { return Integer.valueOf(value.toString()); } catch (Throwable t) { logger.error("Error converting value to integer. value=" + value, t); } return 0; } public long toLong(Object value) { if (value == null) { return 0; } if (value instanceof Long) { return (Long) value; } if (value.toString().isEmpty()) { return 0; } try { return Long.valueOf(value.toString()); } catch (Throwable t) { logger.error("Error converting value to long. value=" + value, t); } return 0; } public Date toDate(Object value) { if (value == null) { return null; } if (value instanceof Date) { return (Date) value; } try { // TODO: Do proper parsing based on Solr response value return new Date(value.toString()); } catch (Throwable t) { logger.error("Error converting value to date. value=" + value, t); } return null; } }
RANGER-1548 : Display detailed error messages in Ranger for Audit store issues Signed-off-by: Gautam Borad <37ab8904fb87b483c21dc0dd34f038b995f85196@apache.org>
security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java
RANGER-1548 : Display detailed error messages in Ranger for Audit store issues
Java
apache-2.0
27197303051813c49f669fd19409f9d86d429804
0
maduhu/head,jpodeszwik/mifos,vorburger/mifos-head,maduhu/mifos-head,maduhu/mifos-head,AArhin/head,maduhu/head,maduhu/head,AArhin/head,maduhu/mifos-head,vorburger/mifos-head,maduhu/head,AArhin/head,maduhu/mifos-head,jpodeszwik/mifos,jpodeszwik/mifos,AArhin/head,jpodeszwik/mifos,maduhu/head,maduhu/mifos-head,vorburger/mifos-head,vorburger/mifos-head,AArhin/head
/** * TestAccountBO.java version: 1.0 * Copyright (c) 2005-2006 Grameen Foundation USA * 1029 Vermont Avenue, NW, Suite 400, Washington DC 20005 * All rights reserved. * Apache License * Copyright (c) 2005-2006 Grameen Foundation USA * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an explanation of the license * and how it is applied. * */ package org.mifos.application.accounts.business; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.HibernateException; import org.mifos.application.accounts.TestAccount; import org.mifos.application.accounts.exceptions.AccountException; import org.mifos.application.accounts.financial.business.FinancialTransactionBO; import org.mifos.application.accounts.loan.business.LoanBO; import org.mifos.application.accounts.loan.business.LoanTrxnDetailEntity; import org.mifos.application.accounts.util.helpers.AccountState; import org.mifos.application.accounts.util.helpers.PaymentData; import org.mifos.application.customer.center.business.CenterBO; import org.mifos.application.customer.group.business.GroupBO; import org.mifos.application.fees.business.FeeBO; import org.mifos.application.fees.util.helpers.FeeCategory; import org.mifos.application.fees.util.helpers.FeePayment; import org.mifos.application.master.persistence.MasterPersistence; import org.mifos.application.meeting.business.MeetingBO; import org.mifos.application.meeting.business.WeekDaysEntity; import org.mifos.application.meeting.util.helpers.MeetingType; import org.mifos.application.meeting.util.helpers.RecurrenceType; import org.mifos.application.meeting.util.helpers.WeekDay; import org.mifos.application.personnel.business.PersonnelBO; import org.mifos.application.personnel.persistence.PersonnelPersistence; import org.mifos.config.AccountingRules; import org.mifos.framework.TestUtils; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.SystemException; import org.mifos.framework.hibernate.helper.HibernateUtil; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.TestObjectFactory; public class TestAccountBO extends TestAccount { public static void addAccountFlag(AccountStateFlagEntity flagDetail, AccountBO account) { account.addAccountFlag(flagDetail); } /** * The name of this test, and some now-gone (and broken) * exception-catching code, make it look like it was * supposed to test failure. But it doesn't (and I don't * see a corresponding success test). */ public void testFailureRemoveFees() throws Exception { HibernateUtil.getSessionTL(); HibernateUtil.startTransaction(); UserContext uc = TestUtils.makeUser(); Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees() .getFeeId(), uc.getId()); HibernateUtil.getTransaction().commit(); } private void disburseLoan(LoanBO loan,Date startDate) throws Exception { loan.disburseLoan("receiptNum", startDate, Short.valueOf("1"), loan.getPersonnel(), startDate, Short.valueOf("1")); HibernateUtil.commitTransaction(); } public void testSuccessGetLastPmntAmntToBeAdjusted() throws Exception { LoanBO loan = accountBO; Date currentDate = new Date(System.currentTimeMillis()); Date startDate = new Date(System.currentTimeMillis()); disburseLoan(loan,startDate); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData firstPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(88), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(firstPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); // the loan has to be reloaded from db so that the payment list will be in desc order and the // last payment will be the first in the payment list loan = (LoanBO) HibernateUtil.getSessionTL().get(LoanBO.class, loan.getAccountId()); assertEquals(88.0, loan.getLastPmntAmntToBeAdjusted()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testSuccessAdjustLastPayment() throws Exception { LoanBO loan = accountBO; List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); Date currentDate = new Date(System.currentTimeMillis()); PaymentData firstPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(700), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(firstPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); PaymentData secondPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(100), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(secondPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); loan.setUserContext(TestUtils.makeUser()); try{ loan.adjustLastPayment("Payment with amount 100 has been adjusted by test code"); }catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } TestObjectFactory.updateObject(loan); /*assertEquals("The amount returned should have been 0.0", 0.0, loan.getLastPmntAmntToBeAdjusted());*/ try{ loan.adjustLastPayment("Payment with amount 700 has been adjusted by test code"); }catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } TestObjectFactory.updateObject(loan); /*assertEquals("The amount returned should have been : 0.0", 0.0, loan.getLastPmntAmntToBeAdjusted());*/ accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testSuccessUpdateAccountActionDateEntity() { List<Short> installmentIdList; installmentIdList = getApplicableInstallmentIdsForRemoveFees(accountBO); Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) { accountBO.updateAccountActionDateEntity(installmentIdList, ((AccountFeesEntity) itr.next()).getFees().getFeeId()); } // TODO: assert what? } private List<Short> getApplicableInstallmentIdsForRemoveFees( AccountBO account) { List<Short> installmentIdList = new ArrayList<Short>(); for (AccountActionDateEntity accountActionDateEntity : account .getApplicableIdsForFutureInstallments()) { installmentIdList.add(accountActionDateEntity.getInstallmentId()); } installmentIdList.add(account.getDetailsOfNextInstallment() .getInstallmentId()); return installmentIdList; } public void testSuccessUpdateAccountFeesEntity() { Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); assertEquals (1, accountFeesEntitySet.size()); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) { AccountFeesEntity accountFeesEntity = (AccountFeesEntity) itr .next(); accountBO.updateAccountFeesEntity(accountFeesEntity.getFees() .getFeeId()); assertFalse(accountFeesEntity.isActive()); } } public void testGetLastLoanPmntAmnt() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData paymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(700), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(paymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); assertEquals( "The amount returned for the payment should have been 1272", 700.0, loan.getLastPmntAmnt()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testLoanAdjustment() throws Exception { HibernateUtil.closeSession(); Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.add(loan.getAccountActionDate(Short.valueOf("1"))); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(216), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); loan.applyPaymentWithPersist(TestObjectFactory.getLoanAccountPaymentData(null, TestObjectFactory.getMoneyForMFICurrency(600), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate)); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); loan.adjustPmnt("loan account has been adjusted by test code"); TestObjectFactory.updateObject(loan); assertEquals("The amount returned for the payment should have been 0", 0.0, loan.getLastPmntAmnt()); LoanTrxnDetailEntity lastLoanTrxn = null; for (AccountTrxnEntity accntTrxn : loan.getLastPmnt().getAccountTrxns()) { lastLoanTrxn = (LoanTrxnDetailEntity) accntTrxn; break; } AccountActionDateEntity installment = loan .getAccountActionDate(lastLoanTrxn.getInstallmentId()); assertFalse( "The installment adjusted should now be marked unpaid(due).", installment.isPaid()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testAdjustmentForClosedAccnt() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setAccountState(new AccountStateEntity( AccountState.LOAN_CLOSED_OBLIGATIONS_MET)); loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(712), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.updateObject(loan); try { loan.adjustPmnt("loan account has been adjusted by test code"); fail(); } catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } } public void testRetrievalOfNullMonetaryValue() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(0), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); Set<AccountPaymentEntity> payments = loan.getAccountPayments(); assertEquals(1, payments.size()); AccountPaymentEntity accntPmnt = payments.iterator().next(); TestObjectFactory.flushandCloseSession(); assertEquals( "Account payment retrieved should be zero with currency MFI currency", TestObjectFactory.getMoneyForMFICurrency(0), accntPmnt.getAmount()); } public void testGetTransactionHistoryView() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(100), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); List<Integer> ids = new ArrayList<Integer>(); for (AccountPaymentEntity accountPaymentEntity : loan .getAccountPayments()) { for (AccountTrxnEntity accountTrxnEntity : accountPaymentEntity .getAccountTrxns()) { for (FinancialTransactionBO financialTransactionBO : accountTrxnEntity .getFinancialTransactions()) { ids.add(financialTransactionBO.getTrxnId()); } } } loan.setUserContext(TestUtils.makeUser()); List<TransactionHistoryView> trxnHistlist = loan .getTransactionHistoryView(); assertNotNull("Account TrxnHistoryView list object should not be null", trxnHistlist); assertTrue( "Account TrxnHistoryView list object Size should be greater than zero", trxnHistlist.size() > 0); assertEquals(ids.size(), trxnHistlist.size()); int i = 0; for (TransactionHistoryView transactionHistoryView : trxnHistlist) { assertEquals(ids.get(i), transactionHistoryView.getAccountTrxnId()); i++; } TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); } public void testGetTransactionHistoryViewByOtherUser() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PersonnelBO personnel = new PersonnelPersistence().getPersonnel(Short.valueOf("2")); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(100), null, personnel, "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); List<TransactionHistoryView> trxnHistlist = loan .getTransactionHistoryView(); assertNotNull("Account TrxnHistoryView list object should not be null", trxnHistlist); assertTrue( "Account TrxnHistoryView list object Size should be greater than zero", trxnHistlist.size() > 0); for (TransactionHistoryView transactionHistoryView : trxnHistlist) { assertEquals(transactionHistoryView.getPostedBy(),personnel.getDisplayName()); } TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); } public void testGetPeriodicFeeList() throws PersistenceException { FeeBO oneTimeFee = TestObjectFactory.createOneTimeAmountFee( "One Time Fee", FeeCategory.LOAN, "20", FeePayment.TIME_OF_DISBURSMENT); AccountFeesEntity accountOneTimeFee = new AccountFeesEntity(accountBO, oneTimeFee, new Double("1.0")); accountBO.addAccountFees(accountOneTimeFee); accountPersistence.createOrUpdate(accountBO); TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); assertEquals(1, accountBO.getPeriodicFeeList().size()); } public void testIsTrxnDateValid() throws Exception { Calendar calendar = new GregorianCalendar(); // Added by rajender on 24th July as test case was not passing calendar.add(Calendar.DAY_OF_MONTH, 10); java.util.Date trxnDate = new Date(calendar.getTimeInMillis()); if (AccountingRules.isBackDatedTxnAllowed()) assertTrue(accountBO.isTrxnDateValid(trxnDate)); else assertFalse(accountBO.isTrxnDateValid(trxnDate)); } public void testHandleChangeInMeetingSchedule() throws ApplicationException, SystemException { TestObjectFactory.flushandCloseSession(); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); MeetingBO meeting = center.getCustomerMeeting().getMeeting(); meeting.getMeetingDetails().getMeetingRecurrence().setWeekDay( (WeekDaysEntity) new MasterPersistence() .retrieveMasterEntity(WeekDay.THURSDAY.getValue(), WeekDaysEntity.class, null)); List<java.util.Date> meetingDates = meeting.getAllDates(accountBO .getApplicableIdsForFutureInstallments().size() + 1); TestObjectFactory.updateObject(center); center.getCustomerAccount().handleChangeInMeetingSchedule(); accountBO.handleChangeInMeetingSchedule(); HibernateUtil.getTransaction().commit(); HibernateUtil.closeSession(); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); Calendar calendar = new GregorianCalendar(); int dayOfWeek = calendar.get(calendar.DAY_OF_WEEK); if (dayOfWeek == 5) meetingDates.remove(0); for (AccountActionDateEntity actionDateEntity : center .getCustomerAccount().getAccountActionDates()) { if (actionDateEntity.getInstallmentId().equals(Short.valueOf("2"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(0).getTime())); else if (actionDateEntity.getInstallmentId().equals( Short.valueOf("3"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(1).getTime())); } for (AccountActionDateEntity actionDateEntity : accountBO .getAccountActionDates()) { if (actionDateEntity.getInstallmentId().equals(Short.valueOf("2"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(0).getTime())); else if (actionDateEntity.getInstallmentId().equals( Short.valueOf("3"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(1).getTime())); } } public void testDeleteFutureInstallments() throws HibernateException, SystemException, AccountException { TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); accountBO.deleteFutureInstallments(); HibernateUtil.getTransaction().commit(); HibernateUtil.closeSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); assertEquals(1, accountBO.getAccountActionDates().size()); } public void testUpdate() throws Exception { TestObjectFactory.flushandCloseSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); accountBO.setUserContext(TestUtils.makeUser()); java.sql.Date currentDate = new java.sql.Date(System .currentTimeMillis()); PersonnelBO personnelBO = new PersonnelPersistence() .getPersonnel(TestUtils.makeUser().getId()); AccountNotesEntity accountNotesEntity = new AccountNotesEntity( currentDate, "account updated", personnelBO, accountBO); accountBO.addAccountNotes(accountNotesEntity); TestObjectFactory.updateObject(accountBO); TestObjectFactory.flushandCloseSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); for (AccountNotesEntity accountNotes : accountBO .getRecentAccountNotes()) { assertEquals("Last note added is account updated","account updated", accountNotes.getComment()); assertEquals(currentDate.toString(),accountNotes.getCommentDateStr()); assertEquals(personnelBO.getPersonnelId(),accountNotes.getPersonnel().getPersonnelId()); assertEquals(personnelBO.getDisplayName(),accountNotes.getPersonnel().getDisplayName()); assertEquals(currentDate.toString(),accountNotes.getCommentDate().toString()); assertEquals(accountBO.getAccountId(),accountNotes.getAccount().getAccountId()); assertNotNull(accountNotes.getCommentId()); break; } } public void testGetPastInstallments() { MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory .getTypicalMeeting()); CenterBO centerBO = TestObjectFactory.createCenter("Center_Active", meeting); HibernateUtil.closeSession(); centerBO = TestObjectFactory.getObject(CenterBO.class, centerBO.getCustomerId()); for (AccountActionDateEntity actionDate : centerBO.getCustomerAccount() .getAccountActionDates()) { actionDate.setActionDate(offSetCurrentDate(4)); break; } List<AccountActionDateEntity> pastInstallments = centerBO .getCustomerAccount().getPastInstallments(); assertNotNull(pastInstallments); assertEquals(1, pastInstallments.size()); TestObjectFactory.cleanUp(centerBO); } public void testGetAllInstallments() { MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory .getTypicalMeeting()); CenterBO centerBO = TestObjectFactory.createCenter("Center_Active", meeting); HibernateUtil.closeSession(); centerBO = TestObjectFactory.getObject(CenterBO.class, centerBO.getCustomerId()); List<AccountActionDateEntity> allInstallments = centerBO .getCustomerAccount().getAllInstallments(); assertNotNull(allInstallments); assertEquals(10, allInstallments.size()); TestObjectFactory.cleanUp(centerBO); } public void testUpdatePerformanceHistoryOnAdjustment() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); PaymentData paymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(212), null, accountBO .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); accountBO.applyPaymentWithPersist(paymentData); HibernateUtil.commitTransaction(); LoanBO loan = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); loan.applyPaymentWithPersist(TestObjectFactory.getLoanAccountPaymentData(null, TestObjectFactory.getMoneyForMFICurrency(600), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate)); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); accountBO.setUserContext(TestUtils.makeUser()); accountBO.adjustPmnt("loan account has been adjusted by test code"); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); group = TestObjectFactory.getObject(GroupBO.class, group .getCustomerId()); assertEquals(1, accountBO.getPerformanceHistory().getNoOfPayments().intValue()); } public void testAccountBOClosedDate() { AccountBO account = new AccountBO(); java.util.Date originalDate = new java.util.Date(); final long TEN_SECONDS = 10000; // verify that after the setter is called, changes to the object // passed to the setter do not affect the internal state java.util.Date mutatingDate1 = (java.util.Date)originalDate.clone(); account.setClosedDate(mutatingDate1); mutatingDate1.setTime(System.currentTimeMillis()+ TEN_SECONDS); assertEquals(account.getClosedDate(), originalDate); // verify that after the getter is called, changes to the object // returned by the getter do not affect the internal state java.util.Date originalDate2 = (java.util.Date)originalDate.clone(); account.setClosedDate(originalDate2); java.util.Date mutatingDate2 = account.getClosedDate(); mutatingDate2.setTime(System.currentTimeMillis() + TEN_SECONDS); assertEquals(account.getClosedDate(), originalDate); } public void testGetInstalmentDates() throws Exception { AccountBO account = new AccountBO(); MeetingBO meeting = new MeetingBO(RecurrenceType.DAILY, (short)1, getDate("18/08/2005"), MeetingType.CUSTOMER_MEETING); /* make sure we can handle case where the number of installments is zero */ account.getInstallmentDates(meeting, (short)0, (short)0); } public static void addToAccountStatusChangeHistory(LoanBO loan, AccountStatusChangeHistoryEntity accountStatusChangeHistoryEntity) { loan.addAccountStatusChangeHistory(accountStatusChangeHistoryEntity); } private java.sql.Date offSetCurrentDate(int noOfDays) { Calendar currentDateCalendar = new GregorianCalendar(); int year = currentDateCalendar.get(Calendar.YEAR); int month = currentDateCalendar.get(Calendar.MONTH); int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH); currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays); return new java.sql.Date(currentDateCalendar.getTimeInMillis()); } }
mifos/test/org/mifos/application/accounts/business/TestAccountBO.java
/** * TestAccountBO.java version: 1.0 * Copyright (c) 2005-2006 Grameen Foundation USA * 1029 Vermont Avenue, NW, Suite 400, Washington DC 20005 * All rights reserved. * Apache License * Copyright (c) 2005-2006 Grameen Foundation USA * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an explanation of the license * and how it is applied. * */ package org.mifos.application.accounts.business; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.HibernateException; import org.mifos.application.accounts.TestAccount; import org.mifos.application.accounts.exceptions.AccountException; import org.mifos.application.accounts.financial.business.FinancialTransactionBO; import org.mifos.application.accounts.loan.business.LoanBO; import org.mifos.application.accounts.loan.business.LoanTrxnDetailEntity; import org.mifos.application.accounts.util.helpers.AccountState; import org.mifos.application.accounts.util.helpers.PaymentData; import org.mifos.application.customer.center.business.CenterBO; import org.mifos.application.customer.group.business.GroupBO; import org.mifos.application.fees.business.FeeBO; import org.mifos.application.fees.util.helpers.FeeCategory; import org.mifos.application.fees.util.helpers.FeePayment; import org.mifos.application.master.persistence.MasterPersistence; import org.mifos.application.meeting.business.MeetingBO; import org.mifos.application.meeting.business.WeekDaysEntity; import org.mifos.application.meeting.util.helpers.MeetingType; import org.mifos.application.meeting.util.helpers.RecurrenceType; import org.mifos.application.meeting.util.helpers.WeekDay; import org.mifos.application.personnel.business.PersonnelBO; import org.mifos.application.personnel.persistence.PersonnelPersistence; import org.mifos.config.AccountingRules; import org.mifos.framework.TestUtils; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.SystemException; import org.mifos.framework.hibernate.helper.HibernateUtil; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.TestObjectFactory; public class TestAccountBO extends TestAccount { public static void addAccountFlag(AccountStateFlagEntity flagDetail, AccountBO account) { account.addAccountFlag(flagDetail); } /** * The name of this test, and some now-gone (and broken) * exception-catching code, make it look like it was * supposed to test failure. But it doesn't (and I don't * see a corresponding success test). */ public void testFailureRemoveFees() throws Exception { HibernateUtil.getSessionTL(); HibernateUtil.startTransaction(); UserContext uc = TestUtils.makeUser(); Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees() .getFeeId(), uc.getId()); HibernateUtil.getTransaction().commit(); } private void disburseLoan(LoanBO loan,Date startDate) throws Exception { loan.disburseLoan("receiptNum", startDate, Short.valueOf("1"), loan.getPersonnel(), startDate, Short.valueOf("1")); HibernateUtil.commitTransaction(); } /* * TODO: fn_calc_test_fix * public void testSuccessGetLastPmntAmntToBeAdjusted() throws Exception { LoanBO loan = accountBO; Date currentDate = new Date(System.currentTimeMillis()); Date startDate = new Date(System.currentTimeMillis()); disburseLoan(loan,startDate); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData firstPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(88), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(firstPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); assertEquals(88.0, loan.getLastPmntAmntToBeAdjusted()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } */ public void testSuccessAdjustLastPayment() throws Exception { LoanBO loan = accountBO; List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); Date currentDate = new Date(System.currentTimeMillis()); PaymentData firstPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(700), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(firstPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); PaymentData secondPaymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(100), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(secondPaymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); loan.setUserContext(TestUtils.makeUser()); try{ loan.adjustLastPayment("Payment with amount 100 has been adjusted by test code"); }catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } TestObjectFactory.updateObject(loan); /*assertEquals("The amount returned should have been 0.0", 0.0, loan.getLastPmntAmntToBeAdjusted());*/ try{ loan.adjustLastPayment("Payment with amount 700 has been adjusted by test code"); }catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } TestObjectFactory.updateObject(loan); /*assertEquals("The amount returned should have been : 0.0", 0.0, loan.getLastPmntAmntToBeAdjusted());*/ accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testSuccessUpdateAccountActionDateEntity() { List<Short> installmentIdList; installmentIdList = getApplicableInstallmentIdsForRemoveFees(accountBO); Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) { accountBO.updateAccountActionDateEntity(installmentIdList, ((AccountFeesEntity) itr.next()).getFees().getFeeId()); } // TODO: assert what? } private List<Short> getApplicableInstallmentIdsForRemoveFees( AccountBO account) { List<Short> installmentIdList = new ArrayList<Short>(); for (AccountActionDateEntity accountActionDateEntity : account .getApplicableIdsForFutureInstallments()) { installmentIdList.add(accountActionDateEntity.getInstallmentId()); } installmentIdList.add(account.getDetailsOfNextInstallment() .getInstallmentId()); return installmentIdList; } public void testSuccessUpdateAccountFeesEntity() { Set<AccountFeesEntity> accountFeesEntitySet = accountBO .getAccountFees(); assertEquals (1, accountFeesEntitySet.size()); Iterator itr = accountFeesEntitySet.iterator(); while (itr.hasNext()) { AccountFeesEntity accountFeesEntity = (AccountFeesEntity) itr .next(); accountBO.updateAccountFeesEntity(accountFeesEntity.getFees() .getFeeId()); assertFalse(accountFeesEntity.isActive()); } } public void testGetLastLoanPmntAmnt() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData paymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(700), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(paymentData); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); assertEquals( "The amount returned for the payment should have been 1272", 700.0, loan.getLastPmntAmnt()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testLoanAdjustment() throws Exception { HibernateUtil.closeSession(); Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.add(loan.getAccountActionDate(Short.valueOf("1"))); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(216), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); loan.applyPaymentWithPersist(TestObjectFactory.getLoanAccountPaymentData(null, TestObjectFactory.getMoneyForMFICurrency(600), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate)); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); loan.adjustPmnt("loan account has been adjusted by test code"); TestObjectFactory.updateObject(loan); assertEquals("The amount returned for the payment should have been 0", 0.0, loan.getLastPmntAmnt()); LoanTrxnDetailEntity lastLoanTrxn = null; for (AccountTrxnEntity accntTrxn : loan.getLastPmnt().getAccountTrxns()) { lastLoanTrxn = (LoanTrxnDetailEntity) accntTrxn; break; } AccountActionDateEntity installment = loan .getAccountActionDate(lastLoanTrxn.getInstallmentId()); assertFalse( "The installment adjusted should now be marked unpaid(due).", installment.isPaid()); accountBO = TestObjectFactory.getObject(LoanBO.class, loan.getAccountId()); } public void testAdjustmentForClosedAccnt() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setAccountState(new AccountStateEntity( AccountState.LOAN_CLOSED_OBLIGATIONS_MET)); loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(712), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.updateObject(loan); try { loan.adjustPmnt("loan account has been adjusted by test code"); fail(); } catch (AccountException e) { assertEquals( "exception.accounts.ApplicationException.CannotAdjust", e.getKey()); } } public void testRetrievalOfNullMonetaryValue() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(0), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.updateObject(loan); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); Set<AccountPaymentEntity> payments = loan.getAccountPayments(); assertEquals(1, payments.size()); AccountPaymentEntity accntPmnt = payments.iterator().next(); TestObjectFactory.flushandCloseSession(); assertEquals( "Account payment retrieved should be zero with currency MFI currency", TestObjectFactory.getMoneyForMFICurrency(0), accntPmnt.getAmount()); } public void testGetTransactionHistoryView() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(100), null, loan.getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); List<Integer> ids = new ArrayList<Integer>(); for (AccountPaymentEntity accountPaymentEntity : loan .getAccountPayments()) { for (AccountTrxnEntity accountTrxnEntity : accountPaymentEntity .getAccountTrxns()) { for (FinancialTransactionBO financialTransactionBO : accountTrxnEntity .getFinancialTransactions()) { ids.add(financialTransactionBO.getTrxnId()); } } } loan.setUserContext(TestUtils.makeUser()); List<TransactionHistoryView> trxnHistlist = loan .getTransactionHistoryView(); assertNotNull("Account TrxnHistoryView list object should not be null", trxnHistlist); assertTrue( "Account TrxnHistoryView list object Size should be greater than zero", trxnHistlist.size() > 0); assertEquals(ids.size(), trxnHistlist.size()); int i = 0; for (TransactionHistoryView transactionHistoryView : trxnHistlist) { assertEquals(ids.get(i), transactionHistoryView.getAccountTrxnId()); i++; } TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); } public void testGetTransactionHistoryViewByOtherUser() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); LoanBO loan = accountBO; loan.setUserContext(TestUtils.makeUser()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); accntActionDates.addAll(loan.getAccountActionDates()); PersonnelBO personnel = new PersonnelPersistence().getPersonnel(Short.valueOf("2")); PaymentData accountPaymentDataView = TestObjectFactory .getLoanAccountPaymentData(accntActionDates, TestObjectFactory .getMoneyForMFICurrency(100), null, personnel, "receiptNum", Short.valueOf("1"), currentDate, currentDate); loan.applyPaymentWithPersist(accountPaymentDataView); TestObjectFactory.flushandCloseSession(); loan = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); loan.setUserContext(TestUtils.makeUser()); List<TransactionHistoryView> trxnHistlist = loan .getTransactionHistoryView(); assertNotNull("Account TrxnHistoryView list object should not be null", trxnHistlist); assertTrue( "Account TrxnHistoryView list object Size should be greater than zero", trxnHistlist.size() > 0); for (TransactionHistoryView transactionHistoryView : trxnHistlist) { assertEquals(transactionHistoryView.getPostedBy(),personnel.getDisplayName()); } TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, loan .getAccountId()); } public void testGetPeriodicFeeList() throws PersistenceException { FeeBO oneTimeFee = TestObjectFactory.createOneTimeAmountFee( "One Time Fee", FeeCategory.LOAN, "20", FeePayment.TIME_OF_DISBURSMENT); AccountFeesEntity accountOneTimeFee = new AccountFeesEntity(accountBO, oneTimeFee, new Double("1.0")); accountBO.addAccountFees(accountOneTimeFee); accountPersistence.createOrUpdate(accountBO); TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); assertEquals(1, accountBO.getPeriodicFeeList().size()); } public void testIsTrxnDateValid() throws Exception { Calendar calendar = new GregorianCalendar(); // Added by rajender on 24th July as test case was not passing calendar.add(Calendar.DAY_OF_MONTH, 10); java.util.Date trxnDate = new Date(calendar.getTimeInMillis()); if (AccountingRules.isBackDatedTxnAllowed()) assertTrue(accountBO.isTrxnDateValid(trxnDate)); else assertFalse(accountBO.isTrxnDateValid(trxnDate)); } public void testHandleChangeInMeetingSchedule() throws ApplicationException, SystemException { TestObjectFactory.flushandCloseSession(); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); MeetingBO meeting = center.getCustomerMeeting().getMeeting(); meeting.getMeetingDetails().getMeetingRecurrence().setWeekDay( (WeekDaysEntity) new MasterPersistence() .retrieveMasterEntity(WeekDay.THURSDAY.getValue(), WeekDaysEntity.class, null)); List<java.util.Date> meetingDates = meeting.getAllDates(accountBO .getApplicableIdsForFutureInstallments().size() + 1); TestObjectFactory.updateObject(center); center.getCustomerAccount().handleChangeInMeetingSchedule(); accountBO.handleChangeInMeetingSchedule(); HibernateUtil.getTransaction().commit(); HibernateUtil.closeSession(); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); Calendar calendar = new GregorianCalendar(); int dayOfWeek = calendar.get(calendar.DAY_OF_WEEK); if (dayOfWeek == 5) meetingDates.remove(0); for (AccountActionDateEntity actionDateEntity : center .getCustomerAccount().getAccountActionDates()) { if (actionDateEntity.getInstallmentId().equals(Short.valueOf("2"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(0).getTime())); else if (actionDateEntity.getInstallmentId().equals( Short.valueOf("3"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(1).getTime())); } for (AccountActionDateEntity actionDateEntity : accountBO .getAccountActionDates()) { if (actionDateEntity.getInstallmentId().equals(Short.valueOf("2"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(0).getTime())); else if (actionDateEntity.getInstallmentId().equals( Short.valueOf("3"))) assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity .getActionDate().getTime()), DateUtils .getDateWithoutTimeStamp(meetingDates.get(1).getTime())); } } public void testDeleteFutureInstallments() throws HibernateException, SystemException, AccountException { TestObjectFactory.flushandCloseSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); accountBO.deleteFutureInstallments(); HibernateUtil.getTransaction().commit(); HibernateUtil.closeSession(); accountBO = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); assertEquals(1, accountBO.getAccountActionDates().size()); } public void testUpdate() throws Exception { TestObjectFactory.flushandCloseSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); accountBO.setUserContext(TestUtils.makeUser()); java.sql.Date currentDate = new java.sql.Date(System .currentTimeMillis()); PersonnelBO personnelBO = new PersonnelPersistence() .getPersonnel(TestUtils.makeUser().getId()); AccountNotesEntity accountNotesEntity = new AccountNotesEntity( currentDate, "account updated", personnelBO, accountBO); accountBO.addAccountNotes(accountNotesEntity); TestObjectFactory.updateObject(accountBO); TestObjectFactory.flushandCloseSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); for (AccountNotesEntity accountNotes : accountBO .getRecentAccountNotes()) { assertEquals("Last note added is account updated","account updated", accountNotes.getComment()); assertEquals(currentDate.toString(),accountNotes.getCommentDateStr()); assertEquals(personnelBO.getPersonnelId(),accountNotes.getPersonnel().getPersonnelId()); assertEquals(personnelBO.getDisplayName(),accountNotes.getPersonnel().getDisplayName()); assertEquals(currentDate.toString(),accountNotes.getCommentDate().toString()); assertEquals(accountBO.getAccountId(),accountNotes.getAccount().getAccountId()); assertNotNull(accountNotes.getCommentId()); break; } } public void testGetPastInstallments() { MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory .getTypicalMeeting()); CenterBO centerBO = TestObjectFactory.createCenter("Center_Active", meeting); HibernateUtil.closeSession(); centerBO = TestObjectFactory.getObject(CenterBO.class, centerBO.getCustomerId()); for (AccountActionDateEntity actionDate : centerBO.getCustomerAccount() .getAccountActionDates()) { actionDate.setActionDate(offSetCurrentDate(4)); break; } List<AccountActionDateEntity> pastInstallments = centerBO .getCustomerAccount().getPastInstallments(); assertNotNull(pastInstallments); assertEquals(1, pastInstallments.size()); TestObjectFactory.cleanUp(centerBO); } public void testGetAllInstallments() { MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory .getTypicalMeeting()); CenterBO centerBO = TestObjectFactory.createCenter("Center_Active", meeting); HibernateUtil.closeSession(); centerBO = TestObjectFactory.getObject(CenterBO.class, centerBO.getCustomerId()); List<AccountActionDateEntity> allInstallments = centerBO .getCustomerAccount().getAllInstallments(); assertNotNull(allInstallments); assertEquals(10, allInstallments.size()); TestObjectFactory.cleanUp(centerBO); } public void testUpdatePerformanceHistoryOnAdjustment() throws Exception { Date currentDate = new Date(System.currentTimeMillis()); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>(); PaymentData paymentData = TestObjectFactory.getLoanAccountPaymentData( accntActionDates, TestObjectFactory.getMoneyForMFICurrency(212), null, accountBO .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate); accountBO.applyPaymentWithPersist(paymentData); HibernateUtil.commitTransaction(); LoanBO loan = TestObjectFactory.getObject(LoanBO.class, accountBO.getAccountId()); loan.applyPaymentWithPersist(TestObjectFactory.getLoanAccountPaymentData(null, TestObjectFactory.getMoneyForMFICurrency(600), null, loan .getPersonnel(), "receiptNum", Short.valueOf("1"), currentDate, currentDate)); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); accountBO.setUserContext(TestUtils.makeUser()); accountBO.adjustPmnt("loan account has been adjusted by test code"); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); accountBO = (LoanBO) HibernateUtil.getSessionTL().get( LoanBO.class, accountBO.getAccountId()); center = TestObjectFactory.getObject(CenterBO.class, center .getCustomerId()); group = TestObjectFactory.getObject(GroupBO.class, group .getCustomerId()); assertEquals(1, accountBO.getPerformanceHistory().getNoOfPayments().intValue()); } public void testAccountBOClosedDate() { AccountBO account = new AccountBO(); java.util.Date originalDate = new java.util.Date(); final long TEN_SECONDS = 10000; // verify that after the setter is called, changes to the object // passed to the setter do not affect the internal state java.util.Date mutatingDate1 = (java.util.Date)originalDate.clone(); account.setClosedDate(mutatingDate1); mutatingDate1.setTime(System.currentTimeMillis()+ TEN_SECONDS); assertEquals(account.getClosedDate(), originalDate); // verify that after the getter is called, changes to the object // returned by the getter do not affect the internal state java.util.Date originalDate2 = (java.util.Date)originalDate.clone(); account.setClosedDate(originalDate2); java.util.Date mutatingDate2 = account.getClosedDate(); mutatingDate2.setTime(System.currentTimeMillis() + TEN_SECONDS); assertEquals(account.getClosedDate(), originalDate); } public void testGetInstalmentDates() throws Exception { AccountBO account = new AccountBO(); MeetingBO meeting = new MeetingBO(RecurrenceType.DAILY, (short)1, getDate("18/08/2005"), MeetingType.CUSTOMER_MEETING); /* make sure we can handle case where the number of installments is zero */ account.getInstallmentDates(meeting, (short)0, (short)0); } public static void addToAccountStatusChangeHistory(LoanBO loan, AccountStatusChangeHistoryEntity accountStatusChangeHistoryEntity) { loan.addAccountStatusChangeHistory(accountStatusChangeHistoryEntity); } private java.sql.Date offSetCurrentDate(int noOfDays) { Calendar currentDateCalendar = new GregorianCalendar(); int year = currentDateCalendar.get(Calendar.YEAR); int month = currentDateCalendar.get(Calendar.MONTH); int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH); currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays); return new java.sql.Date(currentDateCalendar.getTimeInMillis()); } }
Financial Calculation Refactoring * continuing to fix and re-enable test cases after removing InterestDeductedAtDisbursement for loan creation in test cases. git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@12976 a8845c50-7012-0410-95d3-8e1449b9b1e4
mifos/test/org/mifos/application/accounts/business/TestAccountBO.java
Financial Calculation Refactoring * continuing to fix and re-enable test cases after removing InterestDeductedAtDisbursement for loan creation in test cases.
Java
apache-2.0
0eee3dd064b82f6bb56dff87612c011894c5965c
0
nhs-digital/gpconnect,nhs-digital/gpconnect,nhs-digital/gpconnect
package uk.gov.hscic.common.filters.model; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import java.util.Arrays; import java.util.List; import org.hl7.fhir.dstu3.model.OperationOutcome.IssueType; import uk.gov.hscic.OperationOutcomeFactory; import uk.gov.hscic.SystemCode; import uk.gov.hscic.SystemURL; public class WebTokenValidator { private static final List<String> PERMITTED_REQUESTED_SCOPES = Arrays.asList("patient/*.read", "patient/*.write", "organization/*.read", "organization/*.write"); public static void validateWebToken(WebToken webToken, int futureRequestLeeway) { verifyNoNullValues(webToken); verifyTimeValues(webToken, futureRequestLeeway); verifyRequestedResourceValues(webToken); // Checking the practionerId and the sub are equal in value if (!(webToken.getRequestingPractitioner().getId().equals(webToken.getSub()))) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Practitioner ids do not match!"), SystemCode.BAD_REQUEST, IssueType.INVALID); } if (!PERMITTED_REQUESTED_SCOPES.contains(webToken.getRequestedScope())) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Bad Request Exception"), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyNoNullValues(WebToken webToken) { assertNotNull(webToken.getAud()); assertNotNull(webToken.getExp()); assertNotNull(webToken.getIat()); assertNotNull(webToken.getIss()); assertNotNull(webToken.getSub()); assertNotNull(webToken.getReasonForRequest()); assertNotNull(webToken.getRequestedScope()); assertNotNull(webToken.getRequestingDevice()); assertNotNull(webToken.getRequestingDevice().getResourceType()); assertNotNull(webToken.getRequestingOrganization()); assertNotNull(webToken.getRequestingOrganization().getResourceType()); assertNotNull(webToken.getRequestingPractitioner()); assertNotNull(webToken.getRequestingPractitioner().getResourceType()); } private static void assertNotNull(Object object) { if (null == object) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("JSON entry incomplete."), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyTimeValues(WebToken webToken, int futureRequestLeeway) { // Checking the creation date is not in the future int timeValidationIdentifierInt = webToken.getIat(); // Checking creation time is not in the future (with a 5 second leeway if (timeValidationIdentifierInt > (System.currentTimeMillis() / 1000) + futureRequestLeeway) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Creation time is in the future"), SystemCode.BAD_REQUEST, IssueType.INVALID); } // Checking the expiry time is 5 minutes after creation if (webToken.getExp() - timeValidationIdentifierInt != 300) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Request time expired"), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyRequestedResourceValues(WebToken webToken) { // Checking the reason for request is directcare if (!"directcare".equals(webToken.getReasonForRequest())) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Reason for request is not directcare"), SystemCode.BAD_REQUEST, IssueType.INVALID); } RequestingDevice requestingDevice = webToken.getRequestingDevice(); if (null == requestingDevice) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("No requesting_device"), SystemCode.BAD_REQUEST, IssueType.INVALID); } String deviceType = requestingDevice.getResourceType(); String organizationType = webToken.getRequestingOrganization().getResourceType(); String practitionerType = webToken.getRequestingPractitioner().getResourceType(); if (!deviceType.equals("Device") || !organizationType.equals("Organization") || !practitionerType.equals("Practitioner")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new UnprocessableEntityException("Invalid resource type"), SystemCode.BAD_REQUEST, IssueType.INVALID ); } } }
gpconnect-demonstrator-api/src/main/java/uk/gov/hscic/common/filters/model/WebTokenValidator.java
package uk.gov.hscic.common.filters.model; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import java.util.Arrays; import java.util.List; import org.hl7.fhir.dstu3.model.OperationOutcome.IssueType; import uk.gov.hscic.OperationOutcomeFactory; import uk.gov.hscic.SystemCode; import uk.gov.hscic.SystemURL; public class WebTokenValidator { private static final List<String> PERMITTED_REQUESTED_SCOPES = Arrays.asList("patient/*.read", "patient/*.write", "organization/*.read", "organization/*.write"); public static void validateWebToken(WebToken webToken, int futureRequestLeeway) { verifyNoNullValues(webToken); verifyTimeValues(webToken, futureRequestLeeway); verifyRequestedResourceValues(webToken); // Checking the practionerId and the sub are equal in value if (!(webToken.getRequestingPractitioner().getId().equals(webToken.getSub()))) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Practitioner ids do not match!"), SystemCode.BAD_REQUEST, IssueType.INVALID); } if (!PERMITTED_REQUESTED_SCOPES.contains(webToken.getRequestedScope())) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Bad Request Exception"), SystemCode.BAD_REQUEST, IssueType.INVALID); } if (!SystemURL.AUTHORIZATION_TOKEN.equals(webToken.getAud()) ) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Bad Request Exception"), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyNoNullValues(WebToken webToken) { assertNotNull(webToken.getAud()); assertNotNull(webToken.getExp()); assertNotNull(webToken.getIat()); assertNotNull(webToken.getIss()); assertNotNull(webToken.getSub()); assertNotNull(webToken.getReasonForRequest()); assertNotNull(webToken.getRequestedScope()); assertNotNull(webToken.getRequestingDevice()); assertNotNull(webToken.getRequestingDevice().getResourceType()); assertNotNull(webToken.getRequestingOrganization()); assertNotNull(webToken.getRequestingOrganization().getResourceType()); assertNotNull(webToken.getRequestingPractitioner()); assertNotNull(webToken.getRequestingPractitioner().getResourceType()); } private static void assertNotNull(Object object) { if (null == object) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("JSON entry incomplete."), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyTimeValues(WebToken webToken, int futureRequestLeeway) { // Checking the creation date is not in the future int timeValidationIdentifierInt = webToken.getIat(); // Checking creation time is not in the future (with a 5 second leeway if (timeValidationIdentifierInt > (System.currentTimeMillis() / 1000) + futureRequestLeeway) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Creation time is in the future"), SystemCode.BAD_REQUEST, IssueType.INVALID); } // Checking the expiry time is 5 minutes after creation if (webToken.getExp() - timeValidationIdentifierInt != 300) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Request time expired"), SystemCode.BAD_REQUEST, IssueType.INVALID); } } private static void verifyRequestedResourceValues(WebToken webToken) { // Checking the reason for request is directcare if (!"directcare".equals(webToken.getReasonForRequest())) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("Reason for request is not directcare"), SystemCode.BAD_REQUEST, IssueType.INVALID); } RequestingDevice requestingDevice = webToken.getRequestingDevice(); if (null == requestingDevice) { throw OperationOutcomeFactory.buildOperationOutcomeException( new InvalidRequestException("No requesting_device"), SystemCode.BAD_REQUEST, IssueType.INVALID); } String deviceType = requestingDevice.getResourceType(); String organizationType = webToken.getRequestingOrganization().getResourceType(); String practitionerType = webToken.getRequestingPractitioner().getResourceType(); if (!deviceType.equals("Device") || !organizationType.equals("Organization") || !practitionerType.equals("Practitioner")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new UnprocessableEntityException("Invalid resource type"), SystemCode.BAD_REQUEST, IssueType.INVALID ); } } }
Removed the no longer required validation of AUD in the JWT
gpconnect-demonstrator-api/src/main/java/uk/gov/hscic/common/filters/model/WebTokenValidator.java
Removed the no longer required validation of AUD in the JWT
Java
apache-2.0
8711d3dbd5b3f64f8d269d5a5ecd651f2b5a9dec
0
billho/symphony,billho/symphony,billho/symphony
/* * Copyright (c) 2012-2016, b3log.org & hacpai.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 org.b3log.symphony.service; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.model.Role; import org.b3log.latke.model.User; import org.b3log.latke.repository.CompositeFilter; import org.b3log.latke.repository.CompositeFilterOperator; import org.b3log.latke.repository.Filter; import org.b3log.latke.repository.FilterOperator; import org.b3log.latke.repository.PropertyFilter; import org.b3log.latke.repository.Query; import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.repository.SortDirection; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.annotation.Service; import org.b3log.latke.util.CollectionUtils; import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Article; import org.b3log.symphony.model.Comment; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.Revision; import org.b3log.symphony.model.Tag; import org.b3log.symphony.model.UserExt; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.processor.channel.ArticleChannel; import org.b3log.symphony.repository.ArticleRepository; import org.b3log.symphony.repository.CommentRepository; import org.b3log.symphony.repository.DomainTagRepository; import org.b3log.symphony.repository.RevisionRepository; import org.b3log.symphony.repository.TagArticleRepository; import org.b3log.symphony.repository.TagRepository; import org.b3log.symphony.repository.UserRepository; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Markdowns; import org.b3log.symphony.util.Symphonys; import org.b3log.symphony.util.Times; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; /** * Article query service. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 2.22.14.29, Oct 12, 2016 * @since 0.2.0 */ @Service public class ArticleQueryService { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ArticleQueryService.class.getName()); /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Tag-Article repository. */ @Inject private TagArticleRepository tagArticleRepository; /** * Tag repository. */ @Inject private TagRepository tagRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Domain tag repository. */ @Inject private DomainTagRepository domainTagRepository; /** * Revision repository. */ @Inject private RevisionRepository revisionRepository; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * Short link query service. */ @Inject private ShortLinkQueryService shortLinkQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Count to fetch article tags for relevant articles. */ private static final int RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT = 3; /** * Get an articles by the specified title. * * @param title the specified title * @return article, returns {@code null} if not found */ public JSONObject getArticleByTitle(final String title) { try { return articleRepository.getByTitle(title); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article by title [" + title + "] failed", e); return null; } } /** * Gets article count of the specified day. * * @param day the specified day * @return article count */ public int getArticleCntInDay(final Date day) { final long time = day.getTime(); final long start = Times.getDayStartTime(time); final long end = Times.getDayEndTime(time); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, start), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN, end), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID) )); try { return (int) articleRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Count day article failed", e); return 1; } } /** * Gets article count of the specified month. * * @param day the specified month * @return article count */ public int getArticleCntInMonth(final Date day) { final long time = day.getTime(); final long start = Times.getMonthStartTime(time); final long end = Times.getMonthEndTime(time); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, start), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN, end), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID) )); try { return (int) articleRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Count month article failed", e); return 1; } } /** * Gets articles by the specified page number and page size. * * @param currentPageNum the specified page number * @param pageSize the specified page size * @param types the specified types * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getValidArticles(final int currentPageNum, final int pageSize, final int... types) throws ServiceException { try { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); if (null != types && types.length > 0) { final List<Filter> typeFilters = new ArrayList<>(); for (int i = 0; i < types.length; i++) { final int type = types[i]; typeFilters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.EQUAL, type)); } final CompositeFilter typeFilter = new CompositeFilter(CompositeFilterOperator.OR, typeFilters); final List<Filter> filters = new ArrayList<>(); filters.add(typeFilter); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); } else { query.setFilter(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); } final JSONObject result = articleRepository.get(query); return CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } } /** * Gets domain articles. * * @param avatarViewMode the specified avatar view mode * @param domainId the specified domain id * @param currentPageNum the specified current page number * @param pageSize the specified page size * @return result * @throws ServiceException service exception */ public JSONObject getDomainArticles(final int avatarViewMode, final String domainId, final int currentPageNum, final int pageSize) throws ServiceException { final JSONObject ret = new JSONObject(); ret.put(Article.ARTICLES, (Object) Collections.emptyList()); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); pagination.put(Pagination.PAGINATION_PAGE_COUNT, 0); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) Collections.emptyList()); try { final JSONArray domainTags = domainTagRepository.getByDomainId(domainId, 1, Integer.MAX_VALUE) .optJSONArray(Keys.RESULTS); if (domainTags.length() <= 0) { return ret; } final List<String> tagIds = new ArrayList<>(); for (int i = 0; i < domainTags.length(); i++) { tagIds.add(domainTags.optJSONObject(i).optString(Tag.TAG + "_" + Keys.OBJECT_ID)); } Query query = new Query().setFilter( new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.IN, tagIds)). setCurrentPageNum(currentPageNum).setPageSize(pageSize). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticles = result.optJSONArray(Keys.RESULTS); if (tagArticles.length() <= 0) { return ret; } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticles.length(); i++) { articleIds.add(tagArticles.optJSONObject(i).optString(Article.ARTICLE + "_" + Keys.OBJECT_ID)); } query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))). setPageCount(1).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(articleRepository.get(query).optJSONArray(Keys.RESULTS)); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); genParticipants(avatarViewMode, articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } catch (final RepositoryException | ServiceException e) { LOGGER.log(Level.ERROR, "Gets domain articles error", e); throw new ServiceException(e); } } /** * Gets the relevant articles of the specified article with the specified fetch size. * * <p> * The relevant articles exist the same tag with the specified article. * </p> * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @param fetchSize the specified fetch size * @return relevant articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRelevantArticles(final int avatarViewMode, final JSONObject article, final int fetchSize) throws ServiceException { final String tagsString = article.optString(Article.ARTICLE_TAGS); final String[] tagTitles = tagsString.split(","); final int tagTitlesLength = tagTitles.length; final int subCnt = tagTitlesLength > RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT ? RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT : tagTitlesLength; final List<Integer> tagIdx = CollectionUtils.getRandomIntegers(0, tagTitlesLength, subCnt); final int subFetchSize = fetchSize / subCnt; final Set<String> fetchedArticleIds = new HashSet<>(); final List<JSONObject> ret = new ArrayList<>(); try { for (int i = 0; i < tagIdx.size(); i++) { final String tagTitle = tagTitles[tagIdx.get(i)].trim(); final JSONObject tag = tagRepository.getByTitle(tagTitle); final String tagId = tag.optString(Keys.OBJECT_ID); JSONObject result = tagArticleRepository.getByTagId(tagId, 1, subFetchSize); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int j = 0; j < tagArticleRelations.length(); j++) { final String articleId = tagArticleRelations.optJSONObject(j).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID); if (fetchedArticleIds.contains(articleId)) { continue; } articleIds.add(articleId); fetchedArticleIds.add(articleId); } articleIds.remove(article.optString(Keys.OBJECT_ID)); final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)); result = articleRepository.get(query); ret.addAll(CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS))); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets relevant articles failed", e); throw new ServiceException(e); } } /** * Gets broadcasts (articles permalink equals to "aBroadcast"). * * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getBroadcasts(final int currentPageNum, final int pageSize) throws ServiceException { try { final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).setFilter( new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, "aBroadcast")). addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING); final JSONObject result = articleRepository.get(query); final JSONArray articles = result.optJSONArray(Keys.RESULTS); if (0 == articles.length()) { return Collections.emptyList(); } final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(articles); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); article.remove(Article.ARTICLE_CONTENT); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets broadcasts [currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + "] failed", e); throw new ServiceException(e); } } /** * Gets interest articles. * * @param currentPageNum the specified current page number * @param pageSize the specified fetch size * @param tagTitles the specified tag titles * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getInterests(final int currentPageNum, final int pageSize, final String... tagTitles) throws ServiceException { try { final List<JSONObject> tagList = new ArrayList<>(); for (final String tagTitle : tagTitles) { final JSONObject tag = tagRepository.getByTitle(tagTitle); if (null == tag) { continue; } tagList.add(tag); } final Map<String, Class<?>> articleFields = new HashMap<>(); articleFields.put(Article.ARTICLE_TITLE, String.class); articleFields.put(Article.ARTICLE_PERMALINK, String.class); articleFields.put(Article.ARTICLE_CREATE_TIME, Long.class); articleFields.put(Article.ARTICLE_AUTHOR_ID, String.class); final List<JSONObject> ret = new ArrayList<>(); if (!tagList.isEmpty()) { final List<JSONObject> tagArticles = getArticlesByTags(currentPageNum, pageSize, articleFields, tagList.toArray(new JSONObject[0])); for (final JSONObject article : tagArticles) { article.remove(Article.ARTICLE_T_PARTICIPANTS); article.remove(Article.ARTICLE_T_PARTICIPANT_NAME); article.remove(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL); article.remove(Article.ARTICLE_LATEST_CMT_TIME); article.remove(Article.ARTICLE_LATEST_CMTER_NAME); article.remove(Article.ARTICLE_UPDATE_TIME); article.remove(Article.ARTICLE_T_HEAT); article.remove(Article.ARTICLE_T_TITLE_EMOJI); article.remove(Common.TIME_AGO); article.put(Article.ARTICLE_CREATE_TIME, ((Date) article.get(Article.ARTICLE_CREATE_TIME)).getTime()); } ret.addAll(tagArticles); } final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(currentPageNum).setPageSize(pageSize).setCurrentPageNum(1); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } final JSONObject result = articleRepository.get(query); final List<JSONObject> recentArticles = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); ret.addAll(recentArticles); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } return ret; } catch (final RepositoryException | ServiceException | JSONException e) { LOGGER.log(Level.ERROR, "Gets interests failed", e); throw new ServiceException(e); } } /** * Gets news (articles tags contains "B3log Announcement"). * * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getNews(final int currentPageNum, final int pageSize) throws ServiceException { try { JSONObject oldAnnouncementTag = tagRepository.getByTitle("B3log Announcement"); JSONObject currentAnnouncementTag = tagRepository.getByTitle("B3log公告"); if (null == oldAnnouncementTag && null == currentAnnouncementTag) { return Collections.emptyList(); } if (null == oldAnnouncementTag) { oldAnnouncementTag = new JSONObject(); } if (null == currentAnnouncementTag) { currentAnnouncementTag = new JSONObject(); } Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(CompositeFilterOperator.or( new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, oldAnnouncementTag.optString(Keys.OBJECT_ID)), new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, currentAnnouncementTag.optString(Keys.OBJECT_ID)) )) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } final JSONObject sa = userQueryService.getSA(); final List<Filter> subFilters = new ArrayList<>(); subFilters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)); subFilters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_EMAIL, FilterOperator.EQUAL, sa.optString(User.USER_EMAIL))); query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, subFilters)) .addProjection(Article.ARTICLE_TITLE, String.class).addProjection(Article.ARTICLE_PERMALINK, String.class) .addProjection(Article.ARTICLE_CREATE_TIME, Long.class).addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING); result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets news failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified tags (order by article create date desc). * * @param tags the specified tags * @param currentPageNum the specified page number * @param articleFields the specified article fields to return * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize, final Map<String, Class<?>> articleFields, final JSONObject... tags) throws ServiceException { try { final List<Filter> filters = new ArrayList<>(); for (final JSONObject tag : tags) { filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))); } Filter filter; if (filters.size() >= 2) { filter = new CompositeFilter(CompositeFilterOperator.OR, filters); } else { filter = filters.get(0); } // XXX: 这里的分页是有问题的,后面取文章的时候会少(因为一篇文章可以有多个标签,但是文章 id 一样) Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(filter).setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(UserExt.USER_AVATAR_VIEW_MODE_C_STATIC, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified city (order by article create date desc). * * @param avatarViewMode the specified avatar view mode * @param city the specified city * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByCity(final int avatarViewMode, final String city, final int currentPageNum, final int pageSize) throws ServiceException { try { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Article.ARTICLE_CITY, FilterOperator.EQUAL, city)) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); final Integer participantsCnt = Symphonys.getInt("cityArticleParticipantsCnt"); genParticipants(avatarViewMode, ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by city [" + city + "] failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified tag (order by article create date desc). * * @param avatarViewMode the specified avatar view mode * @param sortMode the specified sort mode, 0: default, 1: hot, 2: score, 3: reply, 4: perfect * @param tag the specified tag * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByTag(final int avatarViewMode, final int sortMode, final JSONObject tag, final int currentPageNum, final int pageSize) throws ServiceException { try { Query query = new Query(); switch (sortMode) { case 0: query.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 1: query.addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 2: query.addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 3: query.addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 4: query.addSort(Article.ARTICLE_PERFECT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); query.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); } JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final List<String> articleIds = new ArrayList<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)). addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); switch (sortMode) { default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); case 0: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } }); break; case 1: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final int v = o2.optInt(Article.ARTICLE_COMMENT_CNT) - o1.optInt(Article.ARTICLE_COMMENT_CNT); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 2: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final double v = o2.optDouble(Article.REDDIT_SCORE) - o1.optDouble(Article.REDDIT_SCORE); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 3: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final long v = (o2.optLong(Article.ARTICLE_LATEST_CMT_TIME) - o1.optLong(Article.ARTICLE_LATEST_CMT_TIME)); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 4: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final long v = (o2.optLong(Article.ARTICLE_PERFECT) - o1.optLong(Article.ARTICLE_PERFECT)); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; } organizeArticles(avatarViewMode, ret); final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt"); genParticipants(avatarViewMode, ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by tag [tagTitle=" + tag.optString(Tag.TAG_TITLE) + "] failed", e); throw new ServiceException(e); } } /** * Gets an article by the specified client article id. * * @param authorId the specified author id * @param clientArticleId the specified client article id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticleByClientArticleId(final String authorId, final String clientArticleId) throws ServiceException { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, clientArticleId)); filters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, authorId)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); try { final JSONObject result = articleRepository.get(query); final JSONArray array = result.optJSONArray(Keys.RESULTS); if (0 == array.length()) { return null; } return array.optJSONObject(0); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article [clientArticleId=" + clientArticleId + "] failed", e); throw new ServiceException(e); } } /** * Gets an article with {@link #organizeArticle(org.json.JSONObject)} by the specified id. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticleById(final int avatarViewMode, final String articleId) throws ServiceException { Stopwatchs.start("Get article by id"); try { final JSONObject ret = articleRepository.get(articleId); if (null == ret) { return null; } organizeArticle(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } } /** * Gets an article by the specified id. * * @param articleId the specified id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticle(final String articleId) throws ServiceException { try { final JSONObject ret = articleRepository.get(articleId); if (null == ret) { return null; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e); throw new ServiceException(e); } } /** * Gets article revisions. * * @param articleId the specified article id * @return article revisions, returns an empty list if not found */ public List<JSONObject> getArticleRevisions(final String articleId) { final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_ARTICLE) )).addSort(Keys.OBJECT_ID, SortDirection.ASCENDING); try { final List<JSONObject> ret = CollectionUtils.jsonArrayToList(revisionRepository.get(query).optJSONArray(Keys.RESULTS)); for (final JSONObject rev : ret) { final JSONObject data = new JSONObject(rev.optString(Revision.REVISION_DATA)); String articleTitle = data.optString(Article.ARTICLE_TITLE); articleTitle = articleTitle.replace("<", "&lt;").replace(">", "&gt;"); articleTitle = Markdowns.clean(articleTitle, ""); data.put(Article.ARTICLE_TITLE, articleTitle); String articleContent = data.optString(Article.ARTICLE_CONTENT); articleContent = Markdowns.toHTML(articleContent); articleContent = Markdowns.clean(articleContent, ""); data.put(Article.ARTICLE_CONTENT, articleContent); rev.put(Revision.REVISION_DATA, data); } return ret; } catch (final RepositoryException | JSONException e) { LOGGER.log(Level.ERROR, "Get article revisions failed", e); return Collections.emptyList(); } } /** * Gets preview content of the article specified with the given article id. * * @param articleId the given article id * @param request the specified request * @return preview content * @throws ServiceException service exception */ public String getArticlePreviewContent(final String articleId, final HttpServletRequest request) throws ServiceException { final JSONObject article = getArticle(articleId); if (null == article) { return null; } return getPreviewContent(article, request); } private String getPreviewContent(final JSONObject article, final HttpServletRequest request) throws ServiceException { Stopwatchs.start("Get preview content"); try { final int length = Integer.valueOf("150"); String ret = article.optString(Article.ARTICLE_CONTENT); final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userQueryService.getUser(authorId); if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS) || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { return langPropsService.get("articleContentBlockLabel"); } final Set<String> userNames = userQueryService.getUserNames(ret); final JSONObject currentUser = userQueryService.getCurrentUser(request); final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME); final String authorName = author.optString(User.USER_NAME); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) && !authorName.equals(currentUserName)) { boolean invited = false; for (final String userName : userNames) { if (userName.equals(currentUserName)) { invited = true; break; } } if (!invited) { String blockContent = langPropsService.get("articleDiscussionLabel"); blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath() + "/member/" + authorName + "'>" + authorName + "</a>"); return blockContent; } } ret = Emotions.convert(ret); ret = Markdowns.toHTML(ret); ret = Jsoup.clean(ret, Whitelist.none()); if (ret.length() >= length) { ret = StringUtils.substring(ret, 0, length) + " ...."; } return ret; } finally { Stopwatchs.end(); } } /** * Gets the user articles with the specified user id, page number and page size. * * @param avatarViewMode the specified avatar view mode * @param userId the specified user id * @param anonymous the specified article anonymous * @param currentPageNum the specified page number * @param pageSize the specified page size * @return user articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getUserArticles(final int avatarViewMode, final String userId, final int anonymous, final int currentPageNum, final int pageSize) throws ServiceException { final Query query = new Query().addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING) .setCurrentPageNum(currentPageNum).setPageSize(pageSize). setFilter(CompositeFilterOperator.and( new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Article.ARTICLE_ANONYMOUS, FilterOperator.EQUAL, anonymous), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))); try { final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); if (ret.isEmpty()) { return ret; } final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION); final int recordCount = pagination.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject first = ret.get(0); first.put(Pagination.PAGINATION_RECORD_COUNT, recordCount); first.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets user articles failed", e); throw new ServiceException(e); } } /** * Gets side hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getSideHotArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { final String id = String.valueOf(DateUtils.addDays(new Date(), -7).getTime()); try { final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).setCurrentPageNum(1).setPageSize(fetchSize); final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets hot articles failed", e); throw new ServiceException(e); } } /** * Gets the random articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return random articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRandomArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { try { final List<JSONObject> ret = articleRepository.getRandomly(fetchSize); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets random articles failed", e); throw new ServiceException(e); } } /** * Makes article showing filters. * * @return filter the article showing to user */ private CompositeFilter makeArticleShowingFilter() { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); return new CompositeFilter(CompositeFilterOperator.AND, filters); } /** * Makes recent article showing filters. * * @return filter the article showing to user */ private CompositeFilter makeRecentArticleShowingFilter() { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); filters.add(new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_LIKE, "B3log%")); filters.add(new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_LIKE, "Sandbox%")); return new CompositeFilter(CompositeFilterOperator.AND, filters); } /** * Makes the recent (sort by create time desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentDefaultQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by comment count desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentHotQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by score desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentGoodQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by latest comment time desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentReplyQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the top articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return top articles query */ private Query makeTopQuery(final int currentPageNum, final int fetchSize) { final Query query = new Query() .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .setPageCount(1).setPageSize(fetchSize).setCurrentPageNum(currentPageNum); query.setFilter(makeArticleShowingFilter()); return query; } /** * Gets the recent (sort by create time) articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param sortMode the specified sort mode, 0: default, 1: hot, 2: score, 3: reply * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception */ public JSONObject getRecentArticles(final int avatarViewMode, final int sortMode, final int currentPageNum, final int fetchSize) throws ServiceException { final JSONObject ret = new JSONObject(); Query query; switch (sortMode) { case 0: query = makeRecentDefaultQuery(currentPageNum, fetchSize); break; case 1: query = makeRecentHotQuery(currentPageNum, fetchSize); break; case 2: query = makeRecentGoodQuery(currentPageNum, fetchSize); break; case 3: query = makeRecentReplyQuery(currentPageNum, fetchSize); break; default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); query = makeRecentDefaultQuery(currentPageNum, fetchSize); } JSONObject result = null; try { Stopwatchs.start("Query recent articles"); result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } //final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); //genParticipants(articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } /** * Gets the index recent (sort by create time) articles. * * @param avatarViewMode the specified avatar view mode * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexRecentArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1).setPageCount(1); query.setFilter(makeRecentArticleShowingFilter()); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index recent articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index recent articles failed", e); throw new ServiceException(e); } } /** * Gets the hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getHotArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { final Query query = makeTopQuery(1, fetchSize); try { List<JSONObject> ret; Stopwatchs.start("Query hot articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); Stopwatchs.start("Checks author status"); try { for (final JSONObject article : ret) { final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); } } } finally { Stopwatchs.end(); } // final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt"); // genParticipants(ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index articles failed", e); throw new ServiceException(e); } } /** * Gets the perfect articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception */ public JSONObject getPerfectArticles(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { final Query query = new Query() .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setCurrentPageNum(currentPageNum).setPageSize(fetchSize); query.setFilter(new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT)); final JSONObject ret = new JSONObject(); JSONObject result = null; try { Stopwatchs.start("Query recent articles"); result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } //final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); //genParticipants(articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } /** * Gets the index hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexHotArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .setPageCount(1).setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1); query.setFilter(makeArticleShowingFilter()); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index hot articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index hot articles failed", e); throw new ServiceException(e); } } /** * Gets the index perfect articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexPerfectArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(1).setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1); query.setFilter(new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT)); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index perfect articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index perfect articles failed", e); throw new ServiceException(e); } } /** * Gets the recent articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRecentArticlesWithComments(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { return getArticles(avatarViewMode, makeRecentDefaultQuery(currentPageNum, fetchSize)); } /** * Gets the index articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getTopArticlesWithComments(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { return getArticles(avatarViewMode, makeTopQuery(currentPageNum, fetchSize)); } /** * The specific articles. * * @param avatarViewMode the specified avatar view mode * @param query conditions * @return articles * @throws ServiceException service exception */ private List<JSONObject> getArticles(final int avatarViewMode, final Query query) throws ServiceException { try { final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); final List<JSONObject> stories = new ArrayList<>(); for (final JSONObject article : ret) { final JSONObject story = new JSONObject(); final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) { story.put("title", langPropsService.get("articleTitleBlockLabel")); } else { story.put("title", article.optString(Article.ARTICLE_TITLE)); } story.put("id", article.optLong("oId")); story.put("url", Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); story.put("user_display_name", article.optString(Article.ARTICLE_T_AUTHOR_NAME)); story.put("user_job", author.optString(UserExt.USER_INTRO)); story.put("comment_html", article.optString(Article.ARTICLE_CONTENT)); story.put("comment_count", article.optInt(Article.ARTICLE_COMMENT_CNT)); story.put("vote_count", article.optInt(Article.ARTICLE_GOOD_CNT)); story.put("created_at", formatDate(article.get(Article.ARTICLE_CREATE_TIME))); story.put("user_portrait_url", article.optString(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL)); story.put("comments", getAllComments(avatarViewMode, article.optString("oId"))); final String tagsString = article.optString(Article.ARTICLE_TAGS); String[] tags = null; if (!Strings.isEmptyOrNull(tagsString)) { tags = tagsString.split(","); } story.put("badge", tags == null ? "" : tags[0]); stories.add(story); } final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt"); genParticipants(avatarViewMode, stories, participantsCnt); return stories; } catch (final RepositoryException | JSONException e) { LOGGER.log(Level.ERROR, "Gets index articles failed", e); throw new ServiceException(e); } } /** * Gets the article comments with the specified article id. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified article id * @return comments, return an empty list if not found * @throws ServiceException service exception * @throws JSONException json exception * @throws RepositoryException repository exception */ private List<JSONObject> getAllComments(final int avatarViewMode, final String articleId) throws ServiceException, JSONException, RepositoryException { final List<JSONObject> commments = new ArrayList<>(); final List<JSONObject> articleComments = commentQueryService.getArticleComments( avatarViewMode, articleId, 1, Integer.MAX_VALUE, UserExt.USER_COMMENT_VIEW_MODE_C_TRADITIONAL); for (final JSONObject ac : articleComments) { final JSONObject comment = new JSONObject(); final JSONObject author = userRepository.get(ac.optString(Comment.COMMENT_AUTHOR_ID)); comment.put("id", ac.optLong("oId")); comment.put("body_html", ac.optString(Comment.COMMENT_CONTENT)); comment.put("depth", 0); comment.put("user_display_name", ac.optString(Comment.COMMENT_T_AUTHOR_NAME)); comment.put("user_job", author.optString(UserExt.USER_INTRO)); comment.put("vote_count", 0); comment.put("created_at", formatDate(ac.get(Comment.COMMENT_CREATE_TIME))); comment.put("user_portrait_url", ac.optString(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL)); commments.add(comment); } return commments; } /** * The demand format date. * * @param date the original date * @return the format date like "2015-08-03T07:26:57Z" */ private String formatDate(final Object date) { return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd") + "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z"; } /** * Organizes the specified articles. * * <ul> * <li>converts create/update/latest comment time (long) to date type</li> * <li>generates author thumbnail URL</li> * <li>generates author name</li> * <li>escapes article title &lt; and &gt;</li> * <li>generates article heat</li> * <li>generates article view count display format(1k+/1.5k+...)</li> * <li>generates time ago text</li> * <li>generates stick remains minutes</li> * <li>anonymous process</li> * </ul> * * @param avatarViewMode the specified avatarViewMode * @param articles the specified articles * @throws RepositoryException repository exception */ public void organizeArticles(final int avatarViewMode, final List<JSONObject> articles) throws RepositoryException { Stopwatchs.start("Organize articles"); try { for (final JSONObject article : articles) { organizeArticle(avatarViewMode, article); } } finally { Stopwatchs.end(); } } /** * Organizes the specified article. * * <ul> * <li>converts create/update/latest comment time (long) to date type</li> * <li>generates author thumbnail URL</li> * <li>generates author name</li> * <li>escapes article title &lt; and &gt;</li> * <li>generates article heat</li> * <li>generates article view count display format(1k+/1.5k+...)</li> * <li>generates time ago text</li> * <li>generates stick remains minutes</li> * <li>anonymous process</li> * </ul> * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @throws RepositoryException repository exception */ public void organizeArticle(final int avatarViewMode, final JSONObject article) throws RepositoryException { toArticleDate(article); genArticleAuthor(avatarViewMode, article); String title = article.optString(Article.ARTICLE_TITLE).replace("<", "&lt;").replace(">", "&gt;"); title = Markdowns.clean(title, ""); article.put(Article.ARTICLE_TITLE, title); article.put(Article.ARTICLE_T_TITLE_EMOJI, Emotions.convert(title)); if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_T_TITLE_EMOJI, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel")); } final String articleId = article.optString(Keys.OBJECT_ID); Integer viewingCnt = ArticleChannel.ARTICLE_VIEWS.get(articleId); if (null == viewingCnt) { viewingCnt = 0; } article.put(Article.ARTICLE_T_HEAT, viewingCnt); final int viewCnt = article.optInt(Article.ARTICLE_VIEW_CNT); final double views = (double) viewCnt / 1000; if (views >= 1) { final DecimalFormat df = new DecimalFormat("#.#"); article.put(Article.ARTICLE_T_VIEW_CNT_DISPLAY_FORMAT, df.format(views) + "K"); } final long stick = article.optLong(Article.ARTICLE_STICK); long expired; if (stick > 0) { expired = stick + Symphonys.getLong("stickArticleTime"); final long remainsMills = Math.abs(System.currentTimeMillis() - expired); article.put(Article.ARTICLE_T_STICK_REMAINS, (int) Math.floor((double) remainsMills / 1000 / 60)); } else { article.put(Article.ARTICLE_T_STICK_REMAINS, 0); } String articleLatestCmterName = article.optString(Article.ARTICLE_LATEST_CMTER_NAME); if (StringUtils.isNotBlank(articleLatestCmterName) && UserRegisterValidation.invalidUserName(articleLatestCmterName)) { articleLatestCmterName = UserExt.ANONYMOUS_USER_NAME; article.put(Article.ARTICLE_LATEST_CMTER_NAME, articleLatestCmterName); } } /** * Converts the specified article create/update/latest comment time (long) to date type. * * @param article the specified article */ private void toArticleDate(final JSONObject article) { article.put(Common.TIME_AGO, Times.getTimeAgo(article.optLong(Article.ARTICLE_CREATE_TIME), Latkes.getLocale())); article.put(Article.ARTICLE_CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME))); article.put(Article.ARTICLE_UPDATE_TIME, new Date(article.optLong(Article.ARTICLE_UPDATE_TIME))); article.put(Article.ARTICLE_LATEST_CMT_TIME, new Date(article.optLong(Article.ARTICLE_LATEST_CMT_TIME))); } /** * Generates the specified article author name and thumbnail URL. * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @throws RepositoryException repository exception */ private void genArticleAuthor(final int avatarViewMode, final JSONObject article) throws RepositoryException { final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); article.put(Article.ARTICLE_T_AUTHOR, author); if (Article.ARTICLE_ANONYMOUS_C_ANONYMOUS == article.optInt(Article.ARTICLE_ANONYMOUS)) { article.put(Article.ARTICLE_T_AUTHOR_NAME, UserExt.ANONYMOUS_USER_NAME); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "210", avatarQueryService.getDefaultAvatarURL("210")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "48", avatarQueryService.getDefaultAvatarURL("48")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "20", avatarQueryService.getDefaultAvatarURL("20")); } else { article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME)); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "210", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "210")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "48", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "48")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "20", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "20")); } } /** * Generates participants for the specified articles. * * @param avatarViewMode the specified avatar view mode * @param articles the specified articles * @param participantsCnt the specified generate size * @throws ServiceException service exception */ public void genParticipants(final int avatarViewMode, final List<JSONObject> articles, final Integer participantsCnt) throws ServiceException { Stopwatchs.start("Generates participants"); try { for (final JSONObject article : articles) { article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) Collections.emptyList()); if (article.optInt(Article.ARTICLE_COMMENT_CNT) < 1) { continue; } final List<JSONObject> articleParticipants = getArticleLatestParticipants( avatarViewMode, article.optString(Keys.OBJECT_ID), participantsCnt); article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) articleParticipants); } } finally { Stopwatchs.end(); } } /** * Gets the article participants (commenters) with the specified article article id and fetch size. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified article id * @param fetchSize the specified fetch size * @return article participants, for example, <pre> * [ * { * "oId": "", * "articleParticipantName": "", * "articleParticipantThumbnailURL": "", * "articleParticipantThumbnailUpdateTime": long, * "commentId": "" * }, .... * ] * </pre>, returns an empty list if not found * * @throws ServiceException service exception */ public List<JSONObject> getArticleLatestParticipants(final int avatarViewMode, final String articleId, final int fetchSize) throws ServiceException { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId)) .addProjection(Comment.COMMENT_AUTHOR_EMAIL, String.class) .addProjection(Keys.OBJECT_ID, String.class) .addProjection(Comment.COMMENT_AUTHOR_ID, String.class) .setPageCount(1).setCurrentPageNum(1).setPageSize(fetchSize); final List<JSONObject> ret = new ArrayList<>(); try { final JSONObject result = commentRepository.get(query); final List<JSONObject> comments = new ArrayList<>(); final JSONArray records = result.optJSONArray(Keys.RESULTS); for (int i = 0; i < records.length(); i++) { final JSONObject comment = records.optJSONObject(i); boolean exist = false; // deduplicate for (final JSONObject c : comments) { if (comment.optString(Comment.COMMENT_AUTHOR_ID).equals( c.optString(Comment.COMMENT_AUTHOR_ID))) { exist = true; break; } } if (!exist) { comments.add(comment); } } for (final JSONObject comment : comments) { final String email = comment.optString(Comment.COMMENT_AUTHOR_EMAIL); final String userId = comment.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject commenter = userRepository.get(userId); String thumbnailURL = Symphonys.get("defaultThumbnailURL"); if (!UserExt.DEFAULT_CMTER_EMAIL.equals(email)) { thumbnailURL = avatarQueryService.getAvatarURLByUser(avatarViewMode, commenter, "48"); } final JSONObject participant = new JSONObject(); participant.put(Article.ARTICLE_T_PARTICIPANT_NAME, commenter.optString(User.USER_NAME)); participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, thumbnailURL); participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME)); participant.put(Article.ARTICLE_T_PARTICIPANT_URL, commenter.optString(User.USER_URL)); participant.put(Keys.OBJECT_ID, commenter.optString(Keys.OBJECT_ID)); participant.put(Comment.COMMENT_T_ID, comment.optString(Keys.OBJECT_ID)); ret.add(participant); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article [" + articleId + "] participants failed", e); throw new ServiceException(e); } } /** * Processes the specified article content. * * <ul> * <li>Generates &#64;username home URL</li> * <li>Markdowns</li> * <li>Generates secured article content</li> * <li>Blocks the article if need</li> * <li>Generates emotion images</li> * <li>Generates article link with article id</li> * <li>Generates article abstract (preview content)</li> * <li>Generates article ToC</li> * </ul> * * @param article the specified article, for example, <pre> * { * "articleTitle": "", * ...., * "author": {} * } * </pre> * * @param request the specified request * @throws ServiceException service exception */ public void processArticleContent(final JSONObject article, final HttpServletRequest request) throws ServiceException { Stopwatchs.start("Process content"); try { final JSONObject author = article.optJSONObject(Article.ARTICLE_T_AUTHOR); if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS) || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel")); article.put(Article.ARTICLE_T_PREVIEW_CONTENT, langPropsService.get("articleContentBlockLabel")); article.put(Article.ARTICLE_T_TOC, ""); article.put(Article.ARTICLE_REWARD_CONTENT, ""); article.put(Article.ARTICLE_REWARD_POINT, 0); return; } article.put(Article.ARTICLE_T_PREVIEW_CONTENT, article.optString(Article.ARTICLE_TITLE)); String articleContent = article.optString(Article.ARTICLE_CONTENT); article.put(Common.DISCUSSION_VIEWABLE, true); final Set<String> userNames = userQueryService.getUserNames(articleContent); final JSONObject currentUser = userQueryService.getCurrentUser(request); final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME); final String currentRole = null == currentUser ? "" : currentUser.optString(User.USER_ROLE); final String authorName = article.optString(Article.ARTICLE_T_AUTHOR_NAME); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) && !authorName.equals(currentUserName) && !Role.ADMIN_ROLE.equals(currentRole)) { boolean invited = false; for (final String userName : userNames) { if (userName.equals(currentUserName)) { invited = true; break; } } if (!invited) { String blockContent = langPropsService.get("articleDiscussionLabel"); blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath() + "/member/" + authorName + "'>" + authorName + "</a>"); article.put(Article.ARTICLE_CONTENT, blockContent); article.put(Common.DISCUSSION_VIEWABLE, false); article.put(Article.ARTICLE_REWARD_CONTENT, ""); article.put(Article.ARTICLE_REWARD_POINT, 0); article.put(Article.ARTICLE_T_TOC, ""); return; } } for (final String userName : userNames) { articleContent = articleContent.replace('@' + userName, "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a>"); } articleContent = shortLinkQueryService.linkArticle(articleContent); articleContent = shortLinkQueryService.linkTag(articleContent); articleContent = Emotions.convert(articleContent); article.put(Article.ARTICLE_CONTENT, articleContent); if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) { String articleRewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT); final Set<String> rewordContentUserNames = userQueryService.getUserNames(articleRewardContent); for (final String userName : rewordContentUserNames) { articleRewardContent = articleRewardContent.replace('@' + userName, "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a>"); } articleRewardContent = Emotions.convert(articleRewardContent); article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent); } markdown(article); final String articleId = article.optString(Keys.OBJECT_ID); // MP3 player render final StringBuffer contentBuilder = new StringBuffer(); articleContent = article.optString(Article.ARTICLE_CONTENT); final String MP3_URL_REGEX = "<p><a href.*\\.mp3.*</a>( )*</p>"; final Pattern p = Pattern.compile(MP3_URL_REGEX); final Matcher m = p.matcher(articleContent); int i = 0; while (m.find()) { String mp3URL = m.group(); String mp3Name = StringUtils.substringBetween(mp3URL, "\">", ".mp3</a>"); mp3URL = StringUtils.substringBetween(mp3URL, "href=\"", "\" rel="); final String playerId = "player" + articleId + i++; m.appendReplacement(contentBuilder, "<div id=\"" + playerId + "\" class=\"aplayer\"></div>\n" + "<script>\n" + "var " + playerId + " = new APlayer({\n" + " element: document.getElementById('" + playerId + "'),\n" + " narrow: false,\n" + " autoplay: false,\n" + " showlrc: false,\n" + " mutex: true,\n" + " theme: '#e6d0b2',\n" + " music: {\n" + " title: '" + mp3Name + "',\n" + " author: '" + mp3URL + "',\n" + " url: '" + mp3URL + "',\n" + " pic: '" + Latkes.getStaticServePath() + "/js/lib/aplayer/default.jpg'\n" + " }\n" + "});\n" + playerId + ".init();\n" + "</script>"); } m.appendTail(contentBuilder); articleContent = contentBuilder.toString(); articleContent = articleContent.replaceFirst("<div id=\"player", "<script src=\"" + Latkes.getStaticServePath() + "/js/lib/aplayer/APlayer.min.js\"></script>\n<div id=\"player"); article.put(Article.ARTICLE_CONTENT, articleContent); article.put(Article.ARTICLE_T_PREVIEW_CONTENT, getArticleMetaDesc(article)); article.put(Article.ARTICLE_T_TOC, getArticleToC(article)); } finally { Stopwatchs.end(); } } /** * Gets articles by the specified request json object. * * @param avatarViewMode the specified avatar view mode * @param requestJSONObject the specified request json object, for example, <pre> * { * "oId": "", // optional * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10 * }, see {@link Pagination} for more details * </pre> * * @param articleFields the specified article fields to return * * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception * @see Pagination */ public JSONObject getArticles(final int avatarViewMode, final JSONObject requestJSONObject, final Map<String, Class<?>> articleFields) throws ServiceException { final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize). addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } if (requestJSONObject.has(Keys.OBJECT_ID)) { query.setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, requestJSONObject.optString(Keys.OBJECT_ID))); } JSONObject result = null; try { result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } ret.put(Article.ARTICLES, articles); return ret; } /** * Markdowns the specified article content. * * <ul> * <li>Markdowns article content/reward content</li> * <li>Generates secured article content/reward content</li> * </ul> * * @param article the specified article content */ private void markdown(final JSONObject article) { Stopwatchs.start("Markdown"); try { String content = article.optString(Article.ARTICLE_CONTENT); final int articleType = article.optInt(Article.ARTICLE_TYPE); if (Article.ARTICLE_TYPE_C_THOUGHT != articleType) { content = Markdowns.toHTML(content); content = Markdowns.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } else { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); content = Jsoup.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK), Whitelist.relaxed().addAttributes(":all", "id", "target", "class"). addTags("span", "hr").addAttributes("iframe", "src", "width", "height") .addAttributes("audio", "controls", "src"), outputSettings); content = content.replace("\n", "\\n").replace("'", "\\'") .replace("\"", "\\\""); } article.put(Article.ARTICLE_CONTENT, content); if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) { String rewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT); rewardContent = Markdowns.toHTML(rewardContent); rewardContent = Markdowns.clean(rewardContent, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); article.put(Article.ARTICLE_REWARD_CONTENT, rewardContent); } } finally { Stopwatchs.end(); } } /** * Gets meta description content of the specified article. * * @param article the specified article * @return meta description */ private String getArticleMetaDesc(final JSONObject article) { Stopwatchs.start("Meta Desc"); try { final int length = Integer.valueOf("150"); String ret = article.optString(Article.ARTICLE_CONTENT); ret = Jsoup.clean(ret, Whitelist.none()); if (ret.length() >= length) { ret = StringUtils.substring(ret, 0, length) + " ...."; } ret = Jsoup.parse(ret).text(); ret = ret.replaceAll("\"", "'"); return ret; } finally { Stopwatchs.end(); } } /** * Gets ToC of the specified article. * * @param article the specified article * @return ToC */ private String getArticleToC(final JSONObject article) { String content = article.optString(Article.ARTICLE_CONTENT); if (!StringUtils.contains(content, "#") || Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { return ""; } final Document doc = Jsoup.parse(content, StringUtils.EMPTY, Parser.htmlParser()); doc.outputSettings().prettyPrint(false); final StringBuilder listBuilder = new StringBuilder(); final Elements hs = doc.select("h1, h2, h3, h4, h5"); if (hs.isEmpty()) { return ""; } listBuilder.append("<ul class=\"article-toc\">"); for (int i = 0; i < hs.size(); i++) { final Element element = hs.get(i); final String tagName = element.tagName().toLowerCase(); final String text = element.text(); final String id = "toc_" + tagName + "_" + i; element.before("<span id='" + id + "'></span>"); listBuilder.append("<li class='toc-").append(tagName).append("'><a href='#").append(id).append("'>").append(text).append( "</a></li>"); } listBuilder.append("</ul>"); article.put(Article.ARTICLE_CONTENT, doc.select("body").html()); return listBuilder.toString(); } }
src/main/java/org/b3log/symphony/service/ArticleQueryService.java
/* * Copyright (c) 2012-2016, b3log.org & hacpai.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 org.b3log.symphony.service; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.model.Role; import org.b3log.latke.model.User; import org.b3log.latke.repository.CompositeFilter; import org.b3log.latke.repository.CompositeFilterOperator; import org.b3log.latke.repository.Filter; import org.b3log.latke.repository.FilterOperator; import org.b3log.latke.repository.PropertyFilter; import org.b3log.latke.repository.Query; import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.repository.SortDirection; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.annotation.Service; import org.b3log.latke.util.CollectionUtils; import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Article; import org.b3log.symphony.model.Comment; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.Revision; import org.b3log.symphony.model.Tag; import org.b3log.symphony.model.UserExt; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.processor.channel.ArticleChannel; import org.b3log.symphony.repository.ArticleRepository; import org.b3log.symphony.repository.CommentRepository; import org.b3log.symphony.repository.DomainTagRepository; import org.b3log.symphony.repository.RevisionRepository; import org.b3log.symphony.repository.TagArticleRepository; import org.b3log.symphony.repository.TagRepository; import org.b3log.symphony.repository.UserRepository; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Markdowns; import org.b3log.symphony.util.Symphonys; import org.b3log.symphony.util.Times; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; /** * Article query service. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 2.22.14.29, Oct 12, 2016 * @since 0.2.0 */ @Service public class ArticleQueryService { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ArticleQueryService.class.getName()); /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Tag-Article repository. */ @Inject private TagArticleRepository tagArticleRepository; /** * Tag repository. */ @Inject private TagRepository tagRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Domain tag repository. */ @Inject private DomainTagRepository domainTagRepository; /** * Revision repository. */ @Inject private RevisionRepository revisionRepository; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * Short link query service. */ @Inject private ShortLinkQueryService shortLinkQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Count to fetch article tags for relevant articles. */ private static final int RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT = 3; /** * Get an articles by the specified title. * * @param title the specified title * @return article, returns {@code null} if not found */ public JSONObject getArticleByTitle(final String title) { try { return articleRepository.getByTitle(title); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article by title [" + title + "] failed", e); return null; } } /** * Gets article count of the specified day. * * @param day the specified day * @return article count */ public int getArticleCntInDay(final Date day) { final long time = day.getTime(); final long start = Times.getDayStartTime(time); final long end = Times.getDayEndTime(time); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, start), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN, end), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID) )); try { return (int) articleRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Count day article failed", e); return 1; } } /** * Gets article count of the specified month. * * @param day the specified month * @return article count */ public int getArticleCntInMonth(final Date day) { final long time = day.getTime(); final long start = Times.getMonthStartTime(time); final long end = Times.getMonthEndTime(time); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, start), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN, end), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID) )); try { return (int) articleRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Count month article failed", e); return 1; } } /** * Gets articles by the specified page number and page size. * * @param currentPageNum the specified page number * @param pageSize the specified page size * @param types the specified types * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getValidArticles(final int currentPageNum, final int pageSize, final int... types) throws ServiceException { try { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); if (null != types && types.length > 0) { final List<Filter> typeFilters = new ArrayList<>(); for (int i = 0; i < types.length; i++) { final int type = types[i]; typeFilters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.EQUAL, type)); } final CompositeFilter typeFilter = new CompositeFilter(CompositeFilterOperator.OR, typeFilters); final List<Filter> filters = new ArrayList<>(); filters.add(typeFilter); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); } else { query.setFilter(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); } final JSONObject result = articleRepository.get(query); return CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } } /** * Gets domain articles. * * @param avatarViewMode the specified avatar view mode * @param domainId the specified domain id * @param currentPageNum the specified current page number * @param pageSize the specified page size * @return result * @throws ServiceException service exception */ public JSONObject getDomainArticles(final int avatarViewMode, final String domainId, final int currentPageNum, final int pageSize) throws ServiceException { final JSONObject ret = new JSONObject(); ret.put(Article.ARTICLES, (Object) Collections.emptyList()); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); pagination.put(Pagination.PAGINATION_PAGE_COUNT, 0); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) Collections.emptyList()); try { final JSONArray domainTags = domainTagRepository.getByDomainId(domainId, 1, Integer.MAX_VALUE) .optJSONArray(Keys.RESULTS); if (domainTags.length() <= 0) { return ret; } final List<String> tagIds = new ArrayList<>(); for (int i = 0; i < domainTags.length(); i++) { tagIds.add(domainTags.optJSONObject(i).optString(Tag.TAG + "_" + Keys.OBJECT_ID)); } Query query = new Query().setFilter( new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.IN, tagIds)). setCurrentPageNum(currentPageNum).setPageSize(pageSize). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticles = result.optJSONArray(Keys.RESULTS); if (tagArticles.length() <= 0) { return ret; } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticles.length(); i++) { articleIds.add(tagArticles.optJSONObject(i).optString(Article.ARTICLE + "_" + Keys.OBJECT_ID)); } query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))). setPageCount(1).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(articleRepository.get(query).optJSONArray(Keys.RESULTS)); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); genParticipants(avatarViewMode, articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } catch (final RepositoryException | ServiceException e) { LOGGER.log(Level.ERROR, "Gets domain articles error", e); throw new ServiceException(e); } } /** * Gets the relevant articles of the specified article with the specified fetch size. * * <p> * The relevant articles exist the same tag with the specified article. * </p> * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @param fetchSize the specified fetch size * @return relevant articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRelevantArticles(final int avatarViewMode, final JSONObject article, final int fetchSize) throws ServiceException { final String tagsString = article.optString(Article.ARTICLE_TAGS); final String[] tagTitles = tagsString.split(","); final int tagTitlesLength = tagTitles.length; final int subCnt = tagTitlesLength > RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT ? RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT : tagTitlesLength; final List<Integer> tagIdx = CollectionUtils.getRandomIntegers(0, tagTitlesLength, subCnt); final int subFetchSize = fetchSize / subCnt; final Set<String> fetchedArticleIds = new HashSet<>(); final List<JSONObject> ret = new ArrayList<>(); try { for (int i = 0; i < tagIdx.size(); i++) { final String tagTitle = tagTitles[tagIdx.get(i)].trim(); final JSONObject tag = tagRepository.getByTitle(tagTitle); final String tagId = tag.optString(Keys.OBJECT_ID); JSONObject result = tagArticleRepository.getByTagId(tagId, 1, subFetchSize); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int j = 0; j < tagArticleRelations.length(); j++) { final String articleId = tagArticleRelations.optJSONObject(j).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID); if (fetchedArticleIds.contains(articleId)) { continue; } articleIds.add(articleId); fetchedArticleIds.add(articleId); } articleIds.remove(article.optString(Keys.OBJECT_ID)); final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)); result = articleRepository.get(query); ret.addAll(CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS))); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets relevant articles failed", e); throw new ServiceException(e); } } /** * Gets broadcasts (articles permalink equals to "aBroadcast"). * * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getBroadcasts(final int currentPageNum, final int pageSize) throws ServiceException { try { final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).setFilter( new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, "aBroadcast")). addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING); final JSONObject result = articleRepository.get(query); final JSONArray articles = result.optJSONArray(Keys.RESULTS); if (0 == articles.length()) { return Collections.emptyList(); } final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(articles); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); article.remove(Article.ARTICLE_CONTENT); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets broadcasts [currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + "] failed", e); throw new ServiceException(e); } } /** * Gets interest articles. * * @param currentPageNum the specified current page number * @param pageSize the specified fetch size * @param tagTitles the specified tag titles * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getInterests(final int currentPageNum, final int pageSize, final String... tagTitles) throws ServiceException { try { final List<JSONObject> tagList = new ArrayList<>(); for (final String tagTitle : tagTitles) { final JSONObject tag = tagRepository.getByTitle(tagTitle); if (null == tag) { continue; } tagList.add(tag); } final Map<String, Class<?>> articleFields = new HashMap<>(); articleFields.put(Article.ARTICLE_TITLE, String.class); articleFields.put(Article.ARTICLE_PERMALINK, String.class); articleFields.put(Article.ARTICLE_CREATE_TIME, Long.class); articleFields.put(Article.ARTICLE_AUTHOR_ID, String.class); final List<JSONObject> ret = new ArrayList<>(); if (!tagList.isEmpty()) { final List<JSONObject> tagArticles = getArticlesByTags(currentPageNum, pageSize, articleFields, tagList.toArray(new JSONObject[0])); for (final JSONObject article : tagArticles) { article.remove(Article.ARTICLE_T_PARTICIPANTS); article.remove(Article.ARTICLE_T_PARTICIPANT_NAME); article.remove(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL); article.remove(Article.ARTICLE_LATEST_CMT_TIME); article.remove(Article.ARTICLE_LATEST_CMTER_NAME); article.remove(Article.ARTICLE_UPDATE_TIME); article.remove(Article.ARTICLE_T_HEAT); article.remove(Article.ARTICLE_T_TITLE_EMOJI); article.remove(Common.TIME_AGO); article.put(Article.ARTICLE_CREATE_TIME, ((Date) article.get(Article.ARTICLE_CREATE_TIME)).getTime()); } ret.addAll(tagArticles); } final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(currentPageNum).setPageSize(pageSize).setCurrentPageNum(1); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } final JSONObject result = articleRepository.get(query); final List<JSONObject> recentArticles = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); ret.addAll(recentArticles); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } return ret; } catch (final RepositoryException | ServiceException | JSONException e) { LOGGER.log(Level.ERROR, "Gets interests failed", e); throw new ServiceException(e); } } /** * Gets news (articles tags contains "B3log Announcement"). * * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getNews(final int currentPageNum, final int pageSize) throws ServiceException { try { JSONObject oldAnnouncementTag = tagRepository.getByTitle("B3log Announcement"); JSONObject currentAnnouncementTag = tagRepository.getByTitle("B3log公告"); if (null == oldAnnouncementTag && null == currentAnnouncementTag) { return Collections.emptyList(); } if (null == oldAnnouncementTag) { oldAnnouncementTag = new JSONObject(); } if (null == currentAnnouncementTag) { currentAnnouncementTag = new JSONObject(); } Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(CompositeFilterOperator.or( new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, oldAnnouncementTag.optString(Keys.OBJECT_ID)), new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, currentAnnouncementTag.optString(Keys.OBJECT_ID)) )) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } final JSONObject sa = userQueryService.getSA(); final List<Filter> subFilters = new ArrayList<>(); subFilters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)); subFilters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_EMAIL, FilterOperator.EQUAL, sa.optString(User.USER_EMAIL))); query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, subFilters)) .addProjection(Article.ARTICLE_TITLE, String.class).addProjection(Article.ARTICLE_PERMALINK, String.class) .addProjection(Article.ARTICLE_CREATE_TIME, Long.class).addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING); result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); for (final JSONObject article : ret) { article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets news failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified tags (order by article create date desc). * * @param tags the specified tags * @param currentPageNum the specified page number * @param articleFields the specified article fields to return * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize, final Map<String, Class<?>> articleFields, final JSONObject... tags) throws ServiceException { try { final List<Filter> filters = new ArrayList<>(); for (final JSONObject tag : tags) { filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))); } Filter filter; if (filters.size() >= 2) { filter = new CompositeFilter(CompositeFilterOperator.OR, filters); } else { filter = filters.get(0); } // XXX: 这里的分页是有问题的,后面取文章的时候会少(因为一篇文章可以有多个标签,但是文章 id 一样) Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(filter).setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final Set<String> articleIds = new HashSet<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(UserExt.USER_AVATAR_VIEW_MODE_C_STATIC, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified city (order by article create date desc). * * @param avatarViewMode the specified avatar view mode * @param city the specified city * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByCity(final int avatarViewMode, final String city, final int currentPageNum, final int pageSize) throws ServiceException { try { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Article.ARTICLE_CITY, FilterOperator.EQUAL, city)) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); final Integer participantsCnt = Symphonys.getInt("cityArticleParticipantsCnt"); genParticipants(avatarViewMode, ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by city [" + city + "] failed", e); throw new ServiceException(e); } } /** * Gets articles by the specified tag (order by article create date desc). * * @param avatarViewMode the specified avatar view mode * @param sortMode the specified sort mode, 0: default, 1: hot, 2: score, 3: reply, 4: perfect * @param tag the specified tag * @param currentPageNum the specified page number * @param pageSize the specified page size * @return articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getArticlesByTag(final int avatarViewMode, final int sortMode, final JSONObject tag, final int currentPageNum, final int pageSize) throws ServiceException { try { Query query = new Query(); switch (sortMode) { case 0: query.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 1: query.addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 2: query.addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 3: query.addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; case 4: query.addSort(Article.ARTICLE_PERFECT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); break; default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); query.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID))) .setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum); } JSONObject result = tagArticleRepository.get(query); final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS); final List<String> articleIds = new ArrayList<>(); for (int i = 0; i < tagArticleRelations.length(); i++) { articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID)); } query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)); result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); switch (sortMode) { default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); case 0: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } }); break; case 1: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final int v = o2.optInt(Article.ARTICLE_COMMENT_CNT) - o1.optInt(Article.ARTICLE_COMMENT_CNT); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 2: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final double v = o2.optDouble(Article.REDDIT_SCORE) - o1.optDouble(Article.REDDIT_SCORE); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 3: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final long v = (o2.optLong(Article.ARTICLE_LATEST_CMT_TIME) - o1.optLong(Article.ARTICLE_LATEST_CMT_TIME)); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; case 4: Collections.sort(ret, new Comparator<JSONObject>() { @Override public int compare(final JSONObject o1, final JSONObject o2) { final long v = (o2.optLong(Article.ARTICLE_PERFECT) - o1.optLong(Article.ARTICLE_PERFECT)); if (0 == v) { return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)); } return v > 0 ? 1 : -1; } }); break; } organizeArticles(avatarViewMode, ret); final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt"); genParticipants(avatarViewMode, ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles by tag [tagTitle=" + tag.optString(Tag.TAG_TITLE) + "] failed", e); throw new ServiceException(e); } } /** * Gets an article by the specified client article id. * * @param authorId the specified author id * @param clientArticleId the specified client article id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticleByClientArticleId(final String authorId, final String clientArticleId) throws ServiceException { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, clientArticleId)); filters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, authorId)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); try { final JSONObject result = articleRepository.get(query); final JSONArray array = result.optJSONArray(Keys.RESULTS); if (0 == array.length()) { return null; } return array.optJSONObject(0); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article [clientArticleId=" + clientArticleId + "] failed", e); throw new ServiceException(e); } } /** * Gets an article with {@link #organizeArticle(org.json.JSONObject)} by the specified id. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticleById(final int avatarViewMode, final String articleId) throws ServiceException { Stopwatchs.start("Get article by id"); try { final JSONObject ret = articleRepository.get(articleId); if (null == ret) { return null; } organizeArticle(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } } /** * Gets an article by the specified id. * * @param articleId the specified id * @return article, return {@code null} if not found * @throws ServiceException service exception */ public JSONObject getArticle(final String articleId) throws ServiceException { try { final JSONObject ret = articleRepository.get(articleId); if (null == ret) { return null; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e); throw new ServiceException(e); } } /** * Gets article revisions. * * @param articleId the specified article id * @return article revisions, returns an empty list if not found */ public List<JSONObject> getArticleRevisions(final String articleId) { final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_ARTICLE) )).addSort(Keys.OBJECT_ID, SortDirection.ASCENDING); try { final List<JSONObject> ret = CollectionUtils.jsonArrayToList(revisionRepository.get(query).optJSONArray(Keys.RESULTS)); for (final JSONObject rev : ret) { final JSONObject data = new JSONObject(rev.optString(Revision.REVISION_DATA)); String articleTitle = data.optString(Article.ARTICLE_TITLE); articleTitle = articleTitle.replace("<", "&lt;").replace(">", "&gt;"); articleTitle = Markdowns.clean(articleTitle, ""); data.put(Article.ARTICLE_TITLE, articleTitle); String articleContent = data.optString(Article.ARTICLE_CONTENT); articleContent = Markdowns.toHTML(articleContent); articleContent = Markdowns.clean(articleContent, ""); data.put(Article.ARTICLE_CONTENT, articleContent); rev.put(Revision.REVISION_DATA, data); } return ret; } catch (final RepositoryException | JSONException e) { LOGGER.log(Level.ERROR, "Get article revisions failed", e); return Collections.emptyList(); } } /** * Gets preview content of the article specified with the given article id. * * @param articleId the given article id * @param request the specified request * @return preview content * @throws ServiceException service exception */ public String getArticlePreviewContent(final String articleId, final HttpServletRequest request) throws ServiceException { final JSONObject article = getArticle(articleId); if (null == article) { return null; } return getPreviewContent(article, request); } private String getPreviewContent(final JSONObject article, final HttpServletRequest request) throws ServiceException { Stopwatchs.start("Get preview content"); try { final int length = Integer.valueOf("150"); String ret = article.optString(Article.ARTICLE_CONTENT); final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userQueryService.getUser(authorId); if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS) || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { return langPropsService.get("articleContentBlockLabel"); } final Set<String> userNames = userQueryService.getUserNames(ret); final JSONObject currentUser = userQueryService.getCurrentUser(request); final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME); final String authorName = author.optString(User.USER_NAME); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) && !authorName.equals(currentUserName)) { boolean invited = false; for (final String userName : userNames) { if (userName.equals(currentUserName)) { invited = true; break; } } if (!invited) { String blockContent = langPropsService.get("articleDiscussionLabel"); blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath() + "/member/" + authorName + "'>" + authorName + "</a>"); return blockContent; } } ret = Emotions.convert(ret); ret = Markdowns.toHTML(ret); ret = Jsoup.clean(ret, Whitelist.none()); if (ret.length() >= length) { ret = StringUtils.substring(ret, 0, length) + " ...."; } return ret; } finally { Stopwatchs.end(); } } /** * Gets the user articles with the specified user id, page number and page size. * * @param avatarViewMode the specified avatar view mode * @param userId the specified user id * @param anonymous the specified article anonymous * @param currentPageNum the specified page number * @param pageSize the specified page size * @return user articles, return an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getUserArticles(final int avatarViewMode, final String userId, final int anonymous, final int currentPageNum, final int pageSize) throws ServiceException { final Query query = new Query().addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING) .setCurrentPageNum(currentPageNum).setPageSize(pageSize). setFilter(CompositeFilterOperator.and( new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Article.ARTICLE_ANONYMOUS, FilterOperator.EQUAL, anonymous), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))); try { final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); if (ret.isEmpty()) { return ret; } final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION); final int recordCount = pagination.optInt(Pagination.PAGINATION_RECORD_COUNT); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject first = ret.get(0); first.put(Pagination.PAGINATION_RECORD_COUNT, recordCount); first.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets user articles failed", e); throw new ServiceException(e); } } /** * Gets side hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getSideHotArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { final String id = String.valueOf(DateUtils.addDays(new Date(), -7).getTime()); try { final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).setCurrentPageNum(1).setPageSize(fetchSize); final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets hot articles failed", e); throw new ServiceException(e); } } /** * Gets the random articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return random articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRandomArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { try { final List<JSONObject> ret = articleRepository.getRandomly(fetchSize); organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets random articles failed", e); throw new ServiceException(e); } } /** * Makes article showing filters. * * @return filter the article showing to user */ private CompositeFilter makeArticleShowingFilter() { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); return new CompositeFilter(CompositeFilterOperator.AND, filters); } /** * Makes recent article showing filters. * * @return filter the article showing to user */ private CompositeFilter makeRecentArticleShowingFilter() { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); filters.add(new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_LIKE, "B3log%")); filters.add(new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_LIKE, "Sandbox%")); return new CompositeFilter(CompositeFilterOperator.AND, filters); } /** * Makes the recent (sort by create time desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentDefaultQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by comment count desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentHotQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by score desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentGoodQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the recent (sort by latest comment time desc) articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles query */ private Query makeRecentReplyQuery(final int currentPageNum, final int fetchSize) { final Query ret = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(fetchSize).setCurrentPageNum(currentPageNum); ret.setFilter(makeRecentArticleShowingFilter()); ret.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); return ret; } /** * Makes the top articles with the specified fetch size. * * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return top articles query */ private Query makeTopQuery(final int currentPageNum, final int fetchSize) { final Query query = new Query() .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .setPageCount(1).setPageSize(fetchSize).setCurrentPageNum(currentPageNum); query.setFilter(makeArticleShowingFilter()); return query; } /** * Gets the recent (sort by create time) articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param sortMode the specified sort mode, 0: default, 1: hot, 2: score, 3: reply * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception */ public JSONObject getRecentArticles(final int avatarViewMode, final int sortMode, final int currentPageNum, final int fetchSize) throws ServiceException { final JSONObject ret = new JSONObject(); Query query; switch (sortMode) { case 0: query = makeRecentDefaultQuery(currentPageNum, fetchSize); break; case 1: query = makeRecentHotQuery(currentPageNum, fetchSize); break; case 2: query = makeRecentGoodQuery(currentPageNum, fetchSize); break; case 3: query = makeRecentReplyQuery(currentPageNum, fetchSize); break; default: LOGGER.warn("Unknown sort mode [" + sortMode + "]"); query = makeRecentDefaultQuery(currentPageNum, fetchSize); } JSONObject result = null; try { Stopwatchs.start("Query recent articles"); result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } //final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); //genParticipants(articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } /** * Gets the index recent (sort by create time) articles. * * @param avatarViewMode the specified avatar view mode * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexRecentArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1).setPageCount(1); query.setFilter(makeRecentArticleShowingFilter()); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index recent articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index recent articles failed", e); throw new ServiceException(e); } } /** * Gets the hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param fetchSize the specified fetch size * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getHotArticles(final int avatarViewMode, final int fetchSize) throws ServiceException { final Query query = makeTopQuery(1, fetchSize); try { List<JSONObject> ret; Stopwatchs.start("Query hot articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); Stopwatchs.start("Checks author status"); try { for (final JSONObject article : ret) { final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); } } } finally { Stopwatchs.end(); } // final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt"); // genParticipants(ret, participantsCnt); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index articles failed", e); throw new ServiceException(e); } } /** * Gets the perfect articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception */ public JSONObject getPerfectArticles(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { final Query query = new Query() .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setCurrentPageNum(currentPageNum).setPageSize(fetchSize); query.setFilter(new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT)); final JSONObject ret = new JSONObject(); JSONObject result = null; try { Stopwatchs.start("Query recent articles"); result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final int windowSize = Symphonys.getInt("latestArticlesWindowSize"); final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } //final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt"); //genParticipants(articles, participantsCnt); ret.put(Article.ARTICLES, (Object) articles); return ret; } /** * Gets the index hot articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexHotArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING) .addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING) .setPageCount(1).setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1); query.setFilter(makeArticleShowingFilter()); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index hot articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index hot articles failed", e); throw new ServiceException(e); } } /** * Gets the index perfect articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @return hot articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getIndexPerfectArticles(final int avatarViewMode) throws ServiceException { final Query query = new Query() .addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setPageCount(1).setPageSize(Symphonys.getInt("indexListCnt")).setCurrentPageNum(1); query.setFilter(new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT)); query.addProjection(Keys.OBJECT_ID, String.class). addProjection(Article.ARTICLE_STICK, Long.class). addProjection(Article.ARTICLE_CREATE_TIME, Long.class). addProjection(Article.ARTICLE_UPDATE_TIME, Long.class). addProjection(Article.ARTICLE_LATEST_CMT_TIME, Long.class). addProjection(Article.ARTICLE_AUTHOR_ID, String.class). addProjection(Article.ARTICLE_TITLE, String.class). addProjection(Article.ARTICLE_STATUS, Integer.class). addProjection(Article.ARTICLE_VIEW_CNT, Integer.class). addProjection(Article.ARTICLE_TYPE, Integer.class). addProjection(Article.ARTICLE_PERMALINK, String.class). addProjection(Article.ARTICLE_TAGS, String.class). addProjection(Article.ARTICLE_LATEST_CMTER_NAME, String.class). addProjection(Article.ARTICLE_SYNC_TO_CLIENT, Boolean.class). addProjection(Article.ARTICLE_COMMENT_CNT, Integer.class). addProjection(Article.ARTICLE_ANONYMOUS, Integer.class). addProjection(Article.ARTICLE_PERFECT, Integer.class); try { List<JSONObject> ret; Stopwatchs.start("Query index perfect articles"); try { final JSONObject result = articleRepository.get(query); ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); } finally { Stopwatchs.end(); } organizeArticles(avatarViewMode, ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets index perfect articles failed", e); throw new ServiceException(e); } } /** * Gets the recent articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getRecentArticlesWithComments(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { return getArticles(avatarViewMode, makeRecentDefaultQuery(currentPageNum, fetchSize)); } /** * Gets the index articles with the specified fetch size. * * @param avatarViewMode the specified avatar view mode * @param currentPageNum the specified current page number * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception */ public List<JSONObject> getTopArticlesWithComments(final int avatarViewMode, final int currentPageNum, final int fetchSize) throws ServiceException { return getArticles(avatarViewMode, makeTopQuery(currentPageNum, fetchSize)); } /** * The specific articles. * * @param avatarViewMode the specified avatar view mode * @param query conditions * @return articles * @throws ServiceException service exception */ private List<JSONObject> getArticles(final int avatarViewMode, final Query query) throws ServiceException { try { final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(avatarViewMode, ret); final List<JSONObject> stories = new ArrayList<>(); for (final JSONObject article : ret) { final JSONObject story = new JSONObject(); final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) { story.put("title", langPropsService.get("articleTitleBlockLabel")); } else { story.put("title", article.optString(Article.ARTICLE_TITLE)); } story.put("id", article.optLong("oId")); story.put("url", Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); story.put("user_display_name", article.optString(Article.ARTICLE_T_AUTHOR_NAME)); story.put("user_job", author.optString(UserExt.USER_INTRO)); story.put("comment_html", article.optString(Article.ARTICLE_CONTENT)); story.put("comment_count", article.optInt(Article.ARTICLE_COMMENT_CNT)); story.put("vote_count", article.optInt(Article.ARTICLE_GOOD_CNT)); story.put("created_at", formatDate(article.get(Article.ARTICLE_CREATE_TIME))); story.put("user_portrait_url", article.optString(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL)); story.put("comments", getAllComments(avatarViewMode, article.optString("oId"))); final String tagsString = article.optString(Article.ARTICLE_TAGS); String[] tags = null; if (!Strings.isEmptyOrNull(tagsString)) { tags = tagsString.split(","); } story.put("badge", tags == null ? "" : tags[0]); stories.add(story); } final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt"); genParticipants(avatarViewMode, stories, participantsCnt); return stories; } catch (final RepositoryException | JSONException e) { LOGGER.log(Level.ERROR, "Gets index articles failed", e); throw new ServiceException(e); } } /** * Gets the article comments with the specified article id. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified article id * @return comments, return an empty list if not found * @throws ServiceException service exception * @throws JSONException json exception * @throws RepositoryException repository exception */ private List<JSONObject> getAllComments(final int avatarViewMode, final String articleId) throws ServiceException, JSONException, RepositoryException { final List<JSONObject> commments = new ArrayList<>(); final List<JSONObject> articleComments = commentQueryService.getArticleComments( avatarViewMode, articleId, 1, Integer.MAX_VALUE, UserExt.USER_COMMENT_VIEW_MODE_C_TRADITIONAL); for (final JSONObject ac : articleComments) { final JSONObject comment = new JSONObject(); final JSONObject author = userRepository.get(ac.optString(Comment.COMMENT_AUTHOR_ID)); comment.put("id", ac.optLong("oId")); comment.put("body_html", ac.optString(Comment.COMMENT_CONTENT)); comment.put("depth", 0); comment.put("user_display_name", ac.optString(Comment.COMMENT_T_AUTHOR_NAME)); comment.put("user_job", author.optString(UserExt.USER_INTRO)); comment.put("vote_count", 0); comment.put("created_at", formatDate(ac.get(Comment.COMMENT_CREATE_TIME))); comment.put("user_portrait_url", ac.optString(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL)); commments.add(comment); } return commments; } /** * The demand format date. * * @param date the original date * @return the format date like "2015-08-03T07:26:57Z" */ private String formatDate(final Object date) { return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd") + "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z"; } /** * Organizes the specified articles. * * <ul> * <li>converts create/update/latest comment time (long) to date type</li> * <li>generates author thumbnail URL</li> * <li>generates author name</li> * <li>escapes article title &lt; and &gt;</li> * <li>generates article heat</li> * <li>generates article view count display format(1k+/1.5k+...)</li> * <li>generates time ago text</li> * <li>generates stick remains minutes</li> * <li>anonymous process</li> * </ul> * * @param avatarViewMode the specified avatarViewMode * @param articles the specified articles * @throws RepositoryException repository exception */ public void organizeArticles(final int avatarViewMode, final List<JSONObject> articles) throws RepositoryException { Stopwatchs.start("Organize articles"); try { for (final JSONObject article : articles) { organizeArticle(avatarViewMode, article); } } finally { Stopwatchs.end(); } } /** * Organizes the specified article. * * <ul> * <li>converts create/update/latest comment time (long) to date type</li> * <li>generates author thumbnail URL</li> * <li>generates author name</li> * <li>escapes article title &lt; and &gt;</li> * <li>generates article heat</li> * <li>generates article view count display format(1k+/1.5k+...)</li> * <li>generates time ago text</li> * <li>generates stick remains minutes</li> * <li>anonymous process</li> * </ul> * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @throws RepositoryException repository exception */ public void organizeArticle(final int avatarViewMode, final JSONObject article) throws RepositoryException { toArticleDate(article); genArticleAuthor(avatarViewMode, article); String title = article.optString(Article.ARTICLE_TITLE).replace("<", "&lt;").replace(">", "&gt;"); title = Markdowns.clean(title, ""); article.put(Article.ARTICLE_TITLE, title); article.put(Article.ARTICLE_T_TITLE_EMOJI, Emotions.convert(title)); if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_T_TITLE_EMOJI, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel")); } final String articleId = article.optString(Keys.OBJECT_ID); Integer viewingCnt = ArticleChannel.ARTICLE_VIEWS.get(articleId); if (null == viewingCnt) { viewingCnt = 0; } article.put(Article.ARTICLE_T_HEAT, viewingCnt); final int viewCnt = article.optInt(Article.ARTICLE_VIEW_CNT); final double views = (double) viewCnt / 1000; if (views >= 1) { final DecimalFormat df = new DecimalFormat("#.#"); article.put(Article.ARTICLE_T_VIEW_CNT_DISPLAY_FORMAT, df.format(views) + "K"); } final long stick = article.optLong(Article.ARTICLE_STICK); long expired; if (stick > 0) { expired = stick + Symphonys.getLong("stickArticleTime"); final long remainsMills = Math.abs(System.currentTimeMillis() - expired); article.put(Article.ARTICLE_T_STICK_REMAINS, (int) Math.floor((double) remainsMills / 1000 / 60)); } else { article.put(Article.ARTICLE_T_STICK_REMAINS, 0); } String articleLatestCmterName = article.optString(Article.ARTICLE_LATEST_CMTER_NAME); if (StringUtils.isNotBlank(articleLatestCmterName) && UserRegisterValidation.invalidUserName(articleLatestCmterName)) { articleLatestCmterName = UserExt.ANONYMOUS_USER_NAME; article.put(Article.ARTICLE_LATEST_CMTER_NAME, articleLatestCmterName); } } /** * Converts the specified article create/update/latest comment time (long) to date type. * * @param article the specified article */ private void toArticleDate(final JSONObject article) { article.put(Common.TIME_AGO, Times.getTimeAgo(article.optLong(Article.ARTICLE_CREATE_TIME), Latkes.getLocale())); article.put(Article.ARTICLE_CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME))); article.put(Article.ARTICLE_UPDATE_TIME, new Date(article.optLong(Article.ARTICLE_UPDATE_TIME))); article.put(Article.ARTICLE_LATEST_CMT_TIME, new Date(article.optLong(Article.ARTICLE_LATEST_CMT_TIME))); } /** * Generates the specified article author name and thumbnail URL. * * @param avatarViewMode the specified avatar view mode * @param article the specified article * @throws RepositoryException repository exception */ private void genArticleAuthor(final int avatarViewMode, final JSONObject article) throws RepositoryException { final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); article.put(Article.ARTICLE_T_AUTHOR, author); if (Article.ARTICLE_ANONYMOUS_C_ANONYMOUS == article.optInt(Article.ARTICLE_ANONYMOUS)) { article.put(Article.ARTICLE_T_AUTHOR_NAME, UserExt.ANONYMOUS_USER_NAME); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "210", avatarQueryService.getDefaultAvatarURL("210")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "48", avatarQueryService.getDefaultAvatarURL("48")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "20", avatarQueryService.getDefaultAvatarURL("20")); } else { article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME)); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "210", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "210")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "48", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "48")); article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL + "20", avatarQueryService.getAvatarURLByUser(avatarViewMode, author, "20")); } } /** * Generates participants for the specified articles. * * @param avatarViewMode the specified avatar view mode * @param articles the specified articles * @param participantsCnt the specified generate size * @throws ServiceException service exception */ public void genParticipants(final int avatarViewMode, final List<JSONObject> articles, final Integer participantsCnt) throws ServiceException { Stopwatchs.start("Generates participants"); try { for (final JSONObject article : articles) { article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) Collections.emptyList()); if (article.optInt(Article.ARTICLE_COMMENT_CNT) < 1) { continue; } final List<JSONObject> articleParticipants = getArticleLatestParticipants( avatarViewMode, article.optString(Keys.OBJECT_ID), participantsCnt); article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) articleParticipants); } } finally { Stopwatchs.end(); } } /** * Gets the article participants (commenters) with the specified article article id and fetch size. * * @param avatarViewMode the specified avatar view mode * @param articleId the specified article id * @param fetchSize the specified fetch size * @return article participants, for example, <pre> * [ * { * "oId": "", * "articleParticipantName": "", * "articleParticipantThumbnailURL": "", * "articleParticipantThumbnailUpdateTime": long, * "commentId": "" * }, .... * ] * </pre>, returns an empty list if not found * * @throws ServiceException service exception */ public List<JSONObject> getArticleLatestParticipants(final int avatarViewMode, final String articleId, final int fetchSize) throws ServiceException { final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING) .setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId)) .addProjection(Comment.COMMENT_AUTHOR_EMAIL, String.class) .addProjection(Keys.OBJECT_ID, String.class) .addProjection(Comment.COMMENT_AUTHOR_ID, String.class) .setPageCount(1).setCurrentPageNum(1).setPageSize(fetchSize); final List<JSONObject> ret = new ArrayList<>(); try { final JSONObject result = commentRepository.get(query); final List<JSONObject> comments = new ArrayList<>(); final JSONArray records = result.optJSONArray(Keys.RESULTS); for (int i = 0; i < records.length(); i++) { final JSONObject comment = records.optJSONObject(i); boolean exist = false; // deduplicate for (final JSONObject c : comments) { if (comment.optString(Comment.COMMENT_AUTHOR_ID).equals( c.optString(Comment.COMMENT_AUTHOR_ID))) { exist = true; break; } } if (!exist) { comments.add(comment); } } for (final JSONObject comment : comments) { final String email = comment.optString(Comment.COMMENT_AUTHOR_EMAIL); final String userId = comment.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject commenter = userRepository.get(userId); String thumbnailURL = Symphonys.get("defaultThumbnailURL"); if (!UserExt.DEFAULT_CMTER_EMAIL.equals(email)) { thumbnailURL = avatarQueryService.getAvatarURLByUser(avatarViewMode, commenter, "48"); } final JSONObject participant = new JSONObject(); participant.put(Article.ARTICLE_T_PARTICIPANT_NAME, commenter.optString(User.USER_NAME)); participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, thumbnailURL); participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME)); participant.put(Article.ARTICLE_T_PARTICIPANT_URL, commenter.optString(User.USER_URL)); participant.put(Keys.OBJECT_ID, commenter.optString(Keys.OBJECT_ID)); participant.put(Comment.COMMENT_T_ID, comment.optString(Keys.OBJECT_ID)); ret.add(participant); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets article [" + articleId + "] participants failed", e); throw new ServiceException(e); } } /** * Processes the specified article content. * * <ul> * <li>Generates &#64;username home URL</li> * <li>Markdowns</li> * <li>Generates secured article content</li> * <li>Blocks the article if need</li> * <li>Generates emotion images</li> * <li>Generates article link with article id</li> * <li>Generates article abstract (preview content)</li> * <li>Generates article ToC</li> * </ul> * * @param article the specified article, for example, <pre> * { * "articleTitle": "", * ...., * "author": {} * } * </pre> * * @param request the specified request * @throws ServiceException service exception */ public void processArticleContent(final JSONObject article, final HttpServletRequest request) throws ServiceException { Stopwatchs.start("Process content"); try { final JSONObject author = article.optJSONObject(Article.ARTICLE_T_AUTHOR); if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS) || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel")); article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel")); article.put(Article.ARTICLE_T_PREVIEW_CONTENT, langPropsService.get("articleContentBlockLabel")); article.put(Article.ARTICLE_T_TOC, ""); article.put(Article.ARTICLE_REWARD_CONTENT, ""); article.put(Article.ARTICLE_REWARD_POINT, 0); return; } article.put(Article.ARTICLE_T_PREVIEW_CONTENT, article.optString(Article.ARTICLE_TITLE)); String articleContent = article.optString(Article.ARTICLE_CONTENT); article.put(Common.DISCUSSION_VIEWABLE, true); final Set<String> userNames = userQueryService.getUserNames(articleContent); final JSONObject currentUser = userQueryService.getCurrentUser(request); final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME); final String currentRole = null == currentUser ? "" : currentUser.optString(User.USER_ROLE); final String authorName = article.optString(Article.ARTICLE_T_AUTHOR_NAME); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) && !authorName.equals(currentUserName) && !Role.ADMIN_ROLE.equals(currentRole)) { boolean invited = false; for (final String userName : userNames) { if (userName.equals(currentUserName)) { invited = true; break; } } if (!invited) { String blockContent = langPropsService.get("articleDiscussionLabel"); blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath() + "/member/" + authorName + "'>" + authorName + "</a>"); article.put(Article.ARTICLE_CONTENT, blockContent); article.put(Common.DISCUSSION_VIEWABLE, false); article.put(Article.ARTICLE_REWARD_CONTENT, ""); article.put(Article.ARTICLE_REWARD_POINT, 0); article.put(Article.ARTICLE_T_TOC, ""); return; } } for (final String userName : userNames) { articleContent = articleContent.replace('@' + userName, "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a>"); } articleContent = shortLinkQueryService.linkArticle(articleContent); articleContent = shortLinkQueryService.linkTag(articleContent); articleContent = Emotions.convert(articleContent); article.put(Article.ARTICLE_CONTENT, articleContent); if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) { String articleRewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT); final Set<String> rewordContentUserNames = userQueryService.getUserNames(articleRewardContent); for (final String userName : rewordContentUserNames) { articleRewardContent = articleRewardContent.replace('@' + userName, "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a>"); } articleRewardContent = Emotions.convert(articleRewardContent); article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent); } markdown(article); final String articleId = article.optString(Keys.OBJECT_ID); // MP3 player render final StringBuffer contentBuilder = new StringBuffer(); articleContent = article.optString(Article.ARTICLE_CONTENT); final String MP3_URL_REGEX = "<p><a href.*\\.mp3.*</a>( )*</p>"; final Pattern p = Pattern.compile(MP3_URL_REGEX); final Matcher m = p.matcher(articleContent); int i = 0; while (m.find()) { String mp3URL = m.group(); String mp3Name = StringUtils.substringBetween(mp3URL, "\">", ".mp3</a>"); mp3URL = StringUtils.substringBetween(mp3URL, "href=\"", "\" rel="); final String playerId = "player" + articleId + i++; m.appendReplacement(contentBuilder, "<div id=\"" + playerId + "\" class=\"aplayer\"></div>\n" + "<script>\n" + "var " + playerId + " = new APlayer({\n" + " element: document.getElementById('" + playerId + "'),\n" + " narrow: false,\n" + " autoplay: false,\n" + " showlrc: false,\n" + " mutex: true,\n" + " theme: '#e6d0b2',\n" + " music: {\n" + " title: '" + mp3Name + "',\n" + " author: '" + mp3URL + "',\n" + " url: '" + mp3URL + "',\n" + " pic: '" + Latkes.getStaticServePath() + "/js/lib/aplayer/default.jpg'\n" + " }\n" + "});\n" + playerId + ".init();\n" + "</script>"); } m.appendTail(contentBuilder); articleContent = contentBuilder.toString(); articleContent = articleContent.replaceFirst("<div id=\"player", "<script src=\"" + Latkes.getStaticServePath() + "/js/lib/aplayer/APlayer.min.js\"></script>\n<div id=\"player"); article.put(Article.ARTICLE_CONTENT, articleContent); article.put(Article.ARTICLE_T_PREVIEW_CONTENT, getArticleMetaDesc(article)); article.put(Article.ARTICLE_T_TOC, getArticleToC(article)); } finally { Stopwatchs.end(); } } /** * Gets articles by the specified request json object. * * @param avatarViewMode the specified avatar view mode * @param requestJSONObject the specified request json object, for example, <pre> * { * "oId": "", // optional * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10 * }, see {@link Pagination} for more details * </pre> * * @param articleFields the specified article fields to return * * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "articles": [{ * "oId": "", * "articleTitle": "", * "articleContent": "", * .... * }, ....] * } * </pre> * * @throws ServiceException service exception * @see Pagination */ public JSONObject getArticles(final int avatarViewMode, final JSONObject requestJSONObject, final Map<String, Class<?>> articleFields) throws ServiceException { final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize). addSort(Article.ARTICLE_STICK, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) { query.addProjection(articleField.getKey(), articleField.getValue()); } if (requestJSONObject.has(Keys.OBJECT_ID)) { query.setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, requestJSONObject.optString(Keys.OBJECT_ID))); } JSONObject result = null; try { result = articleRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets articles failed", e); throw new ServiceException(e); } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); final JSONArray data = result.optJSONArray(Keys.RESULTS); final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data); try { organizeArticles(avatarViewMode, articles); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Organizes articles failed", e); throw new ServiceException(e); } ret.put(Article.ARTICLES, articles); return ret; } /** * Markdowns the specified article content. * * <ul> * <li>Markdowns article content/reward content</li> * <li>Generates secured article content/reward content</li> * </ul> * * @param article the specified article content */ private void markdown(final JSONObject article) { Stopwatchs.start("Markdown"); try { String content = article.optString(Article.ARTICLE_CONTENT); final int articleType = article.optInt(Article.ARTICLE_TYPE); if (Article.ARTICLE_TYPE_C_THOUGHT != articleType) { content = Markdowns.toHTML(content); content = Markdowns.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); } else { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); content = Jsoup.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK), Whitelist.relaxed().addAttributes(":all", "id", "target", "class"). addTags("span", "hr").addAttributes("iframe", "src", "width", "height") .addAttributes("audio", "controls", "src"), outputSettings); content = content.replace("\n", "\\n").replace("'", "\\'") .replace("\"", "\\\""); } article.put(Article.ARTICLE_CONTENT, content); if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) { String rewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT); rewardContent = Markdowns.toHTML(rewardContent); rewardContent = Markdowns.clean(rewardContent, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK)); article.put(Article.ARTICLE_REWARD_CONTENT, rewardContent); } } finally { Stopwatchs.end(); } } /** * Gets meta description content of the specified article. * * @param article the specified article * @return meta description */ private String getArticleMetaDesc(final JSONObject article) { Stopwatchs.start("Meta Desc"); try { final int length = Integer.valueOf("150"); String ret = article.optString(Article.ARTICLE_CONTENT); ret = Jsoup.clean(ret, Whitelist.none()); if (ret.length() >= length) { ret = StringUtils.substring(ret, 0, length) + " ...."; } ret = Jsoup.parse(ret).text(); ret = ret.replaceAll("\"", "'"); return ret; } finally { Stopwatchs.end(); } } /** * Gets ToC of the specified article. * * @param article the specified article * @return ToC */ private String getArticleToC(final JSONObject article) { String content = article.optString(Article.ARTICLE_CONTENT); if (!StringUtils.contains(content, "#") || Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { return ""; } final Document doc = Jsoup.parse(content, StringUtils.EMPTY, Parser.htmlParser()); doc.outputSettings().prettyPrint(false); final StringBuilder listBuilder = new StringBuilder(); final Elements hs = doc.select("h1, h2, h3, h4, h5"); if (hs.isEmpty()) { return ""; } listBuilder.append("<ul class=\"article-toc\">"); for (int i = 0; i < hs.size(); i++) { final Element element = hs.get(i); final String tagName = element.tagName().toLowerCase(); final String text = element.text(); final String id = "toc_" + tagName + "_" + i; element.before("<span id='" + id + "'></span>"); listBuilder.append("<li class='toc-").append(tagName).append("'><a href='#").append(id).append("'>").append(text).append( "</a></li>"); } listBuilder.append("</ul>"); article.put(Article.ARTICLE_CONTENT, doc.select("body").html()); return listBuilder.toString(); } }
改进 - 标签帖子列表性能优化
src/main/java/org/b3log/symphony/service/ArticleQueryService.java
改进 - 标签帖子列表性能优化
Java
apache-2.0
19ae0d0e00e7265b3282e8cb06b0060e500209b9
0
Addepar/buck,JoelMarcey/buck,brettwooldridge/buck,JoelMarcey/buck,facebook/buck,facebook/buck,Addepar/buck,romanoid/buck,SeleniumHQ/buck,JoelMarcey/buck,SeleniumHQ/buck,clonetwin26/buck,SeleniumHQ/buck,rmaz/buck,Addepar/buck,shs96c/buck,kageiit/buck,brettwooldridge/buck,Addepar/buck,shs96c/buck,brettwooldridge/buck,romanoid/buck,JoelMarcey/buck,JoelMarcey/buck,romanoid/buck,LegNeato/buck,nguyentruongtho/buck,LegNeato/buck,zpao/buck,ilya-klyuchnikov/buck,romanoid/buck,rmaz/buck,JoelMarcey/buck,kageiit/buck,shs96c/buck,shs96c/buck,clonetwin26/buck,ilya-klyuchnikov/buck,romanoid/buck,shs96c/buck,SeleniumHQ/buck,kageiit/buck,brettwooldridge/buck,rmaz/buck,brettwooldridge/buck,romanoid/buck,clonetwin26/buck,LegNeato/buck,clonetwin26/buck,ilya-klyuchnikov/buck,clonetwin26/buck,rmaz/buck,shs96c/buck,zpao/buck,ilya-klyuchnikov/buck,LegNeato/buck,clonetwin26/buck,LegNeato/buck,zpao/buck,SeleniumHQ/buck,nguyentruongtho/buck,brettwooldridge/buck,LegNeato/buck,shs96c/buck,rmaz/buck,romanoid/buck,ilya-klyuchnikov/buck,LegNeato/buck,shs96c/buck,ilya-klyuchnikov/buck,Addepar/buck,shs96c/buck,SeleniumHQ/buck,JoelMarcey/buck,kageiit/buck,shs96c/buck,facebook/buck,zpao/buck,rmaz/buck,rmaz/buck,romanoid/buck,clonetwin26/buck,JoelMarcey/buck,facebook/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,rmaz/buck,nguyentruongtho/buck,clonetwin26/buck,Addepar/buck,ilya-klyuchnikov/buck,Addepar/buck,romanoid/buck,brettwooldridge/buck,clonetwin26/buck,LegNeato/buck,JoelMarcey/buck,rmaz/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,zpao/buck,romanoid/buck,JoelMarcey/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,zpao/buck,ilya-klyuchnikov/buck,Addepar/buck,clonetwin26/buck,JoelMarcey/buck,rmaz/buck,nguyentruongtho/buck,Addepar/buck,brettwooldridge/buck,kageiit/buck,LegNeato/buck,kageiit/buck,LegNeato/buck,clonetwin26/buck,rmaz/buck,rmaz/buck,LegNeato/buck,JoelMarcey/buck,brettwooldridge/buck,SeleniumHQ/buck,romanoid/buck,rmaz/buck,Addepar/buck,facebook/buck,brettwooldridge/buck,nguyentruongtho/buck,clonetwin26/buck,LegNeato/buck,JoelMarcey/buck,SeleniumHQ/buck,brettwooldridge/buck,brettwooldridge/buck,Addepar/buck,Addepar/buck,zpao/buck,SeleniumHQ/buck,shs96c/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,clonetwin26/buck,SeleniumHQ/buck,shs96c/buck,LegNeato/buck,ilya-klyuchnikov/buck,romanoid/buck,kageiit/buck,romanoid/buck,Addepar/buck,shs96c/buck,brettwooldridge/buck,facebook/buck,SeleniumHQ/buck,facebook/buck
/* * Copyright 2017-present Facebook, 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.facebook.buck.cli; import static org.hamcrest.junit.MatcherAssert.assertThat; import static org.junit.Assume.assumeTrue; import com.facebook.buck.apple.AppleNativeIntegrationTestUtils; import com.facebook.buck.apple.toolchain.ApplePlatform; import com.facebook.buck.query.QueryException; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.testutil.integration.TestContext; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.NamedTemporaryFile; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; public class ParserCacheCommandIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Test public void testSaveAndLoad() throws IOException, InterruptedException, QueryException { assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProjectWorkspace.ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--load", tempFile.get().toString()); runBuckResult.assertSuccess(); // Perform the query again. If we didn't load the parser cache, this call would fail because // Apps/BUCK is empty. runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); } @Test public void testInvalidate() throws IOException, InterruptedException, QueryException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProjectWorkspace.ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); // Write an empty content to Apps/BUCK. Path invalidationJsonPath = tmp.getRoot().resolve("invalidation-data.json"); String jsonData = "[{\"path\":\"Apps/BUCK\",\"status\":\"M\"}]"; Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8)); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand( context, "parser-cache", "--load", tempFile.get().toString(), "--changes", invalidationJsonPath.toString()); runBuckResult.assertSuccess(); // Perform the query again. try { workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); } catch (HumanReadableException e) { assertThat( e.getMessage(), Matchers.containsString("//Apps:TestAppsLibrary could not be found")); } } }
test/com/facebook/buck/cli/ParserCacheCommandIntegrationTest.java
/* * Copyright 2017-present Facebook, 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.facebook.buck.cli; import static org.hamcrest.junit.MatcherAssert.assertThat; import com.facebook.buck.query.QueryException; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.testutil.integration.TestContext; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.NamedTemporaryFile; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; public class ParserCacheCommandIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Test public void testSaveAndLoad() throws IOException, InterruptedException, QueryException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProjectWorkspace.ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--load", tempFile.get().toString()); runBuckResult.assertSuccess(); // Perform the query again. If we didn't load the parser cache, this call would fail because // Apps/BUCK is empty. runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); } @Test public void testInvalidate() throws IOException, InterruptedException, QueryException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProjectWorkspace.ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); // Write an empty content to Apps/BUCK. Path invalidationJsonPath = tmp.getRoot().resolve("invalidation-data.json"); String jsonData = "[{\"path\":\"Apps/BUCK\",\"status\":\"M\"}]"; Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8)); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand( context, "parser-cache", "--load", tempFile.get().toString(), "--changes", invalidationJsonPath.toString()); runBuckResult.assertSuccess(); // Perform the query again. try { workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); } catch (HumanReadableException e) { assertThat( e.getMessage(), Matchers.containsString("//Apps:TestAppsLibrary could not be found")); } } }
Add checks for Apple SDK in ParserCacheCommandIntegrationTest Test Plan: CI Reviewed By: ttsugriy fbshipit-source-id: 5ab56ae
test/com/facebook/buck/cli/ParserCacheCommandIntegrationTest.java
Add checks for Apple SDK in ParserCacheCommandIntegrationTest
Java
apache-2.0
9fea1a9e309181777745b03a3cfdf63df7c8f2f4
0
AlexSafatli/NootBot
package net.dirtydeeds.discordsoundboard.games; import java.util.Date; import net.dirtydeeds.discordsoundboard.games.AbstractGameUpdateProcessor; import net.dirtydeeds.discordsoundboard.service.SoundboardBot; import net.dirtydeeds.discordsoundboard.utils.Strings; import net.dirtydeeds.discordsoundboard.utils.StyledEmbedMessage; import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.events.user.UserGameUpdateEvent; import net.dv8tion.jda.core.utils.SimpleLog; public class GenericGameStartProcessor extends AbstractGameUpdateProcessor { public static final SimpleLog LOG = SimpleLog.getLog("GameStartProcessor"); private static final int MIN_NUM_PLAYERS = 3; private static final int NUMBER_SEC_BETWEEN = 60; private static final int MAX_DURATION = 3; private GameStartEvent pastEvent; private String thumbnail; private class GameStartEvent { public VoiceChannel channel; public Date time; public Message message; public GameStartEvent(VoiceChannel channel, Date time, Message msg) { this.channel = channel; this.time = time; this.message = msg; } public void clear() { if (message != null) { message.deleteMessage().queue(); } } } public GenericGameStartProcessor(SoundboardBot bot) { super(bot); } public GenericGameStartProcessor(SoundboardBot bot, String url) { this(bot); thumbnail = url; } public boolean isApplicableUpdateEvent(UserGameUpdateEvent event, User user) { Guild guild = event.getGuild(); VoiceChannel userChannel = null, botChannel = bot.getConnectedChannel(guild); try { userChannel = bot.getUsersVoiceChannel(user); } catch (Exception e) { return false; } if (guild == null || userChannel == null || botChannel == null || !userChannel.equals(botChannel)) return false; Game game = guild.getMemberById(user.getId()).getGame(); return (game != null && userChannel.getMembers().size() >= MIN_NUM_PLAYERS); } protected void handleEvent(UserGameUpdateEvent event, User user) { int numPlayers = 0; Game currentGame = event.getGuild().getMemberById(user.getId()).getGame(); String game = currentGame.getName(); VoiceChannel channel = null; try { channel = bot.getUsersVoiceChannel(user); } catch (Exception e) { return; } // See if there have been multiple people that started playing the game in a channel. // If so: play a sound randomly from top played sounds. User[] users = new User[channel.getMembers().size()]; for (Member m : channel.getMembers()) { if (m.getGame() != null && m.getGame().getName().equals(game)) { users[numPlayers++] = m.getUser(); } } if (numPlayers >= MIN_NUM_PLAYERS) { LOG.info("Found " + user.getName() + " and " + numPlayers + " other users playing " + game + " in channel " + channel); Date now = new Date(System.currentTimeMillis()); if (pastEvent != null && pastEvent.channel != null && pastEvent.channel.equals(channel)) { long secSince = (now.getTime() - pastEvent.time.getTime())/1000; if (secSince < NUMBER_SEC_BETWEEN) { LOG.info("Not enough time since last event in this channel."); return; } } TextChannel publicChannel = channel.getGuild().getPublicChannel(); if (pastEvent != null) pastEvent.clear(); String filePlayed = bot.getRandomTopPlayedSoundName(MAX_DURATION); if (filePlayed != null) { try { bot.playFileForUser(filePlayed, user); pastEvent = new GameStartEvent(channel, now, m); publicChannel.sendMessage( announcement(filePlayed, game, users, numPlayers).getMessage()) .queue((Message m)-> pastEvent.message = m); LOG.info("Played random top sound in channel: \"" + filePlayed + "\"."); } catch (Exception e) { e.printStackTrace(); } } } } public StyledEmbedMessage announcement(String soundPlayed, String game, User[] users, int numPlaying) { StyledEmbedMessage m = new StyledEmbedMessage("Whoa! You're all playing a game."); String mentions = ""; for (int i = 0; i < numPlaying; ++i) { if (users[i] != null) { mentions += users[i].getAsMention() + " "; } } m.addDescription(formatString(Strings.GAME_START_MESSAGE, soundPlayed, game, mentions)); m.addContent("Annoying?", lookupString(Strings.SOUND_REPORT_INFO), false); if (thumbnail != null) m.setThumbnail(thumbnail); return m; } public boolean isMutuallyExclusive() { return false; } }
src/main/java/net/dirtydeeds/discordsoundboard/games/GenericGameStartProcessor.java
package net.dirtydeeds.discordsoundboard.games; import java.util.Date; import net.dirtydeeds.discordsoundboard.games.AbstractGameUpdateProcessor; import net.dirtydeeds.discordsoundboard.service.SoundboardBot; import net.dirtydeeds.discordsoundboard.utils.Strings; import net.dirtydeeds.discordsoundboard.utils.StyledEmbedMessage; import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.events.user.UserGameUpdateEvent; import net.dv8tion.jda.core.utils.SimpleLog; public class GenericGameStartProcessor extends AbstractGameUpdateProcessor { public static final SimpleLog LOG = SimpleLog.getLog("GameStartProcessor"); private static final int MIN_NUM_PLAYERS = 3; private static final int NUMBER_SEC_BETWEEN = 60; private static final int MAX_DURATION = 3; private GameStartEvent pastEvent; private String thumbnail; private class GameStartEvent { public VoiceChannel channel; public Date time; public Message message; public GameStartEvent(VoiceChannel channel, Date time, Message msg) { this.channel = channel; this.time = time; this.message = msg; } public void clear() { if (message != null) { message.deleteMessage().queue(); } } } public GenericGameStartProcessor(SoundboardBot bot) { super(bot); } public GenericGameStartProcessor(SoundboardBot bot, String url) { this(bot); thumbnail = url; } public boolean isApplicableUpdateEvent(UserGameUpdateEvent event, User user) { Guild guild = event.getGuild(); VoiceChannel userChannel = null, botChannel = bot.getConnectedChannel(guild); try { userChannel = bot.getUsersVoiceChannel(user); } catch (Exception e) { return false; } if (guild == null || userChannel == null || botChannel == null || !userChannel.equals(botChannel)) return false; Game game = guild.getMemberById(user.getId()).getGame(); return (game != null && userChannel.getMembers().size() >= MIN_NUM_PLAYERS); } protected void handleEvent(UserGameUpdateEvent event, User user) { int numPlayers = 0; Game currentGame = event.getGuild().getMemberById(user.getId()).getGame(); String game = currentGame.getName(); VoiceChannel channel = null; try { channel = bot.getUsersVoiceChannel(user); } catch (Exception e) { return; } // See if there have been multiple people that started playing the game in a channel. // If so: play a sound randomly from top played sounds. User[] users = new User[channel.getMembers().size()]; for (Member m : channel.getMembers()) { if (m.getGame() != null && m.getGame().getName().equals(game)) { users[numPlayers++] = m.getUser(); } } if (numPlayers >= MIN_NUM_PLAYERS) { LOG.info("Found " + user.getName() + " and " + numPlayers + " other users playing " + game + " in channel " + channel); Date now = new Date(System.currentTimeMillis()); if (pastEvent != null && pastEvent.channel != null && pastEvent.channel.equals(channel)) { long secSince = (now.getTime() - pastEvent.time.getTime())/1000; if (secSince < NUMBER_SEC_BETWEEN) { LOG.info("Not enough time since last event in this channel."); return; } } TextChannel publicChannel = channel.getGuild().getPublicChannel(); if (pastEvent != null) pastEvent.clear(); String filePlayed = bot.getRandomTopPlayedSoundName(MAX_DURATION); if (filePlayed != null) { try { bot.playFileForUser(filePlayed, user); publicChannel.sendMessage( announcement(filePlayed, game, users, numPlayers).getMessage()) .queue((Message m)-> pastEvent = new GameStartEvent(channel, now, m)); LOG.info("Played random top sound in channel: \"" + filePlayed + "\"."); } catch (Exception e) { e.printStackTrace(); } } } } public StyledEmbedMessage announcement(String soundPlayed, String game, User[] users, int numPlaying) { StyledEmbedMessage m = new StyledEmbedMessage("Whoa! You're all playing a game."); String mentions = ""; for (int i = 0; i < numPlaying; ++i) { if (users[i] != null) { mentions += users[i].getAsMention() + " "; } } m.addDescription(formatString(Strings.GAME_START_MESSAGE, soundPlayed, game, mentions)); m.addContent("Annoying?", lookupString(Strings.SOUND_REPORT_INFO), false); if (thumbnail != null) m.setThumbnail(thumbnail); return m; } public boolean isMutuallyExclusive() { return false; } }
Kawaiiii~
src/main/java/net/dirtydeeds/discordsoundboard/games/GenericGameStartProcessor.java
Kawaiiii~
Java
apache-2.0
8b3336ec49f6dd5575a8eef66825b84c831109f6
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.dalvik.activities; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.ViewTreeObserver; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.adapters.WiFiDirectAdapter; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.framework.DeviceDetailFragment; import org.commcare.android.framework.DeviceListFragment; import org.commcare.android.framework.DeviceListFragment.DeviceActionListener; import org.commcare.android.framework.FileServerFragment; import org.commcare.android.framework.FileServerFragment.FileServerListener; import org.commcare.android.framework.SessionAwareCommCareActivity; import org.commcare.android.framework.WiFiDirectManagementFragment; import org.commcare.android.framework.WiFiDirectManagementFragment.WifiDirectManagerListener; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.tasks.FormTransferTask; import org.commcare.android.tasks.SendTask; import org.commcare.android.tasks.UnzipTask; import org.commcare.android.tasks.WipeTask; import org.commcare.android.tasks.ZipTask; import org.commcare.android.tasks.templates.CommCareTask; import org.commcare.android.util.FileUtil; import org.commcare.dalvik.R; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.AlertDialogFactory; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.services.WiFiDirectBroadcastReceiver; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Vector; /** * An activity that uses WiFi Direct APIs to discover and connect with available * devices. WiFi Direct APIs are asynchronous and rely on callback mechanism * using interfaces to notify the application of operation success or failure. * The application should also register a BroadcastReceiver for notification of * WiFi state related events. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class CommCareWiFiDirectActivity extends SessionAwareCommCareActivity<CommCareWiFiDirectActivity> implements DeviceActionListener, FileServerListener, WifiDirectManagerListener { private static final String TAG = CommCareWiFiDirectActivity.class.getSimpleName(); public static final String KEY_NUMBER_DUMPED ="wd_num_dumped"; public WifiP2pManager mManager; public Channel mChannel; WiFiDirectBroadcastReceiver mReceiver; IntentFilter mIntentFilter; public enum wdState{send,receive,submit} private WiFiDirectAdapter adapter; public static String baseDirectory; public static String sourceDirectory; public static String sourceZipDirectory; public static String receiveDirectory; public static String receiveZipDirectory; public static String writeDirectory; public TextView myStatusText; public TextView formCountText; public TextView stateHeaderText; public TextView stateStatusText; public static final int FILE_SERVER_TASK_ID = 129123; public wdState mState = wdState.send; public FormRecord[] cachedRecords; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.wifi_direct_main); adapter = new WiFiDirectAdapter(this); myStatusText = (TextView)this.findViewById(R.id.my_status_text); formCountText = (TextView)this.findViewById(R.id.form_count_text); stateStatusText = (TextView)this.findViewById(R.id.wifi_state_status); stateHeaderText = (TextView)this.findViewById(R.id.wifi_state_header); String baseDir = this.getFilesDir().getAbsolutePath(); baseDirectory = baseDir + "/" + Localization.get("wifi.direct.base.folder"); sourceDirectory = baseDirectory + "/source"; sourceZipDirectory = baseDirectory + "/zipSource.zip"; receiveDirectory = baseDirectory + "/receive"; receiveZipDirectory = receiveDirectory + "/zipDest"; writeDirectory = baseDirectory + "/write"; mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); setupGridView(); changeState(); if(savedInstanceState == null){ showChangeStateDialog(); } } public void showChangeStateDialog(){ showDialog(this, localize("wifi.direct.change.state.title").toString(), localize("wifi.direct.change.state.text").toString()); } private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); } }); } /** * register the broadcast receiver */ protected void onResume() { super.onResume(); Logger.log(TAG, "resuming wi-fi direct activity"); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); mReceiver = new WiFiDirectBroadcastReceiver(mManager, fragment); registerReceiver(mReceiver, mIntentFilter); fragment.startReceiver(mManager, mChannel); updateStatusText(); } /** * unregister the broadcast receiver */ @Override protected void onPause() { super.onPause(); Logger.log(TAG, "Pausing wi-fi direct activity"); unregisterReceiver(mReceiver); } public void hostGroup(){ Logger.log(TAG, "Hosting Wi-fi direct group"); final FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); fsFragment.startServer(receiveZipDirectory); WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.isWifiP2pEnabled()){ Logger.log(TAG, "returning because Wi-fi direct is not available"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.wifi.direct.off"), Toast.LENGTH_SHORT).show(); return; } mManager.createGroup(mChannel, fragment); } public void changeState(){ adapter.updateDisplayData(); adapter.notifyDataSetChanged(); } public void showDialog(Activity activity, String title, String message) { AlertDialogFactory factory = new AlertDialogFactory(activity, title, message); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case AlertDialog.BUTTON_POSITIVE: beSubmitter(); break; case AlertDialog.BUTTON_NEUTRAL: beReceiver(); break; case AlertDialog.BUTTON_NEGATIVE: beSender(); break; } dialog.dismiss(); } }; factory.setNeutralButton(localize("wifi.direct.receive.forms"), listener); factory.setNegativeButton(localize("wifi.direct.transfer.forms"), listener); factory.setPositiveButton(localize("wifi.direct.submit.forms"), listener); showAlertDialog(factory); } public void beSender(){ myStatusText.setText(localize("wifi.direct.enter.send.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.show(wifiFragment); tr.show(fragmentList); tr.show(fragmentDetails); tr.hide(fsFragment); tr.commit(); wifiFragment.setIsHost(false); wifiFragment.resetConnectionGroup(); Logger.log(TAG, "Device designated as sender"); resetData(); mState = wdState.send; updateStatusText(); adapter.notifyDataSetChanged(); } public void beReceiver(){ Logger.log(AndroidLogger.TYPE_FORM_DUMP, "Became receiver"); myStatusText.setText(localize("wifi.direct.enter.receive.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.show(wifiFragment); tr.show(fragmentList); tr.show(fragmentDetails); tr.show(fsFragment); tr.commit(); wifiFragment.setIsHost(true); wifiFragment.resetConnectionGroup(); Logger.log(TAG, "Device designated as receiver"); resetData(); hostGroup(); mState = wdState.receive; updateStatusText(); adapter.notifyDataSetChanged(); } public void beSubmitter(){ Logger.log(AndroidLogger.TYPE_FORM_DUMP, "Became submitter"); unzipFilesHelper(); myStatusText.setText(localize("wifi.direct.enter.submit.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.hide(fsFragment); tr.hide(wifiFragment); tr.hide(fragmentList); tr.hide(fragmentDetails); tr.commit(); wifiFragment.setIsHost(false); wifiFragment.resetConnectionGroup(); mState = wdState.submit; updateStatusText(); adapter.notifyDataSetChanged(); } public void cleanPostSend(){ Logger.log(TAG, "cleaning forms after successful Wi-fi direct transfer"); // remove Forms from CC WipeTask mWipeTask = new WipeTask(getApplicationContext(), this.cachedRecords){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { receiver.onCleanSuccessful(); } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], WipeTask.WIPE_TASK_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.error.wiping.forms", e.getMessage())); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mWipeTask.connect(CommCareWiFiDirectActivity.this); mWipeTask.execute(); FileUtil.deleteFileOrDir(new File(sourceDirectory)); FileUtil.deleteFileOrDir(new File(sourceZipDirectory)); Logger.log(TAG, "Deleting dirs " + sourceDirectory + " and " + sourceZipDirectory); this.cachedRecords = null; } protected void onCleanSuccessful() { Logger.log(TAG, "clean successful"); updateStatusText(); } public void submitFiles(){ Logger.log(TAG, "submitting forms in Wi-fi direct activity"); unzipFilesHelper(); final String url = this.getString(R.string.PostURL); File receiveFolder = new File(writeDirectory); if(!receiveFolder.isDirectory() || !receiveFolder.exists()){ myStatusText.setText(Localization.get("wifi.direct.submit.missing", new String[] {receiveFolder.getPath()})); } File[] files = receiveFolder.listFiles(); if (files == null){ myStatusText.setText(localize("wifi.direct.error.no.forms")); transplantStyle(myStatusText, R.layout.template_text_notification_problem); return; } final int formsOnSD = files.length; //if there're no forms to dump, just return if(formsOnSD == 0){ myStatusText.setText(Localization.get("bulk.form.no.unsynced")); transplantStyle(myStatusText, R.layout.template_text_notification_problem); return; } SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); SendTask<CommCareWiFiDirectActivity> mSendTask = new SendTask<CommCareWiFiDirectActivity>( settings.getString("PostURL", url), receiveFolder){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { if(result == Boolean.TRUE){ Intent i = new Intent(getIntent()); i.putExtra(KEY_NUMBER_DUMPED, formsOnSD); receiver.setResult(BULK_SEND_ID, i); Logger.log(TAG, "Sucessfully dumped " + formsOnSD); receiver.finish(); } else { //assume that we've already set the error message, but make it look scary receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], BULK_SEND_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { Logger.log(TAG, "Error submitting forms in wi-fi direct with exception" + e.getMessage()); receiver.myStatusText.setText(Localization.get("bulk.form.error", new String[] {e.getMessage()})); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mSendTask.connect(CommCareWiFiDirectActivity.this); mSendTask.execute(); } public boolean unzipFilesHelper(){ File receiveZipDir = new File(receiveDirectory); if(!receiveZipDir.exists() || !(receiveZipDir.isDirectory())){ return false; } File[] zipDirContents = receiveZipDir.listFiles(); if(zipDirContents.length < 1){ return false; } myStatusText.setText(localize("wifi.direct.zip.unzipping")); for (File zipDirContent : zipDirContents) { unzipFiles(zipDirContent.getAbsolutePath()); } return true; } public void unzipFiles(String fn){ Logger.log(TAG, "Unzipping files in Wi-fi direct"); UnzipTask<CommCareWiFiDirectActivity> mUnzipTask = new UnzipTask<CommCareWiFiDirectActivity>() { @Override protected void deliverResult( CommCareWiFiDirectActivity receiver, Integer result) { Log.d(TAG, "delivering unzip result"); if(result > 0){ receiver.onUnzipSuccessful(result); } else { //assume that we've already set the error message, but make it look scary receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { Log.d(TAG, "delivering unzip upate"); receiver.updateProgress(update[0], CommCareTask.GENERIC_TASK_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { Log.d(TAG, "unzip deliver error: " + e.getMessage()); receiver.myStatusText.setText(Localization.get("mult.install.error", new String[] {e.getMessage()})); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mUnzipTask.connect(CommCareWiFiDirectActivity.this); Logger.log(TAG, "executing task with: " + fn + " , " + writeDirectory); mUnzipTask.execute(fn, writeDirectory); } /* if successful, broadcasts WIFI_P2P_Peers_CHANGED_ACTION intent with list of peers * received in WiFiDirectBroadcastReceiver class */ public void discoverPeers() { Logger.log(TAG, "Discovering Wi-fi direct peers"); WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.isWifiP2pEnabled()){ Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.wifi.direct.off"), Toast.LENGTH_SHORT).show(); return; } final DeviceListFragment dlFragment = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); dlFragment.onInitiateDiscovery(); mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.start"), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int reasonCode) { Logger.log(TAG, "Discovery of Wi-fi peers failed"); if (reasonCode == 0 || reasonCode == 2) { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.failed.generic"), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.failed.specific", "" + reasonCode), Toast.LENGTH_SHORT).show(); } } }); } public void resetData() { DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); if (fragmentList != null) { fragmentList.clearPeers(); } if (fragmentDetails != null) { fragmentDetails.resetViews(); } } @Override public void connect(WifiP2pConfig config) { Logger.log(TAG, "connecting to wi-fi peer"); mManager.connect(mChannel, config, new ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. } @Override public void onFailure(int reason) { Logger.log(TAG,"Connection to peer failed"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.connect.failed"), Toast.LENGTH_SHORT).show(); } }); } public static void deleteIfExists(String filePath){ File toDelete = new File(filePath); if(toDelete.exists()){ toDelete.delete(); } } public void prepareFileTransfer(){ Logger.log(TAG, "Preparing File Transfer"); CommCareWiFiDirectActivity.deleteIfExists(sourceZipDirectory); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.getDeviceConnected()){ myStatusText.setText(localize("wifi.direct.no.group")); return; } zipFiles(); } public void onZipSuccesful(FormRecord[] records){ Logger.log(TAG, "Successfully zipped files of size: " + records.length); myStatusText.setText(localize("wifi.direct.zip.successful")); this.cachedRecords = records; updateStatusText(); sendFiles(); } public void onZipError(){ FileUtil.deleteFileOrDir(new File(sourceDirectory)); Log.d(CommCareWiFiDirectActivity.TAG, "Zip unsuccesful"); } public void onUnzipSuccessful(Integer result){ Logger.log(TAG, "Successfully unzipped " + result.toString() + " files."); myStatusText.setText(localize("wifi.direct.receive.successful", result.toString())); if(!FileUtil.deleteFileOrDir(new File(receiveDirectory))){ Log.d(TAG, "source zip not succesfully deleted"); } updateStatusText(); } public void zipFiles(){ Logger.log(TAG, "Zipping Files"); ZipTask mZipTask = new ZipTask(this) { @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.zip.unsuccessful", e.getMessage())); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, FormRecord[] result) { if(result != null){ receiver.onZipSuccesful(result); } else { receiver.onZipError(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } }; mZipTask.connect(CommCareWiFiDirectActivity.this); mZipTask.execute(); } public void sendFiles(){ Logger.log(TAG, "Sending Files via Wi-fi Direct"); TextView statusText = myStatusText; statusText.setText(localize("wifi.direct.send.forms")); Log.d(CommCareWiFiDirectActivity.TAG, "Starting form transfer task" ); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); String address = fragment.getHostAddress(); FormTransferTask mTransferTask = new FormTransferTask(address,sourceZipDirectory,8988){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { if(result == Boolean.TRUE){ receiver.onSendSuccessful(); } else { receiver.onSendFail(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.send.unsuccessful")); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } }; mTransferTask.connect(CommCareWiFiDirectActivity.this); mTransferTask.execute(); Log.d(CommCareWiFiDirectActivity.TAG, "Task started"); } public void onSendSuccessful(){ Logger.log(TAG, "File Send Successful"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.send.successful"), Toast.LENGTH_SHORT).show(); updateStatusText(); myStatusText.setText(localize("wifi.direct.send.successful")); this.cleanPostSend(); } public void onSendFail(){ Logger.log(TAG, "Error Sending Files"); } public void updateStatusText(){ SqlStorage<FormRecord> storage = CommCareApplication._().getUserStorage(FormRecord.class); //Get all forms which are either unsent or unprocessed Vector<Integer> ids = storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_UNSENT}); ids.addAll(storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_COMPLETE})); int numUnsyncedForms = ids.size(); int numUnsubmittedForms = 0; File wDirectory = new File(writeDirectory); if(!wDirectory.exists() || !wDirectory.isDirectory()){ numUnsubmittedForms = 0; } else{ numUnsubmittedForms = wDirectory.listFiles().length; } if(mState.equals(wdState.send)){ stateHeaderText.setText(localize("wifi.direct.status.transfer.header")); formCountText.setText(localize("wifi.direct.status.transfer.count", ""+numUnsyncedForms)); stateStatusText.setText(localize("wifi.direct.status.transfer.message")); } else if(mState.equals(wdState.receive)){ stateHeaderText.setText(localize("wifi.direct.status.receive.header")); formCountText.setText(localize("wifi.direct.status.receive.count", ""+numUnsubmittedForms)); stateStatusText.setText(localize("wifi.direct.status.receive.message")); } else{ stateHeaderText.setText(localize("wifi.direct.status.submit.header")); formCountText.setText(localize("wifi.direct.status.submit.count", ""+numUnsubmittedForms)); stateStatusText.setText(localize("wifi.direct.status.submit.message")); } } public static boolean copyFile(InputStream inputStream, OutputStream out) { Logger.log(TAG, "File server copying file"); Log.d(CommCareWiFiDirectActivity.TAG, "Copying file"); if(inputStream == null){ Log.d(CommCareWiFiDirectActivity.TAG, "Input Null"); } byte buf[] = new byte[1024]; int len; try { while ((len = inputStream.read(buf)) != -1) { Log.d(CommCareWiFiDirectActivity.TAG, "Copying file : " + new String(buf)); out.write(buf, 0, len); } out.close(); inputStream.close(); } catch (IOException e) { Log.d(CommCareWiFiDirectActivity.TAG, e.toString()); Logger.log(TAG, "Copy in File Server failed"); return false; } Logger.log(TAG, "Copy in File Server successful"); return true; } @Override public void onFormsCopied(String result) { Logger.log(TAG, "Copied files successfully"); Log.d(CommCareWiFiDirectActivity.TAG, "onCopySuccess"); this.unzipFiles(result); } @Override public void updatePeers() { Logger.log(TAG, "Wi-Fi direct peers updating"); mManager.requestPeers(mChannel, (PeerListListener) this.getSupportFragmentManager() .findFragmentById(R.id.frag_list)); } @Override public void updateDeviceStatus(WifiP2pDevice mDevice) { Logger.log(TAG, "Wi-fi direct status updating"); DeviceListFragment fragment = (DeviceListFragment) this.getSupportFragmentManager() .findFragmentById(R.id.frag_list); fragment.updateThisDevice(mDevice); } /** * Implementation of generateProgressDialog() for DialogController -- other methods * handled entirely in CommCareActivity */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { String title, message; switch (taskId) { case ZipTask.ZIP_TASK_ID: title = localize("wifi.direct.zip.task.title").toString(); message = localize("wifi.direct.zip.task.message").toString(); break; case UnzipTask.UNZIP_TASK_ID: title = localize("wifi.direct.unzip.task.title").toString(); message = localize("wifi.direct.unzip.task.message").toString(); break; case SendTask.BULK_SEND_ID: title = localize("wifi.direct.submit.task.title").toString(); message = localize("wifi.direct.submit.task.message").toString(); break; case FormTransferTask.BULK_TRANSFER_ID: title = localize("wifi.direct.transfer.task.title").toString(); message = localize("wifi.direct.transfer.task.message").toString(); break; case FILE_SERVER_TASK_ID: title = localize("wifi.direct.receive.task.title").toString(); message = localize("wifi.direct.receive.task.message").toString(); break; case WipeTask.WIPE_TASK_ID: title = localize("wifi.direct.wipe.task.title").toString(); message = localize("wifi.direct.wipe.task.message").toString(); break; default: Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareWifiDirectActivity"); return null; } return CustomProgressDialog.newInstance(title, message, taskId); } }
app/src/org/commcare/dalvik/activities/CommCareWiFiDirectActivity.java
package org.commcare.dalvik.activities; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.adapters.HomeScreenAdapter; import org.commcare.android.adapters.SquareButtonViewHolder; import org.commcare.android.adapters.WiFiDirectAdapter; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.framework.DeviceDetailFragment; import org.commcare.android.framework.DeviceListFragment; import org.commcare.android.framework.DeviceListFragment.DeviceActionListener; import org.commcare.android.framework.FileServerFragment; import org.commcare.android.framework.FileServerFragment.FileServerListener; import org.commcare.android.framework.SessionAwareCommCareActivity; import org.commcare.android.framework.WiFiDirectManagementFragment; import org.commcare.android.framework.WiFiDirectManagementFragment.WifiDirectManagerListener; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.tasks.FormTransferTask; import org.commcare.android.tasks.SendTask; import org.commcare.android.tasks.UnzipTask; import org.commcare.android.tasks.WipeTask; import org.commcare.android.tasks.ZipTask; import org.commcare.android.tasks.templates.CommCareTask; import org.commcare.android.util.FileUtil; import org.commcare.android.view.SquareButtonWithText; import org.commcare.dalvik.R; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.AlertDialogFactory; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.services.WiFiDirectBroadcastReceiver; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Vector; /** * An activity that uses WiFi Direct APIs to discover and connect with available * devices. WiFi Direct APIs are asynchronous and rely on callback mechanism * using interfaces to notify the application of operation success or failure. * The application should also register a BroadcastReceiver for notification of * WiFi state related events. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class CommCareWiFiDirectActivity extends SessionAwareCommCareActivity<CommCareWiFiDirectActivity> implements DeviceActionListener, FileServerListener, WifiDirectManagerListener { private static final String TAG = CommCareWiFiDirectActivity.class.getSimpleName(); public static final String KEY_NUMBER_DUMPED ="wd_num_dumped"; public WifiP2pManager mManager; public Channel mChannel; WiFiDirectBroadcastReceiver mReceiver; IntentFilter mIntentFilter; public enum wdState{send,receive,submit} private WiFiDirectAdapter adapter; public static String baseDirectory; public static String sourceDirectory; public static String sourceZipDirectory; public static String receiveDirectory; public static String receiveZipDirectory; public static String writeDirectory; public TextView myStatusText; public TextView formCountText; public TextView stateHeaderText; public TextView stateStatusText; public static final int FILE_SERVER_TASK_ID = 129123; public wdState mState = wdState.send; public FormRecord[] cachedRecords; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.wifi_direct_main); adapter = new WiFiDirectAdapter(this); myStatusText = (TextView)this.findViewById(R.id.my_status_text); formCountText = (TextView)this.findViewById(R.id.form_count_text); stateStatusText = (TextView)this.findViewById(R.id.wifi_state_status); stateHeaderText = (TextView)this.findViewById(R.id.wifi_state_header); String baseDir = this.getFilesDir().getAbsolutePath(); baseDirectory = baseDir + "/" + Localization.get("wifi.direct.base.folder"); sourceDirectory = baseDirectory + "/source"; sourceZipDirectory = baseDirectory + "/zipSource.zip"; receiveDirectory = baseDirectory + "/receive"; receiveZipDirectory = receiveDirectory + "/zipDest"; writeDirectory = baseDirectory + "/write"; mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); setupGridView(); changeState(); if(savedInstanceState == null){ showChangeStateDialog(); } } public void showChangeStateDialog(){ showDialog(this, localize("wifi.direct.change.state.title").toString(), localize("wifi.direct.change.state.text").toString()); } private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); configUI(); } }); } private void configUI() { } /** * register the broadcast receiver */ protected void onResume() { super.onResume(); Logger.log(TAG, "resuming wi-fi direct activity"); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); mReceiver = new WiFiDirectBroadcastReceiver(mManager, fragment); registerReceiver(mReceiver, mIntentFilter); fragment.startReceiver(mManager, mChannel); updateStatusText(); } /** * unregister the broadcast receiver */ @Override protected void onPause() { super.onPause(); Logger.log(TAG, "Pausing wi-fi direct activity"); unregisterReceiver(mReceiver); } public void hostGroup(){ Logger.log(TAG, "Hosting Wi-fi direct group"); final FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); fsFragment.startServer(receiveZipDirectory); WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.isWifiP2pEnabled()){ Logger.log(TAG, "returning because Wi-fi direct is not available"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.wifi.direct.off"), Toast.LENGTH_SHORT).show(); return; } mManager.createGroup(mChannel, fragment); } public void changeState(){ adapter.updateDisplayData(); adapter.notifyDataSetChanged(); } public void showDialog(Activity activity, String title, String message) { AlertDialogFactory factory = new AlertDialogFactory(activity, title, message); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case AlertDialog.BUTTON_POSITIVE: beSubmitter(); break; case AlertDialog.BUTTON_NEUTRAL: beReceiver(); break; case AlertDialog.BUTTON_NEGATIVE: beSender(); break; } dialog.dismiss(); } }; factory.setNeutralButton(localize("wifi.direct.receive.forms"), listener); factory.setNegativeButton(localize("wifi.direct.transfer.forms"), listener); factory.setPositiveButton(localize("wifi.direct.submit.forms"), listener); showAlertDialog(factory); } public void beSender(){ myStatusText.setText(localize("wifi.direct.enter.send.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.show(wifiFragment); tr.show(fragmentList); tr.show(fragmentDetails); tr.hide(fsFragment); tr.commit(); wifiFragment.setIsHost(false); wifiFragment.resetConnectionGroup(); Logger.log(TAG, "Device designated as sender"); resetData(); mState = wdState.send; updateStatusText(); adapter.notifyDataSetChanged(); } public void beReceiver(){ Logger.log(AndroidLogger.TYPE_FORM_DUMP, "Became receiver"); myStatusText.setText(localize("wifi.direct.enter.receive.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.show(wifiFragment); tr.show(fragmentList); tr.show(fragmentDetails); tr.show(fsFragment); tr.commit(); wifiFragment.setIsHost(true); wifiFragment.resetConnectionGroup(); Logger.log(TAG, "Device designated as receiver"); resetData(); hostGroup(); mState = wdState.receive; updateStatusText(); adapter.notifyDataSetChanged(); } public void beSubmitter(){ Logger.log(AndroidLogger.TYPE_FORM_DUMP, "Became submitter"); unzipFilesHelper(); myStatusText.setText(localize("wifi.direct.enter.submit.mode")); WiFiDirectManagementFragment wifiFragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); FileServerFragment fsFragment = (FileServerFragment) getSupportFragmentManager() .findFragmentById(R.id.file_server_fragment); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.hide(fsFragment); tr.hide(wifiFragment); tr.hide(fragmentList); tr.hide(fragmentDetails); tr.commit(); wifiFragment.setIsHost(false); wifiFragment.resetConnectionGroup(); mState = wdState.submit; updateStatusText(); adapter.notifyDataSetChanged(); } public void cleanPostSend(){ Logger.log(TAG, "cleaning forms after successful Wi-fi direct transfer"); // remove Forms from CC WipeTask mWipeTask = new WipeTask(getApplicationContext(), this.cachedRecords){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { receiver.onCleanSuccessful(); } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], WipeTask.WIPE_TASK_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.error.wiping.forms", e.getMessage())); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mWipeTask.connect(CommCareWiFiDirectActivity.this); mWipeTask.execute(); FileUtil.deleteFileOrDir(new File(sourceDirectory)); FileUtil.deleteFileOrDir(new File(sourceZipDirectory)); Logger.log(TAG, "Deleting dirs " + sourceDirectory + " and " + sourceZipDirectory); this.cachedRecords = null; } protected void onCleanSuccessful() { Logger.log(TAG, "clean successful"); updateStatusText(); } public void submitFiles(){ Logger.log(TAG, "submitting forms in Wi-fi direct activity"); unzipFilesHelper(); final String url = this.getString(R.string.PostURL); File receiveFolder = new File(writeDirectory); if(!receiveFolder.isDirectory() || !receiveFolder.exists()){ myStatusText.setText(Localization.get("wifi.direct.submit.missing", new String[] {receiveFolder.getPath()})); } File[] files = receiveFolder.listFiles(); if (files == null){ myStatusText.setText(localize("wifi.direct.error.no.forms")); transplantStyle(myStatusText, R.layout.template_text_notification_problem); return; } final int formsOnSD = files.length; //if there're no forms to dump, just return if(formsOnSD == 0){ myStatusText.setText(Localization.get("bulk.form.no.unsynced")); transplantStyle(myStatusText, R.layout.template_text_notification_problem); return; } SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); SendTask<CommCareWiFiDirectActivity> mSendTask = new SendTask<CommCareWiFiDirectActivity>( settings.getString("PostURL", url), receiveFolder){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { if(result == Boolean.TRUE){ Intent i = new Intent(getIntent()); i.putExtra(KEY_NUMBER_DUMPED, formsOnSD); receiver.setResult(BULK_SEND_ID, i); Logger.log(TAG, "Sucessfully dumped " + formsOnSD); receiver.finish(); } else { //assume that we've already set the error message, but make it look scary receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], BULK_SEND_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { Logger.log(TAG, "Error submitting forms in wi-fi direct with exception" + e.getMessage()); receiver.myStatusText.setText(Localization.get("bulk.form.error", new String[] {e.getMessage()})); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mSendTask.connect(CommCareWiFiDirectActivity.this); mSendTask.execute(); } public boolean unzipFilesHelper(){ File receiveZipDir = new File(receiveDirectory); if(!receiveZipDir.exists() || !(receiveZipDir.isDirectory())){ return false; } File[] zipDirContents = receiveZipDir.listFiles(); if(zipDirContents.length < 1){ return false; } myStatusText.setText(localize("wifi.direct.zip.unzipping")); for (File zipDirContent : zipDirContents) { unzipFiles(zipDirContent.getAbsolutePath()); } return true; } public void unzipFiles(String fn){ Logger.log(TAG, "Unzipping files in Wi-fi direct"); UnzipTask<CommCareWiFiDirectActivity> mUnzipTask = new UnzipTask<CommCareWiFiDirectActivity>() { @Override protected void deliverResult( CommCareWiFiDirectActivity receiver, Integer result) { Log.d(TAG, "delivering unzip result"); if(result > 0){ receiver.onUnzipSuccessful(result); } else { //assume that we've already set the error message, but make it look scary receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { Log.d(TAG, "delivering unzip upate"); receiver.updateProgress(update[0], CommCareTask.GENERIC_TASK_ID); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { Log.d(TAG, "unzip deliver error: " + e.getMessage()); receiver.myStatusText.setText(Localization.get("mult.install.error", new String[] {e.getMessage()})); receiver.transplantStyle(myStatusText, R.layout.template_text_notification_problem); } }; mUnzipTask.connect(CommCareWiFiDirectActivity.this); Logger.log(TAG, "executing task with: " + fn + " , " + writeDirectory); mUnzipTask.execute(fn, writeDirectory); } /* if successful, broadcasts WIFI_P2P_Peers_CHANGED_ACTION intent with list of peers * received in WiFiDirectBroadcastReceiver class */ public void discoverPeers() { Logger.log(TAG, "Discovering Wi-fi direct peers"); WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.isWifiP2pEnabled()){ Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.wifi.direct.off"), Toast.LENGTH_SHORT).show(); return; } final DeviceListFragment dlFragment = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); dlFragment.onInitiateDiscovery(); mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.start"), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int reasonCode) { Logger.log(TAG, "Discovery of Wi-fi peers failed"); if (reasonCode == 0 || reasonCode == 2) { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.failed.generic"), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.discovery.failed.specific", "" + reasonCode), Toast.LENGTH_SHORT).show(); } } }); } public void resetData() { DeviceListFragment fragmentList = (DeviceListFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_list); DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.frag_detail); if (fragmentList != null) { fragmentList.clearPeers(); } if (fragmentDetails != null) { fragmentDetails.resetViews(); } } @Override public void connect(WifiP2pConfig config) { Logger.log(TAG, "connecting to wi-fi peer"); mManager.connect(mChannel, config, new ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. } @Override public void onFailure(int reason) { Logger.log(TAG,"Connection to peer failed"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.connect.failed"), Toast.LENGTH_SHORT).show(); } }); } public static void deleteIfExists(String filePath){ File toDelete = new File(filePath); if(toDelete.exists()){ toDelete.delete(); } } public void prepareFileTransfer(){ Logger.log(TAG, "Preparing File Transfer"); CommCareWiFiDirectActivity.deleteIfExists(sourceZipDirectory); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); if(!fragment.getDeviceConnected()){ myStatusText.setText(localize("wifi.direct.no.group")); return; } zipFiles(); } public void onZipSuccesful(FormRecord[] records){ Logger.log(TAG, "Successfully zipped files of size: " + records.length); myStatusText.setText(localize("wifi.direct.zip.successful")); this.cachedRecords = records; updateStatusText(); sendFiles(); } public void onZipError(){ FileUtil.deleteFileOrDir(new File(sourceDirectory)); Log.d(CommCareWiFiDirectActivity.TAG, "Zip unsuccesful"); } public void onUnzipSuccessful(Integer result){ Logger.log(TAG, "Successfully unzipped " + result.toString() + " files."); myStatusText.setText(localize("wifi.direct.receive.successful", result.toString())); if(!FileUtil.deleteFileOrDir(new File(receiveDirectory))){ Log.d(TAG, "source zip not succesfully deleted"); } updateStatusText(); } public void zipFiles(){ Logger.log(TAG, "Zipping Files"); ZipTask mZipTask = new ZipTask(this) { @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.zip.unsuccessful", e.getMessage())); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, FormRecord[] result) { if(result != null){ receiver.onZipSuccesful(result); } else { receiver.onZipError(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } }; mZipTask.connect(CommCareWiFiDirectActivity.this); mZipTask.execute(); } public void sendFiles(){ Logger.log(TAG, "Sending Files via Wi-fi Direct"); TextView statusText = myStatusText; statusText.setText(localize("wifi.direct.send.forms")); Log.d(CommCareWiFiDirectActivity.TAG, "Starting form transfer task" ); final WiFiDirectManagementFragment fragment = (WiFiDirectManagementFragment) getSupportFragmentManager() .findFragmentById(R.id.wifi_manager_fragment); String address = fragment.getHostAddress(); FormTransferTask mTransferTask = new FormTransferTask(address,sourceZipDirectory,8988){ @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Boolean result) { if(result == Boolean.TRUE){ receiver.onSendSuccessful(); } else { receiver.onSendFail(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.send.unsuccessful")); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } }; mTransferTask.connect(CommCareWiFiDirectActivity.this); mTransferTask.execute(); Log.d(CommCareWiFiDirectActivity.TAG, "Task started"); } public void onSendSuccessful(){ Logger.log(TAG, "File Send Successful"); Toast.makeText(CommCareWiFiDirectActivity.this, localize("wifi.direct.send.successful"), Toast.LENGTH_SHORT).show(); updateStatusText(); myStatusText.setText(localize("wifi.direct.send.successful")); this.cleanPostSend(); } public void onSendFail(){ Logger.log(TAG, "Error Sending Files"); } public void updateStatusText(){ SqlStorage<FormRecord> storage = CommCareApplication._().getUserStorage(FormRecord.class); //Get all forms which are either unsent or unprocessed Vector<Integer> ids = storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_UNSENT}); ids.addAll(storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_COMPLETE})); int numUnsyncedForms = ids.size(); int numUnsubmittedForms = 0; File wDirectory = new File(writeDirectory); if(!wDirectory.exists() || !wDirectory.isDirectory()){ numUnsubmittedForms = 0; } else{ numUnsubmittedForms = wDirectory.listFiles().length; } if(mState.equals(wdState.send)){ stateHeaderText.setText(localize("wifi.direct.status.transfer.header")); formCountText.setText(localize("wifi.direct.status.transfer.count", ""+numUnsyncedForms)); stateStatusText.setText(localize("wifi.direct.status.transfer.message")); } else if(mState.equals(wdState.receive)){ stateHeaderText.setText(localize("wifi.direct.status.receive.header")); formCountText.setText(localize("wifi.direct.status.receive.count", ""+numUnsubmittedForms)); stateStatusText.setText(localize("wifi.direct.status.receive.message")); } else{ stateHeaderText.setText(localize("wifi.direct.status.submit.header")); formCountText.setText(localize("wifi.direct.status.submit.count", ""+numUnsubmittedForms)); stateStatusText.setText(localize("wifi.direct.status.submit.message")); } } public static boolean copyFile(InputStream inputStream, OutputStream out) { Logger.log(TAG, "File server copying file"); Log.d(CommCareWiFiDirectActivity.TAG, "Copying file"); if(inputStream == null){ Log.d(CommCareWiFiDirectActivity.TAG, "Input Null"); } byte buf[] = new byte[1024]; int len; try { while ((len = inputStream.read(buf)) != -1) { Log.d(CommCareWiFiDirectActivity.TAG, "Copying file : " + new String(buf)); out.write(buf, 0, len); } out.close(); inputStream.close(); } catch (IOException e) { Log.d(CommCareWiFiDirectActivity.TAG, e.toString()); Logger.log(TAG, "Copy in File Server failed"); return false; } Logger.log(TAG, "Copy in File Server successful"); return true; } @Override public void onFormsCopied(String result) { Logger.log(TAG, "Copied files successfully"); Log.d(CommCareWiFiDirectActivity.TAG, "onCopySuccess"); this.unzipFiles(result); } @Override public void updatePeers() { Logger.log(TAG, "Wi-Fi direct peers updating"); mManager.requestPeers(mChannel, (PeerListListener) this.getSupportFragmentManager() .findFragmentById(R.id.frag_list)); } @Override public void updateDeviceStatus(WifiP2pDevice mDevice) { Logger.log(TAG, "Wi-fi direct status updating"); DeviceListFragment fragment = (DeviceListFragment) this.getSupportFragmentManager() .findFragmentById(R.id.frag_list); fragment.updateThisDevice(mDevice); } /** * Implementation of generateProgressDialog() for DialogController -- other methods * handled entirely in CommCareActivity */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { String title, message; switch (taskId) { case ZipTask.ZIP_TASK_ID: title = localize("wifi.direct.zip.task.title").toString(); message = localize("wifi.direct.zip.task.message").toString(); break; case UnzipTask.UNZIP_TASK_ID: title = localize("wifi.direct.unzip.task.title").toString(); message = localize("wifi.direct.unzip.task.message").toString(); break; case SendTask.BULK_SEND_ID: title = localize("wifi.direct.submit.task.title").toString(); message = localize("wifi.direct.submit.task.message").toString(); break; case FormTransferTask.BULK_TRANSFER_ID: title = localize("wifi.direct.transfer.task.title").toString(); message = localize("wifi.direct.transfer.task.message").toString(); break; case FILE_SERVER_TASK_ID: title = localize("wifi.direct.receive.task.title").toString(); message = localize("wifi.direct.receive.task.message").toString(); break; case WipeTask.WIPE_TASK_ID: title = localize("wifi.direct.wipe.task.title").toString(); message = localize("wifi.direct.wipe.task.message").toString(); break; default: Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareWifiDirectActivity"); return null; } return CustomProgressDialog.newInstance(title, message, taskId); } }
PR Comments
app/src/org/commcare/dalvik/activities/CommCareWiFiDirectActivity.java
PR Comments
Java
apache-2.0
bf3db39cffe09c9620089b9cff8d0c9cc9c571e3
0
mrdon/AMPS,mrdon/AMPS,mrdon/AMPS
package com.atlassian.maven.plugins.amps; import static com.google.common.collect.Iterables.transform; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.jfrog.maven.annomojo.annotations.MojoComponent; import org.jfrog.maven.annomojo.annotations.MojoGoal; import org.jfrog.maven.annomojo.annotations.MojoParameter; import org.jfrog.maven.annomojo.annotations.MojoRequiresDependencyResolution; import com.atlassian.maven.plugins.amps.product.ProductHandler; import com.atlassian.util.concurrent.AsyncCompleter; import com.atlassian.util.concurrent.ExceptionPolicy; import com.google.common.base.Function; /** * Run the integration tests against the webapp */ @MojoGoal("integration-test") @MojoRequiresDependencyResolution("test") public class IntegrationTestMojo extends AbstractTestGroupsHandlerMojo { /** * Pattern for to use to find integration tests. Only used if no test groups are defined. */ @MojoParameter(expression = "${functional.test.pattern}") private String functionalTestPattern = "it/**"; /** * The directory containing generated test classes of the project being tested. */ @MojoParameter(expression = "${project.build.testOutputDirectory}", required = true) private File testClassesDirectory; /** * A comma separated list of test groups to run. If not specified, all * test groups are run. */ @MojoParameter(expression = "${testGroups}") private String configuredTestGroupsToRun; /** * Whether the reference application will not be started or not */ @MojoParameter(expression = "${no.webapp}", defaultValue = "false") private boolean noWebapp = false; @MojoComponent private ArtifactHandlerManager artifactHandlerManager; @MojoParameter(expression="${maven.test.skip}", defaultValue = "false") private boolean testsSkip = false; @MojoParameter(expression="${skipTests}", defaultValue = "false") private boolean skipTests = false; protected void doExecute() throws MojoExecutionException { final MavenProject project = getMavenContext().getProject(); // workaround for MNG-1682/MNG-2426: force maven to install artifact using the "jar" handler project.getArtifact().setArtifactHandler(artifactHandlerManager.getArtifactHandler("jar")); if (!new File(testClassesDirectory, "it").exists()) { getLog().info("No integration tests found"); return; } if (skipTests || testsSkip) { getLog().info("Integration tests skipped"); return; } final MavenGoals goals = getMavenGoals(); final String pluginJar = targetDirectory.getAbsolutePath() + "/" + finalName + ".jar"; final Set<String> configuredTestGroupIds = getTestGroupIds(); if (configuredTestGroupIds.isEmpty()) { runTestsForTestGroup(NO_TEST_GROUP, goals, pluginJar, copy(systemPropertyVariables)); } else if (configuredTestGroupsToRun != null) { String[] testGroupIdsToRun = configuredTestGroupsToRun.split(","); // now run the tests for (String testGroupId : testGroupIdsToRun) { if (!configuredTestGroupIds.contains(testGroupId)) { getLog().warn("Test group " + testGroupId + " does not exist"); } else { runTestsForTestGroup(testGroupId, goals, pluginJar, copy(systemPropertyVariables)); } } } else { for (String testGroupId : configuredTestGroupIds) { runTestsForTestGroup(testGroupId, goals, pluginJar, copy(systemPropertyVariables)); } } } private Map<String,Object> copy(Map<String,Object> systemPropertyVariables) { return new HashMap<String,Object>(systemPropertyVariables); } /** * Returns product-specific properties to pass to the container during * integration testing. Default implementation does nothing. * @param product the {@code Product} object to use * @return a {@code Map} of properties to add to the system properties passed * to the container */ protected Map<String, String> getProductFunctionalTestProperties(Product product) { return Collections.emptyMap(); } private Set<String> getTestGroupIds() throws MojoExecutionException { Set<String> ids = new HashSet<String>(); //ids.addAll(ProductHandlerFactory.getIds()); for (TestGroup group : getTestGroups()) { ids.add(group.getId()); } return ids; } private void runTestsForTestGroup(String testGroupId, MavenGoals goals, String pluginJar, Map<String,Object> systemProperties) throws MojoExecutionException { List<String> includes = getIncludesForTestGroup(testGroupId); List<String> excludes = getExcludesForTestGroup(testGroupId); List<ProductExecution> productExecutions = getTestGroupProductExecutions(testGroupId); ExecutorService executor = Executors.newFixedThreadPool(productExecutions.size()); AsyncCompleter completer = new AsyncCompleter.Builder(executor).handleExceptions(ExceptionPolicy.Policies.THROW).build(); // Install the plugin in each product and start it for (Map<String, Object> productProperties : completer.invokeAll(transform(productExecutions, productStarter(pluginJar)))) { systemProperties.putAll(productProperties); } if (productExecutions.size() == 1) { Product product = productExecutions.get(0).getProduct(); systemProperties.put("http.port", systemProperties.get("http." + product.getInstanceId() + ".port")); systemProperties.put("context.path", product.getContextPath()); } systemProperties.put("testGroup", testGroupId); systemProperties.putAll(getTestGroupSystemProperties(testGroupId)); // Actually run the tests goals.runTests("group-" + testGroupId, containerId, includes, excludes, systemProperties, targetDirectory); // Shut all products down if (!noWebapp) { for (Void _ : completer.invokeAll(transform(productExecutions, productStopper()))) {} } executor.shutdown(); } private Function<ProductExecution, Callable<Map<String, Object>>> productStarter(final String pluginJar) { return new Function<ProductExecution, Callable<Map<String,Object>>>() { @Override public Callable<Map<String, Object>> apply(ProductExecution productExecution) { return new ProductStarter(pluginJar, productExecution); } }; } private final class ProductStarter implements Callable<Map<String, Object>> { private final String pluginJar; private final ProductExecution productExecution; public ProductStarter(String pluginJar, ProductExecution productExecution) { this.pluginJar = pluginJar; this.productExecution = productExecution; } @Override public Map<String, Object> call() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); ProductHandler productHandler = productExecution.getProductHandler(); Product product = productExecution.getProduct(); product.setInstallPlugin(installPlugin); int actualHttpPort = 0; if (!noWebapp) { actualHttpPort = productHandler.start(product); } String baseUrl = MavenGoals.getBaseUrl(product.getServer(), actualHttpPort, product.getContextPath()); // hard coded system properties... properties.put("http." + product.getInstanceId() + ".port", String.valueOf(actualHttpPort)); properties.put("context." + product.getInstanceId() + ".path", product.getContextPath()); properties.put("http." + product.getInstanceId() + ".url", MavenGoals.getBaseUrl(product.getServer(), actualHttpPort, product.getContextPath())); properties.put("baseurl." + product.getInstanceId(), baseUrl); properties.put("plugin.jar", pluginJar); properties.put("baseurl", baseUrl); properties.put("homedir." + product.getInstanceId(), productHandler.getHomeDirectory(product).getAbsolutePath()); if (!properties.containsKey("homedir")) { properties.put("homedir", productHandler.getHomeDirectory(product).getAbsolutePath()); } properties.putAll(getProductFunctionalTestProperties(product)); return properties; } } private Function<ProductExecution, Callable<Void>> productStopper() { return ProductStopper.INSTANCE; } enum ProductStopper implements Function<ProductExecution, Callable<Void>> { INSTANCE; @Override public Callable<Void> apply(final ProductExecution productExecution) { return new Callable<Void>() { @Override public Void call() throws Exception { productExecution.getProductHandler().stop(productExecution.getProduct()); return null; } }; } } private Map<String, String> getTestGroupSystemProperties(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.emptyMap(); } for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getSystemProperties(); } } return Collections.emptyMap(); } private List<String> getIncludesForTestGroup(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.singletonList(functionalTestPattern); } else { for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getIncludes(); } } } return Collections.singletonList(functionalTestPattern); } private List<String> getExcludesForTestGroup(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.emptyList(); } else { for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getExcludes(); } } } return Collections.emptyList(); } }
maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/IntegrationTestMojo.java
package com.atlassian.maven.plugins.amps; import static com.google.common.collect.Iterables.transform; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.jfrog.maven.annomojo.annotations.MojoComponent; import org.jfrog.maven.annomojo.annotations.MojoGoal; import org.jfrog.maven.annomojo.annotations.MojoParameter; import org.jfrog.maven.annomojo.annotations.MojoRequiresDependencyResolution; import com.atlassian.maven.plugins.amps.product.ProductHandler; import com.atlassian.util.concurrent.AsyncCompleter; import com.atlassian.util.concurrent.ExceptionPolicy; import com.google.common.base.Function; /** * Run the integration tests against the webapp */ @MojoGoal("integration-test") @MojoRequiresDependencyResolution("test") public class IntegrationTestMojo extends AbstractTestGroupsHandlerMojo { /** * Pattern for to use to find integration tests. Only used if no test groups are defined. */ @MojoParameter(expression = "${functional.test.pattern}") private String functionalTestPattern = "it/**"; /** * The directory containing generated test classes of the project being tested. */ @MojoParameter(expression = "${project.build.testOutputDirectory}", required = true) private File testClassesDirectory; /** * A comma separated list of test groups to run. If not specified, all * test groups are run. */ @MojoParameter(expression = "${testGroups}") private String configuredTestGroupsToRun; /** * Whether the reference application will not be started or not */ @MojoParameter(expression = "${no.webapp}", defaultValue = "false") private boolean noWebapp = false; @MojoComponent private ArtifactHandlerManager artifactHandlerManager; @MojoParameter(expression="${maven.test.skip}", defaultValue = "false") private boolean testsSkip = false; @MojoParameter(expression="${skipTests}", defaultValue = "false") private boolean skipTests = false; protected void doExecute() throws MojoExecutionException { final MavenProject project = getMavenContext().getProject(); // workaround for MNG-1682/MNG-2426: force maven to install artifact using the "jar" handler project.getArtifact().setArtifactHandler(artifactHandlerManager.getArtifactHandler("jar")); if (!new File(testClassesDirectory, "it").exists()) { getLog().info("No integration tests found"); return; } if (skipTests || testsSkip) { getLog().info("Integration tests skipped"); return; } final MavenGoals goals = getMavenGoals(); final String pluginJar = targetDirectory.getAbsolutePath() + "/" + finalName + ".jar"; final Set<String> configuredTestGroupIds = getTestGroupIds(); if (configuredTestGroupIds.isEmpty()) { runTestsForTestGroup(NO_TEST_GROUP, goals, pluginJar, copy(systemPropertyVariables)); } else if (configuredTestGroupsToRun != null) { String[] testGroupIdsToRun = configuredTestGroupsToRun.split(","); // now run the tests for (String testGroupId : testGroupIdsToRun) { if (!configuredTestGroupIds.contains(testGroupId)) { getLog().warn("Test group " + testGroupId + " does not exist"); } else { runTestsForTestGroup(testGroupId, goals, pluginJar, copy(systemPropertyVariables)); } } } else { for (String testGroupId : configuredTestGroupIds) { runTestsForTestGroup(testGroupId, goals, pluginJar, copy(systemPropertyVariables)); } } } private Map<String,Object> copy(Map<String,Object> systemPropertyVariables) { return new HashMap<String,Object>(systemPropertyVariables); } /** * Returns product-specific properties to pass to the container during * integration testing. Default implementation does nothing. * @param product the {@code Product} object to use * @return a {@code Map} of properties to add to the system properties passed * to the container */ protected Map<String, String> getProductFunctionalTestProperties(Product product) { return Collections.emptyMap(); } private Set<String> getTestGroupIds() throws MojoExecutionException { Set<String> ids = new HashSet<String>(); //ids.addAll(ProductHandlerFactory.getIds()); for (TestGroup group : getTestGroups()) { ids.add(group.getId()); } return ids; } private void runTestsForTestGroup(String testGroupId, MavenGoals goals, String pluginJar, Map<String,Object> systemProperties) throws MojoExecutionException { List<String> includes = getIncludesForTestGroup(testGroupId); List<String> excludes = getExcludesForTestGroup(testGroupId); List<ProductExecution> productExecutions = getTestGroupProductExecutions(testGroupId); ExecutorService executor = Executors.newFixedThreadPool(productExecutions.size()); AsyncCompleter completer = new AsyncCompleter.Builder(executor).handleExceptions(ExceptionPolicy.Policies.THROW).build(); // Install the plugin in each product and start it for (Map<String, Object> productProperties : completer.invokeAll(transform(productExecutions, productStarter(pluginJar)))) { systemProperties.putAll(productProperties); } if (productExecutions.size() == 1) { Product product = productExecutions.get(0).getProduct(); systemProperties.put("http.port", systemProperties.get("http." + product.getInstanceId() + ".port")); systemProperties.put("context.path", product.getContextPath()); } systemProperties.put("testGroup", testGroupId); systemProperties.putAll(getTestGroupSystemProperties(testGroupId)); // Actually run the tests goals.runTests("group-" + testGroupId, containerId, includes, excludes, systemProperties, targetDirectory); // Shut all products down if (!noWebapp) { completer.invokeAll(transform(productExecutions, productStopper())); } executor.shutdown(); } private Function<ProductExecution, Callable<Map<String, Object>>> productStarter(final String pluginJar) { return new Function<ProductExecution, Callable<Map<String,Object>>>() { @Override public Callable<Map<String, Object>> apply(ProductExecution productExecution) { return new ProductStarter(pluginJar, productExecution); } }; } private final class ProductStarter implements Callable<Map<String, Object>> { private final String pluginJar; private final ProductExecution productExecution; public ProductStarter(String pluginJar, ProductExecution productExecution) { this.pluginJar = pluginJar; this.productExecution = productExecution; } @Override public Map<String, Object> call() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); ProductHandler productHandler = productExecution.getProductHandler(); Product product = productExecution.getProduct(); product.setInstallPlugin(installPlugin); int actualHttpPort = 0; if (!noWebapp) { actualHttpPort = productHandler.start(product); } String baseUrl = MavenGoals.getBaseUrl(product.getServer(), actualHttpPort, product.getContextPath()); // hard coded system properties... properties.put("http." + product.getInstanceId() + ".port", String.valueOf(actualHttpPort)); properties.put("context." + product.getInstanceId() + ".path", product.getContextPath()); properties.put("http." + product.getInstanceId() + ".url", MavenGoals.getBaseUrl(product.getServer(), actualHttpPort, product.getContextPath())); properties.put("baseurl." + product.getInstanceId(), baseUrl); properties.put("plugin.jar", pluginJar); properties.put("baseurl", baseUrl); properties.put("homedir." + product.getInstanceId(), productHandler.getHomeDirectory(product).getAbsolutePath()); if (!properties.containsKey("homedir")) { properties.put("homedir", productHandler.getHomeDirectory(product).getAbsolutePath()); } properties.putAll(getProductFunctionalTestProperties(product)); return properties; } } private Function<ProductExecution, Callable<Void>> productStopper() { return ProductStopper.INSTANCE; } enum ProductStopper implements Function<ProductExecution, Callable<Void>> { INSTANCE; @Override public Callable<Void> apply(final ProductExecution productExecution) { return new Callable<Void>() { @Override public Void call() throws Exception { productExecution.getProductHandler().stop(productExecution.getProduct()); return null; } }; } } private Map<String, String> getTestGroupSystemProperties(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.emptyMap(); } for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getSystemProperties(); } } return Collections.emptyMap(); } private List<String> getIncludesForTestGroup(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.singletonList(functionalTestPattern); } else { for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getIncludes(); } } } return Collections.singletonList(functionalTestPattern); } private List<String> getExcludesForTestGroup(String testGroupId) { if (NO_TEST_GROUP.equals(testGroupId)) { return Collections.emptyList(); } else { for (TestGroup group : getTestGroups()) { if (group.getId().equals(testGroupId)) { return group.getExcludes(); } } } return Collections.emptyList(); } }
AMPS-515 make sure to wait for apps to finish shutting down git-svn-id: 883a21d237c46b75e72c0e9117e1cd5e6516cdf8@127323 2c54a935-e501-0410-bc05-97a93f6bca70
maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/IntegrationTestMojo.java
AMPS-515 make sure to wait for apps to finish shutting down
Java
apache-2.0
2ff952a9137955ae7ce16d7e8908c374b034db35
0
smadha/tika,icirellik/tika,icirellik/tika,zamattiac/tika,smadha/tika,smadha/tika,icirellik/tika,icirellik/tika,zamattiac/tika,zamattiac/tika,icirellik/tika,zamattiac/tika,smadha/tika,zamattiac/tika,smadha/tika,smadha/tika,smadha/tika,zamattiac/tika,zamattiac/tika,icirellik/tika,icirellik/tika,zamattiac/tika,icirellik/tika,smadha/tika
/* * 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.tika.parser.microsoft; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.PagedText; import org.apache.tika.metadata.Property; /** * Outlook Message Parser. */ class SummaryExtractor { private static final String SUMMARY_INFORMATION = SummaryInformation.DEFAULT_STREAM_NAME; private static final String DOCUMENT_SUMMARY_INFORMATION = DocumentSummaryInformation.DEFAULT_STREAM_NAME; private final Metadata metadata; public SummaryExtractor(Metadata metadata) { this.metadata = metadata; } public void parseSummaries(NPOIFSFileSystem filesystem) throws IOException, TikaException { parseSummaryEntryIfExists(filesystem, SUMMARY_INFORMATION); parseSummaryEntryIfExists(filesystem, DOCUMENT_SUMMARY_INFORMATION); } private void parseSummaryEntryIfExists( NPOIFSFileSystem filesystem, String entryName) throws IOException, TikaException { try { DocumentEntry entry = (DocumentEntry) filesystem.getRoot().getEntry(entryName); PropertySet properties = new PropertySet(new DocumentInputStream(entry)); if (properties.isSummaryInformation()) { parse(new SummaryInformation(properties)); } if (properties.isDocumentSummaryInformation()) { parse(new DocumentSummaryInformation(properties)); } } catch (FileNotFoundException e) { // entry does not exist, just skip it } catch (NoPropertySetStreamException e) { // no property stream, just skip it } catch (UnexpectedPropertySetTypeException e) { throw new TikaException("Unexpected HPSF document", e); } catch (MarkUnsupportedException e) { throw new TikaException("Invalid DocumentInputStream", e); } } private void parse(SummaryInformation summary) { set(Metadata.TITLE, summary.getTitle()); set(Metadata.AUTHOR, summary.getAuthor()); set(Metadata.KEYWORDS, summary.getKeywords()); set(Metadata.SUBJECT, summary.getSubject()); set(Metadata.LAST_AUTHOR, summary.getLastAuthor()); set(Metadata.COMMENTS, summary.getComments()); set(Metadata.TEMPLATE, summary.getTemplate()); set(Metadata.APPLICATION_NAME, summary.getApplicationName()); set(Metadata.REVISION_NUMBER, summary.getRevNumber()); set(Metadata.CREATION_DATE, summary.getCreateDateTime()); set(Metadata.CHARACTER_COUNT, summary.getCharCount()); set(Metadata.EDIT_TIME, summary.getEditTime()); set(Metadata.LAST_SAVED, summary.getLastSaveDateTime()); set(Metadata.PAGE_COUNT, summary.getPageCount()); if (summary.getPageCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getPageCount()); } set(Metadata.SECURITY, summary.getSecurity()); set(Metadata.WORD_COUNT, summary.getWordCount()); set(Metadata.LAST_PRINTED, summary.getLastPrinted()); } private void parse(DocumentSummaryInformation summary) { set(Metadata.COMPANY, summary.getCompany()); set(Metadata.MANAGER, summary.getManager()); set(Metadata.LANGUAGE, getLanguage(summary)); set(Metadata.CATEGORY, summary.getCategory()); set(Metadata.SLIDE_COUNT, summary.getSlideCount()); if (summary.getSlideCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getSlideCount()); } parse(summary.getCustomProperties()); } private String getLanguage(DocumentSummaryInformation summary) { CustomProperties customProperties = summary.getCustomProperties(); if (customProperties != null) { Object value = customProperties.get("Language"); if (value instanceof String) { return (String) value; } } return null; } /** * Attempt to parse custom document properties and add to the collection of metadata * @param customProperties */ private void parse(CustomProperties customProperties){ if (customProperties != null) { for (String name : customProperties.nameSet()) { // Apply the custom prefix String key = Metadata.USER_DEFINED_METADATA_NAME_PREFIX + name; // Get, convert and save property value Object value = customProperties.get(name); if (value instanceof String){ set(key, (String)value); } else if (value instanceof Date) { Property prop = Property.externalDate(key); metadata.set(prop, (Date)value); } else if (value instanceof Boolean) { Property prop = Property.externalBoolean(key); metadata.set(prop, ((Boolean)value).toString()); } else if (value instanceof Long) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Long)value).intValue()); } else if (value instanceof Double) { Property prop = Property.externalReal(key); metadata.set(prop, ((Double)value).doubleValue()); } else if (value instanceof Integer) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Integer)value).intValue()); } } } } private void set(String name, String value) { if (value != null) { metadata.set(name, value); } } private void set(Property property, Date value) { if (value != null) { metadata.set(property, value); } } private void set(String name, long value) { if (value > 0) { metadata.set(name, Long.toString(value)); } } }
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/SummaryExtractor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tika.parser.microsoft; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.PagedText; import org.apache.tika.metadata.Property; /** * Outlook Message Parser. */ class SummaryExtractor { private static final String SUMMARY_INFORMATION = SummaryInformation.DEFAULT_STREAM_NAME; private static final String DOCUMENT_SUMMARY_INFORMATION = DocumentSummaryInformation.DEFAULT_STREAM_NAME; private final Metadata metadata; public SummaryExtractor(Metadata metadata) { this.metadata = metadata; } public void parseSummaries(NPOIFSFileSystem filesystem) throws IOException, TikaException { parseSummaryEntryIfExists(filesystem, SUMMARY_INFORMATION); parseSummaryEntryIfExists(filesystem, DOCUMENT_SUMMARY_INFORMATION); } private void parseSummaryEntryIfExists( NPOIFSFileSystem filesystem, String entryName) throws IOException, TikaException { try { DocumentEntry entry = (DocumentEntry) filesystem.getRoot().getEntry(entryName); PropertySet properties = new PropertySet(new DocumentInputStream(entry)); if (properties.isSummaryInformation()) { parse(new SummaryInformation(properties)); } if (properties.isDocumentSummaryInformation()) { parse(new DocumentSummaryInformation(properties)); } } catch (FileNotFoundException e) { // entry does not exist, just skip it } catch (NoPropertySetStreamException e) { // no property stream, just skip it } catch (UnexpectedPropertySetTypeException e) { throw new TikaException("Unexpected HPSF document", e); } catch (MarkUnsupportedException e) { throw new TikaException("Invalid DocumentInputStream", e); } } private void parse(SummaryInformation summary) { set(Metadata.TITLE, summary.getTitle()); set(Metadata.AUTHOR, summary.getAuthor()); set(Metadata.KEYWORDS, summary.getKeywords()); set(Metadata.SUBJECT, summary.getSubject()); set(Metadata.LAST_AUTHOR, summary.getLastAuthor()); set(Metadata.COMMENTS, summary.getComments()); set(Metadata.TEMPLATE, summary.getTemplate()); set(Metadata.APPLICATION_NAME, summary.getApplicationName()); set(Metadata.REVISION_NUMBER, summary.getRevNumber()); set(Metadata.CREATION_DATE, summary.getCreateDateTime()); set(Metadata.CHARACTER_COUNT, summary.getCharCount()); set(Metadata.EDIT_TIME, summary.getEditTime()); set(Metadata.LAST_SAVED, summary.getLastSaveDateTime()); set(Metadata.PAGE_COUNT, summary.getPageCount()); if (summary.getPageCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getPageCount()); } set(Metadata.SECURITY, summary.getSecurity()); set(Metadata.WORD_COUNT, summary.getWordCount()); set(Metadata.LAST_PRINTED, summary.getLastPrinted()); } private void parse(DocumentSummaryInformation summary) { set(Metadata.COMPANY, summary.getCompany()); set(Metadata.MANAGER, summary.getManager()); set(Metadata.LANGUAGE, getLanguage(summary)); set(Metadata.CATEGORY, summary.getCategory()); set(Metadata.SLIDE_COUNT, summary.getSlideCount()); if (summary.getSlideCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getSlideCount()); } parse(summary.getCustomProperties()); } private String getLanguage(DocumentSummaryInformation summary) { CustomProperties customProperties = summary.getCustomProperties(); if (customProperties != null) { Object value = customProperties.get("Language"); if (value instanceof String) { return (String) value; } } return null; } /** * Attempt to parse custom document properties and add to the collection of metadata * @param customProperties */ private void parse(CustomProperties customProperties){ if (customProperties != null) { for (String key : customProperties.nameSet()) { Object value = customProperties.get(key); if (value == null) { // Continue, don't support empty properties } // Apply the custom prefix key = Metadata.USER_DEFINED_METADATA_NAME_PREFIX + key; // Convert and save if (value instanceof String){ set(key, (String)value); } else if (value instanceof Date) { Property prop = Property.externalDate(key); metadata.set(prop, (Date)value); } else if (value instanceof Boolean) { Property prop = Property.externalBoolean(key); metadata.set(prop, ((Boolean)value).toString()); } else if (value instanceof Long) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Long)value).intValue()); } else if (value instanceof Double) { Property prop = Property.externalReal(key); metadata.set(prop, ((Double)value).doubleValue()); } else if (value instanceof Integer) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Integer)value).intValue()); } } } } private void set(String name, String value) { if (value != null) { metadata.set(name, value); } } private void set(Property property, Date value) { if (value != null) { metadata.set(property, value); } } private void set(String name, long value) { if (value > 0) { metadata.set(name, Long.toString(value)); } } }
TIKA-375: Improve code quality metrics Streamline SummaryExtractor.parse() (avoid empty if) git-svn-id: de575e320ab8ef6bd6941acfb783cdb8d8307cc1@1125425 13f79535-47bb-0310-9956-ffa450edef68
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/SummaryExtractor.java
TIKA-375: Improve code quality metrics
Java
apache-2.0
9d7424b679e5be671d71f6822bba04ee72357081
0
mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict
/* * Copyright 2018 University of Michigan * * 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.verdictdb.core.execplan; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.verdictdb.commons.VerdictDBLogger; import org.verdictdb.connection.CachedDbmsConnection; import org.verdictdb.connection.DbmsConnection; import org.verdictdb.connection.DbmsQueryResult; import org.verdictdb.connection.JdbcConnection; import org.verdictdb.connection.SparkConnection; import org.verdictdb.core.querying.ExecutableNodeBase; import org.verdictdb.core.querying.SelectAggExecutionNode; import org.verdictdb.core.querying.ola.AsyncAggExecutionNode; import org.verdictdb.core.querying.ola.SelectAsyncAggExecutionNode; import org.verdictdb.core.querying.simplifier.ConsolidatedExecutionNode; import org.verdictdb.core.sqlobject.SqlConvertible; import org.verdictdb.exception.VerdictDBDbmsException; import org.verdictdb.exception.VerdictDBException; import org.verdictdb.exception.VerdictDBValueException; import org.verdictdb.sqlsyntax.MysqlSyntax; import org.verdictdb.sqlwriter.QueryToSql; public class ExecutableNodeRunner implements Runnable { DbmsConnection conn; ExecutableNode node; int successSourceCount = 0; int dependentCount; // private boolean isAborted = false; /** * initiated: node is created but has not started running running: currently running aborted: node * running cancelled while running cancelled: nod running cancelled before running completed: node * running successfully finished */ enum NodeRunningStatus { initiated, running, aborted, cancelled, completed, failed; } private NodeRunningStatus status = NodeRunningStatus.initiated; private VerdictDBLogger log = VerdictDBLogger.getLogger(this.getClass()); private Thread runningTask = null; private List<ExecutableNodeRunner> childRunners = new ArrayList<>(); public void markComplete() { status = NodeRunningStatus.completed; clearRunningTask(); } public void markFailure() { status = NodeRunningStatus.failed; clearRunningTask(); } public void markInitiated() { status = NodeRunningStatus.initiated; clearRunningTask(); } private void clearRunningTask() { this.runningTask = null; } public ExecutableNodeRunner(DbmsConnection conn, ExecutableNode node) { this.conn = conn; node.registerNodeRunner(this); this.node = node; this.dependentCount = node.getDependentNodeCount(); } public static ExecutionInfoToken execute(DbmsConnection conn, ExecutableNode node) throws VerdictDBException { return execute(conn, node, Arrays.<ExecutionInfoToken>asList()); } public static ExecutionInfoToken execute( DbmsConnection conn, ExecutableNode node, List<ExecutionInfoToken> tokens) throws VerdictDBException { return (new ExecutableNodeRunner(conn, node)).execute(tokens); } public NodeRunningStatus getStatus() { return status; } /** * Set aborted to the status of this node. */ public void setAborted() { // isAborted = true; // this will effectively end the loop within run(). status = NodeRunningStatus.aborted; // for (ExecutableNodeRunner runner : ((ExecutableNodeBase) node) ) { // runner.setAborted(); // } } public boolean alreadyRunning() { return status == NodeRunningStatus.running; } public boolean noNeedToRun() { return status == NodeRunningStatus.aborted || status == NodeRunningStatus.cancelled || status == NodeRunningStatus.completed || status == NodeRunningStatus.failed; } /** * Aborts this node. */ public void abort() { log.trace(String.format("Aborts running this node %s", node.toString())); setAborted(); if (node instanceof SelectAsyncAggExecutionNode) { ((SelectAsyncAggExecutionNode) node).abort(); } conn.abort(); // for (ExecutableNodeRunner runner : childRunners) { // runner.abort(); // } } public boolean runThisAndDependents() { // first run all children on separate threads // this function may be called again when run() is triggered upon a completion of one of // child nodes. Therefore, runChildren() is responsible for ensuring the same node does not // run again. runDependents(); return runOnThread(); } private boolean doesThisNodeContainAsyncAggExecutionNode() { ExecutableNodeBase leafOfThis = (ExecutableNodeBase) node; while (leafOfThis instanceof ConsolidatedExecutionNode) { leafOfThis = ((ConsolidatedExecutionNode) leafOfThis).getChildNode(); } return leafOfThis instanceof AsyncAggExecutionNode; } public boolean runOnThread() { log.trace(String.format("Invoked to run: %s", node.toString())); // https://stackoverflow.com/questions/11165852/java-singleton-and-synchronization Thread runningTask = this.runningTask; if (runningTask == null) { synchronized (this) { runningTask = this.runningTask; if (runningTask == null) { if (noNeedToRun()) { log.trace(String.format("No need to run: %s", node.toString())); return false; } status = NodeRunningStatus.running; runningTask = new Thread(this); this.runningTask = runningTask; runningTask.start(); return true; // this.runningTask is set to null at the end of run() } } } return false; } private int getMaxNumberOfRunningNode() { if ((conn instanceof JdbcConnection && conn.getSyntax() instanceof MysqlSyntax) || (conn instanceof CachedDbmsConnection && ((CachedDbmsConnection)conn).getOriginalConnection() instanceof JdbcConnection) && ((CachedDbmsConnection)conn).getOriginalConnection().getSyntax() instanceof MysqlSyntax) { // For MySQL, issue query one by one. if (node instanceof SelectAsyncAggExecutionNode || node instanceof AsyncAggExecutionNode) { return 1; } else { return 1; } } else if (((conn instanceof SparkConnection) || (conn instanceof CachedDbmsConnection && ((CachedDbmsConnection) conn).getOriginalConnection() instanceof SparkConnection)) && !(node instanceof SelectAsyncAggExecutionNode)) { // Since abort() does not work for Spark (or I don't know how to do so), we issue query // one by one. return 1; } else { return 10; } } private void runDependents() { if (doesThisNodeContainAsyncAggExecutionNode()) { int maxNumberOfRunningNode = getMaxNumberOfRunningNode(); int currentlyRunningOrCompleteNodeCount = childRunners.size(); // check the number of currently running nodes int runningChildCount = 0; int completedChildCount = 0; for (ExecutableNodeRunner r : childRunners) { if (r.getStatus() == NodeRunningStatus.running) { runningChildCount++; } else if (r.getStatus() == NodeRunningStatus.completed) { completedChildCount++; } } log.trace(String.format( "Running child: %d, Completed Child: %d, Success token received: %d", runningChildCount, completedChildCount, successSourceCount)); // maintain the number of running nodes to a certain number List<ExecutableNodeBase> childNodes = ((ExecutableNodeBase) node).getSources(); int moreToRun = Math.min( maxNumberOfRunningNode - runningChildCount, ((ExecutableNodeBase) node).getSourceCount() - currentlyRunningOrCompleteNodeCount); for (int i = currentlyRunningOrCompleteNodeCount; i < currentlyRunningOrCompleteNodeCount + moreToRun; i++) { ExecutableNodeBase child = childNodes.get(i); ExecutableNodeRunner runner = child.getRegisteredRunner(); boolean started = runner.runThisAndDependents(); if (started) { childRunners.add(runner); } } } else { // by default, run every child for (ExecutableNodeBase child : ((ExecutableNodeBase) node).getSources()) { ExecutableNodeRunner runner = child.getRegisteredRunner(); boolean started = runner.runThisAndDependents(); if (started) { childRunners.add(runner); } } } } /** * A single run of this method consumes all combinations of the tokens in the queue. */ @Override public synchronized void run() { // String nodeType = node.getClass().getSimpleName(); // int nodeGroupId = ((ExecutableNodeBase) node).getGroupId(); if (noNeedToRun()) { log.debug(String.format("This node (%s) has been aborted; do not run.", node.toString())); clearRunningTask(); return; } // no dependency exists if (node.getSourceQueues().size() == 0) { log.trace(String.format("No dependency exists. Simply run %s", node.toString())); try { executeAndBroadcast(Arrays.<ExecutionInfoToken>asList()); broadcastAndTriggerRun(ExecutionInfoToken.successToken()); markComplete(); //clearRunningTask(); return; } catch (Exception e) { if (noNeedToRun()) { // do nothing return; } else { e.printStackTrace(); broadcastAndTriggerRun(ExecutionInfoToken.failureToken(e)); } } markFailure(); // clearRunningTask(); return; } // dependency exists while (!noNeedToRun()) { // not enough source nodes are finished (i.e., tokens = null) // then, this loop immediately terminates. // this function will be called again whenever a child node completes. List<ExecutionInfoToken> tokens = retrieve(); if (tokens == null) { log.trace("Not enough source nodes are finished, loop terminates"); // markInitiated(); clearRunningTask(); return; } log.trace(String.format("Attempts to process %s (%s)", node.toString(), status)); ExecutionInfoToken failureToken = getFailureTokenIfExists(tokens); if (failureToken != null) { log.trace(String.format("One or more dependent nodes failed for %s", node.toString())); broadcastAndTriggerRun(failureToken); // clearRunningTask(); markFailure(); return; } if (areAllSuccess(tokens)) { log.trace(String.format("All dependent nodes are finished for %s", node.toString())); broadcastAndTriggerRun(ExecutionInfoToken.successToken()); //clearRunningTask(); markComplete(); return; } // This happens because some of the children (e.g., individual agg blocks) // finished their processing (with parts of blocks). // Since there still are other children to process, we continue operation. if (areAllStatusTokens(tokens)) { continue; } // actual processing try { log.trace( String.format("Main processing starts for %s with token: %s", node.toString(), tokens)); executeAndBroadcast(tokens); } catch (Exception e) { if (noNeedToRun()) { // do nothing return; } else { e.printStackTrace(); broadcastAndTriggerRun(ExecutionInfoToken.failureToken(e)); markFailure(); // clearRunningTask(); return; } } } } synchronized List<ExecutionInfoToken> retrieve() { Map<Integer, ExecutionTokenQueue> sourceChannelAndQueues = node.getSourceQueues(); for (ExecutionTokenQueue queue : sourceChannelAndQueues.values()) { ExecutionInfoToken rs = queue.peek(); if (rs == null) { return null; } } // all results available now List<ExecutionInfoToken> results = new ArrayList<>(); for (Entry<Integer, ExecutionTokenQueue> channelAndQueue : sourceChannelAndQueues.entrySet()) { int channel = channelAndQueue.getKey(); ExecutionInfoToken rs = channelAndQueue.getValue().take(); rs.setKeyValue("channel", channel); results.add(rs); } return results; } void broadcastAndTriggerRun(ExecutionInfoToken token) { if (noNeedToRun() && !areAllStatusTokens(Arrays.asList(token))) { log.trace( String.format( "This node (%s) has been aborted. Do not broadcast: %s", this.toString(), token)); return; } // for understandable logs synchronized (VerdictDBLogger.class) { VerdictDBLogger logger = VerdictDBLogger.getLogger(this.getClass()); logger.trace(String.format("[%s] Broadcasting:", node.toString())); logger.trace(token.toString()); for (ExecutableNode dest : node.getSubscribers()) { logger.trace(String.format(" -> %s", dest.toString())); } // logger.trace(token.toString()); } //if (node instanceof SelectAggExecutionNode && areAllStatusTokens(Arrays.asList(token))) { // status = NodeRunningStatus.completed; //} for (ExecutableNode dest : node.getSubscribers()) { ExecutionInfoToken copiedToken = token.deepcopy(); // set runner with success token complete before notifying subscriber if (copiedToken.isSuccessToken() && node.getRegisteredRunner().getStatus()!=NodeRunningStatus.completed) { node.getRegisteredRunner().status = NodeRunningStatus.completed; } dest.getNotified(node, copiedToken); // signal the runner of the broadcasted node so that its associated runner performs // execution if necessary. ExecutableNodeRunner runner = dest.getRegisteredRunner(); if (runner != null) { // runner.runOnThread(); log.trace("Broadcast: status " + status); runner.runThisAndDependents(); // this is needed due to async node. } } } void executeAndBroadcast(List<ExecutionInfoToken> tokens) throws VerdictDBException { ExecutionInfoToken resultToken = execute(tokens); if (resultToken != null) { broadcastAndTriggerRun(resultToken); } } /** * Execute the associated node. This method is synchronized on object level, assuming that * every node has its own associated ExecutableNodeRunner, which is actually the case. * * @param tokens Contains information from the downstream nodes. * @return Information for the upstream nodes. * @throws VerdictDBException */ public ExecutionInfoToken execute(List<ExecutionInfoToken> tokens) throws VerdictDBException { if (tokens.size() > 0 && tokens.get(0).isStatusToken()) { return null; } // basic operations: execute a query and creates a token based on that result. SqlConvertible sqlObj = node.createQuery(tokens); DbmsQueryResult intermediate = null; if (sqlObj != null) { String sql = QueryToSql.convert(conn.getSyntax(), sqlObj); try { intermediate = conn.execute(sql); } catch (VerdictDBDbmsException e) { if (noNeedToRun()) { // the errors from the underlying dbms are expected if the query is cancelled. } else { throw e; } } } ExecutionInfoToken token = node.createToken(intermediate); // extended operations: if the node has additional method invocation list, we perform the method // calls // on DbmsConnection and sets its results in the token. if (token == null) { token = new ExecutionInfoToken(); } Map<String, MethodInvocationInformation> tokenKeysAndmethodsToInvoke = node.getMethodsToInvokeOnConnection(); for (Entry<String, MethodInvocationInformation> keyAndMethod : tokenKeysAndmethodsToInvoke.entrySet()) { String tokenKey = keyAndMethod.getKey(); MethodInvocationInformation methodInfo = keyAndMethod.getValue(); String methodName = methodInfo.getMethodName(); Class<?>[] methodParameters = methodInfo.getMethodParameters(); Object[] methodArguments = methodInfo.getArguments(); try { Method method = conn.getClass().getMethod(methodName, methodParameters); Object ret = method.invoke(conn, methodArguments); token.setKeyValue(tokenKey, ret); } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); throw new VerdictDBValueException(e); } } return token; } ExecutionInfoToken getFailureTokenIfExists(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { // System.out.println(t); if (t.isFailureToken()) { // System.out.println("yes"); return t; } } return null; } boolean areAllStatusTokens(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { if (!t.isStatusToken()) { return false; } } return true; } boolean areAllSuccess(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { if (t.isSuccessToken()) { synchronized ((Object) successSourceCount) { successSourceCount++; } log.trace(String.format("Success count of %s: %d", node.toString(), successSourceCount)); } else { return false; } } if (successSourceCount == dependentCount) { return true; } else { return false; } } }
src/main/java/org/verdictdb/core/execplan/ExecutableNodeRunner.java
/* * Copyright 2018 University of Michigan * * 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.verdictdb.core.execplan; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.verdictdb.commons.VerdictDBLogger; import org.verdictdb.connection.CachedDbmsConnection; import org.verdictdb.connection.DbmsConnection; import org.verdictdb.connection.DbmsQueryResult; import org.verdictdb.connection.JdbcConnection; import org.verdictdb.connection.SparkConnection; import org.verdictdb.core.querying.ExecutableNodeBase; import org.verdictdb.core.querying.SelectAggExecutionNode; import org.verdictdb.core.querying.ola.AsyncAggExecutionNode; import org.verdictdb.core.querying.ola.SelectAsyncAggExecutionNode; import org.verdictdb.core.querying.simplifier.ConsolidatedExecutionNode; import org.verdictdb.core.sqlobject.SqlConvertible; import org.verdictdb.exception.VerdictDBDbmsException; import org.verdictdb.exception.VerdictDBException; import org.verdictdb.exception.VerdictDBValueException; import org.verdictdb.sqlsyntax.MysqlSyntax; import org.verdictdb.sqlwriter.QueryToSql; public class ExecutableNodeRunner implements Runnable { DbmsConnection conn; ExecutableNode node; int successSourceCount = 0; int dependentCount; int executionCount = 0; // private boolean isAborted = false; /** * initiated: node is created but has not started running running: currently running aborted: node * running cancelled while running cancelled: nod running cancelled before running completed: node * running successfully finished */ enum NodeRunningStatus { initiated, running, aborted, cancelled, completed, failed; } private NodeRunningStatus status = NodeRunningStatus.initiated; private VerdictDBLogger log = VerdictDBLogger.getLogger(this.getClass()); private Thread runningTask = null; private List<ExecutableNodeRunner> childRunners = new ArrayList<>(); public void markComplete() { status = NodeRunningStatus.completed; clearRunningTask(); } public void markFailure() { status = NodeRunningStatus.failed; clearRunningTask(); } public void markInitiated() { status = NodeRunningStatus.initiated; clearRunningTask(); } private void clearRunningTask() { this.runningTask = null; } public ExecutableNodeRunner(DbmsConnection conn, ExecutableNode node) { this.conn = conn; node.registerNodeRunner(this); this.node = node; this.dependentCount = node.getDependentNodeCount(); } public static ExecutionInfoToken execute(DbmsConnection conn, ExecutableNode node) throws VerdictDBException { return execute(conn, node, Arrays.<ExecutionInfoToken>asList()); } public static ExecutionInfoToken execute( DbmsConnection conn, ExecutableNode node, List<ExecutionInfoToken> tokens) throws VerdictDBException { return (new ExecutableNodeRunner(conn, node)).execute(tokens); } public NodeRunningStatus getStatus() { return status; } /** * Set aborted to the status of this node. */ public void setAborted() { // isAborted = true; // this will effectively end the loop within run(). status = NodeRunningStatus.aborted; // for (ExecutableNodeRunner runner : ((ExecutableNodeBase) node) ) { // runner.setAborted(); // } } public boolean alreadyRunning() { return status == NodeRunningStatus.running; } public boolean noNeedToRun() { return status == NodeRunningStatus.aborted || status == NodeRunningStatus.cancelled || status == NodeRunningStatus.completed || status == NodeRunningStatus.failed; } /** * Aborts this node. */ public void abort() { log.trace(String.format("Aborts running this node %s", node.toString())); setAborted(); if (node instanceof SelectAsyncAggExecutionNode) { ((SelectAsyncAggExecutionNode) node).abort(); } conn.abort(); // for (ExecutableNodeRunner runner : childRunners) { // runner.abort(); // } } public boolean runThisAndDependents() { // first run all children on separate threads // this function may be called again when run() is triggered upon a completion of one of // child nodes. Therefore, runChildren() is responsible for ensuring the same node does not // run again. runDependents(); return runOnThread(); } private boolean doesThisNodeContainAsyncAggExecutionNode() { ExecutableNodeBase leafOfThis = (ExecutableNodeBase) node; while (leafOfThis instanceof ConsolidatedExecutionNode) { leafOfThis = ((ConsolidatedExecutionNode) leafOfThis).getChildNode(); } return leafOfThis instanceof AsyncAggExecutionNode; } public boolean runOnThread() { log.trace(String.format("Invoked to run: %s", node.toString())); // https://stackoverflow.com/questions/11165852/java-singleton-and-synchronization Thread runningTask = this.runningTask; if (runningTask == null) { synchronized (this) { runningTask = this.runningTask; if (runningTask == null) { if (noNeedToRun()) { log.trace(String.format("No need to run: %s", node.toString())); return false; } status = NodeRunningStatus.running; runningTask = new Thread(this); this.runningTask = runningTask; runningTask.start(); return true; // this.runningTask is set to null at the end of run() } } } return false; } private int getMaxNumberOfRunningNode() { if ((conn instanceof JdbcConnection && conn.getSyntax() instanceof MysqlSyntax) || (conn instanceof CachedDbmsConnection && ((CachedDbmsConnection)conn).getOriginalConnection() instanceof JdbcConnection) && ((CachedDbmsConnection)conn).getOriginalConnection().getSyntax() instanceof MysqlSyntax) { // For MySQL, issue query one by one. if (node instanceof SelectAsyncAggExecutionNode || node instanceof AsyncAggExecutionNode) { return 1; } else { return 1; } } else if (((conn instanceof SparkConnection) || (conn instanceof CachedDbmsConnection && ((CachedDbmsConnection) conn).getOriginalConnection() instanceof SparkConnection)) && !(node instanceof SelectAsyncAggExecutionNode)) { // Since abort() does not work for Spark (or I don't know how to do so), we issue query // one by one. return 1; } else { return 10; } } private void runDependents() { if (doesThisNodeContainAsyncAggExecutionNode()) { int maxNumberOfRunningNode = getMaxNumberOfRunningNode(); int currentlyRunningOrCompleteNodeCount = childRunners.size(); // check the number of currently running nodes int runningChildCount = 0; int completedChildCount = 0; for (ExecutableNodeRunner r : childRunners) { if (r.getStatus() == NodeRunningStatus.running) { runningChildCount++; } else if (r.getStatus() == NodeRunningStatus.completed) { completedChildCount++; } } log.trace(String.format( "Running child: %d, Completed Child: %d, Success token received: %d", runningChildCount, completedChildCount, successSourceCount)); // maintain the number of running nodes to a certain number List<ExecutableNodeBase> childNodes = ((ExecutableNodeBase) node).getSources(); int moreToRun = Math.min( maxNumberOfRunningNode - runningChildCount, ((ExecutableNodeBase) node).getSourceCount() - currentlyRunningOrCompleteNodeCount); for (int i = currentlyRunningOrCompleteNodeCount; i < currentlyRunningOrCompleteNodeCount + moreToRun; i++) { ExecutableNodeBase child = childNodes.get(i); ExecutableNodeRunner runner = child.getRegisteredRunner(); boolean started = runner.runThisAndDependents(); if (started) { childRunners.add(runner); } } } else { // by default, run every child for (ExecutableNodeBase child : ((ExecutableNodeBase) node).getSources()) { ExecutableNodeRunner runner = child.getRegisteredRunner(); boolean started = runner.runThisAndDependents(); if (started) { childRunners.add(runner); } } } } /** * A single run of this method consumes all combinations of the tokens in the queue. */ @Override public synchronized void run() { // String nodeType = node.getClass().getSimpleName(); // int nodeGroupId = ((ExecutableNodeBase) node).getGroupId(); if (noNeedToRun()) { log.debug(String.format("This node (%s) has been aborted; do not run.", node.toString())); clearRunningTask(); return; } // no dependency exists if (node.getSourceQueues().size() == 0) { log.trace(String.format("No dependency exists. Simply run %s", node.toString())); try { executeAndBroadcast(Arrays.<ExecutionInfoToken>asList()); broadcastAndTriggerRun(ExecutionInfoToken.successToken()); markComplete(); //clearRunningTask(); return; } catch (Exception e) { if (noNeedToRun()) { // do nothing return; } else { e.printStackTrace(); broadcastAndTriggerRun(ExecutionInfoToken.failureToken(e)); } } markFailure(); // clearRunningTask(); return; } // dependency exists while (!noNeedToRun()) { // not enough source nodes are finished (i.e., tokens = null) // then, this loop immediately terminates. // this function will be called again whenever a child node completes. List<ExecutionInfoToken> tokens = retrieve(); if (tokens == null) { log.trace("Not enough source nodes are finished, loop terminates"); // markInitiated(); clearRunningTask(); return; } log.trace(String.format("Attempts to process %s (%s)", node.toString(), status)); ExecutionInfoToken failureToken = getFailureTokenIfExists(tokens); if (failureToken != null) { log.trace(String.format("One or more dependent nodes failed for %s", node.toString())); broadcastAndTriggerRun(failureToken); // clearRunningTask(); markFailure(); return; } if (areAllSuccess(tokens)) { log.trace(String.format("All dependent nodes are finished for %s", node.toString())); broadcastAndTriggerRun(ExecutionInfoToken.successToken()); //clearRunningTask(); markComplete(); return; } // This happens because some of the children (e.g., individual agg blocks) // finished their processing (with parts of blocks). // Since there still are other children to process, we continue operation. if (areAllStatusTokens(tokens)) { continue; } // actual processing try { log.trace( String.format("Main processing starts for %s with token: %s", node.toString(), tokens)); executeAndBroadcast(tokens); } catch (Exception e) { if (noNeedToRun()) { // do nothing return; } else { e.printStackTrace(); broadcastAndTriggerRun(ExecutionInfoToken.failureToken(e)); markFailure(); // clearRunningTask(); return; } } } } synchronized List<ExecutionInfoToken> retrieve() { Map<Integer, ExecutionTokenQueue> sourceChannelAndQueues = node.getSourceQueues(); for (ExecutionTokenQueue queue : sourceChannelAndQueues.values()) { ExecutionInfoToken rs = queue.peek(); if (rs == null) { return null; } } // all results available now List<ExecutionInfoToken> results = new ArrayList<>(); for (Entry<Integer, ExecutionTokenQueue> channelAndQueue : sourceChannelAndQueues.entrySet()) { int channel = channelAndQueue.getKey(); ExecutionInfoToken rs = channelAndQueue.getValue().take(); rs.setKeyValue("channel", channel); results.add(rs); } return results; } void broadcastAndTriggerRun(ExecutionInfoToken token) { if (noNeedToRun() && !areAllStatusTokens(Arrays.asList(token))) { log.trace( String.format( "This node (%s) has been aborted. Do not broadcast: %s", this.toString(), token)); return; } // for understandable logs synchronized (VerdictDBLogger.class) { VerdictDBLogger logger = VerdictDBLogger.getLogger(this.getClass()); logger.trace(String.format("[%s] Broadcasting:", node.toString())); logger.trace(token.toString()); for (ExecutableNode dest : node.getSubscribers()) { logger.trace(String.format(" -> %s", dest.toString())); } // logger.trace(token.toString()); } if (node instanceof SelectAggExecutionNode && areAllStatusTokens(Arrays.asList(token))) { status = NodeRunningStatus.completed; } for (ExecutableNode dest : node.getSubscribers()) { ExecutionInfoToken copiedToken = token.deepcopy(); if (areAllStatusTokens(Arrays.asList(copiedToken)) && node.getRegisteredRunner().getStatus()!=NodeRunningStatus.completed) { node.getRegisteredRunner().status = NodeRunningStatus.completed; } else if (areAllStatusTokens(Arrays.asList(copiedToken))) { log.trace("Broadcast success token"); } dest.getNotified(node, copiedToken); // signal the runner of the broadcasted node so that its associated runner performs // execution if necessary. ExecutableNodeRunner runner = dest.getRegisteredRunner(); if (runner != null) { // runner.runOnThread(); log.trace("Broadcast: status " + status); runner.runThisAndDependents(); // this is needed due to async node. } } } void executeAndBroadcast(List<ExecutionInfoToken> tokens) throws VerdictDBException { ExecutionInfoToken resultToken = execute(tokens); if (resultToken != null) { broadcastAndTriggerRun(resultToken); } } /** * Execute the associated node. This method is synchronized on object level, assuming that * every node has its own associated ExecutableNodeRunner, which is actually the case. * * @param tokens Contains information from the downstream nodes. * @return Information for the upstream nodes. * @throws VerdictDBException */ public ExecutionInfoToken execute(List<ExecutionInfoToken> tokens) throws VerdictDBException { if (tokens.size() > 0 && tokens.get(0).isStatusToken()) { return null; } // basic operations: execute a query and creates a token based on that result. SqlConvertible sqlObj = node.createQuery(tokens); DbmsQueryResult intermediate = null; if (sqlObj != null) { String sql = QueryToSql.convert(conn.getSyntax(), sqlObj); try { intermediate = conn.execute(sql); } catch (VerdictDBDbmsException e) { if (noNeedToRun()) { // the errors from the underlying dbms are expected if the query is cancelled. } else { throw e; } } } ExecutionInfoToken token = node.createToken(intermediate); // extended operations: if the node has additional method invocation list, we perform the method // calls // on DbmsConnection and sets its results in the token. if (token == null) { token = new ExecutionInfoToken(); } Map<String, MethodInvocationInformation> tokenKeysAndmethodsToInvoke = node.getMethodsToInvokeOnConnection(); for (Entry<String, MethodInvocationInformation> keyAndMethod : tokenKeysAndmethodsToInvoke.entrySet()) { String tokenKey = keyAndMethod.getKey(); MethodInvocationInformation methodInfo = keyAndMethod.getValue(); String methodName = methodInfo.getMethodName(); Class<?>[] methodParameters = methodInfo.getMethodParameters(); Object[] methodArguments = methodInfo.getArguments(); try { Method method = conn.getClass().getMethod(methodName, methodParameters); Object ret = method.invoke(conn, methodArguments); token.setKeyValue(tokenKey, ret); } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); throw new VerdictDBValueException(e); } } synchronized ((Object)executionCount) { executionCount++; } return token; } ExecutionInfoToken getFailureTokenIfExists(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { // System.out.println(t); if (t.isFailureToken()) { // System.out.println("yes"); return t; } } return null; } boolean areAllStatusTokens(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { if (!t.isStatusToken()) { return false; } } return true; } boolean areAllSuccess(List<ExecutionInfoToken> tokens) { for (ExecutionInfoToken t : tokens) { if (t.isSuccessToken()) { synchronized ((Object) successSourceCount) { successSourceCount++; } log.trace(String.format("Success count of %s: %d", node.toString(), successSourceCount)); } else { return false; } } if (successSourceCount == dependentCount) { log.trace(String.format("Success: %d, execution count: %d", successSourceCount, executionCount)); return true; } else { return false; } } }
use isSuccessToken() to judge token
src/main/java/org/verdictdb/core/execplan/ExecutableNodeRunner.java
use isSuccessToken() to judge token
Java
apache-2.0
70a4ed863f4993617f53d9050d4947b6f54bf964
0
mdogan/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,lmjacksoniii/hazelcast,tkountis/hazelcast,tkountis/hazelcast,mdogan/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,lmjacksoniii/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,dsukhoroslov/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast
/* * Copyright (c) 2008-2013, 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.concurrent.atomiclong; import com.hazelcast.client.ClientCommandHandler; import com.hazelcast.concurrent.atomiclong.client.GetAndSetHandler; import com.hazelcast.concurrent.atomiclong.proxy.AtomicLongProxy; import com.hazelcast.config.Config; import com.hazelcast.nio.protocol.Command; import com.hazelcast.partition.MigrationEndpoint; import com.hazelcast.partition.MigrationType; import com.hazelcast.spi.*; import com.hazelcast.util.ConcurrencyUtil; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; // author: sancar - 21.12.2012 public class AtomicLongService implements ManagedService, RemoteService, MigrationAwareService, ClientProtocolService { public static final String SERVICE_NAME = "hz:impl:atomicLongService"; private NodeEngine nodeEngine; private final ConcurrentMap<String, AtomicLong> numbers = new ConcurrentHashMap<String, AtomicLong>(); private final ConcurrencyUtil.ConstructorFunction<String, AtomicLong> atomicLongConstructorFunction = new ConcurrencyUtil.ConstructorFunction<String, AtomicLong>() { public AtomicLong createNew(String key) { return new AtomicLong(0L); } }; public AtomicLongService() { } public AtomicLong getNumber(String name) { return ConcurrencyUtil.getOrPutIfAbsent(numbers, name, atomicLongConstructorFunction); } public void init(NodeEngine nodeEngine, Properties properties) { this.nodeEngine = nodeEngine; } public void reset() { numbers.clear(); } public void shutdown() { reset(); } public Config getConfig() { return nodeEngine.getConfig(); } public String getServiceName() { return SERVICE_NAME; } public AtomicLongProxy createDistributedObject(Object objectId) { return new AtomicLongProxy(String.valueOf(objectId), nodeEngine, this); } public AtomicLongProxy createDistributedObjectForClient(Object objectId) { return createDistributedObject(objectId); } public void destroyDistributedObject(Object objectId) { numbers.remove(String.valueOf(objectId)); } public void beforeMigration(MigrationServiceEvent migrationServiceEvent) { } public Operation prepareMigrationOperation(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return null; } Map<String, Long> data = new HashMap<String, Long>(); final int partitionId = migrationServiceEvent.getPartitionId(); for (String name : numbers.keySet()) { if (partitionId == nodeEngine.getPartitionService().getPartitionId(name)) { data.put(name, numbers.get(name).get()); } } return data.isEmpty() ? null : new AtomicLongMigrationOperation(data); } public void commitMigration(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return; } if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { if (migrationServiceEvent.getMigrationType() == MigrationType.MOVE) { removeNumber(migrationServiceEvent.getPartitionId()); } } else if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { } else { throw new IllegalStateException("Nor source neither destination, probably bug"); } } public void rollbackMigration(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return; } if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { removeNumber(migrationServiceEvent.getPartitionId()); } } public void removeNumber(int partitionId) { final Iterator<String> iterator = numbers.keySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (nodeEngine.getPartitionService().getPartitionId(name) == partitionId) { iterator.remove(); } } } @Override public Map<Command, ClientCommandHandler> getCommandsAsMap() { Map<Command, ClientCommandHandler> commandHandlers = new HashMap<Command, ClientCommandHandler>(); commandHandlers.put(Command.ALADDANDGET, new GetAndSetHandler(this)); commandHandlers.put(Command.ALGETANDADD, new GetAndSetHandler(this)); commandHandlers.put(Command.ALGETANDSET, new GetAndSetHandler(this)); // commandHandlers.put(Command.ALCOMPAREANDSET, new CompareAndSetHandler(this)); return commandHandlers ; } }
hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/AtomicLongService.java
/* * Copyright (c) 2008-2013, 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.concurrent.atomiclong; import com.hazelcast.client.ClientCommandHandler; import com.hazelcast.concurrent.atomiclong.client.CompareAndSetHandler; import com.hazelcast.concurrent.atomiclong.client.GetAndSetHandler; import com.hazelcast.concurrent.atomiclong.proxy.AtomicLongProxy; import com.hazelcast.config.Config; import com.hazelcast.nio.protocol.Command; import com.hazelcast.partition.MigrationEndpoint; import com.hazelcast.partition.MigrationType; import com.hazelcast.spi.*; import com.hazelcast.util.ConcurrencyUtil; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; // author: sancar - 21.12.2012 public class AtomicLongService implements ManagedService, RemoteService, MigrationAwareService, ClientProtocolService { public static final String SERVICE_NAME = "hz:impl:atomicLongService"; private NodeEngine nodeEngine; private final ConcurrentMap<String, AtomicLong> numbers = new ConcurrentHashMap<String, AtomicLong>(); private final ConcurrencyUtil.ConstructorFunction<String, AtomicLong> atomicLongConstructorFunction = new ConcurrencyUtil.ConstructorFunction<String, AtomicLong>() { public AtomicLong createNew(String key) { return new AtomicLong(0L); } }; public AtomicLongService() { } public AtomicLong getNumber(String name) { return ConcurrencyUtil.getOrPutIfAbsent(numbers, name, atomicLongConstructorFunction); } public void init(NodeEngine nodeEngine, Properties properties) { this.nodeEngine = nodeEngine; } public void reset() { numbers.clear(); } public void shutdown() { reset(); } public Config getConfig() { return nodeEngine.getConfig(); } public String getServiceName() { return SERVICE_NAME; } public AtomicLongProxy createDistributedObject(Object objectId) { return new AtomicLongProxy(String.valueOf(objectId), nodeEngine, this); } public AtomicLongProxy createDistributedObjectForClient(Object objectId) { return createDistributedObject(objectId); } public void destroyDistributedObject(Object objectId) { numbers.remove(String.valueOf(objectId)); } public void beforeMigration(MigrationServiceEvent migrationServiceEvent) { } public Operation prepareMigrationOperation(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return null; } Map<String, Long> data = new HashMap<String, Long>(); final int partitionId = migrationServiceEvent.getPartitionId(); for (String name : numbers.keySet()) { if (partitionId == nodeEngine.getPartitionService().getPartitionId(name)) { data.put(name, numbers.get(name).get()); } } return data.isEmpty() ? null : new AtomicLongMigrationOperation(data); } public void commitMigration(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return; } if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { if (migrationServiceEvent.getMigrationType() == MigrationType.MOVE) { removeNumber(migrationServiceEvent.getPartitionId()); } } else if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { } else { throw new IllegalStateException("Nor source neither destination, probably bug"); } } public void rollbackMigration(MigrationServiceEvent migrationServiceEvent) { if (migrationServiceEvent.getReplicaIndex() > 1) { return; } if (migrationServiceEvent.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { removeNumber(migrationServiceEvent.getPartitionId()); } } public void removeNumber(int partitionId) { final Iterator<String> iterator = numbers.keySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (nodeEngine.getPartitionService().getPartitionId(name) == partitionId) { iterator.remove(); } } } @Override public Map<Command, ClientCommandHandler> getCommandsAsMap() { Map<Command, ClientCommandHandler> commandHandlers = new HashMap<Command, ClientCommandHandler>(); commandHandlers.put(Command.ALADDANDGET, new GetAndSetHandler(this)); commandHandlers.put(Command.ALGETANDADD, new GetAndSetHandler(this)); commandHandlers.put(Command.ALGETANDSET, new GetAndSetHandler(this)); commandHandlers.put(Command.ALCOMPAREANDSET, new CompareAndSetHandler(this)); return commandHandlers ; } }
Compilation fix.
hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/AtomicLongService.java
Compilation fix.
Java
bsd-3-clause
6ff36acc1ce9228709d57cf77eef9f4a9c698319
0
smartdevicelink/sdl_android
/* * Copyright (c) 2019 Livio, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Livio Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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 com.smartdevicelink.managers.screen.choiceset; import android.support.annotation.NonNull; import com.smartdevicelink.managers.file.filetypes.SdlArtwork; import java.util.List; public class ChoiceCell { private String text, secondaryText, tertiaryText; private List<String> voiceCommands; private SdlArtwork artwork, secondaryArtwork; private Integer choiceId; /** * MAX ID for cells - Cannot use Integer.MAX_INT as the value is too high. */ private static final int MAX_ID = 2000000000; /** * Initialize the cell with text and nothing else. * * @param text - The primary text of the cell. */ public ChoiceCell(@NonNull String text) { setText(text); setChoiceId(MAX_ID); } /** * Initialize the cell with text, optional artwork, and optional voice commands * * @param text - The primary text of the cell * @param voiceCommands - Strings that can be spoken by the user to activate this cell in a voice or both interaction mode * @param artwork - The primary artwork of the cell */ public ChoiceCell(@NonNull String text, List<String> voiceCommands, SdlArtwork artwork) { setText(text); setVoiceCommands(voiceCommands); setArtwork(artwork); setChoiceId(MAX_ID); } /** * Initialize the cell with all optional items * * @param text - The primary text * @param secondaryText - The secondary text * @param tertiaryText - The tertiary text * @param voiceCommands - Strings that can be spoken by the user to activate this cell in a voice or both interaction mode * @param artwork - The primary artwork of the cell * @param secondaryArtwork - The secondary artwork of the cell */ public ChoiceCell(@NonNull String text, String secondaryText, String tertiaryText, List<String> voiceCommands, SdlArtwork artwork, SdlArtwork secondaryArtwork) { setText(text); setSecondaryText(secondaryText); setTertiaryText(tertiaryText); setVoiceCommands(voiceCommands); setArtwork(artwork); setSecondaryArtwork(secondaryArtwork); setChoiceId(MAX_ID); } /** * Maps to Choice.menuName. The primary text of the cell. Duplicates within an `ChoiceSet` * are not permitted and will result in the `ChoiceSet` failing to initialize. * @return The primary text of the cell */ public String getText() { return text; } /** * @param text - Maps to Choice.menuName. The primary text of the cell. Duplicates within an `ChoiceSet` * are not permitted and will result in the `ChoiceSet` failing to initialize. */ void setText(@NonNull String text) { this.text = text; } /** * Maps to Choice.secondaryText. Optional secondary text of the cell, if available. Duplicates * within an `ChoiceSet` are permitted. * @return Optional secondary text of the cell */ public String getSecondaryText() { return secondaryText; } /** * @param secondaryText - Maps to Choice.secondaryText. Optional secondary text of the cell, if * available. Duplicates within an `ChoiceSet` are permitted. */ void setSecondaryText(String secondaryText) { this.secondaryText = secondaryText; } /** * Maps to Choice.tertiaryText. Optional tertiary text of the cell, if available. Duplicates within an `ChoiceSet` are permitted. * @return Optional tertiary text of the cell */ public String getTertiaryText() { return tertiaryText; } /** * @param tertiaryText - Maps to Choice.tertiaryText. Optional tertiary text of the cell, if * available. Duplicates within an `ChoiceSet` are permitted. */ void setTertiaryText(String tertiaryText) { this.tertiaryText = tertiaryText; } /** * Maps to Choice.vrCommands. Optional voice commands the user can speak to activate the cell. * If not set and the head unit requires it, this will be set to the number in the list that this * item appears. However, this would be a very poor experience for a user if the choice set is * presented as a voice only interaction or both interaction mode. Therefore, consider not setting * this only when you know the choice set will be presented as a touch only interaction. * @return The list of voice command strings */ public List<String> getVoiceCommands() { return voiceCommands; } /** * @param voiceCommands - Maps to Choice.vrCommands. Optional voice commands the user can speak to activate the cell. * If not set and the head unit requires it, this will be set to the number in the list that this * item appears. However, this would be a very poor experience for a user if the choice set is * presented as a voice only interaction or both interaction mode. Therefore, consider not setting * this only when you know the choice set will be presented as a touch only interaction. */ void setVoiceCommands(List<String> voiceCommands) { this.voiceCommands = voiceCommands; } /** * Maps to Choice.image. Optional image for the cell. This will be uploaded before the cell is * used when the cell is preloaded or presented for the first time. * @return The SdlArtwork */ public SdlArtwork getArtwork() { return artwork; } /** * @param artwork - Maps to Choice.image. Optional image for the cell. This will be uploaded * before the cell is used when the cell is preloaded or presented for the first time. */ void setArtwork(SdlArtwork artwork) { this.artwork = artwork; } /** * Maps to Choice.secondaryImage. Optional secondary image for the cell. This will be uploaded * before the cell is used when the cell is preloaded or presented for the first time. * @return The SdlArtwork */ public SdlArtwork getSecondaryArtwork() { return secondaryArtwork; } /** * @param secondaryArtwork - Maps to Choice.secondaryImage. Optional secondary image for the cell. * This will be uploaded before the cell is used when the cell is preloaded or presented for the first time. */ void setSecondaryArtwork(SdlArtwork secondaryArtwork) { this.secondaryArtwork = secondaryArtwork; } /** * NOTE: USED INTERNALLY * Set the choice Id. * @param choiceId - the choice Id */ void setChoiceId(int choiceId) { this.choiceId = choiceId; } /** * NOTE: USED INTERNALLY * Get the choiceId * @return the choiceId for this Choice Cell */ int getChoiceId() { return choiceId; } @Override public int hashCode() { int result = 1; result += ((getText() == null) ? 0 : Integer.rotateLeft(getText().hashCode(), 1)); result += ((getSecondaryText() == null) ? 0 : Integer.rotateLeft(getSecondaryText().hashCode(), 2)); result += ((getTertiaryText() == null) ? 0 : Integer.rotateLeft(getTertiaryText().hashCode(), 3)); result += ((getArtwork() == null) ? 0 : Integer.rotateLeft(getArtwork().hashCode(), 4)); result += ((getSecondaryArtwork() == null) ? 0 : Integer.rotateLeft(getSecondaryArtwork().hashCode(), 5)); result += ((getVoiceCommands() == null) ? 0 : Integer.rotateLeft(getVoiceCommands().hashCode(), 6)); return result; } /** * Uses our custom hashCode for ChoiceCell objects * @param o - The object to compare * @return boolean of whether the objects are the same or not */ @Override public boolean equals(Object o) { if (o == null) { return false; } // if this is the same memory address, its the same if (this == o) return true; // if this is not an instance of this class, not the same if (!(o instanceof ChoiceCell)) return false; // return comparison return hashCode() == o.hashCode(); } /** * @return A string description of the cell, useful for debugging. */ @Override @NonNull public String toString() { return "ChoiceCell: ID: " + this.choiceId + " Text: " + text+ " - Secondary Text: "+ secondaryText+" - Tertiary Text: "+ tertiaryText+ " " + "| Artwork Names: "+ ((getArtwork() == null || getArtwork().getName() == null) ? "Primary Art null" : getArtwork().getName()) + " Secondary Art - "+((getSecondaryArtwork() == null || getSecondaryArtwork().getName() == null) ? "Secondary Art null" : getSecondaryArtwork().getName()) + " | Voice Commands Size: "+ ((getVoiceCommands() == null) ? 0 : getVoiceCommands().size()); } }
base/src/main/java/com/smartdevicelink/managers/screen/choiceset/ChoiceCell.java
/* * Copyright (c) 2019 Livio, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Livio Inc. nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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 com.smartdevicelink.managers.screen.choiceset; import android.support.annotation.NonNull; import com.smartdevicelink.managers.file.filetypes.SdlArtwork; import java.util.List; public class ChoiceCell { private String text, secondaryText, tertiaryText; private List<String> voiceCommands; private SdlArtwork artwork, secondaryArtwork; private Integer choiceId; /** * MAX ID for cells - Cannot use Integer.MAX_INT as the value is too high. */ private static final int MAX_ID = 2000000000; /** * Initialize the cell with text and nothing else. * * @param text - The primary text of the cell. */ public ChoiceCell(@NonNull String text) { setText(text); setChoiceId(MAX_ID); } /** * Initialize the cell with text, optional artwork, and optional voice commands * * @param text - The primary text of the cell * @param voiceCommands - Strings that can be spoken by the user to activate this cell in a voice or both interaction mode * @param artwork - The primary artwork of the cell */ public ChoiceCell(@NonNull String text, List<String> voiceCommands, SdlArtwork artwork) { setText(text); setVoiceCommands(voiceCommands); setArtwork(artwork); setChoiceId(MAX_ID); } /** * Initialize the cell with all optional items * * @param text - The primary text * @param secondaryText - The secondary text * @param tertiaryText - The tertiary text * @param voiceCommands - Strings that can be spoken by the user to activate this cell in a voice or both interaction mode * @param artwork - The primary artwork of the cell * @param secondaryArtwork - The secondary artwork of the cell */ public ChoiceCell(@NonNull String text, String secondaryText, String tertiaryText, List<String> voiceCommands, SdlArtwork artwork, SdlArtwork secondaryArtwork) { setText(text); setSecondaryText(secondaryText); setTertiaryText(tertiaryText); setVoiceCommands(voiceCommands); setArtwork(artwork); setSecondaryArtwork(secondaryArtwork); setChoiceId(MAX_ID); } /** * Maps to Choice.menuName. The primary text of the cell. Duplicates within an `ChoiceSet` * are not permitted and will result in the `ChoiceSet` failing to initialize. * @return The primary text of the cell */ public String getText() { return text; } /** * @param text - Maps to Choice.menuName. The primary text of the cell. Duplicates within an `ChoiceSet` * are not permitted and will result in the `ChoiceSet` failing to initialize. */ void setText(@NonNull String text) { this.text = text; } /** * Maps to Choice.secondaryText. Optional secondary text of the cell, if available. Duplicates * within an `ChoiceSet` are permitted. * @return Optional secondary text of the cell */ public String getSecondaryText() { return secondaryText; } /** * @param secondaryText - Maps to Choice.secondaryText. Optional secondary text of the cell, if * available. Duplicates within an `ChoiceSet` are permitted. */ void setSecondaryText(String secondaryText) { this.secondaryText = secondaryText; } /** * Maps to Choice.tertiaryText. Optional tertiary text of the cell, if available. Duplicates within an `ChoiceSet` are permitted. * @return Optional tertiary text of the cell */ public String getTertiaryText() { return tertiaryText; } /** * @param tertiaryText - Maps to Choice.tertiaryText. Optional tertiary text of the cell, if * available. Duplicates within an `ChoiceSet` are permitted. */ void setTertiaryText(String tertiaryText) { this.tertiaryText = tertiaryText; } /** * Maps to Choice.vrCommands. Optional voice commands the user can speak to activate the cell. * If not set and the head unit requires it, this will be set to the number in the list that this * item appears. However, this would be a very poor experience for a user if the choice set is * presented as a voice only interaction or both interaction mode. Therefore, consider not setting * this only when you know the choice set will be presented as a touch only interaction. * @return The list of voice command strings */ public List<String> getVoiceCommands() { return voiceCommands; } /** * @param voiceCommands - Maps to Choice.vrCommands. Optional voice commands the user can speak to activate the cell. * If not set and the head unit requires it, this will be set to the number in the list that this * item appears. However, this would be a very poor experience for a user if the choice set is * presented as a voice only interaction or both interaction mode. Therefore, consider not setting * this only when you know the choice set will be presented as a touch only interaction. */ void setVoiceCommands(List<String> voiceCommands) { this.voiceCommands = voiceCommands; } /** * Maps to Choice.image. Optional image for the cell. This will be uploaded before the cell is * used when the cell is preloaded or presented for the first time. * @return The SdlArtwork */ public SdlArtwork getArtwork() { return artwork; } /** * @param artwork - Maps to Choice.image. Optional image for the cell. This will be uploaded * before the cell is used when the cell is preloaded or presented for the first time. */ void setArtwork(SdlArtwork artwork) { this.artwork = artwork; } /** * Maps to Choice.secondaryImage. Optional secondary image for the cell. This will be uploaded * before the cell is used when the cell is preloaded or presented for the first time. * @return The SdlArtwork */ public SdlArtwork getSecondaryArtwork() { return secondaryArtwork; } /** * @param secondaryArtwork - Maps to Choice.secondaryImage. Optional secondary image for the cell. * This will be uploaded before the cell is used when the cell is preloaded or presented for the first time. */ void setSecondaryArtwork(SdlArtwork secondaryArtwork) { this.secondaryArtwork = secondaryArtwork; } /** * NOTE: USED INTERNALLY * Set the choice Id. * @param choiceId - the choice Id */ void setChoiceId(int choiceId) { this.choiceId = choiceId; } /** * NOTE: USED INTERNALLY * Get the choiceId * @return the choiceId for this Choice Cell */ int getChoiceId() { return choiceId; } @Override public int hashCode() { int result = 1; result += ((getText() == null) ? 0 : Integer.rotateLeft(getText().hashCode(), 1)); result += ((getSecondaryText() == null) ? 0 : Integer.rotateLeft(getSecondaryText().hashCode(), 2)); result += ((getTertiaryText() == null) ? 0 : Integer.rotateLeft(getTertiaryText().hashCode(), 3)); result += ((getArtwork() == null) ? 0 : Integer.rotateLeft(getArtwork().hashCode(), 4)); result += ((getSecondaryArtwork() == null || getSecondaryArtwork().getName() == null) ? 0 : Integer.rotateLeft(getSecondaryArtwork().getName().hashCode(), 5)); result += ((getVoiceCommands() == null) ? 0 : Integer.rotateLeft(getVoiceCommands().hashCode(), 6)); return result; } /** * Uses our custom hashCode for ChoiceCell objects * @param o - The object to compare * @return boolean of whether the objects are the same or not */ @Override public boolean equals(Object o) { if (o == null) { return false; } // if this is the same memory address, its the same if (this == o) return true; // if this is not an instance of this class, not the same if (!(o instanceof ChoiceCell)) return false; // return comparison return hashCode() == o.hashCode(); } /** * @return A string description of the cell, useful for debugging. */ @Override @NonNull public String toString() { return "ChoiceCell: ID: " + this.choiceId + " Text: " + text+ " - Secondary Text: "+ secondaryText+" - Tertiary Text: "+ tertiaryText+ " " + "| Artwork Names: "+ ((getArtwork() == null || getArtwork().getName() == null) ? "Primary Art null" : getArtwork().getName()) + " Secondary Art - "+((getSecondaryArtwork() == null || getSecondaryArtwork().getName() == null) ? "Secondary Art null" : getSecondaryArtwork().getName()) + " | Voice Commands Size: "+ ((getVoiceCommands() == null) ? 0 : getVoiceCommands().size()); } }
Update ChoiceCell.hashCode() to use SdlFile.hashCode()
base/src/main/java/com/smartdevicelink/managers/screen/choiceset/ChoiceCell.java
Update ChoiceCell.hashCode() to use SdlFile.hashCode()
Java
mit
5ab5b5a1ee9025644006c8c7d5c7da91745e7562
0
TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android
package org.deviceconnect.android.deviceplugin.fabo.service.virtual.profile; import android.content.Intent; import android.os.Bundle; import org.deviceconnect.android.deviceplugin.fabo.device.IVCNL4010; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventError; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.api.DeleteApi; import org.deviceconnect.android.profile.api.GetApi; import org.deviceconnect.android.profile.api.PutApi; import org.deviceconnect.message.DConnectMessage; import java.util.List; import static org.deviceconnect.android.event.EventManager.INSTANCE; /** * I2C用Proximityプロファイル. * <p> * ID: #205<br> * Name: Proximity I2C Brick<br> * </p> */ public class I2CProximityProfile extends BaseFaBoProfile { /** * コンストラクタ. */ public I2CProximityProfile() { // GET /gotapi/proximity/onUserProximity addApi(new GetApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "FaBo device is not connected."); } else if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { ivcnl4010.readProximity(new IVCNL4010.OnProximityListener() { @Override public void onStarted() { } @Override public void onData(final boolean proximity) { response.putExtra("proximity", createProximity(proximity)); setResult(response, DConnectMessage.RESULT_OK); sendResponse(response); } @Override public void onError(String message) { MessageUtils.setIllegalDeviceStateError(response, message); sendResponse(response); } }); } return false; } }); // PUT /gotapi/proximity/onUserProximity addApi(new PutApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "FaBo device is not connected."); } else if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { EventError error = INSTANCE.addEvent(request); switch (error) { case NONE: ivcnl4010.startProximity(mOnProximityListener); setResult(response, DConnectMessage.RESULT_OK); break; default: MessageUtils.setUnknownError(response); break; } } return true; } }); // DELETE /gotapi/proximity/onUserProximity addApi(new DeleteApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { EventError error = INSTANCE.removeEvent(request); switch (error) { case NONE: if (isEmptyEvent()) { ivcnl4010.stopProximity(mOnProximityListener); } setResult(response, DConnectMessage.RESULT_OK); break; case NOT_FOUND: MessageUtils.setIllegalDeviceStateError(response, "Not register event."); break; default: MessageUtils.setUnknownError(response); break; } } return true; } }); } @Override public String getProfileName() { return "proximity"; } /** * 登録されているイベントが空か確認します. * @return イベントが登録されていない場合はtrue、それ以外はfalse */ private boolean isEmptyEvent() { String serviceId = getService().getId(); List<Event> events = EventManager.INSTANCE.getEventList(serviceId, "proximity", null, "onUserProximity"); return events.isEmpty(); } /** * Proximityのオブジェクトを作成します. * @param value 距離 * @return Proximityのオブジェクト */ private Bundle createProximity(final boolean value) { Bundle proximity = new Bundle(); proximity.putBoolean("near", value); return proximity; } /** * Arduinoから渡されてきた値をProximityとして通知します. * @param value 値が渡されてきたピン */ private void notifyProximity(final boolean value) { String serviceId = getService().getId(); List<Event> events = EventManager.INSTANCE.getEventList(serviceId, "proximity", null, "onUserProximity"); for (Event event : events) { Intent intent = EventManager.createEventMessage(event); intent.putExtra("proximity", createProximity(value)); sendEvent(intent, event.getAccessToken()); } } private IVCNL4010.OnProximityListener mOnProximityListener = new IVCNL4010.OnProximityListener() { @Override public void onData(final boolean proximity) { notifyProximity(proximity); } @Override public void onError(final String message) { } @Override public void onStarted() { } }; }
dConnectDevicePlugin/dConnectDeviceFaBo/app/src/main/java/org/deviceconnect/android/deviceplugin/fabo/service/virtual/profile/I2CProximityProfile.java
package org.deviceconnect.android.deviceplugin.fabo.service.virtual.profile; import android.content.Intent; import android.os.Bundle; import org.deviceconnect.android.deviceplugin.fabo.device.IVCNL4010; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventError; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.api.DeleteApi; import org.deviceconnect.android.profile.api.GetApi; import org.deviceconnect.android.profile.api.PutApi; import org.deviceconnect.message.DConnectMessage; import java.util.List; import static org.deviceconnect.android.event.EventManager.INSTANCE; /** * I2C用Proximityプロファイル. * <p> * ID: #205<br> * Name: Proximity I2C Brick<br> * </p> */ public class I2CProximityProfile extends BaseFaBoProfile { /** * イベントを送信するためのインターバル. */ private long mInterval = 100; /** * 前回送信したイベントの時間. */ private long mSendTime; /** * コンストラクタ. */ public I2CProximityProfile() { // GET /gotapi/proximity/onUserProximity addApi(new GetApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "FaBo device is not connected."); } else if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { ivcnl4010.readProximity(new IVCNL4010.OnProximityListener() { @Override public void onStarted() { } @Override public void onData(final boolean proximity) { response.putExtra("proximity", createProximity(proximity)); setResult(response, DConnectMessage.RESULT_OK); sendResponse(response); } @Override public void onError(String message) { MessageUtils.setIllegalDeviceStateError(response, message); sendResponse(response); } }); } return false; } }); // PUT /gotapi/proximity/onUserProximity addApi(new PutApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { final Integer interval = parseInteger(request, "interval"); if (interval != null) { mInterval = interval; } else { mInterval = 100; } IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (!getService().isOnline()) { MessageUtils.setIllegalDeviceStateError(response, "FaBo device is not connected."); } else if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { EventError error = INSTANCE.addEvent(request); switch (error) { case NONE: ivcnl4010.startProximity(mOnProximityListener); setResult(response, DConnectMessage.RESULT_OK); break; default: MessageUtils.setUnknownError(response); break; } } return true; } }); // DELETE /gotapi/proximity/onUserProximity addApi(new DeleteApi() { @Override public String getAttribute() { return "onUserProximity"; } @Override public boolean onRequest(final Intent request, final Intent response) { IVCNL4010 ivcnl4010 = getFaBoDeviceControl().getVCNL4010(); if (ivcnl4010 == null) { MessageUtils.setNotSupportAttributeError(response, "Not support."); } else { EventError error = INSTANCE.removeEvent(request); switch (error) { case NONE: if (isEmptyEvent()) { ivcnl4010.stopProximity(mOnProximityListener); } setResult(response, DConnectMessage.RESULT_OK); break; case NOT_FOUND: MessageUtils.setIllegalDeviceStateError(response, "Not register event."); break; default: MessageUtils.setUnknownError(response); break; } } return true; } }); } @Override public String getProfileName() { return "proximity"; } /** * 登録されているイベントが空か確認します. * @return イベントが登録されていない場合はtrue、それ以外はfalse */ private boolean isEmptyEvent() { String serviceId = getService().getId(); List<Event> events = EventManager.INSTANCE.getEventList(serviceId, "proximity", null, "onUserProximity"); return events.isEmpty(); } /** * Proximityのオブジェクトを作成します. * @param value 距離 * @return Proximityのオブジェクト */ private Bundle createProximity(final boolean value) { Bundle proximity = new Bundle(); proximity.putBoolean("near", value); return proximity; } /** * Arduinoから渡されてきた値をProximityとして通知します. * @param value 値が渡されてきたピン */ private void notifyProximity(final boolean value) { long interval = (System.currentTimeMillis() - mSendTime); if (interval >= mInterval) { String serviceId = getService().getId(); List<Event> events = EventManager.INSTANCE.getEventList(serviceId, "proximity", null, "onUserProximity"); for (Event event : events) { Intent intent = EventManager.createEventMessage(event); intent.putExtra("proximity", createProximity(value)); sendEvent(intent, event.getAccessToken()); } mSendTime = System.currentTimeMillis(); } } private IVCNL4010.OnProximityListener mOnProximityListener = new IVCNL4010.OnProximityListener() { @Override public void onData(final boolean proximity) { notifyProximity(proximity); } @Override public void onError(final String message) { } @Override public void onStarted() { } }; }
VCNL4010のイベント配信からインターバルを削除
dConnectDevicePlugin/dConnectDeviceFaBo/app/src/main/java/org/deviceconnect/android/deviceplugin/fabo/service/virtual/profile/I2CProximityProfile.java
VCNL4010のイベント配信からインターバルを削除
Java
mit
b9b9a248f827417caa3dd7fd7f35fb7bb3beebd2
0
tobiatesan/serleena-android,tobiatesan/serleena-android
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ExperienceTest.java * Package: com.hitchikers.serleena.model * Author: Filippo Sestini * * History: * Version Programmer Changes * 1.0 Filippo Sestini Creazione del file e stesura * della documentazione Javadoc. */ package com.kyloth.serleena.model; import com.kyloth.serleena.common.GeoPoint; import com.kyloth.serleena.common.IQuadrant; import com.kyloth.serleena.common.UserPoint; import com.kyloth.serleena.persistence.IExperienceStorage; import com.kyloth.serleena.persistence.ITrackStorage; import com.kyloth.serleena.persistence.NoSuchQuadrantException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test di unità per la classe Experience * * @author Filippo Sestini <sestini.filippo@gmail.com> * @version 1.0.0 */ public class ExperienceTest { private IExperienceStorage experienceStorage; private Experience experience; private ITrackStorage track1; private ITrackStorage track2; private ITrackStorage track3; private ArrayList<ITrackStorage> trackStorages; private ArrayList<UserPoint> userPoints; private String testName; private GeoPoint testLocation; private IQuadrant testQuadrant; @Before public void initialize() throws Exception { experienceStorage = mock(IExperienceStorage.class); experience = new Experience(experienceStorage); track1 = mock(ITrackStorage.class); track2 = mock(ITrackStorage.class); track3 = mock(ITrackStorage.class); trackStorages = new ArrayList<ITrackStorage>(); trackStorages.add(track1); trackStorages.add(track2); trackStorages.add(track3); when(track1.name()).thenReturn("track1"); when(track2.name()).thenReturn("track2"); when(track3.name()).thenReturn("track3"); when(experienceStorage.getTracks()).thenReturn(trackStorages); userPoints = new ArrayList<UserPoint>(); userPoints.add(mock(UserPoint.class)); userPoints.add(mock(UserPoint.class)); when(experienceStorage.getUserPoints()).thenReturn(userPoints); testName = "Experience Name"; when(experienceStorage.getName()).thenReturn(testName); testLocation = mock(GeoPoint.class); testQuadrant = mock(IQuadrant.class); when(experienceStorage.getQuadrant(testLocation)) .thenReturn(testQuadrant); } /** * Verifica che vengano correttamente restituiti i Percorsi di * un'Esperienza in base a quanto restituito dall'oggetto di persistenza. */ @Test public void testGetTracks() throws Exception { Iterable<ITrack> tracks = experience.getTracks(); for (ITrackStorage ts : trackStorages) { boolean contains = false; for (ITrack t : tracks) contains = contains || t.name().equals(ts.name()); assertTrue(contains); } } /** * Verifica che vengano correttamente restituiti i Punti Utente di * un'Esperienza in base a quanto restituito dall'oggetto di persistenza. */ @Test public void testGetUserPoints() throws Exception { assertEquals(userPoints, experience.getUserPoints()); } /** * Verifica che l'aggiunta di un Punto Utente inoltri la richiesta * all'oggetto di persistenza. */ @Test public void testAddUserPoints() throws Exception { UserPoint up = mock(UserPoint.class); experience.addUserPoints(up); verify(experienceStorage).addUserPoint(up); } /** * Verifica che venga correttamente restituito il nome di * un'Esperienza in base a quanto restituito dall'oggetto di persistenza. */ @Test public void testGetName() throws Exception { assertEquals(testName, experience.getName()); } /** * Verifica che la richiesta di un quadrante associato all'Esperienza * venga inoltrata all'oggetto di persistenza. */ @Test public void testGetQuadrantQueriesStorage() throws Exception { experience.getQuadrant(testLocation); verify(experienceStorage).getQuadrant(testLocation); } /** * Verifica che venga correttamente restituito il quadrante di * un'Esperienza in base a quanto restituito dall'oggetto di persistenza. */ @Test public void testGetQuadrant() throws NoSuchQuadrantException { assertEquals(testQuadrant, experience.getQuadrant(testLocation)); } /** * Verifica che il metodo toString() restituisca il nome dell'Esperienza * rappresentata dall'istanza. */ @Test public void testToString() throws Exception { assertEquals(testName, experience.toString()); } }
serleena/app/src/test/java/com/kyloth/serleena/model/ExperienceTest.java
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ExperienceTest.java * Package: com.kyloth.serleena.presenters; * Author: Gabriele Pozzan * * History: * Version Programmer Changes * 1.0.0 Gabriele Pozzan Creazione file scrittura * codice e documentazione Javadoc */ package com.kyloth.serleena.model; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; import org.junit.Before; import org.junit.After; import static org.mockito.Mockito.*; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import java.util.Iterator; import com.kyloth.serleena.BuildConfig; import com.kyloth.serleena.persistence.sqlite.SerleenaSQLiteDataSource; import com.kyloth.serleena.persistence.sqlite.SerleenaDatabase; import com.kyloth.serleena.common.UserPoint; import com.kyloth.serleena.persistence.sqlite.TestFixtures; /** * Contiene test per la classe Experience. * * @author Gabriele Pozzan <gabriele.pozzan@studenti.unipd.it> * @version 1.0.0 */ @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, emulateSdk = 19) public class ExperienceTest { SQLiteDatabase db; SerleenaDatabase serleenaDB; SerleenaSQLiteDataSource serleenaSQLDS; SerleenaDataSource dataSource; /** * Inizializza i campi dati necessari alla conduzione dei test. */ @Before public void initialize() { serleenaDB = new SerleenaDatabase(RuntimeEnvironment.application, "sample.db", null, 1); db = serleenaDB.getWritableDatabase(); serleenaDB.onConfigure(db); serleenaDB.onUpgrade(db, 1, 2); ContentValues values = TestFixtures.pack(TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_1); db.insertOrThrow(SerleenaDatabase.TABLE_EXPERIENCES, null, values); values = TestFixtures.pack(TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_2); db.insertOrThrow(SerleenaDatabase.TABLE_EXPERIENCES, null, values); serleenaSQLDS = new SerleenaSQLiteDataSource(serleenaDB); dataSource = new SerleenaDataSource(serleenaSQLDS); } /** * Chiude il database per permettere il funzionamento dei test successivi. */ @After public void cleanUp() { serleenaDB.close(); } /** * Verifica che il metodo getName restituisca il nome effettivo * delle Esperienze salvate nel db. */ @Test public void testGetName() { Iterable<IExperience> experiences = dataSource.getExperiences(); Iterator<IExperience> i_experiences = experiences.iterator(); String name = i_experiences.next().getName(); assertTrue( name.equals(TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_1_NAME) || name.equals(TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_2_NAME) ); } /** * Verifica che il metodo getUserPoints restituisca i corretti * Punti Utente per le diverse Esperienze. */ @Test public void testGetUserPoints() { String insertUserPoints_1 = "INSERT INTO user_points " + "(userpoint_id, userpoint_x, userpoint_y, userpoint_experience) " + "VALUES (1, 2, 2, \"" + TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_1_UUID + "\")"; String insertUserPoints_2 = "INSERT INTO user_points " + "(userpoint_id, userpoint_x, userpoint_y, userpoint_experience) " + "VALUES (2, 3, 3, \"" + TestFixtures.EXPERIENCES_FIXTURE_EXPERIENCE_1_UUID + "\")"; db.execSQL(insertUserPoints_1); db.execSQL(insertUserPoints_2); Iterable<IExperience> experiences = dataSource.getExperiences(); Iterator<IExperience> i_experiences = experiences.iterator(); Experience exp_1 = (Experience) i_experiences.next(); Experience exp_2 = (Experience) i_experiences.next(); Iterable<UserPoint> up_1 = exp_1.getUserPoints(); Iterable<UserPoint> up_2 = exp_2.getUserPoints(); Iterator<UserPoint> i_1 = up_1.iterator(); Iterator<UserPoint> i_2 = up_2.iterator(); assertFalse(i_2.hasNext()); assertTrue(i_1.next().latitude() == 2); assertTrue(i_1.next().latitude() == 3); } /** * Verifica che il metodo addUserPoints aggiunga un Punto * Utente per l'Esperienza sul quale è chiamato. */ @Test public void testAddUserPoints() { UserPoint up = new UserPoint(5, 5); Iterable<IExperience> experiences = dataSource.getExperiences(); Experience exp = (Experience) experiences.iterator().next(); exp.addUserPoints(up); Iterable<UserPoint> ups = exp.getUserPoints(); assertTrue(up.equals(ups.iterator().next())); } /** * Verifica che il metodo getTracks restituisca correttamente * i Percorsi in base all'Esperienza sul quale è chiamato. */ @Test public void testGetTracks() { // TODO } }
MODEL/TEST: Riscrivi ExperienceTest come test di unità
serleena/app/src/test/java/com/kyloth/serleena/model/ExperienceTest.java
MODEL/TEST: Riscrivi ExperienceTest come test di unità
Java
epl-1.0
7cf3c99e611b9f2ae9caea6a15839086fb2e7df6
0
Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt
/************************************************************************************* * Copyright (c) 2004 Actuate Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.service; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.logging.Logger; import org.eclipse.birt.report.IBirtConstants; import org.eclipse.birt.report.engine.api.HTMLActionHandler; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.IAction; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.PDFRenderContext; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.utility.DataUtil; import org.eclipse.birt.report.utility.ParameterAccessor; /** * HTML action handler for url generation. */ class ViewerHTMLActionHandler extends HTMLActionHandler { /** * Logger for this handler. */ protected Logger log = Logger.getLogger( ViewerHTMLActionHandler.class .getName( ) ); /** * Document instance. */ protected IReportDocument document = null; /** * Locale of the requester. */ protected Locale locale = null; /** * Page number of the action requester. */ protected long page = -1; /** * if the page is embedded, the bookmark should always be a url to submit. */ protected boolean isEmbeddable = false; /** * RTL option setting by the command line or URL parameter. */ protected boolean isRtl = false; /** * if wanna use the master page, then set it to true. */ protected boolean isMasterPageContent = true; /** * Constructor. */ public ViewerHTMLActionHandler( ) { } /** * Constructor. This is for renderTask. * * @param document * @param page * @param locale * @param isEmbeddable * @param isRtl * @param isMasterPageContent */ public ViewerHTMLActionHandler( IReportDocument document, long page, Locale locale, boolean isEmbeddable, boolean isRtl, boolean isMasterPageContent ) { this.document = document; this.page = page; this.locale = locale; this.isEmbeddable = isEmbeddable; this.isRtl = isRtl; this.isMasterPageContent = isMasterPageContent; } /** * Constructor. This is for runAndRender task. * * @param locale * @param isEmbeddable * @param isRtl * @param isMasterPageContent */ public ViewerHTMLActionHandler( Locale locale, boolean isRtl, boolean isMasterPageContent ) { this.locale = locale; this.isRtl = isRtl; this.isMasterPageContent = isMasterPageContent; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.HTMLActionHandler#getURL(org.eclipse.birt.report.engine.api.IAction, * org.eclipse.birt.report.engine.api.script.IReportContext) */ public String getURL( IAction actionDefn, IReportContext context ) { if ( actionDefn == null ) return null; switch ( actionDefn.getType( ) ) { case IAction.ACTION_BOOKMARK : { return buildBookmarkAction( actionDefn, context ); } case IAction.ACTION_HYPERLINK : { return actionDefn.getActionString( ); } case IAction.ACTION_DRILLTHROUGH : { return buildDrillAction( actionDefn, context ); } } return null; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.HTMLActionHandler#getURL(org.eclipse.birt.report.engine.api.IAction, * java.lang.Object) */ public String getURL( IAction actionDefn, Object context ) { if ( actionDefn == null ) return null; if ( context instanceof IReportContext ) return getURL( actionDefn, (IReportContext) context ); throw new IllegalArgumentException( "The context is of wrong type." ); //$NON-NLS-1$ } /** * Build URL for bookmark. * * @param action * @param context * @return the bookmark url */ protected String buildBookmarkAction( IAction action, IReportContext context ) { if ( action == null || context == null ) return null; // Get Base URL String baseURL = null; Object renderContext = getRenderContext( context ); if ( renderContext instanceof HTMLRenderContext ) { baseURL = ( (HTMLRenderContext) renderContext ).getBaseURL( ); } if ( renderContext instanceof PDFRenderContext ) { baseURL = ( (PDFRenderContext) renderContext ).getBaseURL( ); } if ( baseURL == null ) return null; // Get bookmark String bookmark = action.getBookmark( ); // In frameset mode, use javascript function to fire Ajax request to // link to internal bookmark if ( baseURL.lastIndexOf( IBirtConstants.SERVLET_PATH_FRAMESET ) > 0 ) { return "javascript:catchBookmark('" + bookmark + "')"; //$NON-NLS-1$//$NON-NLS-2$ } // Save the URL String StringBuffer link = new StringBuffer( ); boolean realBookmark = false; if ( this.document != null ) { long pageNumber = this.document .getPageNumber( action.getBookmark( ) ); realBookmark = ( pageNumber == this.page && !isEmbeddable ); } try { bookmark = URLEncoder.encode( bookmark, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // Does nothing } link.append( baseURL ); link.append( ParameterAccessor.QUERY_CHAR ); // if the document is not null, then use it if ( document != null ) { link.append( ParameterAccessor.PARAM_REPORT_DOCUMENT ); link.append( ParameterAccessor.EQUALS_OPERATOR ); String documentName = document.getName( ); try { documentName = URLEncoder.encode( documentName, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // Does nothing } link.append( documentName ); } else if ( action.getReportName( ) != null && action.getReportName( ).length( ) > 0 ) { link.append( ParameterAccessor.PARAM_REPORT ); link.append( ParameterAccessor.EQUALS_OPERATOR ); String reportName = getReportName( context, action ); try { reportName = URLEncoder.encode( reportName, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // do nothing } link.append( reportName ); } else { // its an iternal bookmark return "#" + action.getActionString( ); //$NON-NLS-1$ } if ( locale != null ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_LOCALE, locale.toString( ) ) ); } if ( isRtl ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_RTL, String.valueOf( isRtl ) ) ); } // add isMasterPageContent link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_MASTERPAGE, String .valueOf( this.isMasterPageContent ) ) ); if ( realBookmark ) { link.append( "#" ); //$NON-NLS-1$ link.append( bookmark ); } else { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_BOOKMARK, bookmark ) ); } return link.toString( ); } /** * builds URL for drillthrough action * * @param action * instance of the IAction instance * @param context * the context for building the action string * @return a URL */ protected String buildDrillAction( IAction action, IReportContext context ) { if ( action == null || context == null ) return null; String baseURL = null; Object renderContext = getRenderContext( context ); if ( renderContext instanceof HTMLRenderContext ) { baseURL = ( (HTMLRenderContext) renderContext ).getBaseURL( ); } if ( renderContext instanceof PDFRenderContext ) { baseURL = ( (PDFRenderContext) renderContext ).getBaseURL( ); } if ( baseURL == null ) baseURL = IBirtConstants.VIEWER_RUN; StringBuffer link = new StringBuffer( ); String reportName = getReportName( context, action ); if ( reportName != null && !reportName.equals( "" ) ) //$NON-NLS-1$ { link.append( baseURL ); link .append( reportName.toLowerCase( ) .endsWith( ".rptdocument" ) ? "?__document=" : "?__report=" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { link.append( URLEncoder.encode( reportName, ParameterAccessor.UTF_8_ENCODE ) ); } catch ( UnsupportedEncodingException e1 ) { // It should not happen. Does nothing } // add format support String format = action.getFormat( ); if ( format != null && format.length( ) > 0 ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_FORMAT, format ) ); } // Adds the parameters if ( action.getParameterBindings( ) != null ) { Iterator paramsIte = action.getParameterBindings( ).entrySet( ) .iterator( ); while ( paramsIte.hasNext( ) ) { Map.Entry entry = (Map.Entry) paramsIte.next( ); try { String key = (String) entry.getKey( ); Object valueObj = entry.getValue( ); if ( valueObj != null ) { // TODO: here need the get the format from the // parameter. String value = DataUtil.getDisplayValue( valueObj ); link .append( ParameterAccessor .getQueryParameterString( URLEncoder .encode( key, ParameterAccessor.UTF_8_ENCODE ), URLEncoder .encode( value, ParameterAccessor.UTF_8_ENCODE ) ) ); } } catch ( UnsupportedEncodingException e ) { // Does nothing } } // Adding overwrite. if ( !reportName.toLowerCase( ).endsWith( ParameterAccessor.SUFFIX_REPORT_DOCUMENT ) && baseURL .lastIndexOf( IBirtConstants.SERVLET_PATH_FRAMESET ) > 0 ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_OVERWRITE, String .valueOf( true ) ) ); } } if ( locale != null ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_LOCALE, locale.toString( ) ) ); } if ( isRtl ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_RTL, String.valueOf( isRtl ) ) ); } // add isMasterPageContent link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_MASTERPAGE, String .valueOf( this.isMasterPageContent ) ) ); // add bookmark if ( action.getBookmark( ) != null ) { try { // In RUN mode or pdf format, don't support bookmark as // parameter if ( baseURL.lastIndexOf( IBirtConstants.SERVLET_PATH_RUN ) > 0 || IBirtConstants.PDF_RENDER_FORMAT .equalsIgnoreCase( format ) ) { link.append( "#" ); //$NON-NLS-1$ } else { link.append( "&__bookmark=" ); //$NON-NLS-1$ } link.append( URLEncoder.encode( action.getBookmark( ), ParameterAccessor.UTF_8_ENCODE ) ); } catch ( UnsupportedEncodingException e ) { // Does nothing } } } return link.toString( ); } /** * Gets the effective report path. * * @param context * @param action * @return the effective report path */ private String getReportName( IReportContext context, IAction action ) { assert context != null; assert action != null; String reportName = action.getReportName( ); IReportRunnable runnable = context.getReportRunnable( ); if ( runnable != null ) { ModuleHandle moduleHandle = runnable.getDesignHandle( ) .getModuleHandle( ); URL url = moduleHandle.findResource( reportName, -1 ); if ( url != null ) { if ( "file".equals( url.getProtocol( ) ) ) //$NON-NLS-1$ reportName = url.getFile( ); else reportName = url.toExternalForm( ); } } return reportName; } }
viewer/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ViewerHTMLActionHandler.java
/************************************************************************************* * Copyright (c) 2004 Actuate Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.service; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.logging.Logger; import org.eclipse.birt.report.IBirtConstants; import org.eclipse.birt.report.engine.api.HTMLActionHandler; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.IAction; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.PDFRenderContext; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.utility.DataUtil; import org.eclipse.birt.report.utility.ParameterAccessor; /** * HTML action handler for url generation. */ class ViewerHTMLActionHandler extends HTMLActionHandler { /** * Logger for this handler. */ protected Logger log = Logger.getLogger( ViewerHTMLActionHandler.class .getName( ) ); /** * Document instance. */ protected IReportDocument document = null; /** * Locale of the requester. */ protected Locale locale = null; /** * Page number of the action requester. */ protected long page = -1; /** * if the page is embedded, the bookmark should always be a url to submit. */ protected boolean isEmbeddable = false; /** * RTL option setting by the command line or URL parameter. */ protected boolean isRtl = false; /** * if wanna use the master page, then set it to true. */ protected boolean isMasterPageContent = true; /** * Constructor. */ public ViewerHTMLActionHandler( ) { } /** * Constructor. This is for renderTask. * * @param document * @param page * @param locale * @param isEmbeddable * @param isRtl * @param isMasterPageContent */ public ViewerHTMLActionHandler( IReportDocument document, long page, Locale locale, boolean isEmbeddable, boolean isRtl, boolean isMasterPageContent ) { this.document = document; this.page = page; this.locale = locale; this.isEmbeddable = isEmbeddable; this.isRtl = isRtl; this.isMasterPageContent = isMasterPageContent; } /** * Constructor. This is for runAndRender task. * * @param locale * @param isEmbeddable * @param isRtl * @param isMasterPageContent */ public ViewerHTMLActionHandler( Locale locale, boolean isRtl, boolean isMasterPageContent ) { this.locale = locale; this.isRtl = isRtl; this.isMasterPageContent = isMasterPageContent; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.api.HTMLActionHandler#getURL(org.eclipse.birt.report.engine.api.IAction, * org.eclipse.birt.report.engine.api.script.IReportContext) */ public String getURL( IAction actionDefn, IReportContext context ) { if ( actionDefn == null ) return null; switch ( actionDefn.getType( ) ) { case IAction.ACTION_BOOKMARK : { return buildBookmarkAction( actionDefn, context ); } case IAction.ACTION_HYPERLINK : { return actionDefn.getActionString( ); } case IAction.ACTION_DRILLTHROUGH : { return buildDrillAction( actionDefn, context ); } } return null; } /** * Build URL for bookmark. * * @param action * @param context * @return the bookmark url */ protected String buildBookmarkAction( IAction action, IReportContext context ) { if ( action == null || context == null ) return null; // Get Base URL String baseURL = null; Object renderContext = getRenderContext( context ); if ( renderContext instanceof HTMLRenderContext ) { baseURL = ( (HTMLRenderContext) renderContext ).getBaseURL( ); } if ( renderContext instanceof PDFRenderContext ) { baseURL = ( (PDFRenderContext) renderContext ).getBaseURL( ); } if ( baseURL == null ) return null; // Get bookmark String bookmark = action.getBookmark( ); // In frameset mode, use javascript function to fire Ajax request to // link to internal bookmark if ( baseURL.lastIndexOf( IBirtConstants.SERVLET_PATH_FRAMESET ) > 0 ) { return "javascript:catchBookmark('" + bookmark + "')"; //$NON-NLS-1$//$NON-NLS-2$ } // Save the URL String StringBuffer link = new StringBuffer( ); boolean realBookmark = false; if ( this.document != null ) { long pageNumber = this.document .getPageNumber( action.getBookmark( ) ); realBookmark = ( pageNumber == this.page && !isEmbeddable ); } try { bookmark = URLEncoder.encode( bookmark, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // Does nothing } link.append( baseURL ); link.append( ParameterAccessor.QUERY_CHAR ); // if the document is not null, then use it if ( document != null ) { link.append( ParameterAccessor.PARAM_REPORT_DOCUMENT ); link.append( ParameterAccessor.EQUALS_OPERATOR ); String documentName = document.getName( ); try { documentName = URLEncoder.encode( documentName, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // Does nothing } link.append( documentName ); } else if ( action.getReportName( ) != null && action.getReportName( ).length( ) > 0 ) { link.append( ParameterAccessor.PARAM_REPORT ); link.append( ParameterAccessor.EQUALS_OPERATOR ); String reportName = getReportName( context, action ); try { reportName = URLEncoder.encode( reportName, ParameterAccessor.UTF_8_ENCODE ); } catch ( UnsupportedEncodingException e ) { // do nothing } link.append( reportName ); } else { // its an iternal bookmark return "#" + action.getActionString( ); //$NON-NLS-1$ } if ( locale != null ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_LOCALE, locale.toString( ) ) ); } if ( isRtl ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_RTL, String.valueOf( isRtl ) ) ); } // add isMasterPageContent link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_MASTERPAGE, String .valueOf( this.isMasterPageContent ) ) ); if ( realBookmark ) { link.append( "#" ); //$NON-NLS-1$ link.append( bookmark ); } else { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_BOOKMARK, bookmark ) ); } return link.toString( ); } /** * builds URL for drillthrough action * * @param action * instance of the IAction instance * @param context * the context for building the action string * @return a URL */ protected String buildDrillAction( IAction action, IReportContext context ) { if ( action == null || context == null ) return null; String baseURL = null; Object renderContext = getRenderContext( context ); if ( renderContext instanceof HTMLRenderContext ) { baseURL = ( (HTMLRenderContext) renderContext ).getBaseURL( ); } if ( renderContext instanceof PDFRenderContext ) { baseURL = ( (PDFRenderContext) renderContext ).getBaseURL( ); } if ( baseURL == null ) baseURL = IBirtConstants.VIEWER_RUN; StringBuffer link = new StringBuffer( ); String reportName = getReportName( context, action ); if ( reportName != null && !reportName.equals( "" ) ) //$NON-NLS-1$ { link.append( baseURL ); link .append( reportName.toLowerCase( ) .endsWith( ".rptdocument" ) ? "?__document=" : "?__report=" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { link.append( URLEncoder.encode( reportName, ParameterAccessor.UTF_8_ENCODE ) ); } catch ( UnsupportedEncodingException e1 ) { // It should not happen. Does nothing } // add format support String format = action.getFormat( ); if ( format != null && format.length( ) > 0 ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_FORMAT, format ) ); } // Adds the parameters if ( action.getParameterBindings( ) != null ) { Iterator paramsIte = action.getParameterBindings( ).entrySet( ) .iterator( ); while ( paramsIte.hasNext( ) ) { Map.Entry entry = (Map.Entry) paramsIte.next( ); try { String key = (String) entry.getKey( ); Object valueObj = entry.getValue( ); if ( valueObj != null ) { // TODO: here need the get the format from the // parameter. String value = DataUtil.getDisplayValue( valueObj ); link .append( ParameterAccessor .getQueryParameterString( URLEncoder .encode( key, ParameterAccessor.UTF_8_ENCODE ), URLEncoder .encode( value, ParameterAccessor.UTF_8_ENCODE ) ) ); } } catch ( UnsupportedEncodingException e ) { // Does nothing } } // Adding overwrite. if ( !reportName.toLowerCase( ).endsWith( ParameterAccessor.SUFFIX_REPORT_DOCUMENT ) && baseURL .lastIndexOf( IBirtConstants.SERVLET_PATH_FRAMESET ) > 0 ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_OVERWRITE, String .valueOf( true ) ) ); } } if ( locale != null ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_LOCALE, locale.toString( ) ) ); } if ( isRtl ) { link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_RTL, String.valueOf( isRtl ) ) ); } // add isMasterPageContent link.append( ParameterAccessor.getQueryParameterString( ParameterAccessor.PARAM_MASTERPAGE, String .valueOf( this.isMasterPageContent ) ) ); // add bookmark if ( action.getBookmark( ) != null ) { try { // In RUN mode or pdf format, don't support bookmark as parameter if ( baseURL.lastIndexOf( IBirtConstants.SERVLET_PATH_RUN ) > 0 || IBirtConstants.PDF_RENDER_FORMAT .equalsIgnoreCase( format ) ) { link.append( "#" ); //$NON-NLS-1$ } else { link.append( "&__bookmark=" ); //$NON-NLS-1$ } link.append( URLEncoder.encode( action.getBookmark( ), ParameterAccessor.UTF_8_ENCODE ) ); } catch ( UnsupportedEncodingException e ) { // Does nothing } } } return link.toString( ); } /** * Gets the effective report path. * * @param context * @param action * @return the effective report path */ private String getReportName( IReportContext context, IAction action ) { assert context != null; assert action != null; String reportName = action.getReportName( ); IReportRunnable runnable = context.getReportRunnable( ); if ( runnable != null ) { ModuleHandle moduleHandle = runnable.getDesignHandle( ) .getModuleHandle( ); URL url = moduleHandle.findResource( reportName, -1 ); if ( url != null ) { if ( "file".equals( url.getProtocol( ) ) ) //$NON-NLS-1$ reportName = url.getFile( ); else reportName = url.toExternalForm( ); } } return reportName; } }
Fix 152948 -- support the actions for chart.
viewer/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ViewerHTMLActionHandler.java
Fix 152948 -- support the actions for chart.
Java
agpl-3.0
1cd73ea37d5b418c50d6fdf7e930cbc2f0309306
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
e442cbca-2e5f-11e5-9284-b827eb9e62be
hello.java
e43d136a-2e5f-11e5-9284-b827eb9e62be
e442cbca-2e5f-11e5-9284-b827eb9e62be
hello.java
e442cbca-2e5f-11e5-9284-b827eb9e62be
Java
agpl-3.0
91e5463b4736c1706738392948ab5a6f9bf1da94
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
6fa52676-2e61-11e5-9284-b827eb9e62be
hello.java
6f9fad40-2e61-11e5-9284-b827eb9e62be
6fa52676-2e61-11e5-9284-b827eb9e62be
hello.java
6fa52676-2e61-11e5-9284-b827eb9e62be
Java
lgpl-2.1
700390b1ea3067e746cdbb13049f0cb91c5f1ca9
0
cawka/ndnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,cawka/ndnx
package com.parc.ccn.apps; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Level; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.MalformedContentNameStringException; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.io.CCNFileOutputStream; import com.parc.ccn.library.io.CCNOutputStream; import com.parc.ccn.library.io.repo.RepositoryFileOutputStream; import com.parc.ccn.library.io.repo.RepositoryOutputStream; public class put_file { private static int BLOCK_SIZE = 8096; private static boolean rawMode = false; private static Integer timeout = null; private static boolean unversioned = false; /** * @param args */ public static void main(String[] args) { int startArg = 0; for (int i = 0; i < args.length - 2; i++) { if (args[i].equals(("-raw"))) { if (startArg <= i) startArg = i + 1; rawMode = true; } else if (args[i].equals("-unversioned")) { if (startArg <= i) startArg = i + 1; unversioned = true; } else if (args[i].equals("-timeout")) { if (args.length < (i + 2)) { usage(); } try { timeout = Integer.parseInt(args[++i]); } catch (NumberFormatException nfe) { usage(); } if (startArg <= i) startArg = i + 1; } else if (args[i].equals("-log")) { Level level = null; if (args.length < (i + 2)) { usage(); } try { level = Level.parse(args[++i]); } catch (NumberFormatException nfe) { usage(); } Library.logger().setLevel(level); if (startArg <= i) startArg = i + 1; } else { usage(); } } if (args.length < startArg + 2) { usage(); } long starttime = System.currentTimeMillis(); try { // If we get one file name, put as the specific name given. // If we get more than one, put underneath the first as parent. // Ideally want to use newVersion to get latest version. Start // with random version. ContentName argName = ContentName.fromURI(args[startArg]); CCNLibrary library = CCNLibrary.open(); if (args.length == (startArg + 2)) { File theFile = new File(args[startArg + 1]); if (!theFile.exists()) { System.out.println("No such file: " + args[startArg + 1]); usage(); } Library.logger().info("put_file: putting file " + args[startArg + 1] + " bytes: " + theFile.length()); CCNOutputStream ostream; if (rawMode) { if (unversioned) ostream = new CCNOutputStream(argName, library); else ostream = new CCNFileOutputStream(argName, library); } else { if (unversioned) ostream = new RepositoryOutputStream(argName, library); else ostream = new RepositoryFileOutputStream(argName, library); } if (timeout != null) ostream.setTimeout(timeout); do_write(ostream, theFile); System.out.println("Inserted file " + args[startArg + 1] + "."); System.out.println("put_file took: "+(System.currentTimeMillis() - starttime)+"ms"); System.exit(0); } else { for (int i=startArg + 1; i < args.length; ++i) { File theFile = new File(args[i]); if (!theFile.exists()) { System.out.println("No such file: " + args[i]); usage(); } //FileOutputStream testOut = new FileOutputStream("put_file" + i + ".dat"); //testOut.write(contents); //testOut.flush(); //testOut.close(); // put as child of name ContentName nodeName = ContentName.fromURI(argName, theFile.getName()); // int version = new Random().nextInt(1000); // would be version = library.latestVersion(argName) + 1; CCNOutputStream ostream; // Use file stream in both cases to match behavior. CCNOutputStream doesn't do // versioning and neither it nor CCNVersionedOutputStream add headers. if (rawMode) { if (unversioned) ostream = new CCNOutputStream(nodeName, library); else ostream = new CCNFileOutputStream(nodeName, library); } else { if (unversioned) ostream = new RepositoryOutputStream(nodeName, library); else ostream = new RepositoryFileOutputStream(nodeName, library); } if (timeout != null) ostream.setTimeout(timeout); do_write(ostream, theFile); System.out.println("Inserted file " + args[i] + "."); } System.out.println("put_file took: "+(System.currentTimeMillis() - starttime)+"ms"); System.exit(0); } } catch (ConfigurationException e) { System.out.println("Configuration exception in put: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot read file. " + e.getMessage()); e.printStackTrace(); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(1); } private static void do_write(CCNOutputStream ostream, File file) throws IOException { long time = System.currentTimeMillis(); FileInputStream fis = new FileInputStream(file); int size = BLOCK_SIZE; int readLen = 0; byte [] buffer = new byte[BLOCK_SIZE]; //do { Library.logger().info("do_write: " + fis.available() + " bytes left."); while((readLen = fis.read(buffer, 0, size)) != -1){ //if (size > fis.available()) // size = fis.available(); //if (size > 0) { // fis.read(buffer, 0, size); // ostream.write(buffer, 0, size); ostream.write(buffer, 0, readLen); Library.logger().info("do_write: wrote " + size + " bytes."); Library.logger().info("do_write: " + fis.available() + " bytes left."); } //} while (fis.available() > 0); ostream.close(); Library.logger().info("finished write: "+(System.currentTimeMillis() - time)); } public static void usage() { System.out.println("usage: put_file [-raw] [-unversioned] [-timeout millis] [-log level] <ccnname> <filename> [<filename> ...]"); System.exit(1); } }
Java_CCN/com/parc/ccn/apps/put_file.java
package com.parc.ccn.apps; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.MalformedContentNameStringException; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.io.CCNFileOutputStream; import com.parc.ccn.library.io.CCNOutputStream; import com.parc.ccn.library.io.repo.RepositoryFileOutputStream; import com.parc.ccn.library.io.repo.RepositoryOutputStream; public class put_file { private static int BLOCK_SIZE = 8096; private static boolean rawMode = false; private static Integer timeout = null; private static boolean unversioned = false; /** * @param args */ public static void main(String[] args) { int startArg = 0; for (int i = 0; i < args.length - 2; i++) { if (args[i].equals(("-raw"))) { if (startArg <= i) startArg = i + 1; rawMode = true; } else if (args[i].equals("-unversioned")) { if (startArg <= i) startArg = i + 1; unversioned = true; } else if (args[i].equals("-timeout")) { if (args.length < (i + 2)) { usage(); return; } try { timeout = Integer.parseInt(args[++i]); } catch (NumberFormatException nfe) { usage(); return; } if (startArg <= i) startArg = i + 1; } else { usage(); System.exit(1); } } if (args.length < startArg + 2) { usage(); System.exit(1); } long starttime = System.currentTimeMillis(); try { // If we get one file name, put as the specific name given. // If we get more than one, put underneath the first as parent. // Ideally want to use newVersion to get latest version. Start // with random version. ContentName argName = ContentName.fromURI(args[startArg]); CCNLibrary library = CCNLibrary.open(); if (args.length == (startArg + 2)) { File theFile = new File(args[startArg + 1]); if (!theFile.exists()) { System.out.println("No such file: " + args[startArg + 1]); usage(); return; } Library.logger().info("put_file: putting file " + args[startArg + 1] + " bytes: " + theFile.length()); CCNOutputStream ostream; if (rawMode) { if (unversioned) ostream = new CCNOutputStream(argName, library); else ostream = new CCNFileOutputStream(argName, library); } else { if (unversioned) ostream = new RepositoryOutputStream(argName, library); else ostream = new RepositoryFileOutputStream(argName, library); } if (timeout != null) ostream.setTimeout(timeout); do_write(ostream, theFile); System.out.println("Inserted file " + args[startArg + 1] + "."); System.out.println("put_file took: "+(System.currentTimeMillis() - starttime)+"ms"); System.exit(0); } else { for (int i=startArg + 1; i < args.length; ++i) { File theFile = new File(args[i]); if (!theFile.exists()) { System.out.println("No such file: " + args[i]); usage(); return; } //FileOutputStream testOut = new FileOutputStream("put_file" + i + ".dat"); //testOut.write(contents); //testOut.flush(); //testOut.close(); // put as child of name ContentName nodeName = ContentName.fromURI(argName, theFile.getName()); // int version = new Random().nextInt(1000); // would be version = library.latestVersion(argName) + 1; CCNOutputStream ostream; // Use file stream in both cases to match behavior. CCNOutputStream doesn't do // versioning and neither it nor CCNVersionedOutputStream add headers. if (rawMode) { if (unversioned) ostream = new CCNOutputStream(nodeName, library); else ostream = new CCNFileOutputStream(nodeName, library); } else { if (unversioned) ostream = new RepositoryOutputStream(nodeName, library); else ostream = new RepositoryFileOutputStream(nodeName, library); } if (timeout != null) ostream.setTimeout(timeout); do_write(ostream, theFile); System.out.println("Inserted file " + args[i] + "."); } System.out.println("put_file took: "+(System.currentTimeMillis() - starttime)+"ms"); System.exit(0); } } catch (ConfigurationException e) { System.out.println("Configuration exception in put: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot read file. " + e.getMessage()); e.printStackTrace(); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(1); } private static void do_write(CCNOutputStream ostream, File file) throws IOException { long time = System.currentTimeMillis(); FileInputStream fis = new FileInputStream(file); int size = BLOCK_SIZE; int readLen = 0; byte [] buffer = new byte[BLOCK_SIZE]; //do { Library.logger().info("do_write: " + fis.available() + " bytes left."); while((readLen = fis.read(buffer, 0, size)) != -1){ //if (size > fis.available()) // size = fis.available(); //if (size > 0) { // fis.read(buffer, 0, size); // ostream.write(buffer, 0, size); ostream.write(buffer, 0, readLen); Library.logger().info("do_write: wrote " + size + " bytes."); Library.logger().info("do_write: " + fis.available() + " bytes left."); } //} while (fis.available() > 0); ostream.close(); Library.logger().info("finished write: "+(System.currentTimeMillis() - time)); } public static void usage() { System.out.println("usage: put_file [-raw] [-unversioned] [-timeout millis] <ccnname> <filename> [<filename> ...]"); } }
Add logging option to put_file
Java_CCN/com/parc/ccn/apps/put_file.java
Add logging option to put_file
Java
apache-2.0
13aae1fa592fc61d4dff55bd54efab01607e8a8f
0
mmacfadden/orientdb,intfrr/orientdb,giastfader/orientdb,joansmith/orientdb,orientechnologies/orientdb,rprabhat/orientdb,allanmoso/orientdb,wyzssw/orientdb,intfrr/orientdb,tempbottle/orientdb,sanyaade-g2g-repos/orientdb,rprabhat/orientdb,alonsod86/orientdb,giastfader/orientdb,giastfader/orientdb,intfrr/orientdb,tempbottle/orientdb,alonsod86/orientdb,rprabhat/orientdb,wouterv/orientdb,cstamas/orientdb,rprabhat/orientdb,cstamas/orientdb,jdillon/orientdb,mmacfadden/orientdb,joansmith/orientdb,jdillon/orientdb,sanyaade-g2g-repos/orientdb,mbhulin/orientdb,tempbottle/orientdb,allanmoso/orientdb,sanyaade-g2g-repos/orientdb,wouterv/orientdb,wouterv/orientdb,orientechnologies/orientdb,wyzssw/orientdb,orientechnologies/orientdb,alonsod86/orientdb,intfrr/orientdb,cstamas/orientdb,tempbottle/orientdb,allanmoso/orientdb,allanmoso/orientdb,mbhulin/orientdb,joansmith/orientdb,mmacfadden/orientdb,mbhulin/orientdb,mbhulin/orientdb,orientechnologies/orientdb,wyzssw/orientdb,mmacfadden/orientdb,joansmith/orientdb,wyzssw/orientdb,sanyaade-g2g-repos/orientdb,jdillon/orientdb,cstamas/orientdb,giastfader/orientdb,wouterv/orientdb,alonsod86/orientdb
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.core.serialization.serializer.record.string; import com.orientechnologies.common.profiler.OProfilerMBean; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.OUserObject2RecordHandler; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationSetThreadLocal; import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerAnyStreamable; import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerEmbedded; import com.orientechnologies.orient.core.util.ODateHelper; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; @SuppressWarnings("serial") public abstract class ORecordSerializerStringAbstract implements ORecordSerializer, Serializable { protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler(); private static final char DECIMAL_SEPARATOR = '.'; private static final String MAX_INTEGER_AS_STRING = String.valueOf(Integer.MAX_VALUE); private static final int MAX_INTEGER_DIGITS = MAX_INTEGER_AS_STRING.length(); public static Object fieldTypeFromStream(final ODocument iDocument, OType iType, final Object iValue) { if (iValue == null) return null; if (iType == null) iType = OType.EMBEDDED; switch (iType) { case STRING: case INTEGER: case BOOLEAN: case FLOAT: case DECIMAL: case LONG: case DOUBLE: case SHORT: case BYTE: case BINARY: case DATE: case DATETIME: case LINK: return simpleValueFromStream(iValue, iType); case EMBEDDED: { // EMBEDED RECORD final Object embeddedObject = OStringSerializerEmbedded.INSTANCE.fromStream((String) iValue); if (embeddedObject instanceof ODocument) ((ODocument) embeddedObject).addOwner(iDocument); // EMBEDDED OBJECT return embeddedObject; } case CUSTOM: // RECORD final Object result = OStringSerializerAnyStreamable.INSTANCE.fromStream((String) iValue); if (result instanceof ODocument) ((ODocument) result).addOwner(iDocument); return result; case EMBEDDEDSET: case EMBEDDEDLIST: { final String value = (String) iValue; return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionFromStream(iDocument, iType, null, null, value); } case EMBEDDEDMAP: { final String value = (String) iValue; return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapFromStream(iDocument, null, value, null); } } throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue); } public static Object convertValue(final String iValue, final OType iExpectedType) { final Object v = getTypeValue((String) iValue); return OType.convert(v, iExpectedType.getDefaultJavaType()); } public static void fieldTypeToString(final StringBuilder iBuffer, OType iType, final Object iValue) { if (iValue == null) return; final long timer = PROFILER.startChrono(); if (iType == null) { if (iValue instanceof ORID) iType = OType.LINK; else iType = OType.EMBEDDED; } switch (iType) { case STRING: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.string2string"), "Serialize string to string", timer); break; case BOOLEAN: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.bool2string"), "Serialize boolean to string", timer); break; case INTEGER: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.int2string"), "Serialize integer to string", timer); break; case FLOAT: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.float2string"), "Serialize float to string", timer); break; case DECIMAL: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.decimal2string"), "Serialize decimal to string", timer); break; case LONG: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.long2string"), "Serialize long to string", timer); break; case DOUBLE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.double2string"), "Serialize double to string", timer); break; case SHORT: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.short2string"), "Serialize short to string", timer); break; case BYTE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.byte2string"), "Serialize byte to string", timer); break; case BINARY: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.binary2string"), "Serialize binary to string", timer); break; case DATE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.date2string"), "Serialize date to string", timer); break; case DATETIME: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.datetime2string"), "Serialize datetime to string", timer); break; case LINK: if (iValue instanceof ORecordId) ((ORecordId) iValue).toString(iBuffer); else ((ORecord<?>) iValue).getIdentity().toString(iBuffer); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer); break; case EMBEDDEDSET: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true, true); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string", timer); break; case EMBEDDEDLIST: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true, false); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"), "Serialize embeddedlist to string", timer); break; case EMBEDDEDMAP: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string", timer); break; case EMBEDDED: OStringSerializerEmbedded.INSTANCE.toStream(iBuffer, iValue); PROFILER .stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer); break; case CUSTOM: OStringSerializerAnyStreamable.INSTANCE.toStream(iBuffer, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.custom2string"), "Serialize custom to string", timer); break; default: throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue); } } /** * Parses a string returning the closer type. Numbers by default are INTEGER if haven't decimal separator, otherwise FLOAT. To * treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short, l=long, f=float, * d=double, t=date. * * @param iValue * Value to parse * @return The closest type recognized */ public static OType getType(final String iValue) { if (iValue.length() == 0) return null; final char firstChar = iValue.charAt(0); if (firstChar == ORID.PREFIX) // RID return OType.LINK; else if (firstChar == '\'' || firstChar == '"') return OType.STRING; else if (firstChar == OStringSerializerHelper.BINARY_BEGINEND) return OType.BINARY; else if (firstChar == OStringSerializerHelper.EMBEDDED_BEGIN) return OType.EMBEDDED; else if (firstChar == OStringSerializerHelper.LINK) return OType.LINK; else if (firstChar == OStringSerializerHelper.LIST_BEGIN) return OType.EMBEDDEDLIST; else if (firstChar == OStringSerializerHelper.SET_BEGIN) return OType.EMBEDDEDSET; else if (firstChar == OStringSerializerHelper.MAP_BEGIN) return OType.EMBEDDEDMAP; else if (firstChar == OStringSerializerHelper.CUSTOM_TYPE) return OType.CUSTOM; // BOOLEAN? if (iValue.equalsIgnoreCase("true") || iValue.equalsIgnoreCase("false")) return OType.BOOLEAN; // NUMBER OR STRING? boolean integer = true; for (int index = 0; index < iValue.length(); ++index) { final char c = iValue.charAt(index); if (c < '0' || c > '9') if ((index == 0 && (c == '+' || c == '-'))) continue; else if (c == DECIMAL_SEPARATOR) integer = false; else { if (index > 0) if (!integer && c == 'E') { // CHECK FOR SCIENTIFIC NOTATION if (index < iValue.length()) { if (iValue.charAt(index + 1) == '-') // JUMP THE DASH IF ANY (NOT MANDATORY) index++; continue; } } else if (c == 'f') return OType.FLOAT; else if (c == 'c') return OType.DECIMAL; else if (c == 'l') return OType.LONG; else if (c == 'd') return OType.DOUBLE; else if (c == 'b') return OType.BYTE; else if (c == 'a') return OType.DATE; else if (c == 't') return OType.DATETIME; else if (c == 's') return OType.SHORT; return OType.STRING; } } if (integer) { // AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG final int numberLength = iValue.length(); if (numberLength > MAX_INTEGER_DIGITS || (numberLength == MAX_INTEGER_DIGITS && iValue.compareTo(MAX_INTEGER_AS_STRING) > 0)) return OType.LONG; return OType.INTEGER; } // CHECK IF THE DECIMAL NUMBER IS A FLOAT OR DOUBLE final double dou = Double.parseDouble(iValue); if (dou <= Float.MAX_VALUE || dou >= Float.MIN_VALUE) return OType.FLOAT; return OType.DOUBLE; } /** * Parses the field type char returning the closer type. Default is STRING. b=binary if iValue.lenght() >= 4 b=byte if * iValue.lenght() <= 3 s=short, l=long f=float d=double a=date t=datetime * * @param iValue * Value to parse * @param iCharType * Char value indicating the type * @return The closest type recognized */ public static OType getType(final String iValue, final char iCharType) { if (iCharType == 'f') return OType.FLOAT; else if (iCharType == 'c') return OType.DECIMAL; else if (iCharType == 'l') return OType.LONG; else if (iCharType == 'd') return OType.DOUBLE; else if (iCharType == 'b') { if (iValue.length() >= 1 && iValue.length() <= 3) return OType.BYTE; else return OType.BINARY; } else if (iCharType == 'a') return OType.DATE; else if (iCharType == 't') return OType.DATETIME; else if (iCharType == 's') return OType.SHORT; else if (iCharType == 'e') return OType.EMBEDDEDSET; else if (iCharType == 'g') return OType.LINKBAG; else if (iCharType == 'z') return OType.LINKLIST; else if (iCharType == 'x') return OType.LINK; else if (iCharType == 'n') return OType.LINKSET; return OType.STRING; } /** * Parses a string returning the value with the closer type. Numbers by default are INTEGER if haven't decimal separator, * otherwise FLOAT. To treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short, * l=long, f=float, d=double, t=date. If starts with # it's a RecordID. Most of the code is equals to getType() but has been * copied to speed-up it. * * @param iValue * Value to parse * @return The closest type recognized */ public static Object getTypeValue(final String iValue) { if (iValue == null || iValue.equalsIgnoreCase("NULL")) return null; if (iValue.length() == 0) return ""; if (iValue.length() > 1) if (iValue.charAt(0) == '"' && iValue.charAt(iValue.length() - 1) == '"') // STRING return OStringSerializerHelper.decode(iValue.substring(1, iValue.length() - 1)); else if (iValue.charAt(0) == OStringSerializerHelper.BINARY_BEGINEND && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.BINARY_BEGINEND) // STRING return OStringSerializerHelper.getBinaryContent(iValue); else if (iValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.LIST_END) { // LIST final ArrayList<String> coll = new ArrayList<String>(); OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.LIST_BEGIN, OStringSerializerHelper.LIST_END, OStringSerializerHelper.COLLECTION_SEPARATOR); return coll; } else if (iValue.charAt(0) == OStringSerializerHelper.SET_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.SET_END) { // SET final Set<String> coll = new HashSet<String>(); OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.SET_BEGIN, OStringSerializerHelper.SET_END, OStringSerializerHelper.COLLECTION_SEPARATOR); return coll; } else if (iValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.MAP_END) { // MAP return OStringSerializerHelper.getMap(iValue); } if (iValue.charAt(0) == ORID.PREFIX) // RID return new ORecordId(iValue); boolean integer = true; char c; for (int index = 0; index < iValue.length(); ++index) { c = iValue.charAt(index); if (c < '0' || c > '9') if ((index == 0 && (c == '+' || c == '-'))) continue; else if (c == DECIMAL_SEPARATOR) integer = false; else { if (index > 0) { if (!integer && c == 'E') { // CHECK FOR SCIENTIFIC NOTATION if (index < iValue.length()) index++; if (iValue.charAt(index) == '-') continue; } final String v = iValue.substring(0, index); if (c == 'f') return new Float(v); else if (c == 'c') return new BigDecimal(v); else if (c == 'l') return new Long(v); else if (c == 'd') return new Double(v); else if (c == 'b') return new Byte(v); else if (c == 'a' || c == 't') return new Date(Long.parseLong(v)); else if (c == 's') return new Short(v); } return iValue; } } if (integer) { try { return new Integer(iValue); } catch (NumberFormatException e) { return new Long(iValue); } } else if ("NaN".equals(iValue) || "Infinity".equals(iValue)) // NaN and Infinity CANNOT BE MANAGED BY BIG-DECIMAL TYPE return new Double(iValue); else return new BigDecimal(iValue); } public static Object simpleValueFromStream(final Object iValue, final OType iType) { switch (iType) { case STRING: if (iValue instanceof String) { final String s = OStringSerializerHelper.getStringContent(iValue); return OStringSerializerHelper.decode(s); } return iValue.toString(); case INTEGER: if (iValue instanceof Integer) return iValue; return new Integer(iValue.toString()); case BOOLEAN: if (iValue instanceof Boolean) return iValue; return new Boolean(iValue.toString()); case FLOAT: if (iValue instanceof Float) return iValue; return convertValue((String) iValue, iType); case DECIMAL: if (iValue instanceof BigDecimal) return iValue; return convertValue((String) iValue, iType); case LONG: if (iValue instanceof Long) return iValue; return convertValue((String) iValue, iType); case DOUBLE: if (iValue instanceof Double) return iValue; return convertValue((String) iValue, iType); case SHORT: if (iValue instanceof Short) return iValue; return convertValue((String) iValue, iType); case BYTE: if (iValue instanceof Byte) return iValue; return convertValue((String) iValue, iType); case BINARY: return OStringSerializerHelper.getBinaryContent(iValue); case DATE: case DATETIME: if (iValue instanceof Date) return iValue; return convertValue((String) iValue, iType); case LINK: if (iValue instanceof ORID) return iValue.toString(); else if (iValue instanceof String) return new ORecordId((String) iValue); else return ((ORecord<?>) iValue).getIdentity().toString(); } throw new IllegalArgumentException("Type " + iType + " is not simple type."); } public static void simpleValueToStream(final StringBuilder iBuffer, final OType iType, final Object iValue) { if (iValue == null || iType == null) return; switch (iType) { case STRING: iBuffer.append('"'); iBuffer.append(OStringSerializerHelper.encode(iValue.toString())); iBuffer.append('"'); break; case BOOLEAN: iBuffer.append(String.valueOf(iValue)); break; case INTEGER: iBuffer.append(String.valueOf(iValue)); break; case FLOAT: iBuffer.append(String.valueOf(iValue)); iBuffer.append('f'); break; case DECIMAL: if (iValue instanceof BigDecimal) iBuffer.append(((BigDecimal) iValue).toPlainString()); else iBuffer.append(String.valueOf(iValue)); iBuffer.append('c'); break; case LONG: iBuffer.append(String.valueOf(iValue)); iBuffer.append('l'); break; case DOUBLE: iBuffer.append(String.valueOf(iValue)); iBuffer.append('d'); break; case SHORT: iBuffer.append(String.valueOf(iValue)); iBuffer.append('s'); break; case BYTE: if (iValue instanceof Character) iBuffer.append((int) ((Character) iValue).charValue()); else if (iValue instanceof String) iBuffer.append(String.valueOf((int) ((String) iValue).charAt(0))); else iBuffer.append(String.valueOf(iValue)); iBuffer.append('b'); break; case BINARY: iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND); if (iValue instanceof Byte) iBuffer.append(OBase64Utils.encodeBytes(new byte[] { ((Byte) iValue).byteValue() })); else iBuffer.append(OBase64Utils.encodeBytes((byte[]) iValue)); iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND); break; case DATE: if (iValue instanceof Date) { // RESET HOURS, MINUTES, SECONDS AND MILLISECONDS final Calendar calendar = ODateHelper.getDatabaseCalendar(); calendar.setTime((Date) iValue); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); iBuffer.append(calendar.getTimeInMillis()); } else iBuffer.append(iValue); iBuffer.append('a'); break; case DATETIME: if (iValue instanceof Date) iBuffer.append(((Date) iValue).getTime()); else iBuffer.append(iValue); iBuffer.append('t'); break; } } public abstract ORecordInternal<?> fromString(String iContent, ORecordInternal<?> iRecord, String[] iFields); public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat) { return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(), OSerializationSetThreadLocal.INSTANCE.get(), false, true); } public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat, final boolean autoDetectCollectionType) { return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(), OSerializationSetThreadLocal.INSTANCE.get(), false, autoDetectCollectionType); } public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat) { return toString(iRecord, iOutput, iFormat, null, OSerializationSetThreadLocal.INSTANCE.get(), false, true); } public ORecordInternal<?> fromString(final String iSource) { return fromString(iSource, (ORecordInternal<?>) ODatabaseRecordThreadLocal.INSTANCE.get().newInstance(), null); } public ORecordInternal<?> fromStream(final byte[] iSource, final ORecordInternal<?> iRecord, final String[] iFields) { final long timer = PROFILER.startChrono(); try { return fromString(OBinaryProtocol.bytes2string(iSource), iRecord, iFields); } finally { PROFILER .stopChrono(PROFILER.getProcessMetric("serializer.record.string.fromStream"), "Deserialize record from stream", timer); } } public byte[] toStream(final ORecordInternal<?> iRecord, boolean iOnlyDelta) { final long timer = PROFILER.startChrono(); try { return OBinaryProtocol.string2bytes(toString(iRecord, new StringBuilder(2048), null, null, OSerializationSetThreadLocal.INSTANCE.get(), iOnlyDelta, true).toString()); } finally { PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.toStream"), "Serialize record to stream", timer); } } protected abstract StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat, final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta, boolean autoDetectCollectionType); }
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.core.serialization.serializer.record.string; import com.orientechnologies.common.profiler.OProfilerMBean; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.OUserObject2RecordHandler; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationSetThreadLocal; import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerAnyStreamable; import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerEmbedded; import com.orientechnologies.orient.core.util.ODateHelper; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; @SuppressWarnings("serial") public abstract class ORecordSerializerStringAbstract implements ORecordSerializer, Serializable { protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler(); private static final char DECIMAL_SEPARATOR = '.'; private static final String MAX_INTEGER_AS_STRING = String.valueOf(Integer.MAX_VALUE); private static final int MAX_INTEGER_DIGITS = MAX_INTEGER_AS_STRING.length(); public static Object fieldTypeFromStream(final ODocument iDocument, OType iType, final Object iValue) { if (iValue == null) return null; if (iType == null) iType = OType.EMBEDDED; switch (iType) { case STRING: case INTEGER: case BOOLEAN: case FLOAT: case DECIMAL: case LONG: case DOUBLE: case SHORT: case BYTE: case BINARY: case DATE: case DATETIME: case LINK: return simpleValueFromStream(iValue, iType); case EMBEDDED: { // EMBEDED RECORD final Object embeddedObject = OStringSerializerEmbedded.INSTANCE.fromStream((String) iValue); if (embeddedObject instanceof ODocument) ((ODocument) embeddedObject).addOwner(iDocument); // EMBEDDED OBJECT return embeddedObject; } case CUSTOM: // RECORD final Object result = OStringSerializerAnyStreamable.INSTANCE.fromStream((String) iValue); if (result instanceof ODocument) ((ODocument) result).addOwner(iDocument); return result; case EMBEDDEDSET: case EMBEDDEDLIST: { final String value = (String) iValue; return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionFromStream(iDocument, iType, null, null, value); } case EMBEDDEDMAP: { final String value = (String) iValue; return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapFromStream(iDocument, null, value, null); } } throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue); } public static Object convertValue(final String iValue, final OType iExpectedType) { final Object v = getTypeValue((String) iValue); return OType.convert(v, iExpectedType.getDefaultJavaType()); } public static void fieldTypeToString(final StringBuilder iBuffer, OType iType, final Object iValue) { if (iValue == null) return; final long timer = PROFILER.startChrono(); if (iType == null) { if (iValue instanceof ORID) iType = OType.LINK; else iType = OType.EMBEDDED; } switch (iType) { case STRING: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.string2string"), "Serialize string to string", timer); break; case BOOLEAN: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.bool2string"), "Serialize boolean to string", timer); break; case INTEGER: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.int2string"), "Serialize integer to string", timer); break; case FLOAT: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.float2string"), "Serialize float to string", timer); break; case DECIMAL: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.decimal2string"), "Serialize decimal to string", timer); break; case LONG: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.long2string"), "Serialize long to string", timer); break; case DOUBLE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.double2string"), "Serialize double to string", timer); break; case SHORT: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.short2string"), "Serialize short to string", timer); break; case BYTE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.byte2string"), "Serialize byte to string", timer); break; case BINARY: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.binary2string"), "Serialize binary to string", timer); break; case DATE: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.date2string"), "Serialize date to string", timer); break; case DATETIME: simpleValueToStream(iBuffer, iType, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.datetime2string"), "Serialize datetime to string", timer); break; case LINK: if (iValue instanceof ORecordId) ((ORecordId) iValue).toString(iBuffer); else ((ORecord<?>) iValue).getIdentity().toString(iBuffer); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer); break; case EMBEDDEDSET: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true, true); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string", timer); break; case EMBEDDEDLIST: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true, false); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"), "Serialize embeddedlist to string", timer); break; case EMBEDDEDMAP: ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null, iBuffer, null, null, iValue, null, true); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string", timer); break; case EMBEDDED: OStringSerializerEmbedded.INSTANCE.toStream(iBuffer, iValue); PROFILER .stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer); break; case CUSTOM: OStringSerializerAnyStreamable.INSTANCE.toStream(iBuffer, iValue); PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.custom2string"), "Serialize custom to string", timer); break; default: throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue); } } /** * Parses a string returning the closer type. Numbers by default are INTEGER if haven't decimal separator, otherwise FLOAT. To * treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short, l=long, f=float, * d=double, t=date. * * @param iValue * Value to parse * @return The closest type recognized */ public static OType getType(final String iValue) { if (iValue.length() == 0) return null; final char firstChar = iValue.charAt(0); if (firstChar == ORID.PREFIX) // RID return OType.LINK; else if (firstChar == '\'' || firstChar == '"') return OType.STRING; else if (firstChar == OStringSerializerHelper.BINARY_BEGINEND) return OType.BINARY; else if (firstChar == OStringSerializerHelper.EMBEDDED_BEGIN) return OType.EMBEDDED; else if (firstChar == OStringSerializerHelper.LINK) return OType.LINK; else if (firstChar == OStringSerializerHelper.LIST_BEGIN) return OType.EMBEDDEDLIST; else if (firstChar == OStringSerializerHelper.SET_BEGIN) return OType.EMBEDDEDSET; else if (firstChar == OStringSerializerHelper.MAP_BEGIN) return OType.EMBEDDEDMAP; else if (firstChar == OStringSerializerHelper.CUSTOM_TYPE) return OType.CUSTOM; // BOOLEAN? if (iValue.equalsIgnoreCase("true") || iValue.equalsIgnoreCase("false")) return OType.BOOLEAN; // NUMBER OR STRING? boolean integer = true; for (int index = 0; index < iValue.length(); ++index) { final char c = iValue.charAt(index); if (c < '0' || c > '9') if ((index == 0 && (c == '+' || c == '-'))) continue; else if (c == DECIMAL_SEPARATOR) integer = false; else { if (index > 0) if (!integer && c == 'E') { // CHECK FOR SCIENTIFIC NOTATION if (index < iValue.length()) { if (iValue.charAt(index + 1) == '-') // JUMP THE DASH IF ANY (NOT MANDATORY) index++; continue; } } else if (c == 'f') return OType.FLOAT; else if (c == 'c') return OType.DECIMAL; else if (c == 'l') return OType.LONG; else if (c == 'd') return OType.DOUBLE; else if (c == 'b') return OType.BYTE; else if (c == 'a') return OType.DATE; else if (c == 't') return OType.DATETIME; else if (c == 's') return OType.SHORT; return OType.STRING; } } if (integer) { // AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG final int numberLength = iValue.length(); if (numberLength > MAX_INTEGER_DIGITS || (numberLength == MAX_INTEGER_DIGITS && iValue.compareTo(MAX_INTEGER_AS_STRING) > 0)) return OType.LONG; return OType.INTEGER; } // CHECK IF THE DECIMAL NUMBER IS A FLOAT OR DOUBLE final double dou = Double.parseDouble(iValue); if (dou <= Float.MAX_VALUE || dou >= Float.MIN_VALUE) return OType.FLOAT; return OType.DOUBLE; } /** * Parses the field type char returning the closer type. Default is STRING. b=binary if iValue.lenght() >= 4 b=byte if * iValue.lenght() <= 3 s=short, l=long f=float d=double a=date t=datetime * * @param iValue * Value to parse * @param iCharType * Char value indicating the type * @return The closest type recognized */ public static OType getType(final String iValue, final char iCharType) { if (iCharType == 'f') return OType.FLOAT; else if (iCharType == 'c') return OType.DECIMAL; else if (iCharType == 'l') return OType.LONG; else if (iCharType == 'd') return OType.DOUBLE; else if (iCharType == 'b') { if (iValue.length() >= 1 && iValue.length() <= 3) return OType.BYTE; else return OType.BINARY; } else if (iCharType == 'a') return OType.DATE; else if (iCharType == 't') return OType.DATETIME; else if (iCharType == 's') return OType.SHORT; else if (iCharType == 'e') return OType.EMBEDDEDSET; else if (iCharType == 'g') return OType.LINKBAG; else if (iCharType == 'z') return OType.LINKLIST; else if (iCharType == 'x') return OType.LINK; else if (iCharType == 'n') return OType.LINKSET; return OType.STRING; } /** * Parses a string returning the value with the closer type. Numbers by default are INTEGER if haven't decimal separator, * otherwise FLOAT. To treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short, * l=long, f=float, d=double, t=date. If starts with # it's a RecordID. Most of the code is equals to getType() but has been * copied to speed-up it. * * @param iValue * Value to parse * @return The closest type recognized */ public static Object getTypeValue(final String iValue) { if (iValue == null || iValue.equalsIgnoreCase("NULL")) return null; if (iValue.length() == 0) return ""; if (iValue.length() > 1) if (iValue.charAt(0) == '"' && iValue.charAt(iValue.length() - 1) == '"') // STRING return OStringSerializerHelper.decode(iValue.substring(1, iValue.length() - 1)); else if (iValue.charAt(0) == OStringSerializerHelper.BINARY_BEGINEND && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.BINARY_BEGINEND) // STRING return OStringSerializerHelper.getBinaryContent(iValue); else if (iValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.LIST_END) { // LIST final ArrayList<String> coll = new ArrayList<String>(); OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.LIST_BEGIN, OStringSerializerHelper.LIST_END, OStringSerializerHelper.COLLECTION_SEPARATOR); return coll; } else if (iValue.charAt(0) == OStringSerializerHelper.SET_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.SET_END) { // SET final Set<String> coll = new HashSet<String>(); OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.SET_BEGIN, OStringSerializerHelper.SET_END, OStringSerializerHelper.COLLECTION_SEPARATOR); return coll; } else if (iValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.MAP_END) { // MAP return OStringSerializerHelper.getMap(iValue); } if (iValue.charAt(0) == ORID.PREFIX) // RID return new ORecordId(iValue); boolean integer = true; char c; for (int index = 0; index < iValue.length(); ++index) { c = iValue.charAt(index); if (c < '0' || c > '9') if ((index == 0 && (c == '+' || c == '-'))) continue; else if (c == DECIMAL_SEPARATOR) integer = false; else { if (index > 0) { if (!integer && c == 'E') { // CHECK FOR SCIENTIFIC NOTATION if (index < iValue.length()) index++; if (iValue.charAt(index) == '-') continue; } final String v = iValue.substring(0, index); if (c == 'f') return new Float(v); else if (c == 'c') return new BigDecimal(v); else if (c == 'l') return new Long(v); else if (c == 'd') return new Double(v); else if (c == 'b') return new Byte(v); else if (c == 'a' || c == 't') return new Date(Long.parseLong(v)); else if (c == 's') return new Short(v); } return iValue; } } if (integer) { try { return new Integer(iValue); } catch (NumberFormatException e) { return new Long(iValue); } } else if ("NaN".equals(iValue) || "Infinity".equals(iValue)) // NaN and Infinity CANNOT BE MANAGED BY BIG-DECIMAL TYPE return new Double(iValue); else return new BigDecimal(iValue); } public static Object simpleValueFromStream(final Object iValue, final OType iType) { switch (iType) { case STRING: if (iValue instanceof String) { final String s = OStringSerializerHelper.getStringContent(iValue); return OStringSerializerHelper.decode(s); } return iValue.toString(); case INTEGER: if (iValue instanceof Integer) return iValue; return new Integer(iValue.toString()); case BOOLEAN: if (iValue instanceof Boolean) return iValue; return new Boolean(iValue.toString()); case FLOAT: if (iValue instanceof Float) return iValue; return convertValue((String) iValue, iType); case DECIMAL: if (iValue instanceof BigDecimal) return iValue; return convertValue((String) iValue, iType); case LONG: if (iValue instanceof Long) return iValue; return convertValue((String) iValue, iType); case DOUBLE: if (iValue instanceof Double) return iValue; return convertValue((String) iValue, iType); case SHORT: if (iValue instanceof Short) return iValue; return convertValue((String) iValue, iType); case BYTE: if (iValue instanceof Byte) return iValue; return convertValue((String) iValue, iType); case BINARY: return OStringSerializerHelper.getBinaryContent(iValue); case DATE: case DATETIME: if (iValue instanceof Date) return iValue; return convertValue((String) iValue, iType); case LINK: if (iValue instanceof ORID) return iValue.toString(); else if (iValue instanceof String) return new ORecordId((String) iValue); else return ((ORecord<?>) iValue).getIdentity().toString(); } throw new IllegalArgumentException("Type " + iType + " is not simple type."); } public static void simpleValueToStream(final StringBuilder iBuffer, final OType iType, final Object iValue) { if (iValue == null || iType == null) return; switch (iType) { case STRING: iBuffer.append('"'); iBuffer.append(OStringSerializerHelper.encode(iValue.toString())); iBuffer.append('"'); break; case BOOLEAN: iBuffer.append(String.valueOf(iValue)); break; case INTEGER: iBuffer.append(String.valueOf(iValue)); break; case FLOAT: iBuffer.append(String.valueOf(iValue)); iBuffer.append('f'); break; case DECIMAL: if (iValue instanceof BigDecimal) iBuffer.append(((BigDecimal) iValue).toPlainString()); else iBuffer.append(String.valueOf(iValue)); iBuffer.append('c'); break; case LONG: iBuffer.append(String.valueOf(iValue)); iBuffer.append('l'); break; case DOUBLE: iBuffer.append(String.valueOf(iValue)); iBuffer.append('d'); break; case SHORT: iBuffer.append(String.valueOf(iValue)); iBuffer.append('s'); break; case BYTE: if (iValue instanceof Character) iBuffer.append((int) ((Character) iValue).charValue()); else if (iValue instanceof String) iBuffer.append(String.valueOf((int) ((String) iValue).charAt(0))); else iBuffer.append(String.valueOf(iValue)); iBuffer.append('b'); break; case BINARY: iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND); if (iValue instanceof Byte) iBuffer.append(OBase64Utils.encodeBytes(new byte[] { ((Byte) iValue).byteValue() })); else iBuffer.append(OBase64Utils.encodeBytes((byte[]) iValue)); iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND); break; case DATE: if (iValue instanceof Date) { // RESET HOURS, MINUTES, SECONDS AND MILLISECONDS final Calendar calendar = ODateHelper.getDatabaseCalendar(); calendar.setTime((Date) iValue); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); iBuffer.append(calendar.getTimeInMillis()); } else iBuffer.append(iValue); iBuffer.append('a'); break; case DATETIME: if (iValue instanceof Date) iBuffer.append(((Date) iValue).getTime()); else iBuffer.append(iValue); iBuffer.append('t'); break; } } public abstract ORecordInternal<?> fromString(String iContent, ORecordInternal<?> iRecord, String[] iFields); public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat) { return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(), OSerializationSetThreadLocal.INSTANCE.get(), false, true); } public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat, final boolean autoDetectCollectionType) { return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(), OSerializationSetThreadLocal.INSTANCE.get(), false, autoDetectCollectionType); } public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat) { return toString(iRecord, iOutput, iFormat, null, OSerializationSetThreadLocal.INSTANCE.get(), false, true); } public ORecordInternal<?> fromString(final String iSource) { return fromString(iSource, (ORecordInternal<?>) ODatabaseRecordThreadLocal.INSTANCE.get().newInstance(), null); } public ORecordInternal<?> fromStream(final byte[] iSource, final ORecordInternal<?> iRecord, final String[] iFields) { final long timer = PROFILER.startChrono(); try { return fromString(OBinaryProtocol.bytes2string(iSource), iRecord, iFields); } finally { PROFILER .stopChrono(PROFILER.getProcessMetric("serializer.record.string.fromStream"), "Deserialize record from stream", timer); } } public byte[] toStream(final ORecordInternal<?> iRecord, boolean iOnlyDelta) { final long timer = PROFILER.startChrono(); try { return OBinaryProtocol.string2bytes(toString(iRecord, new StringBuilder(), null, null, OSerializationSetThreadLocal.INSTANCE.get(), iOnlyDelta, true).toString()); } finally { PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.toStream"), "Serialize record to stream", timer); } } protected abstract StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat, final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta, boolean autoDetectCollectionType); }
Minor: pre-allocated 2k of stream for serialization
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerStringAbstract.java
Minor: pre-allocated 2k of stream for serialization
Java
apache-2.0
21584b132d23a30c60ec6d8da65f60b525cfd768
0
lukecwik/incubator-beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,apache/beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,chamikaramj/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,chamikaramj/beam,chamikaramj/beam,apache/beam
/* * 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.beam.runners.dataflow.util; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import org.apache.beam.runners.core.construction.SdkComponents; import org.apache.beam.sdk.coders.SerializableCoder; /** A {@link CloudObjectTranslator} for {@link SerializableCoder}. */ @SuppressWarnings({ "rawtypes" // TODO(https://github.com/apache/beam/issues/20447) }) class SerializableCoderCloudObjectTranslator implements CloudObjectTranslator<SerializableCoder> { private static final String TYPE_FIELD = "type"; @Override public CloudObject toCloudObject(SerializableCoder target, SdkComponents sdkComponents) { CloudObject base = CloudObject.forClass(SerializableCoder.class); Structs.addString(base, TYPE_FIELD, target.getRecordType().getName()); return base; } @Override public SerializableCoder<?> fromCloudObject(CloudObject cloudObject) { String className = Structs.getString(cloudObject, TYPE_FIELD); try { Class<? extends Serializable> targetClass = (Class<? extends Serializable>) Class.forName(className, false, Thread.currentThread().getContextClassLoader()); checkArgument( Serializable.class.isAssignableFrom(targetClass), "Target class %s does not extend %s", targetClass.getName(), Serializable.class.getSimpleName()); return SerializableCoder.of(targetClass); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } } @Override public Class<SerializableCoder> getSupportedClass() { return SerializableCoder.class; } @Override public String cloudObjectClassName() { return CloudObject.forClass(SerializableCoder.class).getClassName(); } }
runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/util/SerializableCoderCloudObjectTranslator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.dataflow.util; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import org.apache.beam.runners.core.construction.SdkComponents; import org.apache.beam.sdk.coders.SerializableCoder; /** A {@link CloudObjectTranslator} for {@link SerializableCoder}. */ @SuppressWarnings({ "rawtypes" // TODO(https://github.com/apache/beam/issues/20447) }) class SerializableCoderCloudObjectTranslator implements CloudObjectTranslator<SerializableCoder> { private static final String TYPE_FIELD = "type"; @Override public CloudObject toCloudObject(SerializableCoder target, SdkComponents sdkComponents) { CloudObject base = CloudObject.forClass(SerializableCoder.class); Structs.addString(base, TYPE_FIELD, target.getRecordType().getName()); return base; } @Override public SerializableCoder<?> fromCloudObject(CloudObject cloudObject) { String className = Structs.getString(cloudObject, TYPE_FIELD); try { Class<? extends Serializable> targetClass = (Class<? extends Serializable>) Class.forName(className); checkArgument( Serializable.class.isAssignableFrom(targetClass), "Target class %s does not extend %s", targetClass.getName(), Serializable.class.getSimpleName()); return SerializableCoder.of(targetClass); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } } @Override public Class<SerializableCoder> getSupportedClass() { return SerializableCoder.class; } @Override public String cloudObjectClassName() { return CloudObject.forClass(SerializableCoder.class).getClassName(); } }
Attempt to fix SpannerIO test flakes (#22688)
runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/util/SerializableCoderCloudObjectTranslator.java
Attempt to fix SpannerIO test flakes (#22688)
Java
apache-2.0
e3fb8cd111d321e1defd73eb9ef09db55026dbc1
0
j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.storage.core.manager.clinical; import org.apache.commons.lang.StringUtils; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResult; import org.opencb.commons.datastore.core.result.FacetedQueryResult; import org.opencb.opencga.catalog.db.api.ClinicalAnalysisDBAdaptor; import org.opencb.opencga.catalog.db.api.DBIterator; import org.opencb.opencga.catalog.db.api.StudyDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.CatalogManager; import org.opencb.opencga.catalog.managers.ClinicalAnalysisManager; import org.opencb.opencga.core.models.ClinicalAnalysis; import org.opencb.opencga.core.models.Group; import org.opencb.opencga.core.models.Study; import org.opencb.opencga.core.models.clinical.Comment; import org.opencb.opencga.core.models.clinical.Interpretation; import org.opencb.opencga.core.models.clinical.ReportedVariant; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.clinical.ClinicalVariantEngine; import org.opencb.opencga.storage.core.clinical.ClinicalVariantException; import org.opencb.opencga.storage.core.clinical.ReportedVariantIterator; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.manager.StorageManager; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class ClinicalInterpretationManager extends StorageManager { private ClinicalAnalysisManager clinicalAnalysisManager; private ClinicalVariantEngine clinicalVariantEngine; public ClinicalInterpretationManager(CatalogManager catalogManager, StorageEngineFactory storageEngineFactory) { super(catalogManager, storageEngineFactory); clinicalAnalysisManager = catalogManager.getClinicalAnalysisManager(); } // FIXME Class path to a new section in storage-configuration.yml file private void init() { try { this.clinicalVariantEngine = (ClinicalVariantEngine) Class.forName("org.opencb.opencga.enterprise.clinical.ClinicalVariantSolrEngine").newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } } @Override public void testConnection() throws StorageEngineException { } public QueryResult<ReportedVariant> index(String token) throws IOException, ClinicalVariantException { return null; } public QueryResult<ReportedVariant> index(String study, String token) throws IOException, ClinicalVariantException, CatalogException { DBIterator<ClinicalAnalysis> iterator = clinicalAnalysisManager.iterator(study, new Query(), QueryOptions.empty(), token); return null; } public QueryResult<ReportedVariant> query(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.query(query, options, ""); } public QueryResult<Interpretation> interpretationQuery(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.interpretationQuery(query, options, ""); } public FacetedQueryResult facet(Query query, QueryOptions queryOptions, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.facet(query, queryOptions, ""); } public ReportedVariantIterator iterator(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.iterator(query, options, ""); } public void addInterpretationComment(String study, long interpretationId, Comment comment, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions checkInterpretationPermissions(study, interpretationId, token); clinicalVariantEngine.addInterpretationComment(interpretationId, comment, ""); } public void addReportedVariantComment(String study, long interpretationId, String variantId, Comment comment, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions checkInterpretationPermissions(study, interpretationId, token); clinicalVariantEngine.addReportedVariantComment(interpretationId, variantId, comment, ""); } /*--------------------------------------------------------------------------*/ /* P R I V A T E M E T H O D S */ /*--------------------------------------------------------------------------*/ private Query checkQueryPermissions(Query query, String token) throws ClinicalVariantException, CatalogException { if (query == null) { throw new ClinicalVariantException("Query object is null"); } // Get userId from token and Study numeric IDs from the query String userId = catalogManager.getUserManager().getUserId(token); List<Long> studyIds = getStudyLongIds(userId, query); // If one specific clinical analysis, sample or individual is provided we expect a single valid study as well if (isCaseProvided(query)) { if (studyIds.size() == 1) { // This checks that the user has permission to the clinical analysis, family, sample or individual QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(String.valueOf(studyIds.get(0)), query, QueryOptions.empty(), token); if (clinicalAnalysisQueryResult.getResult().isEmpty()) { throw new ClinicalVariantException("Either the ID does not exist or the user does not have permissions to view it"); } else { if (!query.containsKey(ClinicalVariantEngine.QueryParams.CLINICAL_ANALYSIS_ID.key())) { query.remove(ClinicalVariantEngine.QueryParams.FAMILY.key()); query.remove(ClinicalVariantEngine.QueryParams.SAMPLE.key()); query.remove(ClinicalVariantEngine.QueryParams.SUBJECT.key()); String clinicalAnalysisList = StringUtils.join( clinicalAnalysisQueryResult.getResult().stream().map(ClinicalAnalysis::getId).collect(Collectors.toList()), ","); query.put("clinicalAnalysisId", clinicalAnalysisList); } } } else { throw new ClinicalVariantException("No single valid study provided: " + query.getString(ClinicalVariantEngine.QueryParams.STUDY.key())); } } else { // Get the owner of all the studies Set<String> users = new HashSet<>(); for (Long studyId : studyIds) { users.add(catalogManager.getStudyManager().getUserId(studyId)); } // There must be one single owner for all the studies, we do nt allow to query multiple databases if (users.size() == 1) { Query studyQuery = new Query(StudyDBAdaptor.QueryParams.ID.key(), StringUtils.join(studyIds, ",")); QueryResult<Study> studyQueryResult = catalogManager.getStudyManager().get(studyQuery, QueryOptions.empty(), token); // If the user is the owner we do not have to check anything else List<String> studyAliases = new ArrayList<>(studyIds.size()); if (users.contains(userId)) { for (Study study : studyQueryResult.getResult()) { studyAliases.add(study.getAlias()); } } else { for (Study study : studyQueryResult.getResult()) { for (Group group : study.getGroups()) { if (group.getName().equalsIgnoreCase("admins") && group.getUserIds().contains(userId)) { studyAliases.add(study.getAlias()); break; } } } } if (studyAliases.isEmpty()) { throw new ClinicalVariantException("This user is not owner or admins for the provided studies"); } else { query.put(ClinicalVariantEngine.QueryParams.STUDY.key(), StringUtils.join(studyAliases, ",")); } } else { throw new ClinicalVariantException(""); } } return query; } private void checkInterpretationPermissions(String study, long interpretationId, String token) throws CatalogException, ClinicalVariantException { // Get user ID from token and study numeric ID String userId = catalogManager.getUserManager().getUserId(token); long studyId = catalogManager.getStudyManager().getId(userId, study); // This checks that the user has permission to this interpretation Query query = new Query(ClinicalAnalysisDBAdaptor.QueryParams.INTERPRETATIONS_ID.key(), interpretationId); QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(String.valueOf(studyId), query, QueryOptions.empty(), token); if (clinicalAnalysisQueryResult.getResult().isEmpty()) { throw new ClinicalVariantException("Either the interpretation ID (" + interpretationId + ") does not exist or the user does" + " not have access permissions"); } } private List<Long> getStudyLongIds(String userId, Query query) throws CatalogException { List<Long> studyIds = new ArrayList<>(); if (query != null && query.containsKey(ClinicalVariantEngine.QueryParams.STUDY.key())) { String study = query.getString(ClinicalVariantEngine.QueryParams.STUDY.key()); List<String> studies = Arrays.asList(study.split(",")); studyIds = catalogManager.getStudyManager().getIds(userId, studies); } return studyIds; } private boolean isCaseProvided(Query query) { if (query != null) { return query.containsKey(ClinicalVariantEngine.QueryParams.CLINICAL_ANALYSIS_ID.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.FAMILY.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.SUBJECT.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.SAMPLE.key()); } return false; } }
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/manager/clinical/ClinicalInterpretationManager.java
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.storage.core.manager.clinical; import org.apache.commons.lang.StringUtils; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResult; import org.opencb.commons.datastore.core.result.FacetedQueryResult; import org.opencb.opencga.catalog.db.api.ClinicalAnalysisDBAdaptor; import org.opencb.opencga.catalog.db.api.DBIterator; import org.opencb.opencga.catalog.db.api.StudyDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.CatalogManager; import org.opencb.opencga.catalog.managers.ClinicalAnalysisManager; import org.opencb.opencga.core.models.ClinicalAnalysis; import org.opencb.opencga.core.models.Group; import org.opencb.opencga.core.models.Study; import org.opencb.opencga.core.models.clinical.Comment; import org.opencb.opencga.core.models.clinical.Interpretation; import org.opencb.opencga.core.models.clinical.ReportedVariant; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.clinical.ClinicalVariantEngine; import org.opencb.opencga.storage.core.clinical.ClinicalVariantException; import org.opencb.opencga.storage.core.clinical.ReportedVariantIterator; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.manager.StorageManager; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class ClinicalInterpretationManager extends StorageManager { private ClinicalAnalysisManager clinicalAnalysisManager; private ClinicalVariantEngine clinicalVariantEngine; public ClinicalInterpretationManager(CatalogManager catalogManager, StorageEngineFactory storageEngineFactory) { super(catalogManager, storageEngineFactory); clinicalAnalysisManager = catalogManager.getClinicalAnalysisManager(); } @Override public void testConnection() throws StorageEngineException { } public QueryResult<ReportedVariant> index(String token) throws IOException, ClinicalVariantException { return null; } public QueryResult<ReportedVariant> index(String study, String token) throws IOException, ClinicalVariantException, CatalogException { DBIterator<ClinicalAnalysis> iterator = clinicalAnalysisManager.iterator(study, new Query(), QueryOptions.empty(), token); return null; } public QueryResult<ReportedVariant> query(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.query(query, options, ""); } public QueryResult<Interpretation> interpretationQuery(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.interpretationQuery(query, options, ""); } public FacetedQueryResult facet(Query query, QueryOptions queryOptions, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.facet(query, queryOptions, ""); } public ReportedVariantIterator iterator(Query query, QueryOptions options, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions query = checkQueryPermissions(query, token); return clinicalVariantEngine.iterator(query, options, ""); } public void addInterpretationComment(String study, long interpretationId, Comment comment, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions checkInterpretationPermissions(study, interpretationId, token); clinicalVariantEngine.addInterpretationComment(interpretationId, comment, ""); } public void addReportedVariantComment(String study, long interpretationId, String variantId, Comment comment, String token) throws IOException, ClinicalVariantException, CatalogException { // Check permissions checkInterpretationPermissions(study, interpretationId, token); clinicalVariantEngine.addReportedVariantComment(interpretationId, variantId, comment, ""); } /*--------------------------------------------------------------------------*/ /* P R I V A T E M E T H O D S */ /*--------------------------------------------------------------------------*/ private Query checkQueryPermissions(Query query, String token) throws ClinicalVariantException, CatalogException { if (query == null) { throw new ClinicalVariantException("Query object is null"); } // Get userId from token and Study numeric IDs from the query String userId = catalogManager.getUserManager().getUserId(token); List<Long> studyIds = getStudyLongIds(userId, query); // If one specific clinical analysis, sample or individual is provided we expect a single valid study as well if (isCaseProvided(query)) { if (studyIds.size() == 1) { // This checks that the user has permission to the clinical analysis, family, sample or individual QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(String.valueOf(studyIds.get(0)), query, QueryOptions.empty(), token); if (clinicalAnalysisQueryResult.getResult().isEmpty()) { throw new ClinicalVariantException("Either the ID does not exist or the user does not have permissions to view it"); } else { if (!query.containsKey(ClinicalVariantEngine.QueryParams.CLINICAL_ANALYSIS_ID.key())) { query.remove(ClinicalVariantEngine.QueryParams.FAMILY.key()); query.remove(ClinicalVariantEngine.QueryParams.SAMPLE.key()); query.remove(ClinicalVariantEngine.QueryParams.SUBJECT.key()); String clinicalAnalysisList = StringUtils.join( clinicalAnalysisQueryResult.getResult().stream().map(ClinicalAnalysis::getId).collect(Collectors.toList()), ","); query.put("clinicalAnalysisId", clinicalAnalysisList); } } } else { throw new ClinicalVariantException("No single valid study provided: " + query.getString(ClinicalVariantEngine.QueryParams.STUDY.key())); } } else { // Get the owner of all the studies Set<String> users = new HashSet<>(); for (Long studyId : studyIds) { users.add(catalogManager.getStudyManager().getUserId(studyId)); } // There must be one single owner for all the studies, we do nt allow to query multiple databases if (users.size() == 1) { Query studyQuery = new Query(StudyDBAdaptor.QueryParams.ID.key(), StringUtils.join(studyIds, ",")); QueryResult<Study> studyQueryResult = catalogManager.getStudyManager().get(studyQuery, QueryOptions.empty(), token); // If the user is the owner we do not have to check anything else List<String> studyAliases = new ArrayList<>(studyIds.size()); if (users.contains(userId)) { for (Study study : studyQueryResult.getResult()) { studyAliases.add(study.getAlias()); } } else { for (Study study : studyQueryResult.getResult()) { for (Group group : study.getGroups()) { if (group.getName().equalsIgnoreCase("admins") && group.getUserIds().contains(userId)) { studyAliases.add(study.getAlias()); break; } } } } if (studyAliases.isEmpty()) { throw new ClinicalVariantException("This user is not owner or admins for the provided studies"); } else { query.put(ClinicalVariantEngine.QueryParams.STUDY.key(), StringUtils.join(studyAliases, ",")); } } else { throw new ClinicalVariantException(""); } } return query; } private void checkInterpretationPermissions(String study, long interpretationId, String token) throws CatalogException, ClinicalVariantException { // Get user ID from token and study numeric ID String userId = catalogManager.getUserManager().getUserId(token); long studyId = catalogManager.getStudyManager().getId(userId, study); // This checks that the user has permission to this interpretation Query query = new Query(ClinicalAnalysisDBAdaptor.QueryParams.INTERPRETATIONS_ID.key(), interpretationId); QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(String.valueOf(studyId), query, QueryOptions.empty(), token); if (clinicalAnalysisQueryResult.getResult().isEmpty()) { throw new ClinicalVariantException("Either the interpretation ID (" + interpretationId + ") does not exist or the user does" + " not have access permissions"); } } private List<Long> getStudyLongIds(String userId, Query query) throws CatalogException { List<Long> studyIds = new ArrayList<>(); if (query != null && query.containsKey(ClinicalVariantEngine.QueryParams.STUDY.key())) { String study = query.getString(ClinicalVariantEngine.QueryParams.STUDY.key()); List<String> studies = Arrays.asList(study.split(",")); studyIds = catalogManager.getStudyManager().getIds(userId, studies); } return studyIds; } private boolean isCaseProvided(Query query) { if (query != null) { return query.containsKey(ClinicalVariantEngine.QueryParams.CLINICAL_ANALYSIS_ID.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.FAMILY.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.SUBJECT.key()) || query.containsKey(ClinicalVariantEngine.QueryParams.SAMPLE.key()); } return false; } }
storage: load clinical interpretation class
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/manager/clinical/ClinicalInterpretationManager.java
storage: load clinical interpretation class
Java
apache-2.0
89af96230be7fdf4414ef89dfcb0e892bf220074
0
yubin154/memcache_loadtest
package com.google.cloud.cache.apps.loadtest; import static com.google.appengine.api.memcache.transcoders.Serialization.makeKey; import static com.google.appengine.api.memcache.transcoders.Serialization.makeKeys; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue; import com.google.appengine.api.memcache.MemcacheServiceFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.spy.memcached.CASResponse; import net.spy.memcached.CASValue; /** */ public final class TranscoderTest extends SpyMemcachedBaseTest { private MemcacheService aeClient = MemcacheServiceFactory.getMemcacheService(); TranscoderTest(String server, int port, String version) { super(server, port, version, false); } public void testAll() throws Exception { testStr(); testBoolean(); testInteger(); testLong(); testShort(); testByte(); testSerializableObject(); testBytes(); testIncrDecr(); testDelete(); testMultiKeySetGet(); testCas(); testNull(); } public void testStr() throws Exception { checkValuesInBothClients("string", "some string"); checkValuesInBothClients("empty string", ""); checkValuesInBothClients("max string", "long string at max length(TBD)"); } public void testBoolean() throws Exception { checkValuesInBothClients("false", Boolean.FALSE); checkValuesInBothClients("true", Boolean.TRUE); } public void testInteger() throws Exception { checkValuesInBothClients("integer zero", new Integer(0)); checkValuesInBothClients("integer max", Integer.MAX_VALUE); checkValuesInBothClients("integer min", Integer.MIN_VALUE); checkValuesInBothClients("integer max overflow", Integer.MAX_VALUE + 1); checkValuesInBothClients("integer min overflow", Integer.MIN_VALUE - 1); } public void testLong() throws Exception { checkValuesInBothClients("long zero", new Long(0)); checkValuesInBothClients("long max", Long.MAX_VALUE); checkValuesInBothClients("long min", Long.MIN_VALUE); checkValuesInBothClients("long max overflow", Long.MAX_VALUE + 1); checkValuesInBothClients("long min overflow", Long.MIN_VALUE - 1); } public void testShort() throws Exception { checkValuesInBothClients("short zero", new Short("0")); checkValuesInBothClients("short max", Short.MAX_VALUE); checkValuesInBothClients("short min", Short.MIN_VALUE); checkValuesInBothClients("short max overflow", Short.MAX_VALUE + 1); checkValuesInBothClients("short min overflow", Short.MIN_VALUE - 1); } public void testByte() throws Exception { checkValuesInBothClients("byte zero", (byte) 0); checkValuesInBothClients("byte max", Byte.MAX_VALUE); checkValuesInBothClients("byte min", Byte.MIN_VALUE); checkValuesInBothClients("byte max overflow", Byte.MAX_VALUE + 1); checkValuesInBothClients("byte min overflow", Byte.MIN_VALUE - 1); } public void testSerializableObject() throws Exception { java.util.Date dateObj = new java.util.Date(); checkValuesInBothClients("date", dateObj); java.util.ArrayList listObj = new java.util.ArrayList(); checkValuesInBothClients("list", listObj); java.util.HashMap mapObj = new java.util.HashMap(); checkValuesInBothClients("map", mapObj); } public void testNull() throws Exception { checkValuesInBothClients("null", null); } public void testBytes() throws Exception { checkValuesInBothClients("zero byte", new byte[0]); byte[] data = new byte[] {1, 2, 3, 4, 5, 6}; checkValuesInBothClients("bytes", data); data = new byte[] {65, 66, 67, 0, 68, 69, 70}; checkValuesInBothClients("someBytesWithNull", data); //checkValuesInBothClients("bigKeyBytes", Strings.repeat("x", 300).getBytes()); } public void testIncrDecr() throws Exception { result.append("\nTesting incr decr\n"); String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); expectTrue( client.incr(makeKey(key1), 1, 10, DEFAULT_EXP) == 10, "increment with default value"); expectTrue(client.incr(makeKey(key1), 1) == 11, "increment d"); expectTrue(client.decr(makeKey(key1), 1) == 10, "decrement d"); expectTrue(aeClient.increment(key1, 1) == 11, "increment g"); expectTrue(aeClient.increment(key1, -1) == 10, "decrement g"); } public void testDelete() throws Exception { result.append("\nTesting delete\n"); String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); // add by memcached, delete from memcacheg expectTrue(client.add(makeKey(key1), DEFAULT_EXP, "").get(), "PUT"); expectTrue(aeClient.delete(key1), "DELETE verified"); String key2 = randomKey(); result.append(String.format("g2d key=%s\n", key2)); // add by memcacheg, delete from memcached aeClient.put(key2, ""); expectTrue(client.delete(makeKey(key2)).get(), "DELETE verified"); } public void testMultiKeySetGet() throws Exception { result.append("\nTesting multi-ket SETGET\n"); Map<String, Object> map = new HashMap<>(); List<String> keys = new ArrayList<>(); for (int i = 0; i < 10; i++) { String key = randomKey(); keys.add(key); map.put(key, Integer.toString(i)); } // add by memcacheg, retrieved from memcached aeClient.putAll(map); Map<String, Object> values = client.getBulk(makeKeys(keys)); expectTrue(aeClient.getAll(keys).size() == 10, "GETALL verified"); expectTrue(values.size() == 10, "GETBULK verified"); } public void testCas() throws Exception { result.append("\nTesting cas\n"); String key1 = randomKey(); aeClient.put(key1, "value"); // cas from g IdentifiableValue casValue = aeClient.getIdentifiable(key1); client.add(makeKey(key1), DEFAULT_EXP, "value").get(); expectFalse(aeClient.putIfUntouched(key1, casValue, "valueg"), "CAS4g verified"); // cas from d CASValue<Object> cas = client.gets(makeKey(key1)); aeClient.put(key1, "value"); expectTrue( client.cas(makeKey(key1), cas.getCas(), "valued").equals(CASResponse.EXISTS), "CAS4d verified"); } private void checkValuesInBothClients(String testDesc, Object obj) throws Exception { if (obj != null) { result.append( String.format("\nTesting %s, %s=%s\n", testDesc, obj.getClass().getName(), obj)); } else { result.append(String.format("\nTesting %s, value=null\n", testDesc)); } String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); // add by memcached, retrieved from memcacheg expectTrue(client.add(makeKey(key1), DEFAULT_EXP, obj).get(), "PUT"); expectEqual(obj, aeClient.get(key1), "GET verified"); String key2 = randomKey(); result.append(String.format("g2d key=%s\n", key2)); // add by memcacheg, retrieved from memcached aeClient.put(key2, obj); expectEqual(obj, aeClient.get(key2), "PUT"); expectEqual(obj, client.get(makeKey(key2)), "GET verified"); } }
src/main/java/com/google/cloud/cache/apps/loadtest/TranscoderTest.java
package com.google.cloud.cache.apps.loadtest; import static com.google.appengine.api.memcache.transcoders.Serialization.makeKey; import static com.google.appengine.api.memcache.transcoders.Serialization.makeKeys; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue; import com.google.appengine.api.memcache.MemcacheServiceFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.spy.memcached.CASResponse; import net.spy.memcached.CASValue; /** */ public final class TranscoderTest extends SpyMemcachedBaseTest { private MemcacheService aeClient = MemcacheServiceFactory.getMemcacheService(); TranscoderTest(String server, int port, String version) { super(server, port, version, false); } public void testAll() throws Exception { testStr(); testBoolean(); testInteger(); testLong(); testShort(); testByte(); testSerializableObject(); testBytes(); testIncrDecr(); testDelete(); testMultiKeySetGet(); testNull(); } public void testStr() throws Exception { checkValuesInBothClients("string", "some string"); checkValuesInBothClients("empty string", ""); checkValuesInBothClients("max string", "long string at max length(TBD)"); } public void testBoolean() throws Exception { checkValuesInBothClients("false", Boolean.FALSE); checkValuesInBothClients("true", Boolean.TRUE); } public void testInteger() throws Exception { checkValuesInBothClients("integer zero", new Integer(0)); checkValuesInBothClients("integer max", Integer.MAX_VALUE); checkValuesInBothClients("integer min", Integer.MIN_VALUE); checkValuesInBothClients("integer max overflow", Integer.MAX_VALUE + 1); checkValuesInBothClients("integer min overflow", Integer.MIN_VALUE - 1); } public void testLong() throws Exception { checkValuesInBothClients("long zero", new Long(0)); checkValuesInBothClients("long max", Long.MAX_VALUE); checkValuesInBothClients("long min", Long.MIN_VALUE); checkValuesInBothClients("long max overflow", Long.MAX_VALUE + 1); checkValuesInBothClients("long min overflow", Long.MIN_VALUE - 1); } public void testShort() throws Exception { checkValuesInBothClients("short zero", new Short("0")); checkValuesInBothClients("short max", Short.MAX_VALUE); checkValuesInBothClients("short min", Short.MIN_VALUE); checkValuesInBothClients("short max overflow", Short.MAX_VALUE + 1); checkValuesInBothClients("short min overflow", Short.MIN_VALUE - 1); } public void testByte() throws Exception { checkValuesInBothClients("byte zero", (byte) 0); checkValuesInBothClients("byte max", Byte.MAX_VALUE); checkValuesInBothClients("byte min", Byte.MIN_VALUE); checkValuesInBothClients("byte max overflow", Byte.MAX_VALUE + 1); checkValuesInBothClients("byte min overflow", Byte.MIN_VALUE - 1); } public void testSerializableObject() throws Exception { java.util.Date dateObj = new java.util.Date(); checkValuesInBothClients("date", dateObj); java.util.ArrayList listObj = new java.util.ArrayList(); checkValuesInBothClients("list", listObj); java.util.HashMap mapObj = new java.util.HashMap(); checkValuesInBothClients("map", mapObj); } public void testNull() throws Exception { checkValuesInBothClients("null", null); } public void testBytes() throws Exception { checkValuesInBothClients("zero byte", new byte[0]); byte[] data = new byte[] {1, 2, 3, 4, 5, 6}; checkValuesInBothClients("bytes", data); data = new byte[] {65, 66, 67, 0, 68, 69, 70}; checkValuesInBothClients("someBytesWithNull", data); //checkValuesInBothClients("bigKeyBytes", Strings.repeat("x", 300).getBytes()); } public void testIncrDecr() throws Exception { result.append("\nTesting incr decr\n"); String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); expectTrue( client.incr(makeKey(key1), 1, 10, DEFAULT_EXP) == 10, "increment with default value"); expectTrue(client.incr(makeKey(key1), 1) == 11, "increment d"); expectTrue(client.decr(makeKey(key1), 1) == 10, "decrement d"); expectTrue(aeClient.increment(key1, 1) == 11, "increment g"); expectTrue(aeClient.increment(key1, -1) == 10, "decrement g"); } public void testDelete() throws Exception { result.append("\nTesting delete\n"); String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); // add by memcached, delete from memcacheg expectTrue(client.add(makeKey(key1), DEFAULT_EXP, "").get(), "PUT"); expectTrue(aeClient.delete(key1), "DELETE verified"); String key2 = randomKey(); result.append(String.format("g2d key=%s\n", key2)); // add by memcacheg, delete from memcached aeClient.put(key2, ""); expectTrue(client.delete(makeKey(key2)).get(), "DELETE verified"); } public void testMultiKeySetGet() throws Exception { result.append("\nTesting multi-ket SETGET\n"); Map<String, Object> map = new HashMap<>(); List<String> keys = new ArrayList<>(); for (int i = 0; i < 10; i++) { String key = randomKey(); keys.add(key); map.put(key, Integer.toString(i)); } // add by memcacheg, retrieved from memcached aeClient.putAll(map); Map<String, Object> values = client.getBulk(makeKeys(keys)); result.append(map.toString()).append("\n"); result.append(values.toString()).append("\n"); expectTrue(aeClient.getAll(keys).size() == 10, "GETALL verified"); expectTrue(values.size() == 10, "GETBULK verified"); } public void testCas() throws Exception { result.append("\nTesting cas\n"); String key1 = randomKey(); aeClient.put(key1, "value"); // cas from g IdentifiableValue casValue = aeClient.getIdentifiable(key1); client.add(makeKey(key1), DEFAULT_EXP, "value").get(); expectFalse(aeClient.putIfUntouched(key1, casValue, "valueg"), "CAS4g verified"); // cas from d CASValue<Object> cas = client.gets(makeKey(key1)); aeClient.put(key1, "value"); expectTrue( client.cas(makeKey(key1), cas.getCas(), "valued").equals(CASResponse.EXISTS), "CAS4d verified"); } private void checkValuesInBothClients(String testDesc, Object obj) throws Exception { if (obj != null) { result.append( String.format("\nTesting %s, %s=%s\n", testDesc, obj.getClass().getName(), obj)); } else { result.append(String.format("\nTesting %s, value=null\n", testDesc)); } String key1 = randomKey(); result.append(String.format("d2g key=%s\n", key1)); // add by memcached, retrieved from memcacheg expectTrue(client.add(makeKey(key1), DEFAULT_EXP, obj).get(), "PUT"); expectEqual(obj, aeClient.get(key1), "GET verified"); String key2 = randomKey(); result.append(String.format("g2d key=%s\n", key2)); // add by memcacheg, retrieved from memcached aeClient.put(key2, obj); expectEqual(obj, aeClient.get(key2), "PUT"); expectEqual(obj, client.get(makeKey(key2)), "GET verified"); } }
test cas
src/main/java/com/google/cloud/cache/apps/loadtest/TranscoderTest.java
test cas
Java
apache-2.0
5fcc0504757c2ced3456e8d44faf475ee5ccb8b6
0
lukas-krecan/ShedLock,lukas-krecan/ShedLock
/** * Copyright 2009-2017 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 net.javacrumbs.shedlock.provider.zookeeper.curator; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.support.LockException; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import java.util.Optional; import static java.util.Objects.requireNonNull; /** * Locks kept using ZooKeeper. When locking, creates an ephemeral node with node name = lock name, when unlocking, removes the node. */ public class ZookeeperCuratorLockProvider implements LockProvider { public static final String DEFAULT_PATH = "/shedlock"; private final String path; private final CuratorFramework client; public ZookeeperCuratorLockProvider(CuratorFramework client) { this(client, DEFAULT_PATH); } public ZookeeperCuratorLockProvider(CuratorFramework client, String path) { this.client = requireNonNull(client); this.path = PathUtils.validatePath(path); } @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { try { String nodePath = getNodePath(lockConfiguration); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(nodePath); return Optional.of(new CuratorLock(nodePath, client)); } catch (KeeperException.NodeExistsException ex) { return Optional.empty(); } catch (Exception e) { throw new LockException("Can not create node", e); } } private String getNodePath(LockConfiguration lockConfiguration) { return path + "/" + lockConfiguration.getName(); } private static final class CuratorLock implements SimpleLock { private final String nodePath; private final CuratorFramework client; private CuratorLock(String nodePath, CuratorFramework client) { this.nodePath = nodePath; this.client = client; } @Override public void unlock() { try { client.delete().forPath(nodePath); } catch (Exception e) { throw new LockException("Can not remove node", e); } } } }
shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java
/** * Copyright 2009-2017 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 net.javacrumbs.shedlock.provider.zookeeper.curator; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.support.LockException; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import java.util.Optional; import static java.util.Objects.requireNonNull; /** * Locks kept using ZooKeeper. When locking, creates an ephemeral node with node name = lock name, when nlocking, removes the node. */ public class ZookeeperCuratorLockProvider implements LockProvider { public static final String DEFAULT_PATH = "/shedlock"; private final String path; private final CuratorFramework client; public ZookeeperCuratorLockProvider(CuratorFramework client) { this(client, DEFAULT_PATH); } public ZookeeperCuratorLockProvider(CuratorFramework client, String path) { this.client = requireNonNull(client); this.path = PathUtils.validatePath(path); } @Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { try { String nodePath = getNodePath(lockConfiguration); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(nodePath); return Optional.of(new CuratorLock(nodePath, client)); } catch (KeeperException.NodeExistsException ex) { return Optional.empty(); } catch (Exception e) { throw new LockException("Can not create node", e); } } private String getNodePath(LockConfiguration lockConfiguration) { return path + "/" + lockConfiguration.getName(); } private static final class CuratorLock implements SimpleLock { private final String nodePath; private final CuratorFramework client; private CuratorLock(String nodePath, CuratorFramework client) { this.nodePath = nodePath; this.client = client; } @Override public void unlock() { try { client.delete().forPath(nodePath); } catch (Exception e) { throw new LockException("Can not remove node", e); } } } }
ZooKeeper configurable with path
shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java
ZooKeeper configurable with path
Java
apache-2.0
5fe76487f88665196181d72e37255b33cc7ba4cd
0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <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 * * 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. * </p> */ package io.shardingsphere.transaction.xa.manager.extractor; import io.shardingsphere.core.config.DataSourceConfiguration; import io.shardingsphere.core.constant.PoolType; import javax.sql.DataSource; /** * Extract datasource parameter from DBCP connection pool. * * @author zhaojun */ public final class DBCPDataSourceParameterExtractor extends DataSourceParameterExtractorAdapter { DBCPDataSourceParameterExtractor(final DataSource dataSource) { super(dataSource); } @Override protected void convertProperties() { DataSourceConfiguration dataSourceConfiguration = getDataSourceConfiguration(); dataSourceConfiguration.getProperties().put("maximumPoolSize", dataSourceConfiguration.getProperties().get("maxTotal")); dataSourceConfiguration.getProperties().put("originPoolType", PoolType.find(dataSourceConfiguration.getDataSourceClassName())); } }
sharding-transaction/sharding-transaction-xa/src/main/java/io/shardingsphere/transaction/xa/manager/extractor/DBCPDataSourceParameterExtractor.java
/* * Copyright 2016-2018 shardingsphere.io. * <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 * * 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. * </p> */ package io.shardingsphere.transaction.xa.manager.extractor; import io.shardingsphere.core.config.DataSourceConfiguration; import io.shardingsphere.core.constant.PoolType; import io.shardingsphere.core.rule.DataSourceParameter; import javax.sql.DataSource; /** * Extract datasource parameter from DBCP connection pool. * * @author zhaojun */ public final class DBCPDataSourceParameterExtractor implements DataSourceParameterExtractor { private final DataSourceConfiguration dataSourceConfiguration; public DBCPDataSourceParameterExtractor(final DataSource dataSource) { dataSourceConfiguration = DataSourceConfiguration.getDataSourceConfiguration(dataSource); } @Override public DataSourceParameter extract() { dataSourceConfiguration.getProperties().put("maximumPoolSize", dataSourceConfiguration.getProperties().get("maxTotal")); dataSourceConfiguration.getProperties().put("originPoolType", PoolType.find(dataSourceConfiguration.getDataSourceClassName())); return dataSourceConfiguration.createDataSourceParameter(); } }
#1363 Refactor DBCPDataSourceParameterExtractor.
sharding-transaction/sharding-transaction-xa/src/main/java/io/shardingsphere/transaction/xa/manager/extractor/DBCPDataSourceParameterExtractor.java
#1363 Refactor DBCPDataSourceParameterExtractor.
Java
apache-2.0
b0a46b5da206b704096df85ff74a0aedbd37ff3a
0
qmx/uberfire-extensions,mbarkley/uberfire-extensions,dgutierr/uberfire-extensions,dgutierr/uberfire-extensions,mbiarnes/uberfire-extensions,mbiarnes/uberfire-extensions,mbarkley/uberfire-extensions,porcelli-forks/uberfire-extensions,cristianonicolai/uberfire-extensions,porcelli-forks/uberfire-extensions,cristianonicolai/uberfire-extensions,wmedvede/uberfire-extensions,pefernan/uberfire-extensions,cristianonicolai/uberfire-extensions,mbiarnes/uberfire-extensions,porcelli-forks/uberfire-extensions,qmx/uberfire-extensions,pefernan/uberfire-extensions,dgutierr/uberfire-extensions,mbarkley/uberfire-extensions,qmx/uberfire-extensions,wmedvede/uberfire-extensions,pefernan/uberfire-extensions,wmedvede/uberfire-extensions
/* * 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. * 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.uberfire.ext.services.shared.preferences; import java.util.HashMap; import java.util.Map; import org.jboss.errai.common.client.api.annotations.Portable; @Portable public class UserWorkbenchPreferences extends UserPreference { private String language; private Map<String, String> perspectiveViewMode = new HashMap<String, String>(); public UserWorkbenchPreferences() { } public UserWorkbenchPreferences( final String language ) { super(); super.type = UserPreferencesType.WORKBENCHSETTINGS; super.preferenceKey = "settings"; this.language = language; } public Map<String, String> getPerspectiveViewMode() { return perspectiveViewMode; } public void setPerspectiveViewMode( final Map<String, String> perspectiveViewMode ) { this.perspectiveViewMode = perspectiveViewMode; } public String getLanguage() { return language; } public void setLanguage( final String language ) { this.language = language; } public String getViewMode( final String perspective ) { return perspectiveViewMode.get( perspective ); } public void setViewMode( final String perspective, final String viewMode ) { perspectiveViewMode.put( perspective, viewMode); } }
uberfire-widgets/uberfire-widgets-service/uberfire-widgets-service-api/src/main/java/org/uberfire/ext/services/shared/preferences/UserWorkbenchPreferences.java
/* * 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. * 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.uberfire.ext.services.shared.preferences; import java.util.HashMap; import java.util.Map; import org.jboss.errai.common.client.api.annotations.Portable; @Portable public class UserWorkbenchPreferences extends UserPreference { private String language; private Map<String, String> perspectiveViewMode = new HashMap<String, String>(); public UserWorkbenchPreferences() { } public UserWorkbenchPreferences( final String language ) { super(); super.type = UserPreferencesType.WORKBENCHSETTINGS; super.preferenceKey = "settings"; this.language = language; } public Map<String, String> getPerspectiveViewMode() { return perspectiveViewMode; } public void setPerspectiveViewMode( final Map<String, String> perspectiveViewMode ) { this.perspectiveViewMode = perspectiveViewMode; } public String getLanguage() { return language; } public String getViewMode( final String perspective ) { return perspectiveViewMode.get( perspective ); } public void setViewMode( final String perspective, final String ViewMode ) { perspectiveViewMode.put( perspective, ViewMode ); } }
Add method : getLanguage
uberfire-widgets/uberfire-widgets-service/uberfire-widgets-service-api/src/main/java/org/uberfire/ext/services/shared/preferences/UserWorkbenchPreferences.java
Add method : getLanguage
Java
apache-2.0
b8e65cb98580c90e57dc22e32b884d5355c60782
0
dharshanaw/carbon-identity-framework,dharshanaw/carbon-identity-framework,dharshanaw/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,omindu/carbon-identity-framework
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.application.authentication.framework.inbound; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder; import org.wso2.carbon.identity.core.util.IdentityUtil; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; public class IdentityServlet extends HttpServlet { private IdentityProcessCoordinator manager = new IdentityProcessCoordinator(); @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpIdentityResponse httpIdentityResponse = process(request, response); processHttpResponse(httpIdentityResponse, response); } /** * Process the {@link HttpServletRequest} and {@link HttpServletResponse}. * * @param request * @param response */ private HttpIdentityResponse process(HttpServletRequest request, HttpServletResponse response) { HttpIdentityRequestFactory factory = getIdentityRequestFactory(request, response); IdentityRequest identityRequest = null; HttpIdentityResponse.HttpIdentityResponseBuilder responseBuilder = null; try { identityRequest = factory.create(request, response).build(); if(identityRequest == null) { throw FrameworkRuntimeException.error("IdentityRequest is Null. Cannot proceed!!"); } } catch (FrameworkClientException e) { responseBuilder = factory.handleException(e, request, response); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } catch (RuntimeException e) { responseBuilder = factory.handleException(e, request, response); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } IdentityResponse identityResponse = null; HttpIdentityResponseFactory responseFactory = null; try { identityResponse = manager.process(identityRequest); if(identityResponse == null) { throw FrameworkRuntimeException.error("IdentityResponse is Null. Cannot proceed!!"); } responseFactory = getHttpIdentityResponseFactory(identityResponse); responseBuilder = responseFactory.create(identityResponse); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!"); } return responseBuilder.build(); } catch (FrameworkException e) { responseFactory = getIdentityResponseFactory(e); responseBuilder = responseFactory.handleException(e); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } catch (RuntimeException e) { responseFactory = getIdentityResponseFactory(e); responseBuilder = responseFactory.handleException(e); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } } /** * Process the {@link HttpIdentityResponse} and {@link HttpServletResponse}. * * @param httpIdentityResponse {@link HttpIdentityResponse} * @param response {@link HttpServletResponse} */ private void processHttpResponse(HttpIdentityResponse httpIdentityResponse, HttpServletResponse response) { for(Map.Entry<String,String> entry: httpIdentityResponse.getHeaders().entrySet()) { response.addHeader(entry.getKey(), entry.getValue()); } for(Map.Entry<String,Cookie> entry: httpIdentityResponse.getCookies().entrySet()) { response.addCookie(entry.getValue()); } if(StringUtils.isNotBlank(httpIdentityResponse.getContentType())) { response.setContentType(httpIdentityResponse.getContentType()); } if (httpIdentityResponse.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY) { try { sendRedirect(response, httpIdentityResponse); } catch (IOException e) { throw FrameworkRuntimeException.error("Error occurred while redirecting response", e); } } else { response.setStatus(httpIdentityResponse.getStatusCode()); try { PrintWriter out = response.getWriter(); if(StringUtils.isNotBlank(httpIdentityResponse.getBody())) { out.print(httpIdentityResponse.getBody()); } } catch (IOException e) { throw FrameworkRuntimeException.error("Error occurred while getting Response writer object", e); } } } /** * Get the HttpIdentityRequestFactory. * * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @return {@link HttpIdentityRequestFactory} */ private HttpIdentityRequestFactory getIdentityRequestFactory(HttpServletRequest request, HttpServletResponse response) { List<HttpIdentityRequestFactory> factories = FrameworkServiceDataHolder.getInstance().getHttpIdentityRequestFactories(); for (HttpIdentityRequestFactory requestBuilder : factories) { if (requestBuilder.canHandle(request, response)) { return requestBuilder; } } throw FrameworkRuntimeException.error("No HttpIdentityRequestFactory found to create the request"); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link IdentityResponse}. * * @param identityResponse IdentityResponse * @return HttpIdentityResponseFactory */ private HttpIdentityResponseFactory getHttpIdentityResponseFactory(IdentityResponse identityResponse) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(identityResponse)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the request"); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link FrameworkException}. * * @param exception {@link FrameworkException} * @return {@link HttpIdentityResponseFactory} */ private HttpIdentityResponseFactory getIdentityResponseFactory(FrameworkException exception) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(exception)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the response", exception); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link RuntimeException}. * * @param exception {@link RuntimeException} * @return {@link HttpIdentityResponseFactory} */ private HttpIdentityResponseFactory getIdentityResponseFactory(RuntimeException exception) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(exception)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the response", exception); } /** * Sends a 302 redirect response to client. * * @param response {@link HttpServletResponse} * @param httpIdentityResponse {@link HttpIdentityResponse} */ private void sendRedirect(HttpServletResponse response, HttpIdentityResponse httpIdentityResponse) throws IOException { String redirectUrl; if(httpIdentityResponse.isFragmentUrl()) { redirectUrl = IdentityUtil.buildFragmentUrl(httpIdentityResponse.getRedirectURL(), httpIdentityResponse.getParameters()); } else { redirectUrl = IdentityUtil.buildQueryUrl(httpIdentityResponse.getRedirectURL(), httpIdentityResponse.getParameters()); } response.sendRedirect(redirectUrl); } }
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/inbound/IdentityServlet.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.application.authentication.framework.inbound; import org.apache.commons.lang.StringUtils; import org.owasp.encoder.Encode; import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder; import org.wso2.carbon.identity.core.util.IdentityUtil; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; public class IdentityServlet extends HttpServlet { private IdentityProcessCoordinator manager = new IdentityProcessCoordinator(); @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpIdentityResponse httpIdentityResponse = process(request, response); processHttpResponse(httpIdentityResponse, response); } /** * Process the {@link HttpServletRequest} and {@link HttpServletResponse}. * * @param request * @param response */ private HttpIdentityResponse process(HttpServletRequest request, HttpServletResponse response) { HttpIdentityRequestFactory factory = getIdentityRequestFactory(request, response); IdentityRequest identityRequest = null; HttpIdentityResponse.HttpIdentityResponseBuilder responseBuilder = null; try { identityRequest = factory.create(request, response).build(); if(identityRequest == null) { throw FrameworkRuntimeException.error("IdentityRequest is Null. Cannot proceed!!"); } } catch (FrameworkClientException e) { responseBuilder = factory.handleException(e, request, response); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } catch (RuntimeException e) { responseBuilder = factory.handleException(e, request, response); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } IdentityResponse identityResponse = null; HttpIdentityResponseFactory responseFactory = null; try { identityResponse = manager.process(identityRequest); if(identityResponse == null) { throw FrameworkRuntimeException.error("IdentityResponse is Null. Cannot proceed!!"); } responseFactory = getHttpIdentityResponseFactory(identityResponse); responseBuilder = responseFactory.create(identityResponse); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!"); } return responseBuilder.build(); } catch (FrameworkException e) { responseFactory = getIdentityResponseFactory(e); responseBuilder = responseFactory.handleException(e); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } catch (RuntimeException e) { responseFactory = getIdentityResponseFactory(e); responseBuilder = responseFactory.handleException(e); if(responseBuilder == null) { throw FrameworkRuntimeException.error("HttpIdentityResponseBuilder is Null. Cannot proceed!!", e); } return responseBuilder.build(); } } /** * Process the {@link HttpIdentityResponse} and {@link HttpServletResponse}. * * @param httpIdentityResponse {@link HttpIdentityResponse} * @param response {@link HttpServletResponse} */ private void processHttpResponse(HttpIdentityResponse httpIdentityResponse, HttpServletResponse response) { for(Map.Entry<String,String> entry: httpIdentityResponse.getHeaders().entrySet()) { response.addHeader(entry.getKey(), entry.getValue()); } for(Map.Entry<String,Cookie> entry: httpIdentityResponse.getCookies().entrySet()) { response.addCookie(entry.getValue()); } if(StringUtils.isNotBlank(httpIdentityResponse.getContentType())) { response.setContentType(httpIdentityResponse.getContentType()); } if (httpIdentityResponse.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY) { try { sendRedirect(response, httpIdentityResponse); } catch (IOException e) { throw FrameworkRuntimeException.error("Error occurred while redirecting response", e); } } else { response.setStatus(httpIdentityResponse.getStatusCode()); try { PrintWriter out = response.getWriter(); if(StringUtils.isNotBlank(httpIdentityResponse.getBody())) { out.print(httpIdentityResponse.getBody()); } } catch (IOException e) { throw FrameworkRuntimeException.error("Error occurred while getting Response writer object", e); } } } /** * Get the HttpIdentityRequestFactory. * * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @return {@link HttpIdentityRequestFactory} */ private HttpIdentityRequestFactory getIdentityRequestFactory(HttpServletRequest request, HttpServletResponse response) { List<HttpIdentityRequestFactory> factories = FrameworkServiceDataHolder.getInstance().getHttpIdentityRequestFactories(); for (HttpIdentityRequestFactory requestBuilder : factories) { if (requestBuilder.canHandle(request, response)) { return requestBuilder; } } throw FrameworkRuntimeException.error("No HttpIdentityRequestFactory found to create the request"); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link IdentityResponse}. * * @param identityResponse IdentityResponse * @return HttpIdentityResponseFactory */ private HttpIdentityResponseFactory getHttpIdentityResponseFactory(IdentityResponse identityResponse) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(identityResponse)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the request"); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link FrameworkException}. * * @param exception {@link FrameworkException} * @return {@link HttpIdentityResponseFactory} */ private HttpIdentityResponseFactory getIdentityResponseFactory(FrameworkException exception) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(exception)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the response", exception); } /** * Get the {@link HttpIdentityResponseFactory} to handle this {@link RuntimeException}. * * @param exception {@link RuntimeException} * @return {@link HttpIdentityResponseFactory} */ private HttpIdentityResponseFactory getIdentityResponseFactory(RuntimeException exception) { List<HttpIdentityResponseFactory> factories = FrameworkServiceDataHolder.getInstance() .getHttpIdentityResponseFactories(); for (HttpIdentityResponseFactory responseFactory : factories) { if (responseFactory.canHandle(exception)) { return responseFactory; } } throw FrameworkRuntimeException.error("No HttpIdentityResponseFactory found to create the response", exception); } /** * Sends a 302 redirect response to client. * * @param response {@link HttpServletResponse} * @param httpIdentityResponse {@link HttpIdentityResponse} */ private void sendRedirect(HttpServletResponse response, HttpIdentityResponse httpIdentityResponse) throws IOException { String redirectUrl; if(httpIdentityResponse.isFragmentUrl()) { redirectUrl = IdentityUtil.buildFragmentUrl(httpIdentityResponse.getRedirectURL(), httpIdentityResponse.getParameters()); } else { redirectUrl = IdentityUtil.buildQueryUrl(httpIdentityResponse.getRedirectURL(), httpIdentityResponse.getParameters()); } response.sendRedirect(redirectUrl); } }
Update IdentityServlet.java
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/inbound/IdentityServlet.java
Update IdentityServlet.java
Java
apache-2.0
b1af3c871ae00268ece4170c8f5750651985af02
0
jenkinsci/intellij-jenkins-control-plugin,dboissier/jenkins-control-plugin
package org.codinjustu.tools.jenkins.logic; import org.apache.log4j.Logger; import org.codinjustu.tools.jenkins.JenkinsConfiguration; import org.codinjustu.tools.jenkins.model.Build; import org.codinjustu.tools.jenkins.model.Jenkins; import org.codinjustu.tools.jenkins.model.Job; import org.codinjustu.tools.jenkins.model.View; import org.codinjustu.tools.jenkins.view.JenkinsBrowserView; import org.jdom.JDOMException; import java.io.IOException; import java.util.*; import java.util.Map.Entry; //TODO gérer les exception JDOM et IO autrements abstract class JenkinsBrowserLogic<V extends JenkinsBrowserView> { private static final Logger LOG = Logger.getLogger(JenkinsBrowserLogic.class); private static final int MILLISECONDS = 1000; private static final int MINUTES = 60 * MILLISECONDS; private final V view; private final JenkinsConfiguration configuration; private final JenkinsRequestManager jenkinsRequestManager; private Jenkins jenkins; private final Map<String, Build> currentBuildMap = new HashMap<String, Build>(); private Timer jobRefreshTimer; private Timer rssRefreshTimer; JenkinsBrowserLogic(JenkinsConfiguration configuration, JenkinsRequestManager jenkinsRequestManager, V view) { this.configuration = configuration; this.jenkinsRequestManager = jenkinsRequestManager; this.view = view; } public void init() { initGui(); reloadConfiguration(); } protected abstract void initGui(); public void reloadConfiguration() { loadJenkinsWorkspace(); initTimers(); } void loadJenkinsWorkspace() { if (configuration.isServerUrlSet()) { try { jenkins = jenkinsRequestManager.loadJenkinsWorkspace(configuration); view.initModel(jenkins); String preferredView = configuration.getPreferredView(); View jenkinsView = findView(preferredView); if (jenkinsView != null) { this.view.setSelectedView(jenkinsView); } else { this.view.setSelectedView(jenkins.getPrimaryView()); } // addLatestBuilds(jenkinsRequestManager.loadJenkinsRssLatestBuilds(configuration)); } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing workspace"); } catch (Exception ex) { LOG.error(buildServerErrorMessage(ex), ex); displayConnectionErrorMsg(); } } else { displayConnectionErrorMsg(); } } public void loadSelectedView() { try { View jenkinsView = getSelectedJenkinsView(); if (jenkinsView != null) { List<Job> jobList = jenkinsRequestManager.loadJenkinsView(jenkinsView.getUrl()); jenkins.setJobs(jobList); this.view.fillJobTree(jenkins); } else { loadJenkinsWorkspace(); } } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing View Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); displayConnectionErrorMsg(); } } public void loadSelectedJob() { try { Job job = getSelectedJob(); Job updatedJob = jenkinsRequestManager.loadJob(job.getUrl()); job.updateContentWith(updatedJob); } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing View Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); displayConnectionErrorMsg(); } } void initTimers() { if (jobRefreshTimer != null) { jobRefreshTimer.cancel(); } if (rssRefreshTimer != null) { rssRefreshTimer.cancel(); } if (configuration.isEnableJobAutoRefresh()) { jobRefreshTimer = new Timer(); jobRefreshTimer.schedule(new JobRefreshTimerTask(), MINUTES, configuration.getJobRefreshPeriod() * MINUTES); } if (configuration.isEnableRssAutoRefresh()) { rssRefreshTimer = new Timer(); rssRefreshTimer.schedule(new RssRefreshTimerTask(), MINUTES, configuration.getRssRefreshPeriod() * MINUTES); } } private View findView(String preferredView) { List<View> viewList = jenkins.getViews(); for (View jenkinsView : viewList) { String viewName = jenkinsView.getName(); if (viewName.equals(preferredView)) { return jenkinsView; } } return jenkins.getPrimaryView(); } protected abstract void displayConnectionErrorMsg(); protected abstract void showErrorDialog(String errorMessage, String title); public void refreshLatestCompletedBuilds() { try { if (jenkins != null && !jenkins.getJobs().isEmpty()) { Map<String, Build> latestBuild = jenkinsRequestManager.loadJenkinsRssLatestBuilds( configuration); displayFinishedBuilds(addLatestBuilds(latestBuild)); } } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing Rss Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); ioEx.printStackTrace(); } } protected abstract void displayFinishedBuilds(Map<String, Build> latestBuilds); public abstract void cleanRssEntries(); Map<String, Build> addLatestBuilds(Map<String, Build> latestBuildMap) { Map<String, Build> newBuildMap = new HashMap<String, Build>(); for (Entry<String, Build> entry : latestBuildMap.entrySet()) { String jobName = entry.getKey(); Build newBuild = entry.getValue(); Build currentBuild = currentBuildMap.get(jobName); if (!currentBuildMap.containsKey(jobName) || newBuild.isDisplayable(currentBuild)) { currentBuildMap.put(jobName, newBuild); newBuildMap.put(jobName, newBuild); } } return newBuildMap; } String buildServerErrorMessage(Exception ex) { return "Server Url=" + configuration.getServerUrl() + "\n" + ex.getMessage(); } public View getSelectedJenkinsView() { return view.getSelectedJenkinsView(); } public Job getSelectedJob() { return view.getSelectedJob(); } public V getView() { return view; } public JenkinsRequestManager getJenkinsManager() { return jenkinsRequestManager; } private class JobRefreshTimerTask extends TimerTask { @Override public void run() { loadSelectedView(); } } private class RssRefreshTimerTask extends TimerTask { @Override public void run() { refreshLatestCompletedBuilds(); } } }
src/main/java/org/codinjustu/tools/jenkins/logic/JenkinsBrowserLogic.java
package org.codinjustu.tools.jenkins.logic; import org.apache.log4j.Logger; import org.codinjustu.tools.jenkins.JenkinsConfiguration; import org.codinjustu.tools.jenkins.model.Build; import org.codinjustu.tools.jenkins.model.Jenkins; import org.codinjustu.tools.jenkins.model.Job; import org.codinjustu.tools.jenkins.model.View; import org.codinjustu.tools.jenkins.view.JenkinsBrowserView; import org.jdom.JDOMException; import java.io.IOException; import java.util.*; import java.util.Map.Entry; //TODO gérer les exception JDOM et IO autrements abstract class JenkinsBrowserLogic<V extends JenkinsBrowserView> { private static final Logger LOG = Logger.getLogger(JenkinsBrowserLogic.class); private static final int MILLISECONDS = 1000; private static final int MINUTES = 60 * MILLISECONDS; private final V view; private final JenkinsConfiguration configuration; private final JenkinsRequestManager jenkinsRequestManager; private Jenkins jenkins; private final Map<String, Build> currentBuildMap = new HashMap<String, Build>(); private Timer jobRefreshTimer; private Timer rssRefreshTimer; JenkinsBrowserLogic(JenkinsConfiguration configuration, JenkinsRequestManager jenkinsRequestManager, V view) { this.configuration = configuration; this.jenkinsRequestManager = jenkinsRequestManager; this.view = view; } public void init() { initGui(); reloadConfiguration(); } protected abstract void initGui(); public void reloadConfiguration() { loadJenkinsWorkspace(); initTimers(); } void loadJenkinsWorkspace() { if (configuration.isServerUrlSet()) { try { jenkins = jenkinsRequestManager.loadJenkinsWorkspace(configuration); view.initModel(jenkins); String preferredView = configuration.getPreferredView(); View jenkinsView = findView(preferredView); if (jenkinsView != null) { this.view.setSelectedView(jenkinsView); } else { this.view.setSelectedView(jenkins.getPrimaryView()); } // addLatestBuilds(jenkinsRequestManager.loadJenkinsRssLatestBuilds(configuration)); } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing workspace"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); displayConnectionErrorMsg(); } } else { displayConnectionErrorMsg(); } } public void loadSelectedView() { try { View jenkinsView = getSelectedJenkinsView(); if (jenkinsView != null) { List<Job> jobList = jenkinsRequestManager.loadJenkinsView(jenkinsView.getUrl()); jenkins.setJobs(jobList); this.view.fillJobTree(jenkins); } else { loadJenkinsWorkspace(); } } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing View Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); displayConnectionErrorMsg(); } } public void loadSelectedJob() { try { Job job = getSelectedJob(); Job updatedJob = jenkinsRequestManager.loadJob(job.getUrl()); job.updateContentWith(updatedJob); } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing View Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); displayConnectionErrorMsg(); } } void initTimers() { if (jobRefreshTimer != null) { jobRefreshTimer.cancel(); } if (rssRefreshTimer != null) { rssRefreshTimer.cancel(); } if (configuration.isEnableJobAutoRefresh()) { jobRefreshTimer = new Timer(); jobRefreshTimer.schedule(new JobRefreshTimerTask(), MINUTES, configuration.getJobRefreshPeriod() * MINUTES); } if (configuration.isEnableRssAutoRefresh()) { rssRefreshTimer = new Timer(); rssRefreshTimer.schedule(new RssRefreshTimerTask(), MINUTES, configuration.getRssRefreshPeriod() * MINUTES); } } private View findView(String preferredView) { List<View> viewList = jenkins.getViews(); for (View jenkinsView : viewList) { String viewName = jenkinsView.getName(); if (viewName.equals(preferredView)) { return jenkinsView; } } return jenkins.getPrimaryView(); } protected abstract void displayConnectionErrorMsg(); protected abstract void showErrorDialog(String errorMessage, String title); public void refreshLatestCompletedBuilds() { try { if (jenkins != null && !jenkins.getJobs().isEmpty()) { Map<String, Build> latestBuild = jenkinsRequestManager.loadJenkinsRssLatestBuilds( configuration); displayFinishedBuilds(addLatestBuilds(latestBuild)); } } catch (JDOMException domEx) { String errorMessage = buildServerErrorMessage(domEx); LOG.error(errorMessage, domEx); showErrorDialog(errorMessage, "Error during parsing Rss Data"); } catch (IOException ioEx) { LOG.error(buildServerErrorMessage(ioEx), ioEx); ioEx.printStackTrace(); } } protected abstract void displayFinishedBuilds(Map<String, Build> latestBuilds); public abstract void cleanRssEntries(); Map<String, Build> addLatestBuilds(Map<String, Build> latestBuildMap) { Map<String, Build> newBuildMap = new HashMap<String, Build>(); for (Entry<String, Build> entry : latestBuildMap.entrySet()) { String jobName = entry.getKey(); Build newBuild = entry.getValue(); Build currentBuild = currentBuildMap.get(jobName); if (!currentBuildMap.containsKey(jobName) || newBuild.isDisplayable(currentBuild)) { currentBuildMap.put(jobName, newBuild); newBuildMap.put(jobName, newBuild); } } return newBuildMap; } String buildServerErrorMessage(Exception ex) { return "Server Url= " + configuration.getServerUrl() + "\n" + ex.getMessage(); } public View getSelectedJenkinsView() { return view.getSelectedJenkinsView(); } public Job getSelectedJob() { return view.getSelectedJob(); } public V getView() { return view; } public JenkinsRequestManager getJenkinsManager() { return jenkinsRequestManager; } private class JobRefreshTimerTask extends TimerTask { @Override public void run() { loadSelectedView(); } } private class RssRefreshTimerTask extends TimerTask { @Override public void run() { refreshLatestCompletedBuilds(); } } }
Generalize temporaly exception
src/main/java/org/codinjustu/tools/jenkins/logic/JenkinsBrowserLogic.java
Generalize temporaly exception
Java
apache-2.0
8e875c14556cec2b4ceb481fc60e3a0d3c36372f
0
remkop/picocli,remkop/picocli,remkop/picocli,remkop/picocli
package picocli; import org.fusesource.jansi.AnsiConsole; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.junit.contrib.java.lang.system.SystemOutRule; import org.junit.rules.TestRule; import picocli.CommandLine.Help.Ansi; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.util.Arrays; import static org.junit.Assert.*; import static picocli.HelpTestUtil.usageString; public class CommandLineHelpAnsiTest { private static final String LINESEP = System.getProperty("line.separator"); private static final String[] ANSI_ENVIRONMENT_VARIABLES = new String[] { "TERM", "OSTYPE", "NO_COLOR", "ANSICON", "CLICOLOR", "ConEmuANSI", "CLICOLOR_FORCE" }; @Rule // allows tests to set any kind of properties they like, without having to individually roll them back public final TestRule restoreSystemProperties = new RestoreSystemProperties(); @Rule public final SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests(); @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @After public void after() { System.getProperties().remove("picocli.color.commands"); System.getProperties().remove("picocli.color.options"); System.getProperties().remove("picocli.color.parameters"); System.getProperties().remove("picocli.color.optionParams"); } @Test public void testTextWithMultipleStyledSections() { assertEquals("\u001B[1m<main class>\u001B[21m\u001B[0m [\u001B[33m-v\u001B[39m\u001B[0m] [\u001B[33m-c\u001B[39m\u001B[0m [\u001B[3m<count>\u001B[23m\u001B[0m]]", Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@ [@|italic <count>|@]]").toString()); } @Test public void testTextAdjacentStyles() { assertEquals("\u001B[3m<commit\u001B[23m\u001B[0m\u001B[3m>\u001B[23m\u001B[0m%n", Ansi.ON.new Text("@|italic <commit|@@|italic >|@%n").toString()); } @Test public void testTextNoConversionWithoutClosingTag() { assertEquals("\u001B[3mabc\u001B[23m\u001B[0m", Ansi.ON.new Text("@|italic abc|@").toString()); assertEquals("@|italic abc", Ansi.ON.new Text("@|italic abc").toString()); } @Test public void testTextNoConversionWithoutSpaceSeparator() { assertEquals("\u001B[3ma\u001B[23m\u001B[0m", Ansi.ON.new Text("@|italic a|@").toString()); assertEquals("@|italic|@", Ansi.ON.new Text("@|italic|@").toString()); assertEquals("", Ansi.ON.new Text("@|italic |@").toString()); } @Test public void testPalette236ColorForegroundIndex() { assertEquals("\u001B[38;5;45mabc\u001B[39m\u001B[0m", Ansi.ON.new Text("@|fg(45) abc|@").toString()); } @Test public void testPalette236ColorForegroundRgb() { int num = 16 + 36 * 5 + 6 * 5 + 5; assertEquals("\u001B[38;5;" + num + "mabc\u001B[39m\u001B[0m", Ansi.ON.new Text("@|fg(5;5;5) abc|@").toString()); } @Test public void testPalette236ColorBackgroundIndex() { assertEquals("\u001B[48;5;77mabc\u001B[49m\u001B[0m", Ansi.ON.new Text("@|bg(77) abc|@").toString()); } @Test public void testPalette236ColorBackgroundRgb() { int num = 16 + 36 * 3 + 6 * 3 + 3; assertEquals("\u001B[48;5;" + num + "mabc\u001B[49m\u001B[0m", Ansi.ON.new Text("@|bg(3;3;3) abc|@").toString()); } @Test public void testAnsiEnabled() { assertTrue(Ansi.ON.enabled()); assertFalse(Ansi.OFF.enabled()); System.setProperty("picocli.ansi", "true"); assertEquals(true, Ansi.AUTO.enabled()); System.setProperty("picocli.ansi", "false"); assertEquals(false, Ansi.AUTO.enabled()); System.clearProperty("picocli.ansi"); boolean isWindows = System.getProperty("os.name").startsWith("Windows"); boolean isXterm = System.getenv("TERM") != null && System.getenv("TERM").startsWith("xterm"); boolean hasOsType = System.getenv("OSTYPE") != null; // null on Windows unless on Cygwin or MSYS boolean isAtty = (isWindows && (isXterm || hasOsType)) // cygwin pseudo-tty || hasConsole(); assertEquals((isAtty && (!isWindows || isXterm || hasOsType)) || isJansiConsoleInstalled(), Ansi.AUTO.enabled()); if (isWindows && !Ansi.AUTO.enabled()) { AnsiConsole.systemInstall(); try { assertTrue(Ansi.AUTO.enabled()); } finally { AnsiConsole.systemUninstall(); } } } private boolean hasConsole() { try { return System.class.getDeclaredMethod("console").invoke(null) != null; } catch (Throwable reflectionFailed) { return true; } } private static boolean isJansiConsoleInstalled() { try { Class<?> ansiConsole = Class.forName("org.fusesource.jansi.AnsiConsole"); Field out = ansiConsole.getField("out"); return out.get(null) == System.out; } catch (Exception reflectionFailed) { return false; } } @Test public void testSystemPropertiesOverrideDefaultColorScheme() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } Ansi ansi = Ansi.ON; // default color scheme assertEquals(ansi.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] @|yellow FILE|@..." + LINESEP), new CommandLine.Help(new App(), ansi).synopsis(0)); System.setProperty("picocli.color.commands", "blue"); System.setProperty("picocli.color.options", "green"); System.setProperty("picocli.color.parameters", "cyan"); System.setProperty("picocli.color.optionParams", "magenta"); assertEquals(ansi.new Text("@|blue <main class>|@ [@|green -v|@] [@|green -c|@=@|magenta <count>|@] @|cyan FILE|@..." + LINESEP), new CommandLine.Help(new App(), ansi).synopsis(0)); } @Test public void testSystemPropertiesOverrideExplicitColorScheme() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } Ansi ansi = Ansi.ON; CommandLine.Help.ColorScheme explicit = new CommandLine.Help.ColorScheme(ansi) .commands(Ansi.Style.faint, Ansi.Style.bg_magenta) .options(Ansi.Style.bg_red) .parameters(Ansi.Style.reverse) .optionParams(Ansi.Style.bg_green); // default color scheme assertEquals(ansi.new Text("@|faint,bg(magenta) <main class>|@ [@|bg(red) -v|@] [@|bg(red) -c|@=@|bg(green) <count>|@] @|reverse FILE|@..." + LINESEP), new CommandLine.Help(CommandLine.Model.CommandSpec.forAnnotatedObject(new App(), CommandLine.defaultFactory()), explicit).synopsis(0)); System.setProperty("picocli.color.commands", "blue"); System.setProperty("picocli.color.options", "blink"); System.setProperty("picocli.color.parameters", "red"); System.setProperty("picocli.color.optionParams", "magenta"); assertEquals(ansi.new Text("@|blue <main class>|@ [@|blink -v|@] [@|blink -c|@=@|magenta <count>|@] @|red FILE|@..." + LINESEP), new CommandLine.Help(CommandLine.Model.CommandSpec.forAnnotatedObject(new App(), CommandLine.defaultFactory()), explicit).synopsis(0)); } @Test public void testUsageWithCustomColorScheme() throws UnsupportedEncodingException { CommandLine.Help.ColorScheme scheme = new CommandLine.Help.ColorScheme(Ansi.ON) .options(Ansi.Style.bg_magenta).parameters(Ansi.Style.bg_cyan).optionParams(Ansi.Style.bg_yellow).commands(Ansi.Style.reverse); class Args { @CommandLine.Parameters(description = "param desc") String[] params; @CommandLine.Option(names = "-x", description = "option desc") String[] options; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); CommandLine.usage(new Args(), new PrintStream(baos, true, "UTF8"), scheme); String actual = baos.toString("UTF8"); String expected = String.format("" + "Usage: @|reverse <main class>|@ [@|bg_magenta -x|@=@|bg_yellow <options>|@]... [@|bg_cyan <params>|@...]%n" + " [@|bg_cyan <params>|@...] param desc%n" + " @|bg_magenta -x|@=@|bg_yellow <|@@|bg_yellow options>|@ option desc%n"); assertEquals(Ansi.ON.new Text(expected).toString(), actual); } @Test public void testAbreviatedSynopsis_withParameters() { @CommandLine.Command(abbreviateSynopsis = true) class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [OPTIONS] [<files>...]" + LINESEP, help.synopsis(0)); } @Test public void testAbreviatedSynopsis_withParameters_ANSI() { @CommandLine.Command(abbreviateSynopsis = true) class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [OPTIONS] [@|yellow <files>|@...]" + LINESEP).toString(), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withParameters() { @CommandLine.Command(separator = ":") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c:<count>] [<files>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withParameters_ANSI() { @CommandLine.Command(separator = ":") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@:@|italic <count>|@] [@|yellow <files>|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledParameters() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>] [FILE...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledParameters_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] [@|yellow FILE|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledRequiredParameters() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>] FILE..." + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledRequiredParameters_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] @|yellow FILE|@..." + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptionsSeparately() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--aaaa", "-a"}) boolean aBoolean; @CommandLine.Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @CommandLine.Option(names = {"--Verbose", "-V"}, required = true) boolean requiredVerbose; @CommandLine.Option(names = {"--Aaaa", "-A"}, required = true) boolean requiredABoolean; @CommandLine.Option(names = {"--Xxxx", "-X"}, required = true) Boolean requiredXBoolean; @CommandLine.Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> -AVX [-avx] [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptionsSeparately_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--aaaa", "-a"}) boolean aBoolean; @CommandLine.Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @CommandLine.Option(names = {"--Verbose", "-V"}, required = true) boolean requiredVerbose; @CommandLine.Option(names = {"--Aaaa", "-A"}, required = true) boolean requiredABoolean; @CommandLine.Option(names = {"--Xxxx", "-X"}, required = true) Boolean requiredXBoolean; @CommandLine.Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ @|yellow -AVX|@ [@|yellow -avx|@] [@|yellow -c|@=@|italic COUNT|@]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_firstLineLengthAdjustedForSynopsisHeading() { //Usage: small-test-program [-acorv!?] [--version] [-h <number>] [-p <file>|<folder>] [-d // <folder> [<folder>]] [-i <includePattern> // [<includePattern>...]] @CommandLine.Command(name="small-test-program", sortOptions = false, separator = " ") class App { @CommandLine.Option(names = "-a") boolean a; @CommandLine.Option(names = "-c") boolean c; @CommandLine.Option(names = "-o") boolean o; @CommandLine.Option(names = "-r") boolean r; @CommandLine.Option(names = "-v") boolean v; @CommandLine.Option(names = "-!") boolean exclamation; @CommandLine.Option(names = "-?") boolean question; @CommandLine.Option(names = {"--version"}) boolean version; @CommandLine.Option(names = {"--handle", "-h"}) int number; @CommandLine.Option(names = {"--ppp", "-p"}, paramLabel = "<file>|<folder>") File f; @CommandLine.Option(names = {"--ddd", "-d"}, paramLabel = "<folder>", arity="1..2") File[] d; @CommandLine.Option(names = {"--include", "-i"}, paramLabel = "<includePattern>") String pattern; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); String expected = "" + "Usage: small-test-program [-!?acorv] [--version] [-h <number>] [-i" + LINESEP + " <includePattern>] [-p <file>|<folder>] [-d <folder>" + LINESEP + " [<folder>]]..." + LINESEP; assertEquals(expected, help.synopsisHeading() + help.synopsis(help.synopsisHeadingLength())); help.commandSpec().usageMessage().synopsisHeading("Usage:%n"); expected = "" + "Usage:" + LINESEP + "small-test-program [-!?acorv] [--version] [-h <number>] [-i <includePattern>]" + LINESEP + " [-p <file>|<folder>] [-d <folder> [<folder>]]..." + LINESEP; assertEquals(expected, help.synopsisHeading() + help.synopsis(help.synopsisHeadingLength())); } @Test public void testLongMultiLineSynopsisIndented() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option-name", paramLabel = "<long-option-value>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "<another-long-option-value>") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=<another-long-option-value>]%n" + " [--fourth-long-option-name=<fourth-long-option-value>]%n" + " [--long-option-name=<long-option-value>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } @Test public void testLongMultiLineSynopsisWithAtMarkIndented() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option@-name", paramLabel = "<long-option-valu@@e>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "^[<another-long-option-value>]") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=^[<another-long-option-value>]]%n" + " [--fourth-long-option-name=<fourth-long-option-value>]%n" + " [--long-option@-name=<long-option-valu@@e>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } @Test public void testLongMultiLineSynopsisWithAtMarkIndented_ANSI() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option@-name", paramLabel = "<long-option-valu@@e>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "^[<another-long-option-value>]") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format( "@|bold <best-app-ever>|@ [@|yellow --another-long-option-name|@=@|italic ^[<another-long-option-value>]|@]%n" + " [@|yellow --fourth-long-option-name|@=@|italic <fourth-long-option-value>|@]%n" + " [@|yellow --long-option@-name|@=@|italic <long-option-valu@@e>|@]%n" + " [@|yellow --third-long-option-name|@=@|italic <third-long-option-value>|@]%n")), help.synopsis(0)); } @Test public void testUsageMainCommand_NoAnsi() { String actual = usageString(Demo.mainCommand(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_MAIN), actual); } @Test public void testUsageMainCommand_ANSI() { String actual = usageString(Demo.mainCommand(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_MAIN_ANSI)), actual); } @Test public void testUsageSubcommandGitStatus_NoAnsi() { String actual = usageString(new Demo.GitStatus(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_GITSTATUS), actual); } @Test public void testUsageSubcommandGitStatus_ANSI() { String actual = usageString(new Demo.GitStatus(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_GITSTATUS_ANSI)), actual); } @Test public void testUsageSubcommandGitCommit_NoAnsi() { String actual = usageString(new Demo.GitCommit(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_GITCOMMIT), actual); } @Test public void testUsageSubcommandGitCommit_ANSI() { String actual = usageString(new Demo.GitCommit(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_GITCOMMIT_ANSI)), actual); } @Test public void testTextConstructorPlain() { assertEquals("--NoAnsiFormat", Ansi.ON.new Text("--NoAnsiFormat").toString()); } @Test public void testTextConstructorWithStyle() { assertEquals("\u001B[1m--NoAnsiFormat\u001B[21m\u001B[0m", Ansi.ON.new Text("@|bold --NoAnsiFormat|@").toString()); } @Test public void testTextApply() { Ansi.Text txt = Ansi.ON.apply("--p", Arrays.<Ansi.IStyle>asList(Ansi.Style.fg_red, Ansi.Style.bold)); assertEquals(Ansi.ON.new Text("@|fg(red),bold --p|@"), txt); } @Test public void testTextDefaultColorScheme() { Ansi ansi = Ansi.ON; CommandLine.Help.ColorScheme scheme = CommandLine.Help.defaultColorScheme(ansi); assertEquals(scheme.ansi().new Text("@|yellow -p|@"), scheme.optionText("-p")); assertEquals(scheme.ansi().new Text("@|bold command|@"), scheme.commandText("command")); assertEquals(scheme.ansi().new Text("@|yellow FILE|@"), scheme.parameterText("FILE")); assertEquals(scheme.ansi().new Text("@|italic NUMBER|@"), scheme.optionParamText("NUMBER")); } @Test public void testTextSubString() { Ansi ansi = Ansi.ON; Ansi.Text txt = ansi.new Text("@|bold 01234|@").concat("56").concat("@|underline 7890|@"); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7890|@"), txt.substring(0)); assertEquals(ansi.new Text("@|bold 1234|@56@|underline 7890|@"), txt.substring(1)); assertEquals(ansi.new Text("@|bold 234|@56@|underline 7890|@"), txt.substring(2)); assertEquals(ansi.new Text("@|bold 34|@56@|underline 7890|@"), txt.substring(3)); assertEquals(ansi.new Text("@|bold 4|@56@|underline 7890|@"), txt.substring(4)); assertEquals(ansi.new Text("56@|underline 7890|@"), txt.substring(5)); assertEquals(ansi.new Text("6@|underline 7890|@"), txt.substring(6)); assertEquals(ansi.new Text("@|underline 7890|@"), txt.substring(7)); assertEquals(ansi.new Text("@|underline 890|@"), txt.substring(8)); assertEquals(ansi.new Text("@|underline 90|@"), txt.substring(9)); assertEquals(ansi.new Text("@|underline 0|@"), txt.substring(10)); assertEquals(ansi.new Text(""), txt.substring(11)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7890|@"), txt.substring(0, 11)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 789|@"), txt.substring(0, 10)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 78|@"), txt.substring(0, 9)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7|@"), txt.substring(0, 8)); assertEquals(ansi.new Text("@|bold 01234|@56"), txt.substring(0, 7)); assertEquals(ansi.new Text("@|bold 01234|@5"), txt.substring(0, 6)); assertEquals(ansi.new Text("@|bold 01234|@"), txt.substring(0, 5)); assertEquals(ansi.new Text("@|bold 0123|@"), txt.substring(0, 4)); assertEquals(ansi.new Text("@|bold 012|@"), txt.substring(0, 3)); assertEquals(ansi.new Text("@|bold 01|@"), txt.substring(0, 2)); assertEquals(ansi.new Text("@|bold 0|@"), txt.substring(0, 1)); assertEquals(ansi.new Text(""), txt.substring(0, 0)); assertEquals(ansi.new Text("@|bold 1234|@56@|underline 789|@"), txt.substring(1, 10)); assertEquals(ansi.new Text("@|bold 234|@56@|underline 78|@"), txt.substring(2, 9)); assertEquals(ansi.new Text("@|bold 34|@56@|underline 7|@"), txt.substring(3, 8)); assertEquals(ansi.new Text("@|bold 4|@56"), txt.substring(4, 7)); assertEquals(ansi.new Text("5"), txt.substring(5, 6)); assertEquals(ansi.new Text("@|bold 2|@"), txt.substring(2, 3)); assertEquals(ansi.new Text("@|underline 8|@"), txt.substring(8, 9)); Ansi.Text txt2 = ansi.new Text("@|bold abc|@@|underline DEF|@"); assertEquals(ansi.new Text("@|bold abc|@@|underline DEF|@"), txt2.substring(0)); assertEquals(ansi.new Text("@|bold bc|@@|underline DEF|@"), txt2.substring(1)); assertEquals(ansi.new Text("@|bold abc|@@|underline DE|@"), txt2.substring(0,5)); assertEquals(ansi.new Text("@|bold bc|@@|underline DE|@"), txt2.substring(1,5)); } @Test public void testTextSplitLines() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("@|bold 012\n34|@").concat("5\nAA\n6").concat("@|underline 78\n90|@"), ansi.new Text("@|bold 012\r34|@").concat("5\rAA\r6").concat("@|underline 78\r90|@"), ansi.new Text("@|bold 012\r\n34|@").concat("5\r\nAA\r\n6").concat("@|underline 78\r\n90|@"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); } } @Test public void testTextSplitLinesStartEnd() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("\n@|bold 012\n34|@").concat("5\nAA\n6").concat("@|underline 78\n90|@\n"), ansi.new Text("\r@|bold 012\r34|@").concat("5\rAA\r6").concat("@|underline 78\r90|@\r"), ansi.new Text("\r\n@|bold 012\r\n34|@").concat("5\r\nAA\r\n6").concat("@|underline 78\r\n90|@\r\n"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); } } @Test public void testTextSplitLinesStartEndIntermediate() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("\n@|bold 012\n\n\n34|@").concat("5\n\n\nAA\n\n\n6").concat("@|underline 78\n90|@\n"), ansi.new Text("\r@|bold 012\r\r\r34|@").concat("5\r\r\rAA\r\r\r6").concat("@|underline 78\r90|@\r"), ansi.new Text("\r\n@|bold 012\r\n\r\n\r\n34|@").concat("5\r\n\r\n\r\nAA\r\n\r\n\r\n6").concat("@|underline 78\r\n90|@\r\n"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); } } @Test public void testTextHashCode() { Ansi ansi = Ansi.ON; assertEquals(ansi.new Text("a").hashCode(), ansi.new Text("a").hashCode()); assertNotEquals(ansi.new Text("a").hashCode(), ansi.new Text("b").hashCode()); } @Test public void testTextAppendString() { Ansi ansi = Ansi.ON; assertEquals(ansi.new Text("a").append("xyz"), ansi.new Text("a").concat("xyz")); } @Test public void testTextAppendText() { Ansi ansi = Ansi.ON; Ansi.Text xyz = ansi.new Text("xyz"); assertEquals(ansi.new Text("a").append(xyz), ansi.new Text("a").concat(xyz)); } @Test public void testStyleParseAllowsMissingClosingBrackets() { Ansi.IStyle whiteBg = Ansi.Style.parse("bg(white")[0]; assertEquals(Ansi.Style.bg_white.on(), whiteBg.on()); Ansi.IStyle blackFg = Ansi.Style.parse("fg(black")[0]; assertEquals(Ansi.Style.fg_black.on(), blackFg.on()); } @Test public void testColorSchemeDefaultConstructorHasAnsiAuto() { CommandLine.Help.ColorScheme colorScheme = new CommandLine.Help.ColorScheme(); assertEquals(Ansi.AUTO, colorScheme.ansi()); } @Test public void testCommandLine_printVersionInfo_printsArrayOfPlainTextStrings() { @CommandLine.Command(version = {"Versioned Command 1.0", "512-bit superdeluxe", "(c) 2017"}) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.OFF); String result = baos.toString(); assertEquals(String.format("Versioned Command 1.0%n512-bit superdeluxe%n(c) 2017%n"), result); } @Test public void testCommandLine_printVersionInfo_printsSingleStringWithMarkup() { @CommandLine.Command(version = "@|red 1.0|@") class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.ON); String result = baos.toString(); assertEquals(String.format("\u001B[31m1.0\u001B[39m\u001B[0m%n"), result); } @Test public void testCommandLine_printVersionInfo_printsArrayOfStringsWithMarkup() { @CommandLine.Command(version = { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@", "@|red,bg(white) (c) 2017|@" }) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.ON); String result = baos.toString(); assertEquals(String.format("" + "\u001B[33mVersioned Command 1.0\u001B[39m\u001B[0m%n" + "\u001B[34mBuild 12345\u001B[39m\u001B[0m%n" + "\u001B[31m\u001B[47m(c) 2017\u001B[49m\u001B[39m\u001B[0m%n"), result); } @Test public void testCommandLine_printVersionInfo_formatsArguments() { @CommandLine.Command(version = {"First line %1$s", "Second line %2$s", "Third line %s %s"}) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, true); new CommandLine(new Versioned()).printVersionHelp(ps, Ansi.OFF, "VALUE1", "VALUE2", "VALUE3"); String result = baos.toString(); assertEquals(String.format("First line VALUE1%nSecond line VALUE2%nThird line VALUE1 VALUE2%n"), result); } @Test public void testCommandLine_printVersionInfo_withMarkupAndParameterContainingMarkup() { @CommandLine.Command(version = { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@%1$s", "@|red,bg(white) (c) 2017|@%2$s" }) class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } static class MarkupVersionProvider implements CommandLine.IVersionProvider { public String[] getVersion() { return new String[] { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@%1$s", "@|red,bg(white) (c) 2017|@%2$s" }; } } @Test public void testCommandLine_printVersionInfo_fromAnnotation_withMarkupAndParameterContainingMarkup() { @CommandLine.Command(versionProvider = MarkupVersionProvider.class) class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } @Test public void testCommandLine_printVersionInfo_usesProviderIfBothProviderAndStaticVersionInfoExist() { @CommandLine.Command(versionProvider = MarkupVersionProvider.class, version = "static version is ignored") class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } private void verifyVersionWithMarkup(CommandLine commandLine) { String[] args = {"@|bold VALUE1|@", "@|underline VALUE2|@", "VALUE3"}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, true); commandLine.printVersionHelp(ps, Ansi.ON, (Object[]) args); String result = baos.toString(); assertEquals(String.format("" + "\u001B[33mVersioned Command 1.0\u001B[39m\u001B[0m%n" + "\u001B[34mBuild 12345\u001B[39m\u001B[0m\u001B[1mVALUE1\u001B[21m\u001B[0m%n" + "\u001B[31m\u001B[47m(c) 2017\u001B[49m\u001B[39m\u001B[0m\u001B[4mVALUE2\u001B[24m\u001B[0m%n"), result); } @Test public void testAnsiIsWindowsDependsOnSystemProperty() { System.setProperty("os.name", "MMIX"); assertFalse(Ansi.isWindows()); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); System.setProperty("os.name", "Windows 10 build 12345"); assertTrue(Ansi.isWindows()); } @Test public void testAnsiIsXtermDependsOnEnvironmentVariable() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse(Ansi.isXterm()); environmentVariables.set("TERM", "random value"); assertFalse(Ansi.isXterm()); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isXterm()); environmentVariables.set("TERM", "xterm asfasfasf"); assertTrue(Ansi.isXterm()); } @Test public void testAnsiHasOstypeDependsOnEnvironmentVariable() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse(Ansi.hasOsType()); environmentVariables.set("OSTYPE", ""); assertTrue(Ansi.hasOsType()); environmentVariables.set("OSTYPE", "42"); assertTrue(Ansi.hasOsType()); } @Test public void testAnsiIsPseudoTtyDependsOnWindowsXtermOrOsType() { System.setProperty("os.name", "MMIX"); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("OSTYPE and XTERM are not set", Ansi.isPseudoTTY()); System.setProperty("os.name", "Windows 10 build 12345"); environmentVariables.set("OSTYPE", "222"); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isPseudoTTY()); System.setProperty("os.name", "MMIX"); assertFalse("Not Windows", Ansi.isPseudoTTY()); System.setProperty("os.name", "Windows 10 build 12345"); // restore assertTrue("restored", Ansi.isPseudoTTY()); environmentVariables.clear("OSTYPE"); assertTrue("Missing OSTYPE, but TERM=xterm", Ansi.isPseudoTTY()); environmentVariables.set("OSTYPE", "anything"); assertTrue("restored", Ansi.isPseudoTTY()); environmentVariables.clear("XTERM"); assertTrue("Missing XTERM, but OSTYPE defined", Ansi.isPseudoTTY()); } @Test public void testAnsiHintDisabledTrueIfCLICOLORZero() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", ""); assertFalse("Just defining CLICOLOR is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "1"); assertFalse("CLICOLOR=1 is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "false"); assertFalse("CLICOLOR=false is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "0"); assertTrue("CLICOLOR=0 disables", Ansi.hintDisabled()); } @Test public void testAnsiHintDisabledTrueIfConEmuANSIisOFF() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", ""); assertFalse("Just defining ConEmuANSI is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "0"); assertFalse("ConEmuANSI=0 is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "false"); assertFalse("ConEmuANSI=false is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "off"); assertFalse("ConEmuANSI=off does not disable", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "Off"); assertFalse("ConEmuANSI=Off does not disable", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "OFF"); assertTrue("ConEmuANSI=OFF disables", Ansi.hintDisabled()); } @Test public void testAnsiHintEnbledTrueIfANSICONDefined() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("ANSICON", ""); assertTrue("ANSICON defined without value", Ansi.hintEnabled()); environmentVariables.set("ANSICON", "abc"); assertTrue("ANSICON defined any value", Ansi.hintEnabled()); } @Test public void testAnsiHintEnbledTrueIfCLICOLOROne() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", ""); assertFalse("Just defining CLICOLOR is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "0"); assertFalse("CLICOLOR=0 is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "true"); assertFalse("CLICOLOR=true is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "1"); assertTrue("CLICOLOR=1 enables", Ansi.hintEnabled()); } @Test public void testAnsiHintEnabledTrueIfConEmuANSIisON() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", ""); assertFalse("Just defining ConEmuANSI is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "1"); assertFalse("ConEmuANSI=1 is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "true"); assertFalse("ConEmuANSI=true is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "on"); assertFalse("ConEmuANSI=on does not enables", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "On"); assertFalse("ConEmuANSI=On does not enables", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "ON"); assertTrue("ConEmuANSI=ON enables", Ansi.hintEnabled()); } @Test public void testAnsiForceEnabledTrueIfCLICOLOR_FORCEisDefinedAndNonZero() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", ""); assertTrue("Just defining CLICOLOR_FORCE is enough", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", "1"); assertTrue("CLICOLOR_FORCE=1 is enough", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", "0"); assertFalse("CLICOLOR_FORCE=0 is not forced", Ansi.forceEnabled()); } @Test public void testAnsiForceDisabledTrueIfNO_COLORDefined() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.forceDisabled()); environmentVariables.set("NO_COLOR", ""); assertTrue("NO_COLOR defined without value", Ansi.forceDisabled()); environmentVariables.set("NO_COLOR", "abc"); assertTrue("NO_COLOR defined any value", Ansi.forceDisabled()); } @Test public void testAnsiOnEnabled() { assertTrue(Ansi.ON.enabled()); } @Test public void testAnsiOffDisabled() { assertFalse(Ansi.OFF.enabled()); } @Test public void testAnsiAutoIfSystemPropertyPicocliAnsiCleared() { environmentVariables.set("CLICOLOR_FORCE", "1"); System.clearProperty("picocli.ansi"); assertTrue(Ansi.AUTO.enabled()); } @Test public void testAnsiAutoIfSystemPropertyPicocliAnsiIsAuto() { environmentVariables.set("CLICOLOR_FORCE", "1"); System.setProperty("picocli.ansi", "auto"); assertTrue(Ansi.AUTO.enabled()); System.setProperty("picocli.ansi", "Auto"); assertTrue(Ansi.AUTO.enabled()); System.setProperty("picocli.ansi", "AUTO"); assertTrue(Ansi.AUTO.enabled()); } @Test public void testAnsiOffIfSystemPropertyPicocliAnsiIsNotAuto() { System.setProperty("picocli.ansi", "auto1"); environmentVariables.set("CLICOLOR_FORCE", "1"); assertFalse(Ansi.AUTO.enabled()); } @Test public void testAnsiAutoForceDisabledOverridesForceEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("NO_COLOR", ""); environmentVariables.set("CLICOLOR_FORCE", "1"); assertTrue(Ansi.forceDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse("forceDisabled overrides forceEnabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoForceDisabledOverridesHintEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("NO_COLOR", ""); environmentVariables.set("CLICOLOR", "1"); assertTrue(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertTrue(Ansi.hintEnabled()); assertFalse("forceDisabled overrides hintEnabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoForcedEnabledOverridesHintDisabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); environmentVariables.set("CLICOLOR_FORCE", "1"); assertFalse(Ansi.forceDisabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintEnabled()); assertTrue("forceEnabled overrides hintDisabled", Ansi.AUTO.enabled()); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("ConEmuANSI", "OFF"); environmentVariables.set("CLICOLOR_FORCE", "1"); assertFalse(Ansi.forceDisabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintEnabled()); assertTrue("forceEnabled overrides hintDisabled 2", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoJansiConsoleInstalledOverridesHintDisabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); // hint disabled System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertTrue(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse(Ansi.isJansiConsoleInstalled()); AnsiConsole.systemInstall(); try { assertTrue(Ansi.isJansiConsoleInstalled()); assertTrue(Ansi.AUTO.enabled()); } finally { AnsiConsole.systemUninstall(); } } @Test public void testAnsiAutoHintDisabledOverridesHintEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); // hint disabled environmentVariables.set("ANSICON", "1"); // hint enabled System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); environmentVariables.set("TERM", "xterm"); // fake Cygwin assertTrue(Ansi.isPseudoTTY()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.hintEnabled()); assertFalse("Disabled overrides enabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoDisabledIfNoTty() { if (Ansi.isTTY()) { return; } // environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse("Must have TTY if no JAnsi", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoEnabledIfNotWindows() { if (!Ansi.isTTY()) { return; } // needs TTY for this test environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "MMIX"); assertFalse(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); // TODO Mock this? assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertTrue("If have TTY, enabled on non-Windows", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoEnabledIfWindowsPseudoTTY() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isPseudoTTY()); assertTrue("If have Cygwin pseudo-TTY, enabled on Windows", Ansi.AUTO.enabled()); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("OSTYPE", "Windows"); assertTrue(Ansi.isPseudoTTY()); assertTrue("If have MSYS pseudo-TTY, enabled on Windows", Ansi.AUTO.enabled()); } }
src/test/java/picocli/CommandLineHelpAnsiTest.java
package picocli; import org.fusesource.jansi.AnsiConsole; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.junit.contrib.java.lang.system.SystemOutRule; import org.junit.rules.TestRule; import picocli.CommandLine.Help.Ansi; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.util.Arrays; import static org.junit.Assert.*; import static picocli.HelpTestUtil.usageString; public class CommandLineHelpAnsiTest { private static final String LINESEP = System.getProperty("line.separator"); private static final String[] ANSI_ENVIRONMENT_VARIABLES = new String[] { "TERM", "OSTYPE", "NO_COLOR", "ANSICON", "CLICOLOR", "ConEmuANSI", "CLICOLOR_FORCE" }; @Rule // allows tests to set any kind of properties they like, without having to individually roll them back public final TestRule restoreSystemProperties = new RestoreSystemProperties(); @Rule public final SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests(); @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @After public void after() { System.getProperties().remove("picocli.color.commands"); System.getProperties().remove("picocli.color.options"); System.getProperties().remove("picocli.color.parameters"); System.getProperties().remove("picocli.color.optionParams"); } @Test public void testTextWithMultipleStyledSections() { assertEquals("\u001B[1m<main class>\u001B[21m\u001B[0m [\u001B[33m-v\u001B[39m\u001B[0m] [\u001B[33m-c\u001B[39m\u001B[0m [\u001B[3m<count>\u001B[23m\u001B[0m]]", Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@ [@|italic <count>|@]]").toString()); } @Test public void testTextAdjacentStyles() { assertEquals("\u001B[3m<commit\u001B[23m\u001B[0m\u001B[3m>\u001B[23m\u001B[0m%n", Ansi.ON.new Text("@|italic <commit|@@|italic >|@%n").toString()); } @Test public void testTextNoConversionWithoutClosingTag() { assertEquals("\u001B[3mabc\u001B[23m\u001B[0m", Ansi.ON.new Text("@|italic abc|@").toString()); assertEquals("@|italic abc", Ansi.ON.new Text("@|italic abc").toString()); } @Test public void testTextNoConversionWithoutSpaceSeparator() { assertEquals("\u001B[3ma\u001B[23m\u001B[0m", Ansi.ON.new Text("@|italic a|@").toString()); assertEquals("@|italic|@", Ansi.ON.new Text("@|italic|@").toString()); assertEquals("", Ansi.ON.new Text("@|italic |@").toString()); } @Test public void testPalette236ColorForegroundIndex() { assertEquals("\u001B[38;5;45mabc\u001B[39m\u001B[0m", Ansi.ON.new Text("@|fg(45) abc|@").toString()); } @Test public void testPalette236ColorForegroundRgb() { int num = 16 + 36 * 5 + 6 * 5 + 5; assertEquals("\u001B[38;5;" + num + "mabc\u001B[39m\u001B[0m", Ansi.ON.new Text("@|fg(5;5;5) abc|@").toString()); } @Test public void testPalette236ColorBackgroundIndex() { assertEquals("\u001B[48;5;77mabc\u001B[49m\u001B[0m", Ansi.ON.new Text("@|bg(77) abc|@").toString()); } @Test public void testPalette236ColorBackgroundRgb() { int num = 16 + 36 * 3 + 6 * 3 + 3; assertEquals("\u001B[48;5;" + num + "mabc\u001B[49m\u001B[0m", Ansi.ON.new Text("@|bg(3;3;3) abc|@").toString()); } @Test public void testAnsiEnabled() { assertTrue(Ansi.ON.enabled()); assertFalse(Ansi.OFF.enabled()); System.setProperty("picocli.ansi", "true"); assertEquals(true, Ansi.AUTO.enabled()); System.setProperty("picocli.ansi", "false"); assertEquals(false, Ansi.AUTO.enabled()); System.clearProperty("picocli.ansi"); boolean isWindows = System.getProperty("os.name").startsWith("Windows"); boolean isXterm = System.getenv("TERM") != null && System.getenv("TERM").startsWith("xterm"); boolean hasOsType = System.getenv("OSTYPE") != null; // null on Windows unless on Cygwin or MSYS boolean isAtty = (isWindows && (isXterm || hasOsType)) // cygwin pseudo-tty || hasConsole(); assertEquals((isAtty && (!isWindows || isXterm || hasOsType)) || isJansiConsoleInstalled(), Ansi.AUTO.enabled()); if (isWindows && !Ansi.AUTO.enabled()) { AnsiConsole.systemInstall(); try { assertTrue(Ansi.AUTO.enabled()); } finally { AnsiConsole.systemUninstall(); } } } private boolean hasConsole() { try { return System.class.getDeclaredMethod("console").invoke(null) != null; } catch (Throwable reflectionFailed) { return true; } } private static boolean isJansiConsoleInstalled() { try { Class<?> ansiConsole = Class.forName("org.fusesource.jansi.AnsiConsole"); Field out = ansiConsole.getField("out"); return out.get(null) == System.out; } catch (Exception reflectionFailed) { return false; } } @Test public void testSystemPropertiesOverrideDefaultColorScheme() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } Ansi ansi = Ansi.ON; // default color scheme assertEquals(ansi.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] @|yellow FILE|@..." + LINESEP), new CommandLine.Help(new App(), ansi).synopsis(0)); System.setProperty("picocli.color.commands", "blue"); System.setProperty("picocli.color.options", "green"); System.setProperty("picocli.color.parameters", "cyan"); System.setProperty("picocli.color.optionParams", "magenta"); assertEquals(ansi.new Text("@|blue <main class>|@ [@|green -v|@] [@|green -c|@=@|magenta <count>|@] @|cyan FILE|@..." + LINESEP), new CommandLine.Help(new App(), ansi).synopsis(0)); } @Test public void testSystemPropertiesOverrideExplicitColorScheme() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } Ansi ansi = Ansi.ON; CommandLine.Help.ColorScheme explicit = new CommandLine.Help.ColorScheme(ansi) .commands(Ansi.Style.faint, Ansi.Style.bg_magenta) .options(Ansi.Style.bg_red) .parameters(Ansi.Style.reverse) .optionParams(Ansi.Style.bg_green); // default color scheme assertEquals(ansi.new Text("@|faint,bg(magenta) <main class>|@ [@|bg(red) -v|@] [@|bg(red) -c|@=@|bg(green) <count>|@] @|reverse FILE|@..." + LINESEP), new CommandLine.Help(CommandLine.Model.CommandSpec.forAnnotatedObject(new App(), CommandLine.defaultFactory()), explicit).synopsis(0)); System.setProperty("picocli.color.commands", "blue"); System.setProperty("picocli.color.options", "blink"); System.setProperty("picocli.color.parameters", "red"); System.setProperty("picocli.color.optionParams", "magenta"); assertEquals(ansi.new Text("@|blue <main class>|@ [@|blink -v|@] [@|blink -c|@=@|magenta <count>|@] @|red FILE|@..." + LINESEP), new CommandLine.Help(CommandLine.Model.CommandSpec.forAnnotatedObject(new App(), CommandLine.defaultFactory()), explicit).synopsis(0)); } @Test public void testUsageWithCustomColorScheme() throws UnsupportedEncodingException { CommandLine.Help.ColorScheme scheme = new CommandLine.Help.ColorScheme(Ansi.ON) .options(Ansi.Style.bg_magenta).parameters(Ansi.Style.bg_cyan).optionParams(Ansi.Style.bg_yellow).commands(Ansi.Style.reverse); class Args { @CommandLine.Parameters(description = "param desc") String[] params; @CommandLine.Option(names = "-x", description = "option desc") String[] options; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); CommandLine.usage(new Args(), new PrintStream(baos, true, "UTF8"), scheme); String actual = baos.toString("UTF8"); String expected = String.format("" + "Usage: @|reverse <main class>|@ [@|bg_magenta -x|@=@|bg_yellow <options>|@]... [@|bg_cyan <params>|@...]%n" + " [@|bg_cyan <params>|@...] param desc%n" + " @|bg_magenta -x|@=@|bg_yellow <|@@|bg_yellow options>|@ option desc%n"); assertEquals(Ansi.ON.new Text(expected).toString(), actual); } @Test public void testAbreviatedSynopsis_withParameters() { @CommandLine.Command(abbreviateSynopsis = true) class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [OPTIONS] [<files>...]" + LINESEP, help.synopsis(0)); } @Test public void testAbreviatedSynopsis_withParameters_ANSI() { @CommandLine.Command(abbreviateSynopsis = true) class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [OPTIONS] [@|yellow <files>|@...]" + LINESEP).toString(), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withParameters() { @CommandLine.Command(separator = ":") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c:<count>] [<files>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withParameters_ANSI() { @CommandLine.Command(separator = ":") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@:@|italic <count>|@] [@|yellow <files>|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledParameters() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>] [FILE...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledParameters_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] [@|yellow FILE|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledRequiredParameters() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>] FILE..." + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withSeparator_withLabeledRequiredParameters_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--count", "-c"}) int count; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @CommandLine.Parameters(paramLabel = "FILE", arity = "1..*") File[] files; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@] @|yellow FILE|@..." + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptionsSeparately() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--aaaa", "-a"}) boolean aBoolean; @CommandLine.Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @CommandLine.Option(names = {"--Verbose", "-V"}, required = true) boolean requiredVerbose; @CommandLine.Option(names = {"--Aaaa", "-A"}, required = true) boolean requiredABoolean; @CommandLine.Option(names = {"--Xxxx", "-X"}, required = true) Boolean requiredXBoolean; @CommandLine.Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals("<main class> -AVX [-avx] [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptionsSeparately_ANSI() { @CommandLine.Command(separator = "=") class App { @CommandLine.Option(names = {"--verbose", "-v"}) boolean verbose; @CommandLine.Option(names = {"--aaaa", "-a"}) boolean aBoolean; @CommandLine.Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @CommandLine.Option(names = {"--Verbose", "-V"}, required = true) boolean requiredVerbose; @CommandLine.Option(names = {"--Aaaa", "-A"}, required = true) boolean requiredABoolean; @CommandLine.Option(names = {"--Xxxx", "-X"}, required = true) Boolean requiredXBoolean; @CommandLine.Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text("@|bold <main class>|@ @|yellow -AVX|@ [@|yellow -avx|@] [@|yellow -c|@=@|italic COUNT|@]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_firstLineLengthAdjustedForSynopsisHeading() { //Usage: small-test-program [-acorv!?] [--version] [-h <number>] [-p <file>|<folder>] [-d // <folder> [<folder>]] [-i <includePattern> // [<includePattern>...]] @CommandLine.Command(name="small-test-program", sortOptions = false, separator = " ") class App { @CommandLine.Option(names = "-a") boolean a; @CommandLine.Option(names = "-c") boolean c; @CommandLine.Option(names = "-o") boolean o; @CommandLine.Option(names = "-r") boolean r; @CommandLine.Option(names = "-v") boolean v; @CommandLine.Option(names = "-!") boolean exclamation; @CommandLine.Option(names = "-?") boolean question; @CommandLine.Option(names = {"--version"}) boolean version; @CommandLine.Option(names = {"--handle", "-h"}) int number; @CommandLine.Option(names = {"--ppp", "-p"}, paramLabel = "<file>|<folder>") File f; @CommandLine.Option(names = {"--ddd", "-d"}, paramLabel = "<folder>", arity="1..2") File[] d; @CommandLine.Option(names = {"--include", "-i"}, paramLabel = "<includePattern>") String pattern; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); String expected = "" + "Usage: small-test-program [-!?acorv] [--version] [-h <number>] [-i" + LINESEP + " <includePattern>] [-p <file>|<folder>] [-d <folder>" + LINESEP + " [<folder>]]..." + LINESEP; assertEquals(expected, help.synopsisHeading() + help.synopsis(help.synopsisHeadingLength())); help.commandSpec().usageMessage().synopsisHeading("Usage:%n"); expected = "" + "Usage:" + LINESEP + "small-test-program [-!?acorv] [--version] [-h <number>] [-i <includePattern>]" + LINESEP + " [-p <file>|<folder>] [-d <folder> [<folder>]]..." + LINESEP; assertEquals(expected, help.synopsisHeading() + help.synopsis(help.synopsisHeadingLength())); } @Test public void testLongMultiLineSynopsisIndented() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option-name", paramLabel = "<long-option-value>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "<another-long-option-value>") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=<another-long-option-value>]%n" + " [--fourth-long-option-name=<fourth-long-option-value>]%n" + " [--long-option-name=<long-option-value>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } @Test public void testLongMultiLineSynopsisWithAtMarkIndented() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option@-name", paramLabel = "<long-option-valu@@e>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "^[<another-long-option-value>]") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=^[<another-long-option-value>]]%n" + " [--fourth-long-option-name=<fourth-long-option-value>]%n" + " [--long-option@-name=<long-option-valu@@e>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } @Test public void testLongMultiLineSynopsisWithAtMarkIndented_ANSI() { @CommandLine.Command(name = "<best-app-ever>") class App { @CommandLine.Option(names = "--long-option@-name", paramLabel = "<long-option-valu@@e>") int a; @CommandLine.Option(names = "--another-long-option-name", paramLabel = "^[<another-long-option-value>]") int b; @CommandLine.Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @CommandLine.Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } CommandLine.Help help = new CommandLine.Help(new App(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format( "@|bold <best-app-ever>|@ [@|yellow --another-long-option-name|@=@|italic ^[<another-long-option-value>]|@]%n" + " [@|yellow --fourth-long-option-name|@=@|italic <fourth-long-option-value>|@]%n" + " [@|yellow --long-option@-name|@=@|italic <long-option-valu@@e>|@]%n" + " [@|yellow --third-long-option-name|@=@|italic <third-long-option-value>|@]%n")), help.synopsis(0)); } @Test public void testUsageMainCommand_NoAnsi() { String actual = usageString(Demo.mainCommand(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_MAIN), actual); } @Test public void testUsageMainCommand_ANSI() { String actual = usageString(Demo.mainCommand(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_MAIN_ANSI)), actual); } @Test public void testUsageSubcommandGitStatus_NoAnsi() { String actual = usageString(new Demo.GitStatus(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_GITSTATUS), actual); } @Test public void testUsageSubcommandGitStatus_ANSI() { String actual = usageString(new Demo.GitStatus(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_GITSTATUS_ANSI)), actual); } @Test public void testUsageSubcommandGitCommit_NoAnsi() { String actual = usageString(new Demo.GitCommit(), Ansi.OFF); assertEquals(String.format(Demo.EXPECTED_USAGE_GITCOMMIT), actual); } @Test public void testUsageSubcommandGitCommit_ANSI() { String actual = usageString(new Demo.GitCommit(), Ansi.ON); assertEquals(Ansi.ON.new Text(String.format(Demo.EXPECTED_USAGE_GITCOMMIT_ANSI)), actual); } @Test public void testTextConstructorPlain() { assertEquals("--NoAnsiFormat", Ansi.ON.new Text("--NoAnsiFormat").toString()); } @Test public void testTextConstructorWithStyle() { assertEquals("\u001B[1m--NoAnsiFormat\u001B[21m\u001B[0m", Ansi.ON.new Text("@|bold --NoAnsiFormat|@").toString()); } @Test public void testTextApply() { Ansi.Text txt = Ansi.ON.apply("--p", Arrays.<Ansi.IStyle>asList(Ansi.Style.fg_red, Ansi.Style.bold)); assertEquals(Ansi.ON.new Text("@|fg(red),bold --p|@"), txt); } @Test public void testTextDefaultColorScheme() { Ansi ansi = Ansi.ON; CommandLine.Help.ColorScheme scheme = CommandLine.Help.defaultColorScheme(ansi); assertEquals(scheme.ansi().new Text("@|yellow -p|@"), scheme.optionText("-p")); assertEquals(scheme.ansi().new Text("@|bold command|@"), scheme.commandText("command")); assertEquals(scheme.ansi().new Text("@|yellow FILE|@"), scheme.parameterText("FILE")); assertEquals(scheme.ansi().new Text("@|italic NUMBER|@"), scheme.optionParamText("NUMBER")); } @Test public void testTextSubString() { Ansi ansi = Ansi.ON; Ansi.Text txt = ansi.new Text("@|bold 01234|@").concat("56").concat("@|underline 7890|@"); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7890|@"), txt.substring(0)); assertEquals(ansi.new Text("@|bold 1234|@56@|underline 7890|@"), txt.substring(1)); assertEquals(ansi.new Text("@|bold 234|@56@|underline 7890|@"), txt.substring(2)); assertEquals(ansi.new Text("@|bold 34|@56@|underline 7890|@"), txt.substring(3)); assertEquals(ansi.new Text("@|bold 4|@56@|underline 7890|@"), txt.substring(4)); assertEquals(ansi.new Text("56@|underline 7890|@"), txt.substring(5)); assertEquals(ansi.new Text("6@|underline 7890|@"), txt.substring(6)); assertEquals(ansi.new Text("@|underline 7890|@"), txt.substring(7)); assertEquals(ansi.new Text("@|underline 890|@"), txt.substring(8)); assertEquals(ansi.new Text("@|underline 90|@"), txt.substring(9)); assertEquals(ansi.new Text("@|underline 0|@"), txt.substring(10)); assertEquals(ansi.new Text(""), txt.substring(11)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7890|@"), txt.substring(0, 11)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 789|@"), txt.substring(0, 10)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 78|@"), txt.substring(0, 9)); assertEquals(ansi.new Text("@|bold 01234|@56@|underline 7|@"), txt.substring(0, 8)); assertEquals(ansi.new Text("@|bold 01234|@56"), txt.substring(0, 7)); assertEquals(ansi.new Text("@|bold 01234|@5"), txt.substring(0, 6)); assertEquals(ansi.new Text("@|bold 01234|@"), txt.substring(0, 5)); assertEquals(ansi.new Text("@|bold 0123|@"), txt.substring(0, 4)); assertEquals(ansi.new Text("@|bold 012|@"), txt.substring(0, 3)); assertEquals(ansi.new Text("@|bold 01|@"), txt.substring(0, 2)); assertEquals(ansi.new Text("@|bold 0|@"), txt.substring(0, 1)); assertEquals(ansi.new Text(""), txt.substring(0, 0)); assertEquals(ansi.new Text("@|bold 1234|@56@|underline 789|@"), txt.substring(1, 10)); assertEquals(ansi.new Text("@|bold 234|@56@|underline 78|@"), txt.substring(2, 9)); assertEquals(ansi.new Text("@|bold 34|@56@|underline 7|@"), txt.substring(3, 8)); assertEquals(ansi.new Text("@|bold 4|@56"), txt.substring(4, 7)); assertEquals(ansi.new Text("5"), txt.substring(5, 6)); assertEquals(ansi.new Text("@|bold 2|@"), txt.substring(2, 3)); assertEquals(ansi.new Text("@|underline 8|@"), txt.substring(8, 9)); Ansi.Text txt2 = ansi.new Text("@|bold abc|@@|underline DEF|@"); assertEquals(ansi.new Text("@|bold abc|@@|underline DEF|@"), txt2.substring(0)); assertEquals(ansi.new Text("@|bold bc|@@|underline DEF|@"), txt2.substring(1)); assertEquals(ansi.new Text("@|bold abc|@@|underline DE|@"), txt2.substring(0,5)); assertEquals(ansi.new Text("@|bold bc|@@|underline DE|@"), txt2.substring(1,5)); } @Test public void testTextSplitLines() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("@|bold 012\n34|@").concat("5\nAA\n6").concat("@|underline 78\n90|@"), ansi.new Text("@|bold 012\r34|@").concat("5\rAA\r6").concat("@|underline 78\r90|@"), ansi.new Text("@|bold 012\r\n34|@").concat("5\r\nAA\r\n6").concat("@|underline 78\r\n90|@"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); } } @Test public void testTextSplitLinesStartEnd() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("\n@|bold 012\n34|@").concat("5\nAA\n6").concat("@|underline 78\n90|@\n"), ansi.new Text("\r@|bold 012\r34|@").concat("5\rAA\r6").concat("@|underline 78\r90|@\r"), ansi.new Text("\r\n@|bold 012\r\n34|@").concat("5\r\nAA\r\n6").concat("@|underline 78\r\n90|@\r\n"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); } } @Test public void testTextSplitLinesStartEndIntermediate() { Ansi ansi = Ansi.ON; Ansi.Text[] all = { ansi.new Text("\n@|bold 012\n\n\n34|@").concat("5\n\n\nAA\n\n\n6").concat("@|underline 78\n90|@\n"), ansi.new Text("\r@|bold 012\r\r\r34|@").concat("5\r\r\rAA\r\r\r6").concat("@|underline 78\r90|@\r"), ansi.new Text("\r\n@|bold 012\r\n\r\n\r\n34|@").concat("5\r\n\r\n\r\nAA\r\n\r\n\r\n6").concat("@|underline 78\r\n90|@\r\n"), }; for (Ansi.Text text : all) { Ansi.Text[] lines = text.splitLines(); int i = 0; assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 012|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("@|bold 34|@5"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("AA"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); assertEquals(ansi.new Text("6@|underline 78|@"), lines[i++]); assertEquals(ansi.new Text("@|underline 90|@"), lines[i++]); assertEquals(ansi.new Text(""), lines[i++]); } } @Test public void testTextHashCode() { Ansi ansi = Ansi.ON; assertEquals(ansi.new Text("a").hashCode(), ansi.new Text("a").hashCode()); assertNotEquals(ansi.new Text("a").hashCode(), ansi.new Text("b").hashCode()); } @Test public void testTextAppendString() { Ansi ansi = Ansi.ON; assertEquals(ansi.new Text("a").append("xyz"), ansi.new Text("a").concat("xyz")); } @Test public void testTextAppendText() { Ansi ansi = Ansi.ON; Ansi.Text xyz = ansi.new Text("xyz"); assertEquals(ansi.new Text("a").append(xyz), ansi.new Text("a").concat(xyz)); } @Test public void testStyleParseAllowsMissingClosingBrackets() { Ansi.IStyle whiteBg = Ansi.Style.parse("bg(white")[0]; assertEquals(Ansi.Style.bg_white.on(), whiteBg.on()); Ansi.IStyle blackFg = Ansi.Style.parse("fg(black")[0]; assertEquals(Ansi.Style.fg_black.on(), blackFg.on()); } @Test public void testColorSchemeDefaultConstructorHasAnsiAuto() { CommandLine.Help.ColorScheme colorScheme = new CommandLine.Help.ColorScheme(); assertEquals(Ansi.AUTO, colorScheme.ansi()); } @Test public void testCommandLine_printVersionInfo_printsArrayOfPlainTextStrings() { @CommandLine.Command(version = {"Versioned Command 1.0", "512-bit superdeluxe", "(c) 2017"}) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.OFF); String result = baos.toString(); assertEquals(String.format("Versioned Command 1.0%n512-bit superdeluxe%n(c) 2017%n"), result); } @Test public void testCommandLine_printVersionInfo_printsSingleStringWithMarkup() { @CommandLine.Command(version = "@|red 1.0|@") class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.ON); String result = baos.toString(); assertEquals(String.format("\u001B[31m1.0\u001B[39m\u001B[0m%n"), result); } @Test public void testCommandLine_printVersionInfo_printsArrayOfStringsWithMarkup() { @CommandLine.Command(version = { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@", "@|red,bg(white) (c) 2017|@" }) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), Ansi.ON); String result = baos.toString(); assertEquals(String.format("" + "\u001B[33mVersioned Command 1.0\u001B[39m\u001B[0m%n" + "\u001B[34mBuild 12345\u001B[39m\u001B[0m%n" + "\u001B[31m\u001B[47m(c) 2017\u001B[49m\u001B[39m\u001B[0m%n"), result); } @Test public void testCommandLine_printVersionInfo_formatsArguments() { @CommandLine.Command(version = {"First line %1$s", "Second line %2$s", "Third line %s %s"}) class Versioned {} ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, true); new CommandLine(new Versioned()).printVersionHelp(ps, Ansi.OFF, "VALUE1", "VALUE2", "VALUE3"); String result = baos.toString(); assertEquals(String.format("First line VALUE1%nSecond line VALUE2%nThird line VALUE1 VALUE2%n"), result); } @Test public void testCommandLine_printVersionInfo_withMarkupAndParameterContainingMarkup() { @CommandLine.Command(version = { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@%1$s", "@|red,bg(white) (c) 2017|@%2$s" }) class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } static class MarkupVersionProvider implements CommandLine.IVersionProvider { public String[] getVersion() { return new String[] { "@|yellow Versioned Command 1.0|@", "@|blue Build 12345|@%1$s", "@|red,bg(white) (c) 2017|@%2$s" }; } } @Test public void testCommandLine_printVersionInfo_fromAnnotation_withMarkupAndParameterContainingMarkup() { @CommandLine.Command(versionProvider = MarkupVersionProvider.class) class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } @Test public void testCommandLine_printVersionInfo_usesProviderIfBothProviderAndStaticVersionInfoExist() { @CommandLine.Command(versionProvider = MarkupVersionProvider.class, version = "static version is ignored") class Versioned {} CommandLine commandLine = new CommandLine(new Versioned()); verifyVersionWithMarkup(commandLine); } private void verifyVersionWithMarkup(CommandLine commandLine) { String[] args = {"@|bold VALUE1|@", "@|underline VALUE2|@", "VALUE3"}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, true); commandLine.printVersionHelp(ps, Ansi.ON, (Object[]) args); String result = baos.toString(); assertEquals(String.format("" + "\u001B[33mVersioned Command 1.0\u001B[39m\u001B[0m%n" + "\u001B[34mBuild 12345\u001B[39m\u001B[0m\u001B[1mVALUE1\u001B[21m\u001B[0m%n" + "\u001B[31m\u001B[47m(c) 2017\u001B[49m\u001B[39m\u001B[0m\u001B[4mVALUE2\u001B[24m\u001B[0m%n"), result); } @Test public void testAnsiIsWindowsDependsOnSystemProperty() { System.setProperty("os.name", "MMIX"); assertFalse(Ansi.isWindows()); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); System.setProperty("os.name", "Windows 10 build 12345"); assertTrue(Ansi.isWindows()); } @Test public void testAnsiIsXtermDependsOnEnvironmentVariable() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse(Ansi.isXterm()); environmentVariables.set("TERM", "random value"); assertFalse(Ansi.isXterm()); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isXterm()); environmentVariables.set("TERM", "xterm asfasfasf"); assertTrue(Ansi.isXterm()); } @Test public void testAnsiHasOstypeDependsOnEnvironmentVariable() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse(Ansi.hasOsType()); environmentVariables.set("OSTYPE", ""); assertTrue(Ansi.hasOsType()); environmentVariables.set("OSTYPE", "42"); assertTrue(Ansi.hasOsType()); } @Test public void testAnsiIsPseudoTtyDependsOnWindowsXtermOrOsType() { System.setProperty("os.name", "MMIX"); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("OSTYPE and XTERM are not set", Ansi.isPseudoTTY()); System.setProperty("os.name", "Windows 10 build 12345"); environmentVariables.set("OSTYPE", "222"); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isPseudoTTY()); System.setProperty("os.name", "MMIX"); assertFalse("Not Windows", Ansi.isPseudoTTY()); System.setProperty("os.name", "Windows 10 build 12345"); // restore assertTrue("restored", Ansi.isPseudoTTY()); environmentVariables.clear("OSTYPE"); assertTrue("Missing OSTYPE, but TERM=xterm", Ansi.isPseudoTTY()); environmentVariables.set("OSTYPE", "anything"); assertTrue("restored", Ansi.isPseudoTTY()); environmentVariables.clear("XTERM"); assertTrue("Missing XTERM, but OSTYPE defined", Ansi.isPseudoTTY()); } @Test public void testAnsiHintDisabledTrueIfCLICOLORZero() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", ""); assertFalse("Just defining CLICOLOR is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "1"); assertFalse("CLICOLOR=1 is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "false"); assertFalse("CLICOLOR=false is not enough", Ansi.hintDisabled()); environmentVariables.set("CLICOLOR", "0"); assertTrue("CLICOLOR=0 disables", Ansi.hintDisabled()); } @Test public void testAnsiHintDisabledTrueIfConEmuANSIisOFF() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", ""); assertFalse("Just defining ConEmuANSI is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "0"); assertFalse("ConEmuANSI=0 is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "false"); assertFalse("ConEmuANSI=false is not enough", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "off"); assertFalse("ConEmuANSI=off does not disable", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "Off"); assertFalse("ConEmuANSI=Off does not disable", Ansi.hintDisabled()); environmentVariables.set("ConEmuANSI", "OFF"); assertTrue("ConEmuANSI=OFF disables", Ansi.hintDisabled()); } @Test public void testAnsiHintEnbledTrueIfANSICONDefined() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("ANSICON", ""); assertTrue("ANSICON defined without value", Ansi.hintEnabled()); environmentVariables.set("ANSICON", "abc"); assertTrue("ANSICON defined any value", Ansi.hintEnabled()); } @Test public void testAnsiHintEnbledTrueIfCLICOLOROne() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", ""); assertFalse("Just defining CLICOLOR is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "0"); assertFalse("CLICOLOR=0 is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "true"); assertFalse("CLICOLOR=true is not enough", Ansi.hintEnabled()); environmentVariables.set("CLICOLOR", "1"); assertTrue("CLICOLOR=1 enables", Ansi.hintEnabled()); } @Test public void testAnsiHintEnabledTrueIfConEmuANSIisON() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", ""); assertFalse("Just defining ConEmuANSI is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "1"); assertFalse("ConEmuANSI=1 is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "true"); assertFalse("ConEmuANSI=true is not enough", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "on"); assertFalse("ConEmuANSI=on does not enables", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "On"); assertFalse("ConEmuANSI=On does not enables", Ansi.hintEnabled()); environmentVariables.set("ConEmuANSI", "ON"); assertTrue("ConEmuANSI=ON enables", Ansi.hintEnabled()); } @Test public void testAnsiForceEnabledTrueIfCLICOLOR_FORCEisDefinedAndNonZero() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", ""); assertTrue("Just defining CLICOLOR_FORCE is enough", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", "1"); assertTrue("CLICOLOR_FORCE=1 is enough", Ansi.forceEnabled()); environmentVariables.set("CLICOLOR_FORCE", "0"); assertFalse("CLICOLOR_FORCE=0 is not forced", Ansi.forceEnabled()); } @Test public void testAnsiForceDisabledTrueIfNO_COLORDefined() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); assertFalse("no env vars set", Ansi.forceDisabled()); environmentVariables.set("NO_COLOR", ""); assertTrue("NO_COLOR defined without value", Ansi.forceDisabled()); environmentVariables.set("NO_COLOR", "abc"); assertTrue("NO_COLOR defined any value", Ansi.forceDisabled()); } @Test public void testAnsiOnEnabled() { assertTrue(Ansi.ON.enabled()); } @Test public void testAnsiOffDisabled() { assertFalse(Ansi.OFF.enabled()); } @Test public void testAnsiAutoForceDisabledOverridesForceEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("NO_COLOR", ""); environmentVariables.set("CLICOLOR_FORCE", "1"); assertTrue(Ansi.forceDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse("forceDisabled overrides forceEnabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoForceDisabledOverridesHintEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("NO_COLOR", ""); environmentVariables.set("CLICOLOR", "1"); assertTrue(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertTrue(Ansi.hintEnabled()); assertFalse("forceDisabled overrides hintEnabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoForcedEnabledOverridesHintDisabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); environmentVariables.set("CLICOLOR_FORCE", "1"); assertFalse(Ansi.forceDisabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintEnabled()); assertTrue("forceEnabled overrides hintDisabled", Ansi.AUTO.enabled()); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("ConEmuANSI", "OFF"); environmentVariables.set("CLICOLOR_FORCE", "1"); assertFalse(Ansi.forceDisabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.forceEnabled()); assertFalse(Ansi.hintEnabled()); assertTrue("forceEnabled overrides hintDisabled 2", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoJansiConsoleInstalledOverridesHintDisabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); // hint disabled System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertTrue(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse(Ansi.isJansiConsoleInstalled()); AnsiConsole.systemInstall(); try { assertTrue(Ansi.isJansiConsoleInstalled()); assertTrue(Ansi.AUTO.enabled()); } finally { AnsiConsole.systemUninstall(); } } @Test public void testAnsiAutoHintDisabledOverridesHintEnabled() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("CLICOLOR", "0"); // hint disabled environmentVariables.set("ANSICON", "1"); // hint enabled System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); environmentVariables.set("TERM", "xterm"); // fake Cygwin assertTrue(Ansi.isPseudoTTY()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertTrue(Ansi.hintDisabled()); assertTrue(Ansi.hintEnabled()); assertFalse("Disabled overrides enabled", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoDisabledIfNoTty() { if (Ansi.isTTY()) { return; } // environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertFalse("Must have TTY if no JAnsi", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoEnabledIfNotWindows() { if (!Ansi.isTTY()) { return; } // needs TTY for this test environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "MMIX"); assertFalse(Ansi.isWindows()); assertFalse(Ansi.isPseudoTTY()); // TODO Mock this? assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); assertTrue("If have TTY, enabled on non-Windows", Ansi.AUTO.enabled()); } @Test public void testAnsiAutoEnabledIfWindowsPseudoTTY() { environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); System.setProperty("os.name", "Windows"); assertTrue(Ansi.isWindows()); assertFalse(Ansi.isJansiConsoleInstalled()); assertFalse(Ansi.forceDisabled()); assertFalse(Ansi.forceEnabled()); assertFalse(Ansi.hintDisabled()); assertFalse(Ansi.hintEnabled()); environmentVariables.set("TERM", "xterm"); assertTrue(Ansi.isPseudoTTY()); assertTrue("If have Cygwin pseudo-TTY, enabled on Windows", Ansi.AUTO.enabled()); environmentVariables.clear(ANSI_ENVIRONMENT_VARIABLES); environmentVariables.set("OSTYPE", "Windows"); assertTrue(Ansi.isPseudoTTY()); assertTrue("If have MSYS pseudo-TTY, enabled on Windows", Ansi.AUTO.enabled()); } }
[#581] add tests for system property "picocli.ansi"
src/test/java/picocli/CommandLineHelpAnsiTest.java
[#581] add tests for system property "picocli.ansi"
Java
apache-2.0
ce845d5392bffe3721a00785203494f6396bd6ab
0
chasegawa/uPortal,GIP-RECIA/esup-uportal,MichaelVose2/uPortal,groybal/uPortal,groybal/uPortal,bjagg/uPortal,stalele/uPortal,drewwills/uPortal,joansmith/uPortal,Jasig/SSP-Platform,ChristianMurphy/uPortal,GIP-RECIA/esup-uportal,Jasig/uPortal-start,ChristianMurphy/uPortal,andrewstuart/uPortal,timlevett/uPortal,doodelicious/uPortal,jameswennmacher/uPortal,MichaelVose2/uPortal,joansmith/uPortal,jhelmer-unicon/uPortal,ASU-Capstone/uPortal,kole9273/uPortal,pspaude/uPortal,bjagg/uPortal,EdiaEducationTechnology/uPortal,bjagg/uPortal,EdiaEducationTechnology/uPortal,Jasig/uPortal,cousquer/uPortal,jhelmer-unicon/uPortal,andrewstuart/uPortal,Jasig/uPortal-start,Jasig/SSP-Platform,Jasig/SSP-Platform,jameswennmacher/uPortal,cousquer/uPortal,mgillian/uPortal,timlevett/uPortal,jl1955/uPortal5,ChristianMurphy/uPortal,GIP-RECIA/esup-uportal,jhelmer-unicon/uPortal,mgillian/uPortal,doodelicious/uPortal,GIP-RECIA/esco-portail,jameswennmacher/uPortal,jhelmer-unicon/uPortal,jonathanmtran/uPortal,vertein/uPortal,pspaude/uPortal,ASU-Capstone/uPortal-Forked,GIP-RECIA/esco-portail,drewwills/uPortal,groybal/uPortal,ASU-Capstone/uPortal-Forked,vertein/uPortal,andrewstuart/uPortal,jonathanmtran/uPortal,GIP-RECIA/esup-uportal,chasegawa/uPortal,doodelicious/uPortal,EdiaEducationTechnology/uPortal,ASU-Capstone/uPortal,stalele/uPortal,ASU-Capstone/uPortal-Forked,kole9273/uPortal,Mines-Albi/esup-uportal,andrewstuart/uPortal,Jasig/uPortal,stalele/uPortal,Jasig/SSP-Platform,Mines-Albi/esup-uportal,timlevett/uPortal,GIP-RECIA/esup-uportal,joansmith/uPortal,ASU-Capstone/uPortal-Forked,apetro/uPortal,doodelicious/uPortal,kole9273/uPortal,vbonamy/esup-uportal,kole9273/uPortal,MichaelVose2/uPortal,pspaude/uPortal,jonathanmtran/uPortal,phillips1021/uPortal,jameswennmacher/uPortal,mgillian/uPortal,andrewstuart/uPortal,jl1955/uPortal5,ASU-Capstone/uPortal-Forked,apetro/uPortal,vbonamy/esup-uportal,apetro/uPortal,jl1955/uPortal5,Jasig/SSP-Platform,doodelicious/uPortal,chasegawa/uPortal,EsupPortail/esup-uportal,apetro/uPortal,vertein/uPortal,joansmith/uPortal,EsupPortail/esup-uportal,pspaude/uPortal,EsupPortail/esup-uportal,vertein/uPortal,apetro/uPortal,GIP-RECIA/esco-portail,stalele/uPortal,Jasig/uPortal,EsupPortail/esup-uportal,timlevett/uPortal,groybal/uPortal,joansmith/uPortal,chasegawa/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal,groybal/uPortal,kole9273/uPortal,jhelmer-unicon/uPortal,drewwills/uPortal,phillips1021/uPortal,ASU-Capstone/uPortal,jl1955/uPortal5,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,phillips1021/uPortal,drewwills/uPortal,cousquer/uPortal,Mines-Albi/esup-uportal,vbonamy/esup-uportal,phillips1021/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal,Mines-Albi/esup-uportal,phillips1021/uPortal,stalele/uPortal,MichaelVose2/uPortal,vbonamy/esup-uportal,jl1955/uPortal5,EsupPortail/esup-uportal,vbonamy/esup-uportal,chasegawa/uPortal
/** * Copyright 2001 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.services.entityproperties; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Timestamp; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.RDBMServices; import org.jasig.portal.concurrency.CachingException; import org.jasig.portal.services.EntityCachingService; import org.jasig.portal.services.LogService; import org.jasig.portal.services.EntityPropertyRegistry; /** * A portal RDBM based entity property store implementation * * @author Alex Vigdor av317@columbia.edu * @version $Revision$ */ public class RDBMPropertyStore implements IEntityPropertyStore { protected static Class propsType = null; protected final static String TABLE_NAME = "UP_ENTITY_PROP"; protected final static String TYPE_COL = "ENTITY_TYPE_ID"; protected final static String KEY_COL = "ENTITY_KEY"; protected final static String NAME_COL = "PROPERTY_NAME"; protected final static String VALUE_COL = "PROPERTY_VALUE"; protected final static String DATE_COL = "LAST_MODIFIED"; protected final static String selectProperties = "SELECT " + NAME_COL + ", " + VALUE_COL + " FROM " + TABLE_NAME + " WHERE " + TYPE_COL + "=? AND " + KEY_COL + "=?"; protected final static String deleteProperty = "DELETE FROM " + TABLE_NAME + " WHERE " + TYPE_COL + "=? AND " + KEY_COL + "=? AND " + NAME_COL + "=?"; protected final static String insertProperty = "INSERT INTO " + TABLE_NAME + " VALUES (?,?,?,?,?)"; public RDBMPropertyStore() { try{ if (propsType == null){ propsType = Class.forName("org.jasig.portal.services.entityproperties.EntityProperties"); } } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.Constructor Unable to create propstype"); LogService.log(LogService.ERROR, e); } } public String[] getPropertyNames(EntityIdentifier entityID) { String[] propNames = null; EntityProperties ep = getCachedProperties(entityID); if (ep != null) { propNames = ep.getPropertyNames(); } return propNames; } public String getProperty(EntityIdentifier entityID, String name) { String propVal = null; EntityProperties ep = getCachedProperties(entityID); if (ep != null) { propVal = ep.getProperty(name); } return propVal; } public void storeProperty(EntityIdentifier entityID, String name, String value) { this.unStoreProperty(entityID, name); Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, insertProperty); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ps.setString(3, name); ps.setString(4, value); ps.setTimestamp(5, new Timestamp(System.currentTimeMillis())); int i = ps.executeUpdate(); //System.out.println(i+" "+ps.toString()); ps.close(); clearCache(entityID); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.storeProperty " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } public void unStoreProperty(EntityIdentifier entityID, String name) { Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, deleteProperty); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ps.setString(3, name); int i = ps.executeUpdate(); //System.out.println(i+" "+ps.toString()); ps.close(); clearCache(entityID); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.unStoreProperty " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } protected Connection getConnection() { return RDBMServices.getConnection(); } protected void releaseConnection(Connection conn) { RDBMServices.releaseConnection(conn); } protected EntityProperties getCachedProperties(EntityIdentifier entityID) { EntityProperties ep = EntityPropertyRegistry.instance().getCachedProperties(entityID); if (ep == null) { ep = new EntityProperties(entityID.getKey()); Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, selectProperties); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ResultSet rs = ps.executeQuery(); while (rs.next()) { ep.setProperty(rs.getString(NAME_COL), rs.getString(VALUE_COL)); } addToCache(ep); rs.close(); ps.close(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.getPropertyNames: " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } return ep; } protected void clearCache(EntityIdentifier entityID) { EntityPropertyRegistry.instance().clearCache(entityID); } protected void addToCache(EntityProperties ep) { EntityPropertyRegistry.instance().addToCache(ep); } }
source/org/jasig/portal/services/entityproperties/RDBMPropertyStore.java
/** * Copyright 2001 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.services.entityproperties; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Timestamp; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.RDBMServices; import org.jasig.portal.concurrency.CachingException; import org.jasig.portal.services.EntityCachingService; import org.jasig.portal.services.LogService; /** * A portal RDBM based entity property store implementation * * @author Alex Vigdor av317@columbia.edu * @version $Revision$ */ public class RDBMPropertyStore implements IEntityPropertyStore { protected static Class propsType = null; protected final static String TABLE_NAME = "UP_ENTITY_PROP"; protected final static String TYPE_COL = "ENTITY_TYPE_ID"; protected final static String KEY_COL = "ENTITY_KEY"; protected final static String NAME_COL = "PROPERTY_NAME"; protected final static String VALUE_COL = "PROPERTY_VALUE"; protected final static String DATE_COL = "LAST_MODIFIED"; protected final static String selectProperties = "SELECT " + NAME_COL + ", " + VALUE_COL + " FROM " + TABLE_NAME + " WHERE " + TYPE_COL + "=? AND " + KEY_COL + "=?"; protected final static String deleteProperty = "DELETE FROM " + TABLE_NAME + " WHERE " + TYPE_COL + "=? AND " + KEY_COL + "=? AND " + NAME_COL + "=?"; protected final static String insertProperty = "INSERT INTO " + TABLE_NAME + " VALUES (?,?,?,?,?)"; public RDBMPropertyStore() { try{ if (propsType == null){ propsType = Class.forName("org.jasig.portal.services.entityproperties.EntityProperties"); } } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.Constructor Unable to create propstype"); LogService.log(LogService.ERROR, e); } } public String[] getPropertyNames(EntityIdentifier entityID) { String[] propNames = null; EntityProperties ep = getCachedProperties(entityID); if (ep != null) { propNames = ep.getPropertyNames(); } return propNames; } public String getProperty(EntityIdentifier entityID, String name) { String propVal = null; EntityProperties ep = getCachedProperties(entityID); if (ep != null) { propVal = ep.getProperty(name); } return propVal; } public void storeProperty(EntityIdentifier entityID, String name, String value) { this.unStoreProperty(entityID, name); Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, insertProperty); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ps.setString(3, name); ps.setString(4, value); ps.setTimestamp(5, new Timestamp(System.currentTimeMillis())); int i = ps.executeUpdate(); //System.out.println(i+" "+ps.toString()); ps.close(); clearCache(entityID); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.storeProperty " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } public void unStoreProperty(EntityIdentifier entityID, String name) { Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, deleteProperty); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ps.setString(3, name); int i = ps.executeUpdate(); //System.out.println(i+" "+ps.toString()); ps.close(); clearCache(entityID); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.unStoreProperty " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } protected Connection getConnection() { return RDBMServices.getConnection(); } protected void releaseConnection(Connection conn) { RDBMServices.releaseConnection(conn); } protected EntityProperties getCachedProperties(EntityIdentifier entityID) { EntityProperties ep = null; try { ep = (EntityProperties) EntityCachingService.instance().get(propsType, entityID.getKey()); } catch (CachingException e) { LogService.log(LogService.ERROR, e); Exception ee = e.getRecordedException(); if (ee != null) { LogService.log(LogService.ERROR, ee); } } if (ep == null) { ep = new EntityProperties(entityID.getKey()); Connection conn = null; RDBMServices.PreparedStatement ps = null; try { conn = this.getConnection(); ps = new RDBMServices.PreparedStatement(conn, selectProperties); ps.clearParameters(); ps.setInt(1, org.jasig.portal.EntityTypes.getEntityTypeID(entityID.getType()).intValue()); ps.setString(2, entityID.getKey()); ResultSet rs = ps.executeQuery(); while (rs.next()) { ep.setProperty(rs.getString(NAME_COL), rs.getString(VALUE_COL)); } addToCache(ep); rs.close(); ps.close(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMPropertyStore.getPropertyNames: " + ps); LogService.log(LogService.ERROR, e); } finally { this.releaseConnection(conn); } } return ep; } protected void clearCache(EntityIdentifier entityID) { try { EntityCachingService.instance().remove(entityID.getType(), entityID.getKey()); } catch (CachingException e) { LogService.log(LogService.ERROR, e); Exception ee = e.getRecordedException(); if (ee != null) { LogService.log(LogService.ERROR, ee); } } } protected void addToCache(EntityProperties ep) { try { EntityCachingService.instance().add(ep); } catch (CachingException e) { LogService.log(LogService.ERROR, e); Exception ee = e.getRecordedException(); if (ee != null) { LogService.log(LogService.ERROR, ee); } } } }
Uses the caching methods provided by the EntityPropertyRegistry class. git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@7549 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/services/entityproperties/RDBMPropertyStore.java
Uses the caching methods provided by the EntityPropertyRegistry class.
Java
apache-2.0
af99fc912ed73959293275f6d891fb7fe7a96be0
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* JSPWiki - a JSP-based WikiWiki clone. 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.ecyrd.jspwiki; import org.apache.commons.lang.StringUtils; /** * Contains release and version information. You may also invoke this * class directly, in which case it prints out the version string. This * is a handy way of checking which JSPWiki version you have - just type * from a command line: * <pre> * % java -cp JSPWiki.jar com.ecyrd.jspwiki.Release * 2.5.38 * </pre> * <p> * As a historical curiosity, this is the oldest JSPWiki file. According * to the CVS history, it dates from 6.7.2001, and it really hasn't changed * much since. * </p> * @since 1.0 */ public final class Release { private static final String VERSION_SEPARATORS = ".-"; /** * This is the default application name. */ public static final String APPNAME = "JSPWiki"; /** * This should be empty when doing a release - otherwise * keep it as "cvs" so that whenever someone checks out the code, * they know it is a bleeding-edge version. Other possible * values are "alpha" and "beta" for alpha and beta versions, * respectively. * <p> * If the POSTFIX is empty, it is not added to the version string. */ private static final String POSTFIX = "beta"; /** The JSPWiki major version. */ public static final int VERSION = 2; /** The JSPWiki revision. */ public static final int REVISION = 8; /** The minor revision. */ public static final int MINORREVISION = 0; /** The build number/identifier. This is a String as opposed to an integer, just * so that people can add other identifiers to it. The build number is incremented * every time a committer checks in code, and reset when the a release is made. * <p> * If you are a person who likes to build his own releases, we recommend that you * add your initials to this identifier (e.g. "13-jj", or 49-aj"). * <p> * If the build identifier is empty, it is not added. */ public static final String BUILD = "1"; /** * This is the generic version string you should use * when printing out the version. It is of the form "VERSION.REVISION.MINORREVISION[-POSTFIX][-BUILD]". */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : "") + ((BUILD.length() != 0 ? "-"+BUILD : "")); /** * Private constructor prevents instantiation. */ private Release() {} /** * This method is useful for templates, because hopefully it will * not be inlined, and thus any change to version number does not * need recompiling the pages. * * @since 2.1.26. * @return The version string (e.g. 2.5.23). */ public static String getVersionString() { return VERSTR; } /** * Returns true, if this version of JSPWiki is newer or equal than what is requested. * @param version A version parameter string (a.b.c-something). B and C are optional. * @return A boolean value describing whether the given version is newer than the current JSPWiki. * @since 2.4.57 * @throws IllegalArgumentException If the version string could not be parsed. */ public static boolean isNewerOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION > reqMinorRevision; } return REVISION > reqRevision; } return VERSION > reqVersion; } /** * Returns true, if this version of JSPWiki is older or equal than what is requested. * @param version A version parameter string (a.b.c-something) * @return A boolean value describing whether the given version is older than the current JSPWiki version * @since 2.4.57 * @throws IllegalArgumentException If the version string could not be parsed. */ public static boolean isOlderOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION < reqMinorRevision; } return REVISION < reqRevision; } return VERSION < reqVersion; } /** * Executing this class directly from command line prints out * the current version. It is very useful for things like * different command line tools. * <P>Example: * <PRE> * % java com.ecyrd.jspwiki.Release * 1.9.26-cvs * </PRE> * * @param argv The argument string. This class takes in no arguments. */ public static void main( String[] argv ) { System.out.println(VERSTR); } }
src/com/ecyrd/jspwiki/Release.java
/* JSPWiki - a JSP-based WikiWiki clone. 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.ecyrd.jspwiki; import org.apache.commons.lang.StringUtils; /** * Contains release and version information. You may also invoke this * class directly, in which case it prints out the version string. This * is a handy way of checking which JSPWiki version you have - just type * from a command line: * <pre> * % java -cp JSPWiki.jar com.ecyrd.jspwiki.Release * 2.5.38 * </pre> * <p> * As a historical curiosity, this is the oldest JSPWiki file. According * to the CVS history, it dates from 6.7.2001, and it really hasn't changed * much since. * </p> * @since 1.0 */ public final class Release { private static final String VERSION_SEPARATORS = ".-"; /** * This is the default application name. */ public static final String APPNAME = "JSPWiki"; /** * This should be empty when doing a release - otherwise * keep it as "cvs" so that whenever someone checks out the code, * they know it is a bleeding-edge version. Other possible * values are "alpha" and "beta" for alpha and beta versions, * respectively. * <p> * If the POSTFIX is empty, it is not added to the version string. */ private static final String POSTFIX = "alpha"; /** The JSPWiki major version. */ public static final int VERSION = 2; /** The JSPWiki revision. */ public static final int REVISION = 7; /** The minor revision. */ public static final int MINORREVISION = 0; /** The build number/identifier. This is a String as opposed to an integer, just * so that people can add other identifiers to it. The build number is incremented * every time a committer checks in code, and reset when the a release is made. * <p> * If you are a person who likes to build his own releases, we recommend that you * add your initials to this identifier (e.g. "13-jj", or 49-aj"). * <p> * If the build identifier is empty, it is not added. */ public static final String BUILD = "37"; /** * This is the generic version string you should use * when printing out the version. It is of the form "VERSION.REVISION.MINORREVISION[-POSTFIX][-BUILD]". */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+ ((POSTFIX.length() != 0 ) ? "-"+POSTFIX : "") + ((BUILD.length() != 0 ? "-"+BUILD : "")); /** * Private constructor prevents instantiation. */ private Release() {} /** * This method is useful for templates, because hopefully it will * not be inlined, and thus any change to version number does not * need recompiling the pages. * * @since 2.1.26. * @return The version string (e.g. 2.5.23). */ public static String getVersionString() { return VERSTR; } /** * Returns true, if this version of JSPWiki is newer or equal than what is requested. * @param version A version parameter string (a.b.c-something). B and C are optional. * @return A boolean value describing whether the given version is newer than the current JSPWiki. * @since 2.4.57 * @throws IllegalArgumentException If the version string could not be parsed. */ public static boolean isNewerOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION > reqMinorRevision; } return REVISION > reqRevision; } return VERSION > reqVersion; } /** * Returns true, if this version of JSPWiki is older or equal than what is requested. * @param version A version parameter string (a.b.c-something) * @return A boolean value describing whether the given version is older than the current JSPWiki version * @since 2.4.57 * @throws IllegalArgumentException If the version string could not be parsed. */ public static boolean isOlderOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION < reqMinorRevision; } return REVISION < reqRevision; } return VERSION < reqVersion; } /** * Executing this class directly from command line prints out * the current version. It is very useful for things like * different command line tools. * <P>Example: * <PRE> * % java com.ecyrd.jspwiki.Release * 1.9.26-cvs * </PRE> * * @param argv The argument string. This class takes in no arguments. */ public static void main( String[] argv ) { System.out.println(VERSTR); } }
git-svn-id: https://svn.apache.org/repos/asf/incubator/jspwiki/trunk@692359 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/Release.java
Java
apache-2.0
5a4b765e24f89280bc56551133e97224eb324550
0
rogerchina/undertow,marschall/undertow,n1hility/undertow,soul2zimate/undertow,golovnin/undertow,pedroigor/undertow,Karm/undertow,undertow-io/undertow,rhatlapa/undertow,rogerchina/undertow,nkhuyu/undertow,TomasHofman/undertow,jasonchaffee/undertow,jstourac/undertow,TomasHofman/undertow,darranl/undertow,pedroigor/undertow,msfm/undertow,popstr/undertow,n1hility/undertow,aradchykov/undertow,jamezp/undertow,ctomc/undertow,soul2zimate/undertow,biddyweb/undertow,aldaris/undertow,ctomc/undertow,baranowb/undertow,wildfly-security-incubator/undertow,jasonchaffee/undertow,Karm/undertow,rhatlapa/undertow,darranl/undertow,jstourac/undertow,yonglehou/undertow,darranl/undertow,jasonchaffee/undertow,jamezp/undertow,pferraro/undertow,baranowb/undertow,TomasHofman/undertow,aradchykov/undertow,popstr/undertow,jamezp/undertow,grassjedi/undertow,n1hility/undertow,ctomc/undertow,rogerchina/undertow,amannm/undertow,aldaris/undertow,popstr/undertow,amannm/undertow,grassjedi/undertow,undertow-io/undertow,yonglehou/undertow,golovnin/undertow,biddyweb/undertow,undertow-io/undertow,rhusar/undertow,wildfly-security-incubator/undertow,grassjedi/undertow,stuartwdouglas/undertow,aldaris/undertow,nkhuyu/undertow,nkhuyu/undertow,biddyweb/undertow,rhusar/undertow,jstourac/undertow,msfm/undertow,marschall/undertow,pferraro/undertow,golovnin/undertow,soul2zimate/undertow,aradchykov/undertow,yonglehou/undertow,marschall/undertow,stuartwdouglas/undertow,amannm/undertow,baranowb/undertow,rhusar/undertow,stuartwdouglas/undertow,pedroigor/undertow,wildfly-security-incubator/undertow,Karm/undertow,msfm/undertow,pferraro/undertow,rhatlapa/undertow
package io.undertow.server.handlers; import io.undertow.Handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DefaultServer.class) public class ExceptionHandlerTestCase { @Test public void testExceptionMappers() throws IOException { HttpHandler pathHandler = Handlers.path() .addExactPath("/", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("expected"); } }) .addExactPath("/exceptionParent", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new ParentException(); } }) .addExactPath("/exceptionChild", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new ChildException(); } }) .addExactPath("/exceptionAnotherChild", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new AnotherChildException(); } }) .addExactPath("/illegalArgumentException", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new IllegalArgumentException(); } }); HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler) .addExceptionHandler(ChildException.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("child exception handled"); } }) .addExceptionHandler(ParentException.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("parent exception handled"); } }) .addExceptionHandler(Throwable.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("catch all throwables"); } }); DefaultServer.setRootHandler(exceptionHandler); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/"); HttpResponse result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("expected", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionParent"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("parent exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionChild"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("child exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionAnotherChild"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("parent exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/illegalArgumentException"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("catch all throwables", HttpClientUtils.readResponse(result)); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReThrowUnmatchedException() throws IOException { HttpHandler pathHandler = Handlers.path() .addExactPath("/", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new IllegalArgumentException(); } }); // intentionally not adding any exception handlers final HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler); DefaultServer.setRootHandler(new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { Throwable throwable = exchange.getAttachment(ExceptionHandler.THROWABLE); Assert.assertNull(throwable); exceptionHandler.handleRequest(exchange); throwable = exchange.getAttachment(ExceptionHandler.THROWABLE); Assert.assertTrue(throwable instanceof IllegalArgumentException); } }); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/"); HttpResponse result = client.execute(get); Assert.assertEquals(500, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } } private static class ParentException extends Exception {} private static class ChildException extends ParentException {} private static class AnotherChildException extends ParentException {} }
core/src/test/java/io/undertow/server/handlers/ExceptionHandlerTestCase.java
package io.undertow.server.handlers; import io.undertow.Handlers; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpClientUtils; import io.undertow.testutils.TestHttpClient; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DefaultServer.class) public class ExceptionHandlerTestCase { @Test public void testExceptionMappers() throws IOException { HttpHandler pathHandler = Handlers.path() .addExactPath("/", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("expected"); } }) .addExactPath("/exceptionParent", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new ParentException(); } }) .addExactPath("/exceptionChild", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new ChildException(); } }) .addExactPath("/exceptionAnotherChild", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new AnotherChildException(); } }) .addExactPath("/illegalArgumentException", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new IllegalArgumentException(); } }); HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler) .addExceptionHandler(ChildException.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("child exception handled"); } }) .addExceptionHandler(ParentException.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("parent exception handled"); } }) .addExceptionHandler(Throwable.class, new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send("catch all throwables"); } }); DefaultServer.setRootHandler(exceptionHandler); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/"); HttpResponse result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("expected", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionParent"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("parent exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionChild"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("child exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/exceptionAnotherChild"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("parent exception handled", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/illegalArgumentException"); result = client.execute(get); Assert.assertEquals(200, result.getStatusLine().getStatusCode()); Assert.assertEquals("catch all throwables", HttpClientUtils.readResponse(result)); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReThrowUnmatchedException() throws IOException { HttpHandler pathHandler = Handlers.path() .addExactPath("/", new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { throw new IllegalArgumentException(); } }); // intentionally not adding any exception handlers HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler); DefaultServer.setRootHandler(exceptionHandler); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/"); HttpResponse result = client.execute(get); Assert.assertEquals(500, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } } private static class ParentException extends Exception {} private static class ChildException extends ParentException {} private static class AnotherChildException extends ParentException {} }
Test that the throwable attachment gets set on the ExceptionHandler
core/src/test/java/io/undertow/server/handlers/ExceptionHandlerTestCase.java
Test that the throwable attachment gets set on the ExceptionHandler
Java
apache-2.0
32d1f8330304641c85f61bc5ba85f795f89f743e
0
jsbaidwan/QuakeReport
/* * Copyright (C) 2016 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.quakereport; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.ArrayList; public class EarthquakeActivity extends AppCompatActivity { //public static final String LOG_TAG = EarthquakeActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.earthquake_activity); // Create a fake list of earthquake locations. ArrayList<Earthquake> earthquakes = new ArrayList<>(); earthquakes.add(new Earthquake ("3.1", "San Francisco", "Jul 4, 2017")); earthquakes.add(new Earthquake ("5.3", "London","Aug 8, 2016")); earthquakes.add(new Earthquake ("7.6", "Tokyo", "Feb 14, 2017")); earthquakes.add(new Earthquake ("2.8", "Mexico City", "May 4, 2017")); earthquakes.add(new Earthquake ("5.5", "Moscow", "Mar 17, 2017")); earthquakes.add(new Earthquake ("3.7", "Paris", "May 24, 2017")); earthquakes.add(new Earthquake ("1.8", "Calgary", "June 04, 2017")); earthquakes.add(new Earthquake ("6.8", "New Delhi", "July 25, 2017")); // Create an {@link EarthquakeAdapter}, whose data source is a list of // {@link Earthquake}s. The adapter knows how to create list item views for each item // in the list. EarthquakeAdapter adapter = new EarthquakeAdapter(this, earthquakes); // Find a reference to the {@link ListView} in the layout ListView earthquakeListView = (ListView) findViewById(R.id.list); // Set the adapter on the {@link ListView} // so the list can be populated in the user interface earthquakeListView.setAdapter(adapter); } }
app/src/main/java/com/example/android/quakereport/EarthquakeActivity.java
/* * Copyright (C) 2016 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.quakereport; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class EarthquakeActivity extends AppCompatActivity { //public static final String LOG_TAG = EarthquakeActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.earthquake_activity); // Create a fake list of earthquake locations. ArrayList<Earthquake> earthquakes = new ArrayList<>(); earthquakes.add(new Earthquake("3.1", "San Francisco", "Jul 4, 2017")); earthquakes.add(new Earthquake ("5.3", "London","Aug 8, 2016")); earthquakes.add(new Earthquake ("7.6", "Tokyo", "Feb 14, 2017")); earthquakes.add(new Earthquake ("2.8", "Mexico City", "May 4, 2017")); earthquakes.add(new Earthquake ("5.5", "Moscow", "Mar 17, 2017")); earthquakes.add(new Earthquake ("3.7", "Paris", "May 24, 2017")); earthquakes.add(new Earthquake ("1.8", "Calgary", "June 04, 2017")); // Create an {@link EarthquakeAdapter}, whose data source is a list of // {@link Earthquake}s. The adapter knows how to create list item views for each item // in the list. EarthquakeAdapter adapter = new EarthquakeAdapter(this, earthquakes); // Find a reference to the {@link ListView} in the layout ListView earthquakeListView = (ListView) findViewById(R.id.list); // Set the adapter on the {@link ListView} // so the list can be populated in the user interface earthquakeListView.setAdapter(adapter); } }
ADD: city to the list
app/src/main/java/com/example/android/quakereport/EarthquakeActivity.java
ADD: city to the list
Java
apache-2.0
554c8f6b93fb9d1cf5ef92054750b6e8657ddc53
0
meltmedia/cadmium,meltmedia/cadmium,meltmedia/cadmium,meltmedia/cadmium,meltmedia/cadmium
/** * Copyright 2012 meltmedia * * 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.meltmedia.cadmium.deployer; import java.io.File; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.Slf4JLoggerFactory; import com.google.inject.AbstractModule; import com.meltmedia.cadmium.core.CadmiumModule; import com.meltmedia.cadmium.maven.ArtifactResolver; import com.meltmedia.cadmium.servlets.guice.CadmiumListener; /** * A Guice module that binds an instance of ArtifactResolver from the maven project. * * @see <a href="http://code.google.com/p/google-guice/">Google Guice</a> * * @author John McEntire * */ @CadmiumModule public class DeployerModule extends AbstractModule { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * The System Property key to set the remote maven repository. <code>(com.meltmedia.cadmium.maven.repository)</code> */ public static final String MAVEN_REPOSITORY = "com.meltmedia.cadmium.maven.repository"; /** * Called to do all bindings for this module. * * @see <a href="http://code.google.com/p/google-guice/">Google Guice</a> */ @Override protected void configure() { try { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } } }
deployer/src/main/java/com/meltmedia/cadmium/deployer/DeployerModule.java
/** * Copyright 2012 meltmedia * * 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.meltmedia.cadmium.deployer; import java.io.File; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.meltmedia.cadmium.core.CadmiumModule; import com.meltmedia.cadmium.maven.ArtifactResolver; import com.meltmedia.cadmium.servlets.guice.CadmiumListener; /** * A Guice module that binds an instance of ArtifactResolver from the maven project. * * @see <a href="http://code.google.com/p/google-guice/">Google Guice</a> * * @author John McEntire * */ @CadmiumModule public class DeployerModule extends AbstractModule { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * The System Property key to set the remote maven repository. <code>(com.meltmedia.cadmium.maven.repository)</code> */ public static final String MAVEN_REPOSITORY = "com.meltmedia.cadmium.maven.repository"; /** * Called to do all bindings for this module. * * @see <a href="http://code.google.com/p/google-guice/">Google Guice</a> */ @Override protected void configure() { try { File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } } }
Fixed logging issue in deployer
deployer/src/main/java/com/meltmedia/cadmium/deployer/DeployerModule.java
Fixed logging issue in deployer
Java
apache-2.0
d10da75bd3a4d8a5293992d7efc0fa638e6b379c
0
atomix/atomix,kuujo/copycat,atomix/atomix,kuujo/copycat
/* * Copyright 2017-present Open Networking 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 io.atomix.cluster.messaging; import java.util.concurrent.CompletableFuture; /** * {@link ClusterEventService} subscription context. * <p> * The subscription represents a node's subscription to a specific topic. A {@code Subscription} instance is returned * once an {@link ClusterEventService} subscription has been propagated. The subscription context can be used to * unsubscribe the node from the given {@link #topic()} by calling {@link #close()}. */ public interface Subscription { /** * Returns the subscription topic. * * @return the topic to which the subscriber is subscribed */ String topic(); /** * Closes the subscription, causing it to be unregistered. * <p> * When the subscription is closed, the subscriber will be unregistered and the change will be propagated to all * the members of the cluster. The returned future will be completed once the change has been propagated to all nodes. * * @return a future to be completed once the subscription has been closed */ CompletableFuture<Void> close(); }
cluster/src/main/java/io/atomix/cluster/messaging/Subscription.java
/* * Copyright 2017-present Open Networking 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 io.atomix.cluster.messaging; import java.util.concurrent.CompletableFuture; /** * Message subscription. */ public interface Subscription { /** * Returns the subscription topic. * * @return the subscription topic */ String topic(); /** * Closes the subscription, causing it to be unregistered. * * @return a future to be completed once the subscription has been closed */ CompletableFuture<Void> close(); }
Add subscription documentation.
cluster/src/main/java/io/atomix/cluster/messaging/Subscription.java
Add subscription documentation.
Java
bsd-3-clause
9bb4a1288428c194b2da8a0b1f45c9454bde85f8
0
lrytz/asm,lrytz/asm
/** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000,2002,2003 INRIA, France Telecom * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.objectweb.asm.attrs; import java.util.ArrayList; import java.util.List; import org.objectweb.asm.ByteVector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * Annotation data contains an annotated type and its array of the element-value * pairs. Structure is in the following format: * <pre> * annotation { * u2 type_index; * u2 num_element_value_pairs; * { * u2 element_name_index; * element_value value; * } element_value_pairs[num_element_value_pairs]; * } * </pre> * The items of the annotation structure are as follows: * <dl> * <dt>type_index</dt> * <dd>The value of the type_index item must be a valid index into the constant_pool * table. The constant_pool entry at that index must be a CONSTANT_Utf8_info * structure representing a field descriptor representing the annotation * interface corresponding to the annotation represented by this annotation * structure.</dd> * <dt>num_element_value_pairs</dt> * <dd>The value of the num_element_value_pairs item gives the number of element-value * pairs in the annotation represented by this annotation structure. Note that a * maximum of 65535 element-value pairs may be contained in a single annotation.</dd> * <dt>element_value_pairs</dt> * <dd>Each value of the element_value_pairs table represents a single element-value * pair in the annotation represented by this annotation structure. * Each element_value_pairs entry contains the following two items: * <dt>element_name_index</dt> * <dd>The value of the element_name_index item must be a valid index into the * constant_pool table. The constant_pool entry at that index must be a * CONSTANT_Utf8_info structure representing the name of the annotation type * element corresponding to this element_value_pairs entry.</dd> * <dt>value</dt> * <dd>The value item represents the value in the element-value pair represented by * this element_value_pairs entry.</dd> * </dl> * </dd> * </dl> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=175">JSR 175 : A Metadata * Facility for the Java Programming Language</a> * * @author Eugene Kuleshov */ public class Annotation { public String type; public List elementValues = new ArrayList(); public void add (String name, Object value) { elementValues.add(new Object[]{name, value}); } /** * Reads annotation data structures. * * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. * * @return offset position in bytecode after reading annotation */ public int read (ClassReader cr, int off, char[] buf) { type = cr.readUTF8(off, buf); int numElementValuePairs = cr.readUnsignedShort(off + 2); off += 4; for (int i = 0; i < numElementValuePairs; i++) { String elementName = cr.readUTF8(off, buf); AnnotationElementValue value = new AnnotationElementValue(); off = value.read(cr, off + 2, buf); elementValues.add(new Object[]{elementName, value}); } return off; } /** * Writes annotation data structures. * * @param bv the byte array form to store data structures. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. */ public void write (ByteVector bv, ClassWriter cw) { bv.putShort(cw.newUTF8(type)); bv.putShort(elementValues.size()); for (int i = 0; i < elementValues.size(); i++) { Object[] value = (Object[])elementValues.get(i); bv.putShort(cw.newUTF8((String)value[0])); ((AnnotationElementValue)value[1]).write(bv, cw); } } /** * Utility method to read List of annotations. Each element of annotations * List will have Annotation instance. * * @param annotations the List to store parameters annotations. * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. * * @return offset position in bytecode after reading annotations */ public static int readAnnotations ( List annotations, ClassReader cr, int off, char[] buf) { int size = cr.readUnsignedShort(off); off += 2; for (int i = 0; i < size; i++) { Annotation ann = new Annotation(); off = ann.read(cr, off, buf); annotations.add(ann); } return off; } /** * Utility method to read List of parameters annotations. * * @param parameters the List to store parameters annotations. * Each element of the parameters List will have List of Annotation * instances. * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. */ public static void readParameterAnnotations ( List parameters, ClassReader cr, int off, char[] buf) { int numParameters = cr.b[off++] & 0xff; for (int i = 0; i < numParameters; i++) { List annotations = new ArrayList(); off = Annotation.readAnnotations(annotations, cr, off, buf); parameters.add(annotations); } } /** * Utility method to write List of annotations. * * @param bv the byte array form to store data structures. * @param annotations the List of annotations to write. * Elements should be instances of the Annotation class. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. * * @return the byte array form with saved annotations. */ public static ByteVector writeAnnotations (ByteVector bv, List annotations, ClassWriter cw) { bv.putShort(annotations.size()); for (int i = 0; i < annotations.size(); i++) { ((Annotation)annotations.get(i)).write(bv, cw); } return bv; } /** * Utility method to write List of parameters annotations. * * @param bv the byte array form to store data structures. * @param parameters the List of parametars to write. Elements should be * instances of the List that contains instances of the Annotation class. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. * * @return the byte array form with saved annotations. */ public static ByteVector writeParametersAnnotations (ByteVector bv, List parameters, ClassWriter cw) { bv.putByte(parameters.size()); for (int i = 0; i < parameters.size(); i++) { writeAnnotations(bv, (List)parameters.get(i), cw); } return bv; } /** * Returns annotation values in the format described in JSR-175 for Java * source code. * * @param annotations a list of annotations. * @return annotation values in the format described in JSR-175 for Java * source code. */ public static String stringAnnotations (List annotations) { StringBuffer sb = new StringBuffer(); if (annotations.size() > 0) { for (int i = 0; i < annotations.size(); i++) { sb.append('\n').append(annotations.get(i)); } } else { sb.append( "<none>"); } return sb.toString(); } /** * Returns parameter annotation values in the format described in JSR-175 * for Java source code. * * @param parameters a list of parameter annotations. * @return parameter annotation values in the format described in JSR-175 * for Java source code. */ public static String stringParameterAnnotations (List parameters) { StringBuffer sb = new StringBuffer(); String sep = ""; for (int i = 0; i < parameters.size(); i++) { sb.append(sep).append(stringAnnotations((List)parameters.get(i))); sep = ", "; } return sb.toString(); } /** * Returns value in the format described in JSR-175 for Java source code. * * @return value in the format described in JSR-175 for Java source code. */ public String toString () { StringBuffer sb = new StringBuffer("@").append(type); // shorthand syntax for marker annotation if (elementValues.size() > 0) { sb.append(" ( "); String sep = ""; for (int i = 0; i < elementValues.size(); i++) { Object[] value = (Object[])elementValues.get(i); // using shorthand syntax for single-element annotation if ( !( elementValues.size()==1 || "value".equals( elementValues.get( 0)))) { sb.append(sep).append(value[0]).append(" = "); } sb.append(value[1]); sep = ", "; } sb.append(" )"); } return sb.toString(); } }
src/org/objectweb/asm/attrs/Annotation.java
/** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000,2002,2003 INRIA, France Telecom * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.objectweb.asm.attrs; import java.util.ArrayList; import java.util.List; import org.objectweb.asm.ByteVector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * Annotation data contains an annotated type and its array of the element-value * pairs. Structure is in the following format: * <pre> * annotation { * u2 type_index; * u2 num_element_value_pairs; * { * u2 element_name_index; * element_value value; * } element_value_pairs[num_element_value_pairs]; * } * </pre> * The items of the annotation structure are as follows: * <dl> * <dt>type_index</dt> * <dd>The value of the type_index item must be a valid index into the constant_pool * table. The constant_pool entry at that index must be a CONSTANT_Utf8_info * structure representing a field descriptor representing the annotation * interface corresponding to the annotation represented by this annotation * structure.</dd> * <dt>num_element_value_pairs</dt> * <dd>The value of the num_element_value_pairs item gives the number of element-value * pairs in the annotation represented by this annotation structure. Note that a * maximum of 65535 element-value pairs may be contained in a single annotation.</dd> * <dt>element_value_pairs</dt> * <dd>Each value of the element_value_pairs table represents a single element-value * pair in the annotation represented by this annotation structure. * Each element_value_pairs entry contains the following two items: * <dt>element_name_index</dt> * <dd>The value of the element_name_index item must be a valid index into the * constant_pool table. The constant_pool entry at that index must be a * CONSTANT_Utf8_info structure representing the name of the annotation type * element corresponding to this element_value_pairs entry.</dd> * <dt>value</dt> * <dd>The value item represents the value in the element-value pair represented by * this element_value_pairs entry.</dd> * </dl> * </dd> * </dl> * * @see <a href="http://www.jcp.org/en/jsr/detail?id=175">JSR 175 : A Metadata * Facility for the Java Programming Language</a> * * @author Eugene Kuleshov */ public class Annotation { public String type; public List elementValues = new ArrayList(); public void add (String name, Object value) { elementValues.add(new Object[]{name, value}); } /** * Reads annotation data structures. * * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. * * @return offset position in bytecode after reading annotation */ public int read (ClassReader cr, int off, char[] buf) { type = cr.readUTF8(off, buf); int numElementValuePairs = cr.readUnsignedShort(off + 2); off += 4; for (int i = 0; i < numElementValuePairs; i++) { String elementName = cr.readUTF8(off, buf); AnnotationElementValue value = new AnnotationElementValue(); off = value.read(cr, off + 2, buf); elementValues.add(new Object[]{elementName, value}); } return off; } /** * Writes annotation data structures. * * @param bv the byte array form to store data structures. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. */ public void write (ByteVector bv, ClassWriter cw) { bv.putShort(cw.newUTF8(type)); bv.putShort(elementValues.size()); for (int i = 0; i < elementValues.size(); i++) { Object[] value = (Object[])elementValues.get(i); bv.putShort(cw.newUTF8((String)value[0])); ((AnnotationElementValue)value[1]).write(bv, cw); } } /** * Utility method to read List of annotations. Each element of annotations * List will have Annotation instance. * * @param annotations the List to store parameters annotations. * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. * * @return offset position in bytecode after reading annotations */ public static int readAnnotations ( List annotations, ClassReader cr, int off, char[] buf) { int size = cr.readUnsignedShort(off); off += 2; for (int i = 0; i < size; i++) { Annotation ann = new Annotation(); off = ann.read(cr, off, buf); annotations.add(ann); } return off; } /** * Utility method to read List of parameters annotations. * * @param parameters the List to store parameters annotations. * Each element of the parameters List will have List of Annotation * instances. * @param cr the class that contains the attribute to be read. * @param off index of the first byte of the data structure. * @param buf buffer to be used to call {@link ClassReader#readUTF8 readUTF8}, * {@link ClassReader#readClass(int,char[]) readClass} or {@link * ClassReader#readConst readConst}. */ public static void readParameterAnnotations ( List parameters, ClassReader cr, int off, char[] buf) { int numParameters = cr.b[off++] & 0xff; for (int i = 0; i < numParameters; i++) { List annotations = new ArrayList(); off = Annotation.readAnnotations(annotations, cr, off, buf); parameters.add(annotations); } } /** * Utility method to write List of annotations. * * @param bv the byte array form to store data structures. * @param annotations the List of annotations to write. * Elements should be instances of the Annotation class. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. * * @return the byte array form with saved annotations. */ public static ByteVector writeAnnotations (ByteVector bv, List annotations, ClassWriter cw) { bv.putShort(annotations.size()); for (int i = 0; i < annotations.size(); i++) { ((Annotation)annotations.get(i)).write(bv, cw); } return bv; } /** * Utility method to write List of parameters annotations. * * @param bv the byte array form to store data structures. * @param parameters the List of parametars to write. Elements should be * instances of the List that contains instances of the Annotation class. * @param cw the class to which this attribute must be added. This parameter * can be used to add to the constant pool of this class the items that * corresponds to this attribute. * * @return the byte array form with saved annotations. */ public static ByteVector writeParametersAnnotations (ByteVector bv, List parameters, ClassWriter cw) { bv.putByte(parameters.size()); for (int i = 0; i < parameters.size(); i++) { writeAnnotations(bv, (List)parameters.get(i), cw); } return bv; } /** * Returns annotation values in the format described in JSR-175 for Java * source code. * * @param annotations a list of annotations. * @return annotation values in the format described in JSR-175 for Java * source code. */ public static String stringAnnotations (List annotations) { StringBuffer sb = new StringBuffer(); if (annotations.size() > 0) { for (int i = 0; i < annotations.size(); i++) { sb.append('\n').append(annotations.get(i)); } } return sb.toString(); } /** * Returns parameter annotation values in the format described in JSR-175 * for Java source code. * * @param parameters a list of parameter annotations. * @return parameter annotation values in the format described in JSR-175 * for Java source code. */ public static String stringParameterAnnotations (List parameters) { StringBuffer sb = new StringBuffer(); String sep = ""; for (int i = 0; i < parameters.size(); i++) { sb.append(sep).append(stringAnnotations((List)parameters.get(i))); sep = ", "; } return sb.toString(); } /** * Returns value in the format described in JSR-175 for Java source code. * * @return value in the format described in JSR-175 for Java source code. */ public String toString () { StringBuffer sb = new StringBuffer("@").append(type); // shorthand syntax for marker annotation if (elementValues.size() > 0) { sb.append(" ( "); String sep = ""; for (int i = 0; i < elementValues.size(); i++) { Object[] value = (Object[])elementValues.get(i); // using shorthand syntax for single-element annotation if ( !( elementValues.size()==1 || "value".equals( elementValues.get( 0)))) { sb.append(sep).append(value[0]).append(" = "); } sb.append(value[1]); sep = ", "; } sb.append(" )"); } return sb.toString(); } }
more verbose toString() for empty annotation list
src/org/objectweb/asm/attrs/Annotation.java
more verbose toString() for empty annotation list
Java
bsd-3-clause
733664e8c2fc2d74dee2d095f1a2213ff38071bd
0
arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr
/* * Copyright (c) 2009, Swedish Institute of Computer Science. * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. * * $Id: LogListener.java,v 1.31 2010/08/13 10:03:12 fros4943 Exp $ */ package se.sics.cooja.plugins; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.Font; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.regex.PatternSyntaxException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.ClassDescription; import se.sics.cooja.GUI; import se.sics.cooja.Mote; import se.sics.cooja.Plugin; import se.sics.cooja.PluginType; import se.sics.cooja.Simulation; import se.sics.cooja.VisPlugin; import se.sics.cooja.SimEventCentral.LogOutputEvent; import se.sics.cooja.SimEventCentral.LogOutputListener; import se.sics.cooja.dialogs.TableColumnAdjuster; import se.sics.cooja.dialogs.UpdateAggregator; /** * A simple mote log listener. * Listens to all motes' log interfaces. * * @author Fredrik Osterlind, Niclas Finne */ @ClassDescription("Log Listener") @PluginType(PluginType.SIM_STANDARD_PLUGIN) public class LogListener extends VisPlugin { private static final long serialVersionUID = 3294595371354857261L; private static Logger logger = Logger.getLogger(LogListener.class); private final static int COLUMN_TIME = 0; private final static int COLUMN_FROM = 1; private final static int COLUMN_DATA = 2; private final static int COLUMN_CONCAT = 3; private final static String[] COLUMN_NAMES = { "Time", "Mote", "Message", "#" }; private final JTable logTable; private TableRowSorter<TableModel> logFilter; private LinkedList<LogData> logs = new LinkedList<LogData>(); private Simulation simulation; private JTextField filterTextField = null; private Color filterTextFieldBackground; private AbstractTableModel model; private LogOutputListener logOutputListener; private boolean backgroundColors = false; private JCheckBoxMenuItem colorCheckbox; private static final int UPDATE_INTERVAL = 250; private UpdateAggregator<LogData> logUpdateAggregator = new UpdateAggregator<LogData>(UPDATE_INTERVAL) { private Runnable scroll = new Runnable() { public void run() { logTable.scrollRectToVisible( new Rectangle(0, logTable.getHeight() - 2, 1, logTable.getHeight())); } }; protected void handle(List<LogData> ls) { boolean isVisible = true; if (logTable.getRowCount() > 0) { Rectangle visible = logTable.getVisibleRect(); if (visible.y + visible.height < logTable.getHeight()) { isVisible = false; } } /* Add */ int index = logs.size(); logs.addAll(ls); model.fireTableRowsInserted(index, logs.size()-1); /* Remove old */ int removed = 0; while (logs.size() > simulation.getEventCentral().getLogOutputBufferSize()) { logs.removeFirst(); removed++; } if (removed > 0) { model.fireTableRowsDeleted(0, removed-1); } if (isVisible) { SwingUtilities.invokeLater(scroll); } } }; /** * @param simulation Simulation * @param gui GUI */ public LogListener(final Simulation simulation, final GUI gui) { super("Log Listener - Listening on ?? mote logs", gui); this.simulation = simulation; model = new AbstractTableModel() { private static final long serialVersionUID = 3065150390849332924L; public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { return logs.size(); } public int getColumnCount() { return COLUMN_NAMES.length; } public Object getValueAt(int row, int col) { LogData log = logs.get(row); if (col == COLUMN_TIME) { return log.strTime; } else if (col == COLUMN_FROM) { return log.strID; } else if (col == COLUMN_DATA) { return log.ev.getMessage(); } else if (col == COLUMN_CONCAT) { return log.strID + ' ' + log.ev.getMessage(); } return null; } }; logTable = new JTable(model) { private static final long serialVersionUID = -930616018336483196L; public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int columnIndex = convertColumnIndexToModel(colIndex); if (rowIndex < 0 || columnIndex < 0) { return super.getToolTipText(e); } Object v = getValueAt(rowIndex, columnIndex); if (v != null) { String t = v.toString(); if (t.length() > 60) { StringBuilder sb = new StringBuilder(); sb.append("<html>"); do { sb.append(t.substring(0, 60)).append("<br>"); t = t.substring(60); } while (t.length() > 60); return sb.append(t).append("</html>").toString(); } } return super.getToolTipText(e); } }; DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() { private static final long serialVersionUID = -340743275865216182L; private final Color[] BG_COLORS = new Color[] { new Color(200, 200, 200), new Color(200, 200, 255), new Color(200, 255, 200), new Color(200, 255, 255), new Color(255, 200, 200), new Color(255, 255, 200), new Color(255, 255, 255), new Color(255, 220, 200), new Color(220, 255, 220), new Color(255, 200, 255), }; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (row >= logTable.getRowCount()) { return super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); } if (backgroundColors) { LogData d = logs.get(logTable.getRowSorter().convertRowIndexToModel(row)); char last = d.strID.charAt(d.strID.length()-1); if (last >= '0' && last <= '9') { setBackground(BG_COLORS[last - '0']); } else { setBackground(null); } } else { setBackground(null); } return super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); } }; logTable.getColumnModel().getColumn(COLUMN_TIME).setCellRenderer(cellRenderer); logTable.getColumnModel().getColumn(COLUMN_FROM).setCellRenderer(cellRenderer); logTable.getColumnModel().getColumn(COLUMN_DATA).setCellRenderer(cellRenderer); logTable.getColumnModel().removeColumn(logTable.getColumnModel().getColumn(COLUMN_CONCAT)); logTable.setFillsViewportHeight(true); logTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); logTable.setFont(new Font("Monospaced", Font.PLAIN, 12)); logTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { timeLineAction.actionPerformed(null); radioLoggerAction.actionPerformed(null); } } }); logFilter = new TableRowSorter<TableModel>(model); for (int i = 0, n = model.getColumnCount(); i < n; i++) { logFilter.setSortable(i, false); } logTable.setRowSorter(logFilter); /* Automatically update column widths */ final TableColumnAdjuster adjuster = new TableColumnAdjuster(logTable); adjuster.packColumns(); /* Popup menu */ JPopupMenu popupMenu = new JPopupMenu(); JMenu copyClipboard = new JMenu("Copy to clipboard"); copyClipboard.add(new JMenuItem(copyAllAction)); copyClipboard.add(new JMenuItem(copyAllMessagesAction)); copyClipboard.add(new JMenuItem(copyAction)); popupMenu.add(copyClipboard); popupMenu.add(new JMenuItem(clearAction)); popupMenu.addSeparator(); popupMenu.add(new JMenuItem(saveAction)); popupMenu.addSeparator(); JMenu focusMenu = new JMenu("Focus (Space)"); focusMenu.add(new JMenuItem(timeLineAction)); focusMenu.add(new JMenuItem(radioLoggerAction)); popupMenu.add(focusMenu); popupMenu.addSeparator(); colorCheckbox = new JCheckBoxMenuItem("Mote-specific coloring"); popupMenu.add(colorCheckbox); colorCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { backgroundColors = colorCheckbox.isSelected(); repaint(); } }); logTable.setComponentPopupMenu(popupMenu); /* Fetch log output history */ LogOutputEvent[] history = simulation.getEventCentral().getLogOutputHistory(); if (history.length > 0) { for (LogOutputEvent historyEv: history) { LogData data = new LogData(historyEv); logs.add(data); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { model.fireTableDataChanged(); logTable.scrollRectToVisible( new Rectangle(0, logTable.getHeight() - 2, 1, logTable.getHeight())); } }); } /* Column width adjustment */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { /* Make sure this happens *after* adding history */ adjuster.setDynamicAdjustment(true); } }); /* Start observing motes for new log output */ logUpdateAggregator.start(); simulation.getEventCentral().addLogOutputListener(logOutputListener = new LogOutputListener() { public void moteWasAdded(Mote mote) { /* Update title */ updateTitle(); } public void moteWasRemoved(Mote mote) { /* Update title */ updateTitle(); } public void newLogOutput(LogOutputEvent ev) { /* Display new log output */ logUpdateAggregator.add(new LogData(ev)); } public void removedLogOutput(LogOutputEvent ev) { } }); /* UI components */ JPanel filterPanel = new JPanel(); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS)); filterTextField = new JTextField(""); filterTextFieldBackground = filterTextField.getBackground(); filterPanel.add(Box.createHorizontalStrut(2)); filterPanel.add(new JLabel("Filter: ")); filterPanel.add(filterTextField); filterTextField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String str = filterTextField.getText(); setFilter(str); /* Autoscroll */ SwingUtilities.invokeLater(new Runnable() { public void run() { int s = logTable.getSelectedRow(); if (s < 0) { return; } s = logTable.getRowSorter().convertRowIndexToView(s); if (s < 0) { return; } int v = logTable.getRowHeight()*s; logTable.scrollRectToVisible(new Rectangle(0, v-5, 1, v+5)); } }); } }); filterPanel.add(Box.createHorizontalStrut(2)); getContentPane().add(BorderLayout.CENTER, new JScrollPane(logTable)); getContentPane().add(BorderLayout.SOUTH, filterPanel); updateTitle(); pack(); setSize(gui.getDesktopPane().getWidth(), 150); setLocation(0, gui.getDesktopPane().getHeight() - 300); } private void updateTitle() { setTitle("Log Listener (listening on " + simulation.getEventCentral().getLogOutputObservationsCount() + " log interfaces)"); } public void closePlugin() { /* Stop observing motes */ logUpdateAggregator.stop(); simulation.getEventCentral().removeLogOutputListener(logOutputListener); } public Collection<Element> getConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element element; element = new Element("filter"); element.setText(filterTextField.getText()); config.add(element); if (backgroundColors) { element = new Element("coloring"); config.add(element); } return config; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { for (Element element : configXML) { String name = element.getName(); if ("filter".equals(name)) { final String str = element.getText(); EventQueue.invokeLater(new Runnable() { public void run() { setFilter(str); } }); } else if ("coloring".equals(name)) { backgroundColors = true; colorCheckbox.setSelected(true); } } return true; } public String getFilter() { return filterTextField.getText(); } public void setFilter(String str) { filterTextField.setText(str); try { if (str != null && str.length() > 0) { logFilter.setRowFilter(RowFilter.regexFilter(str, COLUMN_FROM, COLUMN_DATA, COLUMN_CONCAT)); } else { logFilter.setRowFilter(null); } filterTextField.setBackground(filterTextFieldBackground); filterTextField.setToolTipText(null); } catch (PatternSyntaxException e) { filterTextField.setBackground(Color.red); filterTextField.setToolTipText("Syntax error in regular expression: " + e.getMessage()); } } public void trySelectTime(final long time) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { for (int i=0; i < logs.size(); i++) { if (logs.get(i).ev.getTime() < time) { continue; } int view = logTable.convertRowIndexToView(i); if (view < 0) { continue; } logTable.scrollRectToVisible(logTable.getCellRect(view, 0, true)); logTable.setRowSelectionInterval(view, view); return; } } }); } private static class LogData { public final LogOutputEvent ev; public final String strID; /* cached value */ public final String strTime; /* cached value */ public LogData(LogOutputEvent ev) { this.ev = ev; this.strID = "ID:" + ev.getMote().getID(); this.strTime = "" + ev.getTime()/Simulation.MILLISECOND; } } private Action saveAction = new AbstractAction("Save to file") { private static final long serialVersionUID = -4140706275748686944L; public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(GUI.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File saveFile = fc.getSelectedFile(); if (saveFile.exists()) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( GUI.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } if (saveFile.exists() && !saveFile.canWrite()) { logger.fatal("No write access to file: " + saveFile); return; } try { PrintWriter outStream = new PrintWriter(new FileWriter(saveFile)); for(LogData data : logs) { outStream.println( data.strTime + "\t" + data.strID + "\t" + data.ev.getMessage()); } outStream.close(); } catch (Exception ex) { logger.fatal("Could not write to file: " + saveFile); return; } } }; private Action timeLineAction = new AbstractAction("in Timeline ") { private static final long serialVersionUID = -6358463434933029699L; public void actionPerformed(ActionEvent e) { int view = logTable.getSelectedRow(); if (view < 0) { return; } int model = logTable.convertRowIndexToModel(view); long time = logs.get(model).ev.getTime(); Plugin[] plugins = simulation.getGUI().getStartedPlugins(); for (Plugin p: plugins) { if (!(p instanceof TimeLine)) { continue; } /* Select simulation time */ TimeLine plugin = (TimeLine) p; plugin.trySelectTime(time); } } }; private Action radioLoggerAction = new AbstractAction("in Radio Logger") { private static final long serialVersionUID = -3041714249257346688L; public void actionPerformed(ActionEvent e) { int view = logTable.getSelectedRow(); if (view < 0) { return; } int model = logTable.convertRowIndexToModel(view); long time = logs.get(model).ev.getTime(); Plugin[] plugins = simulation.getGUI().getStartedPlugins(); for (Plugin p: plugins) { if (!(p instanceof RadioLogger)) { continue; } /* Select simulation time */ RadioLogger plugin = (RadioLogger) p; plugin.trySelectTime(time); } } }; private Action clearAction = new AbstractAction("Clear") { private static final long serialVersionUID = -2115620313183440224L; public void actionPerformed(ActionEvent e) { int size = logs.size(); if (size > 0) { logs.clear(); model.fireTableRowsDeleted(0, size - 1); } } }; private Action copyAction = new AbstractAction("Selected") { private static final long serialVersionUID = -8433490108577001803L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); int[] selectedRows = logTable.getSelectedRows(); StringBuilder sb = new StringBuilder(); for (int i: selectedRows) { sb.append(logTable.getValueAt(i, COLUMN_TIME)); sb.append("\t"); sb.append(logTable.getValueAt(i, COLUMN_FROM)); sb.append("\t"); sb.append(logTable.getValueAt(i, COLUMN_DATA)); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action copyAllAction = new AbstractAction("All") { private static final long serialVersionUID = -5038884975254178373L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringBuilder sb = new StringBuilder(); for(LogData data : logs) { sb.append(data.strTime); sb.append("\t"); sb.append(data.strID); sb.append("\t"); sb.append(data.ev.getMessage()); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action copyAllMessagesAction = new AbstractAction("All messages") { private static final long serialVersionUID = -5038884975254178373L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringBuilder sb = new StringBuilder(); for(LogData data : logs) { sb.append(data.ev.getMessage()); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; }
tools/cooja/java/se/sics/cooja/plugins/LogListener.java
/* * Copyright (c) 2009, Swedish Institute of Computer Science. * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. * * $Id: LogListener.java,v 1.30 2010/05/19 12:58:15 nifi Exp $ */ package se.sics.cooja.plugins; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.Font; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.regex.PatternSyntaxException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.ClassDescription; import se.sics.cooja.GUI; import se.sics.cooja.Mote; import se.sics.cooja.PluginType; import se.sics.cooja.Simulation; import se.sics.cooja.VisPlugin; import se.sics.cooja.SimEventCentral.LogOutputEvent; import se.sics.cooja.SimEventCentral.LogOutputListener; import se.sics.cooja.dialogs.TableColumnAdjuster; import se.sics.cooja.dialogs.UpdateAggregator; /** * A simple mote log listener. * Listens to all motes' log interfaces. * * @author Fredrik Osterlind, Niclas Finne */ @ClassDescription("Log Listener") @PluginType(PluginType.SIM_STANDARD_PLUGIN) public class LogListener extends VisPlugin { private static final long serialVersionUID = 3294595371354857261L; private static Logger logger = Logger.getLogger(LogListener.class); private final static int COLUMN_TIME = 0; private final static int COLUMN_FROM = 1; private final static int COLUMN_DATA = 2; private final static int COLUMN_CONCAT = 3; private final static String[] COLUMN_NAMES = { "Time", "Mote", "Message", "#" }; private final JTable logTable; private TableRowSorter<TableModel> logFilter; private LinkedList<LogData> logs = new LinkedList<LogData>(); private Simulation simulation; private JTextField filterTextField = null; private Color filterTextFieldBackground; private AbstractTableModel model; private LogOutputListener logOutputListener; private boolean backgroundColors = false; private JCheckBoxMenuItem colorCheckbox; private static final int UPDATE_INTERVAL = 250; private UpdateAggregator<LogData> logUpdateAggregator = new UpdateAggregator<LogData>(UPDATE_INTERVAL) { private Runnable scroll = new Runnable() { public void run() { logTable.scrollRectToVisible( new Rectangle(0, logTable.getHeight() - 2, 1, logTable.getHeight())); } }; protected void handle(List<LogData> ls) { boolean isVisible = true; if (logTable.getRowCount() > 0) { Rectangle visible = logTable.getVisibleRect(); if (visible.y + visible.height < logTable.getHeight()) { isVisible = false; } } /* Add */ int index = logs.size(); logs.addAll(ls); model.fireTableRowsInserted(index, logs.size()-1); /* Remove old */ int removed = 0; while (logs.size() > simulation.getEventCentral().getLogOutputBufferSize()) { logs.removeFirst(); removed++; } if (removed > 0) { model.fireTableRowsDeleted(0, removed-1); } if (isVisible) { SwingUtilities.invokeLater(scroll); } } }; /** * @param simulation Simulation * @param gui GUI */ public LogListener(final Simulation simulation, final GUI gui) { super("Log Listener - Listening on ?? mote logs", gui); this.simulation = simulation; model = new AbstractTableModel() { private static final long serialVersionUID = 3065150390849332924L; public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { return logs.size(); } public int getColumnCount() { return COLUMN_NAMES.length; } public Object getValueAt(int row, int col) { LogData log = logs.get(row); if (col == COLUMN_TIME) { return log.strTime; } else if (col == COLUMN_FROM) { return log.strID; } else if (col == COLUMN_DATA) { return log.ev.getMessage(); } else if (col == COLUMN_CONCAT) { return log.strID + ' ' + log.ev.getMessage(); } return null; } }; logTable = new JTable(model) { private static final long serialVersionUID = -930616018336483196L; public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int columnIndex = convertColumnIndexToModel(colIndex); if (rowIndex < 0 || columnIndex < 0) { return super.getToolTipText(e); } Object v = getValueAt(rowIndex, columnIndex); if (v != null) { String t = v.toString(); if (t.length() > 60) { StringBuilder sb = new StringBuilder(); sb.append("<html>"); do { sb.append(t.substring(0, 60)).append("<br>"); t = t.substring(60); } while (t.length() > 60); return sb.append(t).append("</html>").toString(); } } return super.getToolTipText(e); } }; DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() { private static final long serialVersionUID = -340743275865216182L; private final Color[] BG_COLORS = new Color[] { new Color(200, 200, 200), new Color(200, 200, 255), new Color(200, 255, 200), new Color(200, 255, 255), new Color(255, 200, 200), new Color(255, 255, 200), new Color(255, 255, 255), new Color(255, 220, 200), new Color(220, 255, 220), new Color(255, 200, 255), }; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (backgroundColors) { LogData d = logs.get(logTable.getRowSorter().convertRowIndexToModel(row)); char last = d.strID.charAt(d.strID.length()-1); if (last >= '0' && last <= '9') { setBackground(BG_COLORS[last - '0']); } else { setBackground(null); } } else { setBackground(null); } return super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); } }; logTable.getColumnModel().getColumn(COLUMN_TIME).setCellRenderer(cellRenderer); logTable.getColumnModel().getColumn(COLUMN_FROM).setCellRenderer(cellRenderer); logTable.getColumnModel().getColumn(COLUMN_DATA).setCellRenderer(cellRenderer); logTable.getColumnModel().removeColumn(logTable.getColumnModel().getColumn(COLUMN_CONCAT)); logTable.setFillsViewportHeight(true); logTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); logTable.setFont(new Font("Monospaced", Font.PLAIN, 12)); logTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { timeLineAction.actionPerformed(null); radioLoggerAction.actionPerformed(null); } } }); logFilter = new TableRowSorter<TableModel>(model); for (int i = 0, n = model.getColumnCount(); i < n; i++) { logFilter.setSortable(i, false); } logTable.setRowSorter(logFilter); /* Automatically update column widths */ final TableColumnAdjuster adjuster = new TableColumnAdjuster(logTable); adjuster.packColumns(); /* Popup menu */ JPopupMenu popupMenu = new JPopupMenu(); JMenu copyClipboard = new JMenu("Copy to clipboard"); copyClipboard.add(new JMenuItem(copyAllAction)); copyClipboard.add(new JMenuItem(copyAllMessagesAction)); copyClipboard.add(new JMenuItem(copyAction)); popupMenu.add(copyClipboard); popupMenu.add(new JMenuItem(clearAction)); popupMenu.addSeparator(); popupMenu.add(new JMenuItem(saveAction)); popupMenu.addSeparator(); JMenu focusMenu = new JMenu("Focus (Space)"); focusMenu.add(new JMenuItem(timeLineAction)); focusMenu.add(new JMenuItem(radioLoggerAction)); popupMenu.add(focusMenu); popupMenu.addSeparator(); colorCheckbox = new JCheckBoxMenuItem("Mote-specific coloring"); popupMenu.add(colorCheckbox); colorCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { backgroundColors = colorCheckbox.isSelected(); repaint(); } }); logTable.setComponentPopupMenu(popupMenu); /* Fetch log output history */ LogOutputEvent[] history = simulation.getEventCentral().getLogOutputHistory(); if (history.length > 0) { for (LogOutputEvent historyEv: history) { LogData data = new LogData(historyEv); logs.add(data); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { model.fireTableDataChanged(); logTable.scrollRectToVisible( new Rectangle(0, logTable.getHeight() - 2, 1, logTable.getHeight())); } }); } /* Column width adjustment */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { /* Make sure this happens *after* adding history */ adjuster.setDynamicAdjustment(true); } }); /* Start observing motes for new log output */ logUpdateAggregator.start(); simulation.getEventCentral().addLogOutputListener(logOutputListener = new LogOutputListener() { public void moteWasAdded(Mote mote) { /* Update title */ updateTitle(); } public void moteWasRemoved(Mote mote) { /* Update title */ updateTitle(); } public void newLogOutput(LogOutputEvent ev) { /* Display new log output */ logUpdateAggregator.add(new LogData(ev)); } public void removedLogOutput(LogOutputEvent ev) { } }); /* UI components */ JPanel filterPanel = new JPanel(); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS)); filterTextField = new JTextField(""); filterTextFieldBackground = filterTextField.getBackground(); filterPanel.add(Box.createHorizontalStrut(2)); filterPanel.add(new JLabel("Filter: ")); filterPanel.add(filterTextField); filterTextField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String str = filterTextField.getText(); setFilter(str); /* Autoscroll */ SwingUtilities.invokeLater(new Runnable() { public void run() { int s = logTable.getSelectedRow(); if (s < 0) { return; } s = logTable.getRowSorter().convertRowIndexToView(s); if (s < 0) { return; } int v = logTable.getRowHeight()*s; logTable.scrollRectToVisible(new Rectangle(0, v-5, 1, v+5)); } }); } }); filterPanel.add(Box.createHorizontalStrut(2)); getContentPane().add(BorderLayout.CENTER, new JScrollPane(logTable)); getContentPane().add(BorderLayout.SOUTH, filterPanel); updateTitle(); pack(); setSize(gui.getDesktopPane().getWidth(), 150); setLocation(0, gui.getDesktopPane().getHeight() - 300); } private void updateTitle() { setTitle("Log Listener (listening on " + simulation.getEventCentral().getLogOutputObservationsCount() + " log interfaces)"); } public void closePlugin() { /* Stop observing motes */ logUpdateAggregator.stop(); simulation.getEventCentral().removeLogOutputListener(logOutputListener); } public Collection<Element> getConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element element; element = new Element("filter"); element.setText(filterTextField.getText()); config.add(element); if (backgroundColors) { element = new Element("coloring"); config.add(element); } return config; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { for (Element element : configXML) { String name = element.getName(); if ("filter".equals(name)) { final String str = element.getText(); EventQueue.invokeLater(new Runnable() { public void run() { setFilter(str); } }); } else if ("coloring".equals(name)) { backgroundColors = true; colorCheckbox.setSelected(true); } } return true; } public String getFilter() { return filterTextField.getText(); } public void setFilter(String str) { filterTextField.setText(str); try { if (str != null && str.length() > 0) { logFilter.setRowFilter(RowFilter.regexFilter(str, COLUMN_FROM, COLUMN_DATA, COLUMN_CONCAT)); } else { logFilter.setRowFilter(null); } filterTextField.setBackground(filterTextFieldBackground); filterTextField.setToolTipText(null); } catch (PatternSyntaxException e) { filterTextField.setBackground(Color.red); filterTextField.setToolTipText("Syntax error in regular expression: " + e.getMessage()); } } public void trySelectTime(final long time) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { for (int i=0; i < logs.size(); i++) { if (logs.get(i).ev.getTime() < time) { continue; } int view = logTable.convertRowIndexToView(i); if (view < 0) { continue; } logTable.scrollRectToVisible(logTable.getCellRect(view, 0, true)); logTable.setRowSelectionInterval(view, view); return; } } }); } private static class LogData { public final LogOutputEvent ev; public final String strID; /* cached value */ public final String strTime; /* cached value */ public LogData(LogOutputEvent ev) { this.ev = ev; this.strID = "ID:" + ev.getMote().getID(); this.strTime = "" + ev.getTime()/Simulation.MILLISECOND; } } private Action saveAction = new AbstractAction("Save to file") { private static final long serialVersionUID = -4140706275748686944L; public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(GUI.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File saveFile = fc.getSelectedFile(); if (saveFile.exists()) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( GUI.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } if (saveFile.exists() && !saveFile.canWrite()) { logger.fatal("No write access to file: " + saveFile); return; } try { PrintWriter outStream = new PrintWriter(new FileWriter(saveFile)); for(LogData data : logs) { outStream.println( data.strTime + "\t" + data.strID + "\t" + data.ev.getMessage()); } outStream.close(); } catch (Exception ex) { logger.fatal("Could not write to file: " + saveFile); return; } } }; private Action timeLineAction = new AbstractAction("in Timeline ") { private static final long serialVersionUID = -6358463434933029699L; public void actionPerformed(ActionEvent e) { TimeLine plugin = (TimeLine) simulation.getGUI().getStartedPlugin(TimeLine.class.getName()); if (plugin == null) { /*logger.fatal("No Timeline plugin");*/ return; } int view = logTable.getSelectedRow(); if (view < 0) { return; } int model = logTable.convertRowIndexToModel(view); /* Select simulation time */ plugin.trySelectTime(logs.get(model).ev.getTime()); } }; private Action radioLoggerAction = new AbstractAction("in Radio Logger") { private static final long serialVersionUID = -3041714249257346688L; public void actionPerformed(ActionEvent e) { RadioLogger plugin = (RadioLogger) simulation.getGUI().getStartedPlugin(RadioLogger.class.getName()); if (plugin == null) { /*logger.fatal("No Radio Logger plugin");*/ return; } int view = logTable.getSelectedRow(); if (view < 0) { return; } int model = logTable.convertRowIndexToModel(view); /* Select simulation time */ plugin.trySelectTime(logs.get(model).ev.getTime()); } }; private Action clearAction = new AbstractAction("Clear") { private static final long serialVersionUID = -2115620313183440224L; public void actionPerformed(ActionEvent e) { int size = logs.size(); if (size > 0) { logs.clear(); model.fireTableRowsDeleted(0, size - 1); } } }; private Action copyAction = new AbstractAction("Selected") { private static final long serialVersionUID = -8433490108577001803L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); int[] selectedRows = logTable.getSelectedRows(); StringBuilder sb = new StringBuilder(); for (int i: selectedRows) { sb.append(logTable.getValueAt(i, COLUMN_TIME)); sb.append("\t"); sb.append(logTable.getValueAt(i, COLUMN_FROM)); sb.append("\t"); sb.append(logTable.getValueAt(i, COLUMN_DATA)); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action copyAllAction = new AbstractAction("All") { private static final long serialVersionUID = -5038884975254178373L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringBuilder sb = new StringBuilder(); for(LogData data : logs) { sb.append(data.strTime); sb.append("\t"); sb.append(data.strID); sb.append("\t"); sb.append(data.ev.getMessage()); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action copyAllMessagesAction = new AbstractAction("All messages") { private static final long serialVersionUID = -5038884975254178373L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringBuilder sb = new StringBuilder(); for(LogData data : logs) { sb.append(data.ev.getMessage()); sb.append("\n"); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; }
mote-specific coloring bug fix + time focus on all active plugins
tools/cooja/java/se/sics/cooja/plugins/LogListener.java
mote-specific coloring bug fix + time focus on all active plugins
Java
mit
2e364826d6b7b2d1d72d26bf47bbd6295e559bd9
0
InfinityPhase/CARIS,InfinityPhase/CARIS
package caris.framework.reactions; import caris.framework.basereactions.Reaction; import caris.framework.library.Variables; import caris.framework.utilities.Logger; import caris.framework.library.GuildInfo.SpecialChannel; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IGuild; import utilities.BotUtils; public class ReactionChannelAssign extends Reaction { public IGuild guild; public IChannel channel; public SpecialChannel channelType; public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType) { this(guild, channel, channelType, -1); } public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType, int priority) { super(priority); this.guild = guild; this.channel = channel; this.channelType = channelType; } @Override public void run() { Variables.guildIndex.get(guild).specialChannels.put(channelType, channel); if( channel == null ) { switch(channelType) { case DEFAULT: Logger.print("Default channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; case LOG: Logger.print("Log channel reset in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; default: Logger.error("Invalid ChannelType in ReactionChannelAssign"); break; } } else { switch(channelType) { case DEFAULT: BotUtils.sendMessage(channel, "This channel has been set as the default channel!"); Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as default channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; case LOG: BotUtils.sendMessage(channel, "This channel has been set as the log channel!"); Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as log channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; default: Logger.error("Invalid ChannelType in ReactionChannelAssign"); break; } } } }
src/caris/framework/reactions/ReactionChannelAssign.java
package caris.framework.reactions; import caris.framework.basereactions.Reaction; import caris.framework.library.Variables; import caris.framework.utilities.Logger; import caris.framework.library.GuildInfo.SpecialChannel; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IGuild; import utilities.BotUtils; public class ReactionChannelAssign extends Reaction { public IGuild guild; public IChannel channel; public SpecialChannel channelType; public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType) { this(guild, channel, channelType, -1); } public ReactionChannelAssign(IGuild guild, IChannel channel, SpecialChannel channelType, int priority) { super(priority); this.guild = guild; this.channel = channel; this.channelType = channelType; } @Override public void run() { Variables.guildIndex.get(guild).specialChannels.put(channelType, channel); switch(channelType) { case DEFAULT: BotUtils.sendMessage(channel, "This channel has been set as the default channel!"); Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as default channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; case LOG: BotUtils.sendMessage(channel, "This channel has been set as the log channel!"); Logger.print("Channel (" + channel.getLongID() + ") <" + channel.getName() + "> set as log channel in guild <" + guild.getName() + "> (" + guild.getLongID() + ")", 3); break; default: Logger.error("Invalid ChannelType in ReactionChannelAssign"); break; } } }
Fixed for logging issues
src/caris/framework/reactions/ReactionChannelAssign.java
Fixed for logging issues
Java
mit
ab713564e12f87cca9f3c50b1fc149c4b6506ebb
0
spotify/robolectric,spotify/robolectric,spotify/robolectric
package org.robolectric.shadows; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; import static android.os.Build.VERSION_CODES.M; import android.net.Network; import java.io.FileDescriptor; import java.net.DatagramSocket; import java.net.Socket; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.shadow.api.Shadow; import org.robolectric.util.ReflectionHelpers; @Implements(value = Network.class, minSdk = LOLLIPOP) public class ShadowNetwork { @RealObject private Network realObject; /** * Creates new instance of {@link Network}, because its constructor is hidden. * * @param netId The netId. * @return The Network instance. */ public static Network newInstance(int netId) { return Shadow.newInstance(Network.class, new Class[] {int.class}, new Object[] {netId}); } /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation(minSdk = LOLLIPOP_MR1) protected void bindSocket(DatagramSocket socket) {} /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation protected void bindSocket(Socket socket) {} /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation(minSdk = M) protected void bindSocket(FileDescriptor fd) {} /** * Allows to get the stored netId. * * @return The netId. */ public int getNetId() { return ReflectionHelpers.getField(realObject, "netId"); } }
shadows/framework/src/main/java/org/robolectric/shadows/ShadowNetwork.java
package org.robolectric.shadows; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; import static android.os.Build.VERSION_CODES.M; import android.net.Network; import java.io.FileDescriptor; import java.net.DatagramSocket; import java.net.Socket; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadow.api.Shadow; @Implements(value = Network.class, minSdk = LOLLIPOP) public class ShadowNetwork { private int netId; /** * Creates new instance of {@link Network}, because its constructor is hidden. * * @param netId The netId. * @return The Network instance. */ public static Network newInstance(int netId) { return Shadow.newInstance(Network.class, new Class[] {int.class}, new Object[] {netId}); } @Implementation protected void __constructor__(int netId) { this.netId = netId; } /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation(minSdk = LOLLIPOP_MR1) protected void bindSocket(DatagramSocket socket) {} /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation protected void bindSocket(Socket socket) {} /** * No-ops. We cannot assume that a Network represents a real network interface on the device * running this test, so we have nothing to bind the socket to. */ @Implementation(minSdk = M) protected void bindSocket(FileDescriptor fd) {} /** * Allows to get the stored netId. * * @return The netId. */ public int getNetId() { return netId; } }
Use real netId in ShadowNetwork, which enables hashCode() and equals(). PiperOrigin-RevId: 229556192
shadows/framework/src/main/java/org/robolectric/shadows/ShadowNetwork.java
Use real netId in ShadowNetwork, which enables hashCode() and equals().
Java
mit
9b907a3e40282a98d9f644cdeb9f6dbb0ae094c2
0
crysxd/ownFX,crysxd/ownFX,crysxd/ownFX,crysxd/ownFX,crysxd/ownFX
package de.crysxd.ownfx; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.Vector; public class Profile { private String name; private int id; private List<Frame> frames = new Vector<>(); public Profile() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Frame> getFrames() { return frames; } public static Profile readProfile(String json) { return GsonSupport.createGson().fromJson(json, Profile.class); } public static Profile readProfile(InputStream jsonStream) throws IOException { return Profile.readProfile(Profile.readStream(jsonStream)); } public static Profile readProfile(File jsonFile) throws IOException { return Profile.readProfile(new FileInputStream(jsonFile)); } private static String readStream(InputStream in) throws IOException { BufferedReader inReader = new BufferedReader(new InputStreamReader(in)); StringBuilder readContent = new StringBuilder(); String line; try { while((line = inReader.readLine()) != null) { readContent.append(line); readContent.append("\n"); } } finally { inReader.close(); } return readContent.toString(); } }
src/de/crysxd/ownfx/Profile.java
package de.crysxd.ownfx; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.Vector; import com.google.gson.GsonBuilder; public class Profile { private String name; private int id; private List<Frame> frames = new Vector<>(); public Profile() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Frame> getFrames() { return frames; } public static Profile readProfile(String json) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(ColorStop.class, new ColorStop.JsonDeserializer()); return gsonBuilder.create().fromJson(json, Profile.class); } public static Profile readProfile(InputStream jsonStream) throws IOException { return Profile.readProfile(Profile.readStream(jsonStream)); } public static Profile readProfile(File jsonFile) throws IOException { return Profile.readProfile(new FileInputStream(jsonFile)); } private static String readStream(InputStream in) throws IOException { BufferedReader inReader = new BufferedReader(new InputStreamReader(in)); StringBuilder readContent = new StringBuilder(); String line; try { while((line = inReader.readLine()) != null) { readContent.append(line); readContent.append("\n"); } } finally { inReader.close(); } return readContent.toString(); } }
Using GsonSupport in Profile
src/de/crysxd/ownfx/Profile.java
Using GsonSupport in Profile
Java
mit
62272a412e343a56564765ba12b1cb3888cb8c99
0
vitalybe/radio-stream,vitalybe/radio-stream,vitalybe/radio-stream,vitalybe/radio-stream,vitalybe/radio-stream,vitalybe/radio-stream
package com.radiostream.player; import com.radiostream.javascript.bridge.PlaylistPlayerEventsEmitter; import com.radiostream.javascript.bridge.PlaylistPlayerBridge; import com.radiostream.networking.MetadataBackend; import com.radiostream.util.SetTimeout; import org.jdeferred.DoneCallback; import org.jdeferred.DonePipe; import org.jdeferred.FailCallback; import org.jdeferred.Promise; import org.jdeferred.impl.DeferredObject; import javax.inject.Inject; import timber.log.Timber; public class PlaylistPlayer implements Song.EventsListener, PlaylistControls { private PlaylistPlayerEventsEmitter mPlayerEventsEmitter; private SetTimeout mSetTimeout; private Playlist mPlaylist; private Song mCurrentSong; private MetadataBackend mMetadataBackend; private boolean mIsLoading = false; private Exception mLastLoadingError = null; private boolean mIsClosed = false; @Inject public PlaylistPlayer(Playlist playlist, PlaylistPlayerEventsEmitter playerEventsEmitter, SetTimeout setTimeout, MetadataBackend metadataBackend) { mPlaylist = playlist; mPlayerEventsEmitter = playerEventsEmitter; mSetTimeout = setTimeout; mMetadataBackend = metadataBackend; } private void setSongLoadingStatus(boolean isLoading, Exception error) { Timber.i("change loading to: %b and error to: %s", isLoading, error != null ? error.toString() : "NULL"); if (isLoading != mIsLoading || mLastLoadingError != error) { Timber.i("value changed"); mIsLoading = isLoading; mLastLoadingError = error; mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } else { Timber.i("value didn't change"); } } public Song getCurrentSong() { return mCurrentSong; } private void setCurrentSong(Song value) { if (value != getCurrentSong()) { if (getCurrentSong() != null) { getCurrentSong().pause(); getCurrentSong().close(); } Timber.i("changing current song to: %s", value.toString()); mCurrentSong = value; mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } } @Override public Promise<Song, Exception, Void> play() { Timber.i("function start"); if (mIsLoading) { Timber.i("invalid request. song already loading"); throw new IllegalStateException("invalid request. song already loading"); } Promise<Song, Exception, Void> promise; if (getCurrentSong() != null && mPlaylist.isCurrentSong(getCurrentSong())) { Timber.i("playing paused song"); getCurrentSong().subscribeToEvents(PlaylistPlayer.this); getCurrentSong().play(); mPlayerEventsEmitter.sendPlaylistPlayerStatus(PlaylistPlayer.this.toBridgeObject()); promise = new DeferredObject<Song, Exception, Void>().resolve(getCurrentSong()).promise(); } else { Timber.i("loading different song from playlist"); promise = retryPreloadAndPlaySong() .then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song result) { return PlaylistPlayer.this.preloadPeekedSong(); } }); } return promise; } @Override public void pause() { Timber.i("function start"); if (mIsLoading || getCurrentSong() == null) { throw new IllegalStateException("no song was loaded yet"); } getCurrentSong().pause(); mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } public boolean getIsPlaying() { if (getCurrentSong() == null) { return false; } else { return getCurrentSong().isPlaying(); } } @Override public void playNext() { Timber.i("function start"); this.mPlaylist.nextSong(); this.play(); } private Promise<Song, Exception, Void> retryPreloadAndPlaySong() { Timber.i("function start"); // Due to: https://github.com/jdeferred/jdeferred/issues/20 // To convert a failed promise to a resolved one, we must create a new deferred object final DeferredObject<Song, Exception, Void> deferredObject = new DeferredObject<>(); // NOTE: the last error to the function is sent since merely retrying // the function doesn't clear the erro setSongLoadingStatus(true, mLastLoadingError); waitForCurrentSongMarkedAsPlayed().then(new DonePipe<Boolean, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Boolean result) { return mPlaylist.peekCurrentSong(); } }).then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { try { Timber.i("preloading song: %s", song.toString()); setCurrentSong(song); return song.preload(); } catch (Exception e) { return new DeferredObject<Song, Exception, Void>().reject(e).promise(); } } }).then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { try { setSongLoadingStatus(false, null); // We won't be playing any new music if playlistPlayer is closed if (!mIsClosed) { PlaylistPlayer.this.play(); } else { Timber.i("playlist player was already closed - not playing loaded song"); } deferredObject.resolve(song); return deferredObject.promise(); } catch (Exception e) { return new DeferredObject<Song, Exception, Void>().reject(e).promise(); } } }).fail(new FailCallback<Exception>() { @Override public void onFail(Exception exception) { Timber.e(exception, "exception occured during next song loading"); setSongLoadingStatus(true, exception); deferredObject.resolve(null); } }); return deferredObject.promise().then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { if (song == null) { Timber.i("no song was loaded - waiting and retrying"); return mSetTimeout.run(10000).then(new DonePipe<Void, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Void result) { Timber.i("timeout finished - retrying"); return PlaylistPlayer.this.retryPreloadAndPlaySong(); } }); } else { Timber.i("song preloaded successfully"); return new DeferredObject<Song, Exception, Void>().resolve(song).promise(); } } }); } private Promise<Boolean, Exception, Void> waitForCurrentSongMarkedAsPlayed() { Timber.i("function start"); if (getCurrentSong() != null) { return getCurrentSong().waitForMarkedAsPlayed(); } else { Timber.i("no current song found - not waiting"); return new DeferredObject<Boolean, Exception, Void>().resolve(true).promise(); } } private Promise<Song, Exception, Void> preloadPeekedSong() { Timber.i("function start"); return mPlaylist.peekNextSong() .then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song peekedSong) { Timber.i("preloading peeked song: %s", peekedSong.toString()); return peekedSong.preload(); } }).fail(new FailCallback<Exception>() { @Override public void onFail(Exception error) { Timber.w("failed to preload song: %s", error.toString()); } }); } void close() { Timber.i("function start"); mIsClosed = true; if (getCurrentSong() != null) { Timber.i("closing current song"); getCurrentSong().close(); } if (mPlaylist != null) { mPlaylist.close(); mPlaylist = null; } } @Override public void onSongFinish(Song song) { Timber.i("function start"); this.playNext(); } @Override public void onSongError(Exception error) { Timber.e(error, "error occured in song '%s'", getCurrentSong()); if (getCurrentSong() != null) { Timber.i("pausing existing song"); getCurrentSong().pause(); } Timber.i("trying to play next song"); play(); } public PlaylistPlayerBridge toBridgeObject() { PlaylistPlayerBridge bridge = new PlaylistPlayerBridge(); bridge.isLoading = mIsLoading; bridge.loadingError = mLastLoadingError; bridge.isPlaying = getIsPlaying(); bridge.playlistBridge = mPlaylist.toBridgeObject(); if (mCurrentSong != null) { bridge.songBridge = mCurrentSong.toBridgeObject(); } return bridge; } public Promise<Void, Exception, Void> updateSongRating(int songId, final int newRating) { Timber.i("function start"); final Song updatedSong = getCurrentSong(); if (updatedSong.getId() == songId) { return mMetadataBackend.updateSongRating(songId, newRating).then(new DoneCallback<Void>() { @Override public void onDone(Void result) { updatedSong.setRating(newRating); Timber.i("song rating updated - sending status update"); mPlayerEventsEmitter.sendPlaylistPlayerStatus(PlaylistPlayer.this.toBridgeObject()); } }); } else { Timber.w("tried to update id %d even though current song %s has id %d", songId, updatedSong.toString(), updatedSong.getId()); return new DeferredObject<Void, Exception, Void>().reject(null); } } }
mobile/android/app/src/main/java/com/radiostream/player/PlaylistPlayer.java
package com.radiostream.player; import com.radiostream.javascript.bridge.PlaylistPlayerEventsEmitter; import com.radiostream.javascript.bridge.PlaylistPlayerBridge; import com.radiostream.networking.MetadataBackend; import com.radiostream.util.SetTimeout; import org.jdeferred.DoneCallback; import org.jdeferred.DonePipe; import org.jdeferred.FailCallback; import org.jdeferred.Promise; import org.jdeferred.impl.DeferredObject; import javax.inject.Inject; import timber.log.Timber; public class PlaylistPlayer implements Song.EventsListener, PlaylistControls { private PlaylistPlayerEventsEmitter mPlayerEventsEmitter; private SetTimeout mSetTimeout; private Playlist mPlaylist; private Song mCurrentSong; private MetadataBackend mMetadataBackend; private boolean mIsLoading = false; private Exception mLoadingError = null; private boolean mIsClosed = false; @Inject public PlaylistPlayer(Playlist playlist, PlaylistPlayerEventsEmitter playerEventsEmitter, SetTimeout setTimeout, MetadataBackend metadataBackend) { mPlaylist = playlist; mPlayerEventsEmitter = playerEventsEmitter; mSetTimeout = setTimeout; mMetadataBackend = metadataBackend; } private void setSongLoadingStatus(boolean isLoading, Exception error) { Timber.i("change loading to: %b and error to: %s", isLoading, error != null ? error.toString() : "NULL"); if (isLoading != mIsLoading || mLoadingError != error) { Timber.i("value changed"); mIsLoading = isLoading; mLoadingError = error; mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } else { Timber.i("value didn't change"); } } public Song getCurrentSong() { return mCurrentSong; } private void setCurrentSong(Song value) { if (value != getCurrentSong()) { if (getCurrentSong() != null) { getCurrentSong().pause(); getCurrentSong().close(); } Timber.i("changing current song to: %s", value.toString()); mCurrentSong = value; mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } } @Override public Promise<Song, Exception, Void> play() { Timber.i("function start"); if (mIsLoading) { Timber.i("invalid request. song already loading"); throw new IllegalStateException("invalid request. song already loading"); } Promise<Song, Exception, Void> promise; if (getCurrentSong() != null && mPlaylist.isCurrentSong(getCurrentSong())) { Timber.i("playing paused song"); getCurrentSong().subscribeToEvents(PlaylistPlayer.this); getCurrentSong().play(); mPlayerEventsEmitter.sendPlaylistPlayerStatus(PlaylistPlayer.this.toBridgeObject()); promise = new DeferredObject<Song, Exception, Void>().resolve(getCurrentSong()).promise(); } else { Timber.i("loading different song from playlist"); promise = retryPreloadAndPlaySong() .then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song result) { return PlaylistPlayer.this.preloadPeekedSong(); } }); } return promise; } @Override public void pause() { Timber.i("function start"); if (mIsLoading || getCurrentSong() == null) { throw new IllegalStateException("no song was loaded yet"); } getCurrentSong().pause(); mPlayerEventsEmitter.sendPlaylistPlayerStatus(this.toBridgeObject()); } public boolean getIsPlaying() { if (getCurrentSong() == null) { return false; } else { return getCurrentSong().isPlaying(); } } @Override public void playNext() { Timber.i("function start"); this.mPlaylist.nextSong(); this.play(); } private Promise<Song, Exception, Void> retryPreloadAndPlaySong() { Timber.i("function start"); // Due to: https://github.com/jdeferred/jdeferred/issues/20 // To convert a failed promise to a resolved one, we must create a new deferred object final DeferredObject<Song, Exception, Void> deferredObject = new DeferredObject<>(); setSongLoadingStatus(true, null); waitForCurrentSongMarkedAsPlayed().then(new DonePipe<Boolean, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Boolean result) { return mPlaylist.peekCurrentSong(); } }).then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { try { Timber.i("preloading song: %s", song.toString()); setCurrentSong(song); return song.preload(); } catch (Exception e) { return new DeferredObject<Song, Exception, Void>().reject(e).promise(); } } }).then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { try { setSongLoadingStatus(false, null); // We won't be playing any new music if playlistPlayer is closed if (!mIsClosed) { PlaylistPlayer.this.play(); } else { Timber.i("playlist player was already closed - not playing loaded song"); } deferredObject.resolve(song); return deferredObject.promise(); } catch (Exception e) { return new DeferredObject<Song, Exception, Void>().reject(e).promise(); } } }).fail(new FailCallback<Exception>() { @Override public void onFail(Exception exception) { Timber.e(exception, "exception occured during next song loading"); setSongLoadingStatus(true, exception); deferredObject.resolve(null); } }); return deferredObject.promise().then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song song) { if (song == null) { Timber.i("no song was loaded - waiting and retrying"); return mSetTimeout.run(10000).then(new DonePipe<Void, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Void result) { Timber.i("timeout finished - retrying"); return PlaylistPlayer.this.retryPreloadAndPlaySong(); } }); } else { Timber.i("song preloaded successfully"); return new DeferredObject<Song, Exception, Void>().resolve(song).promise(); } } }); } private Promise<Boolean, Exception, Void> waitForCurrentSongMarkedAsPlayed() { Timber.i("function start"); if (getCurrentSong() != null) { return getCurrentSong().waitForMarkedAsPlayed(); } else { Timber.i("no current song found - not waiting"); return new DeferredObject<Boolean, Exception, Void>().resolve(true).promise(); } } private Promise<Song, Exception, Void> preloadPeekedSong() { Timber.i("function start"); return mPlaylist.peekNextSong() .then(new DonePipe<Song, Song, Exception, Void>() { @Override public Promise<Song, Exception, Void> pipeDone(Song peekedSong) { Timber.i("preloading peeked song: %s", peekedSong.toString()); return peekedSong.preload(); } }).fail(new FailCallback<Exception>() { @Override public void onFail(Exception error) { Timber.w("failed to preload song: %s", error.toString()); } }); } void close() { Timber.i("function start"); mIsClosed = true; if (getCurrentSong() != null) { Timber.i("closing current song"); getCurrentSong().close(); } if (mPlaylist != null) { mPlaylist.close(); mPlaylist = null; } } @Override public void onSongFinish(Song song) { Timber.i("function start"); this.playNext(); } @Override public void onSongError(Exception error) { Timber.e(error, "error occured in song '%s'", getCurrentSong()); if (getCurrentSong() != null) { Timber.i("pausing existing song"); getCurrentSong().pause(); } Timber.i("trying to play next song"); play(); } public PlaylistPlayerBridge toBridgeObject() { PlaylistPlayerBridge bridge = new PlaylistPlayerBridge(); bridge.isLoading = mIsLoading; bridge.loadingError = mLoadingError; bridge.isPlaying = getIsPlaying(); bridge.playlistBridge = mPlaylist.toBridgeObject(); if (mCurrentSong != null) { bridge.songBridge = mCurrentSong.toBridgeObject(); } return bridge; } public Promise<Void, Exception, Void> updateSongRating(int songId, final int newRating) { Timber.i("function start"); final Song updatedSong = getCurrentSong(); if (updatedSong.getId() == songId) { return mMetadataBackend.updateSongRating(songId, newRating).then(new DoneCallback<Void>() { @Override public void onDone(Void result) { updatedSong.setRating(newRating); Timber.i("song rating updated - sending status update"); mPlayerEventsEmitter.sendPlaylistPlayerStatus(PlaylistPlayer.this.toBridgeObject()); } }); } else { Timber.w("tried to update id %d even though current song %s has id %d", songId, updatedSong.toString(), updatedSong.getId()); return new DeferredObject<Void, Exception, Void>().reject(null); } } }
show error on song loading errors
mobile/android/app/src/main/java/com/radiostream/player/PlaylistPlayer.java
show error on song loading errors
Java
mit
198ca4a030d44515d6c6c6f72568bd7e145abf68
0
simonpercic/WaterfallCache,simonpercic/WaterfallCache
package eu.simonpercic.android.waterfallcache; import android.content.Context; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.List; import eu.simonpercic.android.waterfallcache.cache.Cache; import eu.simonpercic.android.waterfallcache.cache.MemoryLruCache; import eu.simonpercic.android.waterfallcache.cache.ReservoirCache; import rx.Observable; import rx.Observable.Transformer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by Simon Percic on 17/07/15. */ public class WaterfallCache implements Cache { @NonNull private final List<Cache> caches; private WaterfallCache(@NonNull List<Cache> caches) { this.caches = caches; } public <T> Observable<T> get(final String key, final Class<T> classOfT) { return doOnce(null, cache -> cache.get(key, classOfT), value -> value != null) .onErrorReturn(throwable -> null); } public Observable<Boolean> put(final String key, final Object object) { return doOnAll(cache -> cache.put(key, object)); } public Observable<Boolean> contains(final String key) { return doOnce(false, cache -> cache.contains(key), value -> value); } public Observable<Boolean> remove(final String key) { return doOnAll(cache -> cache.remove(key)); } public Observable<Boolean> clear() { return doOnAll(Cache::clear); } private Observable<Boolean> doOnAll(Func1<Cache, Observable<Boolean>> cacheFn) { Observable<Boolean> observable = Observable.just(false); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); observable = observable.flatMap(success -> cacheFn.call(cache)); } return observable.compose(applySchedulers()); } private <T> Observable<T> doOnce(T defaultValue, Func1<Cache, Observable<T>> cacheFn, Predicate<T> condition) { Observable<T> observable = Observable.just(defaultValue); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); if (i == 0) { observable = observable.flatMap(s -> cacheFn.call(cache)); } else { observable = observable.flatMap(value -> { if (condition.apply(value)) { return Observable.just(value).subscribeOn(Schedulers.immediate()); } else { return cacheFn.call(cache); } }); } } return observable.compose(applySchedulers()); } @SuppressWarnings("RedundantCast") private final Transformer schedulersTransformer = observable -> ((Observable) observable).observeOn( AndroidSchedulers.mainThread()); private <T> Transformer<T, T> applySchedulers() { //noinspection unchecked return (Transformer<T, T>) schedulersTransformer; } private interface Predicate<T> { boolean apply(T value); } // region Builder public static class Builder { private final List<Cache> caches; private Builder() { caches = new ArrayList<>(); } public static Builder create() { return new Builder(); } public Builder addMemoryCache(int size) { return addCache(new MemoryLruCache(size)); } public Builder addDiskCache(Context context, int sizeInBytes) { return addCache(new ReservoirCache(context, sizeInBytes)); } public Builder addCache(Cache cache) { caches.add(cache); return this; } public WaterfallCache build() { return new WaterfallCache(caches); } } // endregion }
app/src/main/java/eu/simonpercic/android/waterfallcache/WaterfallCache.java
package eu.simonpercic.android.waterfallcache; import android.content.Context; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.List; import eu.simonpercic.android.waterfallcache.cache.Cache; import eu.simonpercic.android.waterfallcache.cache.MemoryLruCache; import eu.simonpercic.android.waterfallcache.cache.ReservoirCache; import rx.Observable; import rx.Observable.Transformer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Simon Percic on 17/07/15. */ public class WaterfallCache implements Cache { @NonNull private final List<Cache> caches; private WaterfallCache(@NonNull List<Cache> caches) { this.caches = caches; } public <T> Observable<T> get(final String key, final Class<T> classOfT) { Observable<T> observable = Observable.just((T) null); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); if (i == 0) { observable = observable.flatMap(s -> cache.get(key, classOfT)); } else { observable = observable.flatMap(o -> { if (o != null) { return Observable.just(o).subscribeOn(Schedulers.immediate()); } else { return cache.get(key, classOfT); } }); } } return observable .onErrorReturn(throwable -> null) .compose(applySchedulers()); } public Observable<Boolean> put(final String key, final Object object) { Observable<Boolean> observable = Observable.just(false); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); observable = observable.flatMap(success -> cache.put(key, object)); } return observable.compose(applySchedulers()); } public Observable<Boolean> contains(final String key) { Observable<Boolean> observable = Observable.just(false); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); if (i == 0) { observable = observable.flatMap(s -> cache.contains(key)); } else { observable = observable.flatMap(contains -> { if (contains) { return Observable.just(true).subscribeOn(Schedulers.immediate()); } else { return cache.contains(key); } }); } } return observable.compose(applySchedulers()); } public Observable<Boolean> remove(final String key) { Observable<Boolean> observable = Observable.just(false); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); observable = observable.flatMap(success -> cache.remove(key)); } return observable.compose(applySchedulers()); } public Observable<Boolean> clear() { Observable<Boolean> observable = Observable.just(false); for (int i = 0; i < caches.size(); i++) { Cache cache = caches.get(i); observable = observable.flatMap(success -> cache.clear()); } return observable.compose(applySchedulers()); } @SuppressWarnings("RedundantCast") private final Transformer schedulersTransformer = observable -> ((Observable) observable).observeOn( AndroidSchedulers.mainThread()); private <T> Transformer<T, T> applySchedulers() { //noinspection unchecked return (Transformer<T, T>) schedulersTransformer; } // region Builder public static class Builder { private final List<Cache> caches; private Builder() { caches = new ArrayList<>(); } public static Builder create() { return new Builder(); } public Builder addMemoryCache(int size) { return addCache(new MemoryLruCache(size)); } public Builder addDiskCache(Context context, int sizeInBytes) { return addCache(new ReservoirCache(context, sizeInBytes)); } public Builder addCache(Cache cache) { caches.add(cache); return this; } public WaterfallCache build() { return new WaterfallCache(caches); } } // endregion }
Generalized common logic
app/src/main/java/eu/simonpercic/android/waterfallcache/WaterfallCache.java
Generalized common logic
Java
mit
6ca6144fbedb87319f56deea03ce165b131dd8e6
0
jetpeter/android-backswipe-view
package me.jefferey.backswipeview; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; /** * Created by jpetersen on 4/12/15. */ public class BackSwipeManager implements BackSwipeLayout.BackSwipeInterface, FragmentManager.OnBackStackChangedListener { private final String FRAGMENT_TAG = "StackEntry"; private final FragmentManager mFragmentManager; private final BackSwipeLayout mBackSwipeLayout; private final int mContentViewId; public BackSwipeManager(FragmentManager fragmentManager, BackSwipeLayout backSwipeLayout) { mBackSwipeLayout = backSwipeLayout; mBackSwipeLayout.setBackSwipeInterface(this); mBackSwipeLayout.setBackSwipeEnabled(fragmentManager.getBackStackEntryCount() > 0); mContentViewId = mBackSwipeLayout.getId(); mFragmentManager = fragmentManager; hideBackStackFragments(); mFragmentManager.addOnBackStackChangedListener(this); } /** * Must be called when the parent activity is first created. This adds the base level fragment * that cannot be swiped back. * Do not call this if the activity is being recreated from a savedInstanceState since the fragment * manager will add it for you. */ public void setBaseFragment(Fragment fragment) { FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.add(mContentViewId, fragment, FRAGMENT_TAG + "_" + mFragmentManager.getBackStackEntryCount()); ft.commit(); } /** * Adds a new back swipeable content fragment. The fragment should fill the entire page. */ public void addContentFragment(Fragment fragment) { FragmentTransaction ft = mFragmentManager.beginTransaction(); Fragment currentContentFragment = mFragmentManager.findFragmentById(mContentViewId); int backStackCount = mFragmentManager.getBackStackEntryCount(); ft.addToBackStack(FRAGMENT_TAG + "_" + backStackCount); ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right); // Manually increase the current fragment back stack count. ft.add(mContentViewId, fragment, FRAGMENT_TAG + "_" + (backStackCount + 1)); ft.hide(currentContentFragment); ft.commit(); } @Override public void onBackStackChanged() { if (mFragmentManager.getBackStackEntryCount() == 0) { mBackSwipeLayout.setBackSwipeEnabled(false); } else { mBackSwipeLayout.setBackSwipeEnabled(true); } } @Override public void onBackSwipeStarted() { Fragment frag = getLatestFragmentFromBackStack(); mFragmentManager.beginTransaction().show(frag).commit(); } @Override public void onBackSwipeEnd(boolean didSwipeBack) { if (didSwipeBack) { mFragmentManager.popBackStack(); } else { // The swipe was canceled and the animation finished, we now need to hide the first fragment in the stack Fragment frag = getLatestFragmentFromBackStack(); mFragmentManager.beginTransaction().hide(frag).commit(); } } /** * Using the tags set when adding a fragment find the next fragment in the back stack if one exists */ private Fragment getLatestFragmentFromBackStack() { int entryCount = mFragmentManager.getBackStackEntryCount(); if (entryCount > 0) { FragmentManager.BackStackEntry entry = mFragmentManager.getBackStackEntryAt(entryCount - 1); return mFragmentManager.findFragmentByTag(entry.getName()); } else { return null; } } /** * When the fragment manager is restored from saved instance state hidden fragments are made visible * again. This is called in the constructor to make sure that back stack fragments are now made * visible. */ private void hideBackStackFragments() { int entryCount = mFragmentManager.getBackStackEntryCount(); FragmentTransaction ft = mFragmentManager.beginTransaction(); for (int i = 0; i < entryCount; i++) { FragmentManager.BackStackEntry entry = mFragmentManager.getBackStackEntryAt(i); Fragment frag = mFragmentManager.findFragmentByTag(entry.getName()); ft.hide(frag); } ft.commit(); } }
backswipeview/src/main/java/me/jefferey/backswipeview/BackSwipeManager.java
package me.jefferey.backswipeview; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; /** * Created by jpetersen on 4/12/15. */ public class BackSwipeManager implements BackSwipeLayout.BackSwipeInterface, FragmentManager.OnBackStackChangedListener { private final String FRAGMENT_TAG = "StackEntry"; private final FragmentManager mFragmentManager; private final BackSwipeLayout mBackSwipeLayout; private final int mContentViewId; public BackSwipeManager(FragmentManager fragmentManager, BackSwipeLayout backSwipeLayout) { mBackSwipeLayout = backSwipeLayout; mBackSwipeLayout.setBackSwipeInterface(this); mBackSwipeLayout.setBackSwipeEnabled(fragmentManager.getBackStackEntryCount() > 0); mContentViewId = mBackSwipeLayout.getId(); mFragmentManager = fragmentManager; mFragmentManager.addOnBackStackChangedListener(this); } /** * Must be called when the parent activity is first created. This adds the base level fragment * that cannot be swiped back. * Do not call this if the activity is being recreated from a savedInstanceState since the fragment * manager will add it for you. */ public void setBaseFragment(Fragment fragment) { FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.add(mContentViewId, fragment, FRAGMENT_TAG + "_" + mFragmentManager.getBackStackEntryCount()); ft.commit(); } /** * Adds a new back swipeable content fragment. The fragment should fill the entire page. */ public void addContentFragment(Fragment fragment) { FragmentTransaction ft = mFragmentManager.beginTransaction(); Fragment currentContentFragment = mFragmentManager.findFragmentById(mContentViewId); int backStackCount = mFragmentManager.getBackStackEntryCount(); ft.addToBackStack(FRAGMENT_TAG + "_" + backStackCount); ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right); // Manually increase the current fragment back stack count. ft.add(mContentViewId, fragment, FRAGMENT_TAG + "_" + (backStackCount + 1)); ft.hide(currentContentFragment); ft.commit(); } @Override public void onBackStackChanged() { if (mFragmentManager.getBackStackEntryCount() == 0) { mBackSwipeLayout.setBackSwipeEnabled(false); } else { mBackSwipeLayout.setBackSwipeEnabled(true); } } @Override public void onBackSwipeStarted() { Fragment frag = getLatestFragmentFromBackStack(); mFragmentManager.beginTransaction().show(frag).commit(); } @Override public void onBackSwipeEnd(boolean didSwipeBack) { if (didSwipeBack) { mFragmentManager.popBackStack(); } else { // The swipe was canceled and the animation finished, we now need to hide the first fragment in the stack Fragment frag = getLatestFragmentFromBackStack(); mFragmentManager.beginTransaction().hide(frag).commit(); } } /** * Using the tags set when adding a fragment find the next fragment in the back stack if one exists */ private Fragment getLatestFragmentFromBackStack() { int entryCount = mFragmentManager.getBackStackEntryCount(); if (entryCount > 0) { FragmentManager.BackStackEntry entry = mFragmentManager.getBackStackEntryAt(entryCount - 1); return mFragmentManager.findFragmentByTag(entry.getName()); } else { return null; } } }
Fix hidden fragments becoming visible on orientation change
backswipeview/src/main/java/me/jefferey/backswipeview/BackSwipeManager.java
Fix hidden fragments becoming visible on orientation change
Java
lgpl-2.1
6d6f5b685c7d8bb39aab9325fc57ff8febf0b3f0
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/* $Id$ */ package jade.proto; import java.util.Enumeration; import java.util.Vector; import jade.lang.acl.*; /************************************************************** Name: CommunicativeAction Responsibility and Collaborations: + Represents a single step of an agent protocol, holding the ACL message to send back to other protocol participants. (ACLMessage) ****************************************************************/ class CommunicativeAction { private ACLMessage myMessage; private Protocol myProtocol; // This can be either Protocol.initiatorRole or Protocol.responderRole. private int myRole; // This Vector holds the CommunicativeActions that can follow the // current one in its protocol. private Vector allowedAnswers = new Vector(); // A CommunicativeAction is bound to an ACL message and an // interaction protocol for its whole lifetime. public CommunicativeAction(ACLMessage msg, Protocol p) { myMessage = msg; myProtocol = p; } // Role handling methods. public void makeInitiator() { myRole = Protocol.initiatorRole; } public void makeResponder() { myRole = Protocol.responderRole; } public int getRole() { return myRole; } // Sets a link between two CommunicativeActions, meaning that 'ca' // is an allowed message after 'this' in protocol 'myProtocol'. public void addAnswer(CommunicativeAction ca) { allowedAnswers.addElement(ca); } // Returns the allowed answers to the CommunicativeAction in // 'myProtocol' interaction protocol. public Enumeration getAnswers() { return allowedAnswers.elements(); } // Returns the ACL message of the CommunicativeAction public ACLMessage getMessage() { return myMessage; } }
src/jade/proto/CommunicativeAction.java
package jade.proto; /************************************************************** Name: CommunicativeAction Responsibility and Collaborations: + Represents a single step of an agent protocol, holding the ACL message to send back to other protocol participants. (ACLMessage) ****************************************************************/ class CommunicativeAction { }
First implementation of class CommunicativeAction.
src/jade/proto/CommunicativeAction.java
First implementation of class CommunicativeAction.
Java
lgpl-2.1
db8b447927a0df26548d2d673fb34fc32dac7ea0
0
levants/lightmare
package org.lightmare.utils; /** * Utility class for JNDI names * * @author levan * */ public class NamingUtils { // User transaction JNDI name public static final String USER_TRANSACTION_NAME = "java:comp/UserTransaction"; // String prefixes for JNDI names public static final String JPA_NAME_PREF = "java:comp/env/"; public static final String EJB_NAME_PREF = "ejb:"; private static final String DS_JNDI_FREFIX = "java:/"; private static final String EJB_NAME_DELIM = "\\"; private static final String EJB_APP_DELIM = "!"; // Digital values for naming utilities public static final int EJB_NAME_LENGTH = 4; private static final int BEAN_NAMES_INDEX = 1; private static final int INTERFACE_IDEX = 0; private static final int BEAN_INDEX = 1; // Error messages public static final String COULD_NOT_UNBIND_NAME_ERROR = "Could not unbind jndi name %s cause %s"; /** * Descriptor class which contains EJB bean class name and its interface * class name * * @author levan * */ public static class BeanDescriptor { private String beanName; private String interfaceName; public BeanDescriptor(String beanName, String interfaceName) { this.beanName = beanName; this.interfaceName = interfaceName; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } } /** * Creates JNDI name prefixes for EJB objects * * @param jndiName * @return */ public static String createJpaJndiName(String jndiName) { return StringUtils.concat(JPA_NAME_PREF, jndiName); } /** * Converts passed JNDI name to JPA name * * @param jndiName * @return {@link String} */ public static String formatJpaJndiName(String jndiName) { String name = jndiName.replace(JPA_NAME_PREF, StringUtils.EMPTY_STRING); return name; } /** * Creates EJB names from passed JNDI name * * @param jndiName * @return {@link String} */ public static String createEjbJndiName(String jndiName) { return StringUtils.concat(EJB_NAME_PREF, jndiName); } /** * Converts passed JNDI name to bean name * * @param jndiName * @return {@link String} */ public static String formatEjbJndiName(String jndiName) { String name = jndiName.replace(EJB_NAME_PREF, StringUtils.EMPTY_STRING); return name; } /** * Clears JNDI prefix "java:/" for data source name * * @param jndiName * @return {@link String} */ public static String clearDataSourceName(String jndiName) { String clearName; if (StringUtils.valid(jndiName) && jndiName.startsWith(DS_JNDI_FREFIX)) { clearName = jndiName.replace(DS_JNDI_FREFIX, StringUtils.EMPTY_STRING); } else { clearName = jndiName; } return clearName; } /** * Adds JNDI prefix "java:/" to data source name * * @param clearName * @return {@link String} */ public static String toJndiDataSourceName(String clearName) { String jndiName; if (CollectionUtils.valid(clearName) && StringUtils.notContains(clearName, DS_JNDI_FREFIX)) { jndiName = StringUtils.concat(DS_JNDI_FREFIX, clearName); } else { jndiName = clearName; } return jndiName; } /** * Parses bean JNDI name for lookup bean * * @param jndiName * @return {@link BeanDescriptor} */ public static BeanDescriptor parseEjbJndiName(String jndiName) { String pureName = jndiName.substring(EJB_NAME_LENGTH); String[] formatedNames = pureName.split(EJB_NAME_DELIM); String beanNames = formatedNames[BEAN_NAMES_INDEX]; String[] beanDescriptors = beanNames.split(EJB_APP_DELIM); String interfaceName = beanDescriptors[INTERFACE_IDEX]; String beanName = beanDescriptors[BEAN_INDEX]; BeanDescriptor descriptor = new BeanDescriptor(beanName, interfaceName); return descriptor; } }
src/main/java/org/lightmare/utils/NamingUtils.java
package org.lightmare.utils; /** * Utility class for JNDI names * * @author levan * */ public class NamingUtils { // User transaction JNDI name public static final String USER_TRANSACTION_NAME = "java:comp/UserTransaction"; // String prefixes for JNDI names public static final String JPA_NAME_PREF = "java:comp/env/"; public static final String EJB_NAME_PREF = "ejb:"; private static final String DS_JNDI_FREFIX = "java:/"; private static final String EJB_NAME_DELIM = "\\"; private static final String EJB_APP_DELIM = "!"; // Digital values for naming utilities public static final int EJB_NAME_LENGTH = 4; private static final int BEAN_NAMES_INDEX = 1; private static final int INTERFACE_IDEX = 0; private static final int BEAN_INDEX = 1; // Error messages public static final String COULD_NOT_UNBIND_NAME_ERROR = "Could not unbind jndi name %s cause %s"; /** * Descriptor class which contains EJB bean class name and its interface * class name * * @author levan * */ public static class BeanDescriptor { private String beanName; private String interfaceName; public BeanDescriptor(String beanName, String interfaceName) { this.beanName = beanName; this.interfaceName = interfaceName; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } } /** * Creates JNDI name prefixes for EJB objects * * @param jndiName * @return */ public static String createJpaJndiName(String jndiName) { return StringUtils.concat(JPA_NAME_PREF, jndiName); } /** * Converts passed JNDI name to JPA name * * @param jndiName * @return {@link String} */ public static String formatJpaJndiName(String jndiName) { String name = jndiName.replace(JPA_NAME_PREF, StringUtils.EMPTY_STRING); return name; } /** * Creates EJB names from passed JNDI name * * @param jndiName * @return {@link String} */ public static String createEjbJndiName(String jndiName) { return StringUtils.concat(EJB_NAME_PREF, jndiName); } /** * Converts passed JNDI name to bean name * * @param jndiName * @return {@link String} */ public static String formatEjbJndiName(String jndiName) { String name = jndiName.replace(EJB_NAME_PREF, StringUtils.EMPTY_STRING); return name; } /** * Clears JNDI prefix "java:/" for data source name * * @param jndiName * @return {@link String} */ public static String clearDataSourceName(String jndiName) { String clearName; if (CollectionUtils.valid(jndiName) && jndiName.startsWith(DS_JNDI_FREFIX)) { clearName = jndiName.replace(DS_JNDI_FREFIX, StringUtils.EMPTY_STRING); } else { clearName = jndiName; } return clearName; } /** * Adds JNDI prefix "java:/" to data source name * * @param clearName * @return {@link String} */ public static String toJndiDataSourceName(String clearName) { String jndiName; if (CollectionUtils.valid(clearName) && StringUtils.notContains(clearName, DS_JNDI_FREFIX)) { jndiName = StringUtils.concat(DS_JNDI_FREFIX, clearName); } else { jndiName = clearName; } return jndiName; } /** * Parses bean JNDI name for lookup bean * * @param jndiName * @return {@link BeanDescriptor} */ public static BeanDescriptor parseEjbJndiName(String jndiName) { String pureName = jndiName.substring(EJB_NAME_LENGTH); String[] formatedNames = pureName.split(EJB_NAME_DELIM); String beanNames = formatedNames[BEAN_NAMES_INDEX]; String[] beanDescriptors = beanNames.split(EJB_APP_DELIM); String interfaceName = beanDescriptors[INTERFACE_IDEX]; String beanName = beanDescriptors[BEAN_INDEX]; BeanDescriptor descriptor = new BeanDescriptor(beanName, interfaceName); return descriptor; } }
moved "valid" and "invalid" methods from class CollectionUtils to class StringUtils and improved dependent classes
src/main/java/org/lightmare/utils/NamingUtils.java
moved "valid" and "invalid" methods from class CollectionUtils to class StringUtils and improved dependent classes
Java
lgpl-2.1
fb9a43e015a63bf410beb20cd7847803abb0e75b
0
trajano/bizcal,Ayuto/bizcal
/******************************************************************************* * Bizcal is a component library for calendar widgets written in java using swing. * Copyright (C) 2007 Frederik Bertilsson * Contributors: Martin Heinemann martin.heinemann(at)tudor.lu * * http://sourceforge.net/projects/bizcal/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * *******************************************************************************/ package bizcal.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * @author Fredrik Bertilsson * @author martin.heinemann(at)tudor.lu */ public class DateUtil { public static final int MILLIS_SECOND = 1000; public static final int MILLIS_MINUTE = 60 * MILLIS_SECOND; public static final int MILLIS_HOUR = MILLIS_MINUTE * 60; public static final int MILLIS_DAY = MILLIS_HOUR * 24; public static final int MINUTES_HOUR = 60; public static final int MINUTES_DAY = MINUTES_HOUR * 24; public static final int MINUTES_WEEK = MINUTES_DAY * 7; public static final int DAYS_WEEK = 7; private static CalendarFactory calFactory = new DefaultCalendarFactory(); public static Date round2Day(Date date) { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Rounds the date to the given hour. Minutes and seconds are also 0. * * @param date * @param hour * @return */ public static Date round2Hour(Date date, int hour) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); if (hour > -1 && hour < 25) { cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); } return cal.getTime(); /* ================================================== */ } /** * sets the appropriate minute. If the value is bigger than 60 * it will adapt the hours and the day. <strong>Not the month!!!</strong> * * @param date * @param minute * @return */ public static Date round2Minute(Date date, int minute) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); if (minute < 0) minute = (-1) * minute; /* ------------------------------------------------------- */ // get overlapping hours int overlapping = minute / 60; // compute new hour int oldHour = cal.get(Calendar.HOUR_OF_DAY); int addDays = (oldHour+overlapping) / 24; // set the hours cal.set(Calendar.HOUR_OF_DAY, (oldHour+overlapping) % 24); // set the days if (addDays > 0) cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + addDays); // this is not finished yet. Month overflow is not handled!! /* ------------------------------------------------------- */ // set minutes cal.set(Calendar.MINUTE, (minute % 60)); return cal.getTime(); /* ================================================== */ } /** * @param date * @return */ public static Date round2Minute(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); /* ================================================== */ } /** * Rounds the time to a nicer value. One of * 00, 15, 30, 45 depending of the current time. * Minutes are rounded off. * * @param date * @return */ public static Date roundNice(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); /* ------------------------------------------------------- */ int minutes = cal.get(Calendar.MINUTE); int multiplier = (minutes / 15); minutes = multiplier * 15; cal.set(Calendar.MINUTE, minutes); return cal.getTime(); /* ================================================== */ } /** * Returns the day of the week as int * * @param date * @return */ public static int getDayOfWeek(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_WEEK); } public static String getWeekday(Date date) throws Exception { DateFormat format = new SimpleDateFormat("EEEEE", Locale.getDefault()); format.setTimeZone(TimeZone.getDefault()); return format.format(date); } /** * returns the current hour of the date * * @param date * @return */ public static int getHourOfDay(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.HOUR_OF_DAY); /* ================================================== */ } /** * Returns the minutes of the hour * * @param date * @return */ public static int getMinuteOfHour(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.MINUTE); /* ================================================== */ } public static TimeOfDay getTimeOfDay(Date date) throws Exception { return new TimeOfDay(date.getTime() - round2Day(date).getTime()); } public static Date getStartOfWeek(Date date) { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Sets the weekday to the current date * * @param date * @param weekday * @return */ public static Date setDayOfWeek(Date date, int weekday) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, weekday); return cal.getTime(); /* ================================================== */ } public static int getYear(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * @param date * @return * @throws Exception */ public static int getMonth(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.MONTH); } /** * @param date * @return * @throws Exception */ public static int getDayOfMonth(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_MONTH); } /** * Returns the day of the year * @param date * @return */ public static int getDayOfYear(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_YEAR); } /** * Returns the date in distance to the given one, according to the offset (diff) given in days.<br/> * Example:<br/> <strong>date =</strong> 2007-03-23 (Friday)<br/> * <strong>diff = </strong>3<br> * <strong>getDiffDay = </strong> 2007-03-20 (Tuesday) * * @param date * @param diff * @return * @throws Exception */ public static Date getDiffDay(Date date, int diff) { Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.DAY_OF_WEEK, diff); return cal.getTime(); } /** * Moves the date by the given amount of days. * It will consider any month overflows and switches * automatically to the next month. * * @param date * @param offset * @return */ public static Date move(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, offset); return cal.getTime(); /* ================================================== */ } /** * Moves the given date by the given minutes. * * @param date * @param offset * @return */ public static Date moveByMinute(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.MINUTE, offset); return cal.getTime(); /* ================================================== */ } /** * Moves the given date by the given years * * @param date * @param offset years to add * @return */ public static Date moveByYear(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.YEAR, offset); return cal.getTime(); /* ================================================== */ } /** * Sets the date to 23:59:59 * * @param date */ public static Date move2Midnight(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 59); return cal.getTime(); /* ================================================== */ } /** * Sets the date to 00:00:00 * * @param date */ public static Date move2Morning(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); /* ================================================== */ } /** * Returns the diff of the two dates * * @param oldDate * @param newDate * @return */ public static long getDiffDay(Date oldDate, Date newDate) { /* ================================================== */ long diff = 0; // if moved to a later date if (newDate.getTime() > oldDate.getTime()) { /* ------------------------------------------------------- */ diff = newDate.getTime() - oldDate.getTime(); /* ------------------------------------------------------- */ } else { /* ------------------------------------------------------- */ diff = (-1)*(oldDate.getTime() - newDate.getTime()); /* ------------------------------------------------------- */ } return diff; /* ================================================== */ } /** * Returns a list of normalized Dates * that are between the two dates. * Normalized means, the time is set to 00:00:00 * The start and end are the first and last dates in the list and * will not be normalized. * * @param start * @param end * @return */ public static List<Date> getDayRange(Date start, Date end) { /* ================================================== */ List<Date> dates = new ArrayList<Date>(0); /* ------------------------------------------------------- */ if (start == null || end == null) return dates; /* ------------------------------------------------------- */ // add the first element dates.add(start); // loop as long as the next day is before the end Date normalizedEnd = round2Day(end); Date next = start; /* ------------------------------------------------------- */ while (next.before(normalizedEnd)) { dates.add(getDiffDay(next, 1)); next = round2Day(getDiffDay(next, 1)); } /* ------------------------------------------------------- */ // add last element dates.add(end); /* ------------------------------------------------------- */ return dates; /* ================================================== */ } /** * Returns the number of days that are between the two * day of week * [startDay,endDay] * [1..7] * * @param startDay * @param endDay * @return */ public static int getDiffDay(int startDay, int endDay) { /* ================================================== */ // if the startday is greater than the end day // add 7 days to the end plus one to inlcude the end day if (startDay > endDay) endDay = endDay + 7; /* ------------------------------------------------------- */ return endDay - startDay + 1; /* ================================================== */ } /** * Returns the amount of minutes that are between the two dates * * @param startDate * @param end * @return minutes */ public static long getDiffMinutes(Date startDate, Date endDate) { /* ====================================================== */ // if (isSameDay(startDate, endDate)) { // /* ------------------------------------------------------- */ // return getMinutesOfRestDay(endDate) - getMinutesOfRestDay(startDate); // /* ------------------------------------------------------- */ // } /* ------------------------------------------------------- */ return (endDate.getTime() / MILLIS_MINUTE) - (startDate.getTime() / MILLIS_MINUTE); /* ====================================================== */ } /** * Counts the minutes from this date up to midnight * * @param date * @return */ public static int getMinutesOfRestDay(Date date) { /* ================================================== */ if (date == null) return 0; /* ------------------------------------------------------- */ // count minutes to midnight /* ------------------------------------------------------- */ int sum = 0; /* ------------------------------------------------------- */ Calendar cal = new GregorianCalendar(); cal.setTime(date); /* ------------------------------------------------------- */ int minute = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR_OF_DAY); /* ------------------------------------------------------- */ // add the minutes up to the next hour /* ------------------------------------------------------- */ sum = 60 - minute; /* ------------------------------------------------------- */ // for each hour, until midnight, add 60 minutes /* ------------------------------------------------------- */ int fac = 23 - hour; sum = sum + fac * 60; return sum; /* ================================================== */ } /** * Counts the minutes from midnight to this date * * @param date * @return */ public static int getMinutesOfDay(Date date) { /* ================================================== */ if (date == null) return 0; /* ------------------------------------------------------- */ long diffMinutes = getDiffMinutes(move2Morning(date), date); /* ------------------------------------------------------- */ return (int) diffMinutes; /* ================================================== */ } /** * Checks if the dates are the same day of the year. * They can be in different years. Result will be true. * * @param d1 * @param d2 * @return */ public static boolean isSameDayOfYear(Date d1, Date d2) { GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)) return true; return false; } /** * Checks if the dates are on the exact same day. * * @param d1 * @param d2 * @return */ public static boolean isSameDay(Date d1, Date d2) { /* ================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ================================================== */ } /** * Checks if the date in the same week inthe same year * * @param d1 * @param d2 * @return */ public static boolean isSameWeek(Date d1, Date d2) { /* ====================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ====================================================== */ } /** * Checks if the dates are in the same month in the same year * * @param d1 * @param d2 * @return */ public static boolean isSameMonth(Date d1, Date d2) { /* ====================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ====================================================== */ } /** * Returns true if the dates are in the same year * * @param d1 * @param d2 * @return true if both are in the same year */ public static boolean isSameYear(Date d1, Date d2) { /* ================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); /* ------------------------------------------------------- */ return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)); /* ================================================== */ } /** * True if the date1 is a day before date2 * * @param d1 * @param d2 * @return */ public static boolean isBeforeDay(Date d1, Date d2) { /* ====================================================== */ int dy1 = getDayOfYear(d1); int dy2 = getDayOfYear(d2); /* ------------------------------------------------------- */ int y1 = getYear(d1); int y2 = getYear(d2); /* ------------------------------------------------------- */ if (y1 < y2) return true; if (y1 > y2) return false; /* ------------------------------------------------------- */ // else, we are in the same year /* ------------------------------------------------------- */ return (dy1 < dy2); /* ====================================================== */ } /** * Returns the number of days that are between the two given dates * * @param date2 * @param date1 * @return * @throws Exception */ public static int getDateDiff(Date date2, Date date1) { /* ================================================== */ return (int) ((date2.getTime() - date1.getTime()) / 24 / 3600 / 1000); /* ================================================== */ } /** * @param date * @param time * @return * @throws Exception */ public static Date setTimeOfDate(Date date, TimeOfDay time) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, time.getHour()); cal.set(Calendar.MINUTE, time.getMinute()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } public static Date round2Week(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } public static Date round2Month(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Creates an array of dates in distance of the minutes offset * @param minOffset * @return */ public static Date[] createDateList(int minOffset) { /* ================================================== */ if (minOffset < 0) minOffset = 0; if (minOffset > 60) minOffset = 60; /* ------------------------------------------------------- */ try { /* ------------------------------------------------------- */ Calendar cal = newCalendar(); cal.set(Calendar.DAY_OF_MONTH, 0); cal.set(Calendar.MONTH, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); int capacity = 60*24 / minOffset; Date[] dates = new Date[capacity]; int limit = 60 / minOffset; int count = 1; for (int i = 0; i < capacity; i++) { /* ------------------------------------------------------- */ dates[i] = cal.getTime(); cal.roll(Calendar.MINUTE, minOffset); if (count == limit) { cal.roll(Calendar.HOUR_OF_DAY, 1); count = 0; } count++; /* ------------------------------------------------------- */ } return dates; /* ------------------------------------------------------- */ } catch (Exception e) { e.printStackTrace(); return null; } /* ================================================== */ } /** * Creates a Date object with the current local time * and the given type and value. * * @param value * @return */ public static Date createDate(int type, int value) { /* ================================================== */ Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 0); cal.set(Calendar.MONTH, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(type, value); return cal.getTime(); /* ================================================== */ } /** * Extracts the age out of the day of birth * * @param dayOfBirth * @return */ public static long extractAge(Date dayOfBirth) { /* ================================================== */ Calendar c1 = new GregorianCalendar(); Calendar c2 = new GregorianCalendar(); c2.setTime(dayOfBirth); long year = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR); if (getDayOfYear(c1.getTime()) < getDayOfYear(dayOfBirth)) year--; return year; /* ================================================== */ } public static Calendar newCalendar() { return calFactory.newCalendar(); } public static void setCalendarFactory(CalendarFactory factory) { calFactory = factory; } private static class DefaultCalendarFactory implements CalendarFactory { public Calendar newCalendar() { Calendar cal = Calendar.getInstance(LocaleBroker.getLocale()); cal.setTimeZone(TimeZoneBroker.getTimeZone()); return cal; } } }
src/bizcal/util/DateUtil.java
/******************************************************************************* * Bizcal is a component library for calendar widgets written in java using swing. * Copyright (C) 2007 Frederik Bertilsson * Contributors: Martin Heinemann martin.heinemann(at)tudor.lu * * http://sourceforge.net/projects/bizcal/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * *******************************************************************************/ package bizcal.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * @author Fredrik Bertilsson * @author martin.heinemann(at)tudor.lu */ public class DateUtil { public static final int MILLIS_SECOND = 1000; public static final int MILLIS_MINUTE = 60 * MILLIS_SECOND; public static final int MILLIS_HOUR = MILLIS_MINUTE * 60; public static final int MILLIS_DAY = MILLIS_HOUR * 24; public static final int MINUTES_HOUR = 60; public static final int MINUTES_DAY = MINUTES_HOUR * 24; public static final int MINUTES_WEEK = MINUTES_DAY * 7; public static final int DAYS_WEEK = 7; private static CalendarFactory calFactory = new DefaultCalendarFactory(); public static Date round2Day(Date date) { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Rounds the date to the given hour. Minutes and seconds are also 0. * * @param date * @param hour * @return */ public static Date round2Hour(Date date, int hour) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); if (hour > -1 && hour < 25) { cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); } return cal.getTime(); /* ================================================== */ } /** * sets the appropriate minute. If the value is bigger than 60 * it will adapt the hours and the day. <strong>Not the month!!!</strong> * * @param date * @param minute * @return */ public static Date round2Minute(Date date, int minute) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); if (minute < 0) minute = (-1) * minute; /* ------------------------------------------------------- */ // get overlapping hours int overlapping = minute / 60; // compute new hour int oldHour = cal.get(Calendar.HOUR_OF_DAY); int addDays = (oldHour+overlapping) / 24; // set the hours cal.set(Calendar.HOUR_OF_DAY, (oldHour+overlapping) % 24); // set the days if (addDays > 0) cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + addDays); // this is not finished yet. Month overflow is not handled!! /* ------------------------------------------------------- */ // set minutes cal.set(Calendar.MINUTE, (minute % 60)); return cal.getTime(); /* ================================================== */ } /** * @param date * @return */ public static Date round2Minute(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); /* ================================================== */ } /** * Rounds the time to a nicer value. One of * 00, 15, 30, 45 depending of the current time. * Minutes are rounded off. * * @param date * @return */ public static Date roundNice(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); /* ------------------------------------------------------- */ int minutes = cal.get(Calendar.MINUTE); int multiplier = (minutes / 15); minutes = multiplier * 15; cal.set(Calendar.MINUTE, minutes); return cal.getTime(); /* ================================================== */ } /** * Returns the day of the week as int * * @param date * @return */ public static int getDayOfWeek(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_WEEK); } public static String getWeekday(Date date) throws Exception { DateFormat format = new SimpleDateFormat("EEEEE", Locale.getDefault()); format.setTimeZone(TimeZone.getDefault()); return format.format(date); } /** * returns the current hour of the date * * @param date * @return */ public static int getHourOfDay(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.HOUR_OF_DAY); /* ================================================== */ } /** * Returns the minutes of the hour * * @param date * @return */ public static int getMinuteOfHour(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.MINUTE); /* ================================================== */ } public static TimeOfDay getTimeOfDay(Date date) throws Exception { return new TimeOfDay(date.getTime() - round2Day(date).getTime()); } public static Date getStartOfWeek(Date date) { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Sets the weekday to the current date * * @param date * @param weekday * @return */ public static Date setDayOfWeek(Date date, int weekday) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, weekday); return cal.getTime(); /* ================================================== */ } public static int getYear(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * @param date * @return * @throws Exception */ public static int getMonth(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.MONTH); } /** * @param date * @return * @throws Exception */ public static int getDayOfMonth(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_MONTH); } /** * @param date * @return */ public static int getDayOfYear(Date date) { Calendar cal = newCalendar(); cal.setTime(date); return cal.get(Calendar.DAY_OF_YEAR); } /** * Returns the date in distance to the given one, according to the offset (diff) given in days.<br/> * Example:<br/> <strong>date =</strong> 2007-03-23 (Friday)<br/> * <strong>diff = </strong>3<br> * <strong>getDiffDay = </strong> 2007-03-20 (Tuesday) * * @param date * @param diff * @return * @throws Exception */ public static Date getDiffDay(Date date, int diff) { Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.DAY_OF_WEEK, diff); return cal.getTime(); } /** * Moves the date by the given amount of days. * It will consider any month overflows and switches * automatically to the next month. * * @param date * @param offset * @return */ public static Date move(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, offset); return cal.getTime(); /* ================================================== */ } /** * Moves the given date by the given minutes. * * @param date * @param offset * @return */ public static Date moveByMinute(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.MINUTE, offset); return cal.getTime(); /* ================================================== */ } /** * Moves the given date by the given years * * @param date * @param offset years to add * @return */ public static Date moveByYear(Date date, int offset) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.add(Calendar.YEAR, offset); return cal.getTime(); /* ================================================== */ } /** * Sets the date to 23:59:59 * * @param date */ public static Date move2Midnight(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 59); return cal.getTime(); /* ================================================== */ } /** * Sets the date to 00:00:00 * * @param date */ public static Date move2Morning(Date date) { /* ================================================== */ Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); /* ================================================== */ } /** * Returns the diff of the two dates * * @param oldDate * @param newDate * @return */ public static long getDiffDay(Date oldDate, Date newDate) { /* ================================================== */ long diff = 0; // if moved to a later date if (newDate.getTime() > oldDate.getTime()) { /* ------------------------------------------------------- */ diff = newDate.getTime() - oldDate.getTime(); /* ------------------------------------------------------- */ } else { /* ------------------------------------------------------- */ diff = (-1)*(oldDate.getTime() - newDate.getTime()); /* ------------------------------------------------------- */ } return diff; /* ================================================== */ } /** * Returns a list of normalized Dates * that are between the two dates. * Normalized means, the time is set to 00:00:00 * The start and end are the first and last dates in the list and * will not be normalized. * * @param start * @param end * @return */ public static List<Date> getDayRange(Date start, Date end) { /* ================================================== */ List<Date> dates = new ArrayList<Date>(0); /* ------------------------------------------------------- */ if (start == null || end == null) return dates; /* ------------------------------------------------------- */ // add the first element dates.add(start); // loop as long as the next day is before the end Date normalizedEnd = round2Day(end); Date next = start; /* ------------------------------------------------------- */ while (next.before(normalizedEnd)) { dates.add(getDiffDay(next, 1)); next = round2Day(getDiffDay(next, 1)); } /* ------------------------------------------------------- */ // add last element dates.add(end); /* ------------------------------------------------------- */ return dates; /* ================================================== */ } /** * Returns the number of days that are between the two * day of week * [startDay,endDay] * [1..7] * * @param startDay * @param endDay * @return */ public static int getDiffDay(int startDay, int endDay) { /* ================================================== */ // if the startday is greater than the end day // add 7 days to the end plus one to inlcude the end day if (startDay > endDay) endDay = endDay + 7; /* ------------------------------------------------------- */ return endDay - startDay + 1; /* ================================================== */ } /** * Returns the amount of minutes that are between the two dates * * @param startDate * @param end * @return minutes */ public static long getDiffMinutes(Date startDate, Date endDate) { /* ====================================================== */ // if (isSameDay(startDate, endDate)) { // /* ------------------------------------------------------- */ // return getMinutesOfRestDay(endDate) - getMinutesOfRestDay(startDate); // /* ------------------------------------------------------- */ // } /* ------------------------------------------------------- */ return (endDate.getTime() / MILLIS_MINUTE) - (startDate.getTime() / MILLIS_MINUTE); /* ====================================================== */ } /** * Counts the minutes from this date up to midnight * * @param date * @return */ public static int getMinutesOfRestDay(Date date) { /* ================================================== */ if (date == null) return 0; /* ------------------------------------------------------- */ // count minutes to midnight /* ------------------------------------------------------- */ int sum = 0; /* ------------------------------------------------------- */ Calendar cal = new GregorianCalendar(); cal.setTime(date); /* ------------------------------------------------------- */ int minute = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR_OF_DAY); /* ------------------------------------------------------- */ // add the minutes up to the next hour /* ------------------------------------------------------- */ sum = 60 - minute; /* ------------------------------------------------------- */ // for each hour, until midnight, add 60 minutes /* ------------------------------------------------------- */ int fac = 23 - hour; sum = sum + fac * 60; return sum; /* ================================================== */ } /** * Counts the minutes from midnight to this date * * @param date * @return */ public static int getMinutesOfDay(Date date) { /* ================================================== */ if (date == null) return 0; /* ------------------------------------------------------- */ long diffMinutes = getDiffMinutes(move2Morning(date), date); /* ------------------------------------------------------- */ return (int) diffMinutes; /* ================================================== */ } /** * Checks if the dates are the same day of the year. * They can be in different years. Result will be true. * * @param d1 * @param d2 * @return */ public static boolean isSameDayOfYear(Date d1, Date d2) { GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)) return true; return false; } /** * Checks if the dates are on the exact same day. * * @param d1 * @param d2 * @return */ public static boolean isSameDay(Date d1, Date d2) { /* ================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ================================================== */ } /** * Checks if the date in the same week inthe same year * * @param d1 * @param d2 * @return */ public static boolean isSameWeek(Date d1, Date d2) { /* ====================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ====================================================== */ } /** * Checks if the dates are in the same month in the same year * * @param d1 * @param d2 * @return */ public static boolean isSameMonth(Date d1, Date d2) { /* ====================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); if (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) return true; return false; /* ====================================================== */ } /** * Returns true if the dates are in the same year * * @param d1 * @param d2 * @return true if both are in the same year */ public static boolean isSameYear(Date d1, Date d2) { /* ================================================== */ if (d1 == null || d2 == null) return false; /* ------------------------------------------------------- */ GregorianCalendar cal1 = new GregorianCalendar(); cal1.setTime(d1); GregorianCalendar cal2 = new GregorianCalendar(); cal2.setTime(d2); /* ------------------------------------------------------- */ return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)); /* ================================================== */ } /** * True if the date1 is a day before date2 * * @param d1 * @param d2 * @return */ public static boolean isBeforeDay(Date d1, Date d2) { /* ====================================================== */ int dy1 = getDayOfYear(d1); int dy2 = getDayOfYear(d2); /* ------------------------------------------------------- */ int y1 = getYear(d1); int y2 = getYear(d2); /* ------------------------------------------------------- */ if (y1 < y2) return true; if (y1 > y2) return false; /* ------------------------------------------------------- */ // else, we are in the same year /* ------------------------------------------------------- */ return (dy1 < dy2); /* ====================================================== */ } /** * Returns the number of dates that are between the two given dates * * @param date2 * @param date1 * @return * @throws Exception */ public static int getDateDiff(Date date2, Date date1) { /* ================================================== */ return (int) ((date2.getTime() - date1.getTime()) / 24 / 3600 / 1000); /* ================================================== */ } /** * @param date * @param time * @return * @throws Exception */ public static Date setTimeOfDate(Date date, TimeOfDay time) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, time.getHour()); cal.set(Calendar.MINUTE, time.getMinute()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } public static Date round2Week(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } public static Date round2Month(Date date) throws Exception { Calendar cal = newCalendar(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Creates an array of dates in distance of the minutes offset * @param minOffset * @return */ public static Date[] createDateList(int minOffset) { /* ================================================== */ if (minOffset < 0) minOffset = 0; if (minOffset > 60) minOffset = 60; /* ------------------------------------------------------- */ try { /* ------------------------------------------------------- */ Calendar cal = newCalendar(); cal.set(Calendar.DAY_OF_MONTH, 0); cal.set(Calendar.MONTH, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); int capacity = 60*24 / minOffset; Date[] dates = new Date[capacity]; int limit = 60 / minOffset; int count = 1; for (int i = 0; i < capacity; i++) { /* ------------------------------------------------------- */ dates[i] = cal.getTime(); cal.roll(Calendar.MINUTE, minOffset); if (count == limit) { cal.roll(Calendar.HOUR_OF_DAY, 1); count = 0; } count++; /* ------------------------------------------------------- */ } return dates; /* ------------------------------------------------------- */ } catch (Exception e) { e.printStackTrace(); return null; } /* ================================================== */ } /** * Creates a Date object with the current local time * and the given type and value. * * @param value * @return */ public static Date createDate(int type, int value) { /* ================================================== */ Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 0); cal.set(Calendar.MONTH, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(type, value); return cal.getTime(); /* ================================================== */ } /** * Extracts the age out of the day of birth * * @param dayOfBirth * @return */ public static long extractAge(Date dayOfBirth) { /* ================================================== */ Calendar c1 = new GregorianCalendar(); Calendar c2 = new GregorianCalendar(); c2.setTime(dayOfBirth); return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR); /* ================================================== */ } public static Calendar newCalendar() { return calFactory.newCalendar(); } public static void setCalendarFactory(CalendarFactory factory) { calFactory = factory; } private static class DefaultCalendarFactory implements CalendarFactory { public Calendar newCalendar() { Calendar cal = Calendar.getInstance(LocaleBroker.getLocale()); cal.setTimeZone(TimeZoneBroker.getTimeZone()); return cal; } } }
fix for the extractAge method. It covers now also the current day of year for the age computation
src/bizcal/util/DateUtil.java
fix for the extractAge method. It covers now also the current day of year for the age computation
Java
apache-2.0
df4015674c71a0e3c5eede4925e20719455e50a0
0
FlowCI/flow-platform,FlowCI/flow-platform
/* * Copyright 2017 flow.ci * * 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.flow.platform.api.util; import com.flow.platform.api.config.AppConfig; import com.flow.platform.api.domain.node.Flow; import com.flow.platform.api.domain.node.Node; import com.flow.platform.api.exception.YmlException; import com.flow.platform.yml.parser.YmlParser; import com.flow.platform.yml.parser.exception.YmlFormatException; import com.flow.platform.yml.parser.exception.YmlParseException; import com.google.common.io.Files; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; /** * @author yh@firim */ public class NodeUtil { /** * Get node workspace path */ public static Path workspacePath(Path base, Node node) { return Paths.get(base.toString(), node.getName()); } /** * Build node tree structure from yml file * * @param path file path * @return node tree */ public static Node buildFromYml(File path, String root) { try { String ymlString = Files.toString(path, AppConfig.DEFAULT_CHARSET); return buildFromYml(ymlString, root); } catch (YmlException e) { throw e; } catch (Throwable ignore) { return null; } } /** * Build node tree structure from yml string * * @param yml raw yml string * @return root node of yml * @throws YmlException if yml format is illegal */ public static Node buildFromYml(String yml, String root) { Flow[] flows; try { flows = YmlParser.fromYml(yml, Flow[].class); } catch (YmlParseException | YmlFormatException e) { throw new YmlException(e.getMessage()); } // current version only support single flow if (flows.length > 1) { throw new YmlException("Unsupported multiple flows definition"); } flows[0].setName(root); buildNodeRelation(flows[0]); return flows[0]; } /** * find all node */ public static void recurse(final Node root, final Consumer<Node> onNode) { for (Object child : root.getChildren()) { recurse((Node) child, onNode); } onNode.accept(root); } /** * get all nodes includes flow and steps * * @param node the parent node * @return List<Node> include parent node */ public static List<Node> flat(final Node node) { final List<Node> flatted = new LinkedList<>(); recurse(node, flatted::add); return flatted; } /** * find flow node */ public static Node findRootNode(Node node) { if (node.getParent() == null) { return node; } return findRootNode(node.getParent()); } /** * get prev node from flow */ public static Node prev(Node node, List<Node> ordered) { Integer index = -1; Node target = null; for (int i = 0; i < ordered.size(); i++) { Node item = ordered.get(i); if (item.equals(node)) { index = i; } } if (index >= 1 && index != -1 && index < ordered.size() - 1) { target = ordered.get(index - 1); } return target; } /** * get next node compare root * * @param node current node * @param ordered ordered and flatted node tree * @return next node of current */ public static Node next(Node node, List<Node> ordered) { Integer index = -1; Node target = null; //find node for (int i = 0; i < ordered.size(); i++) { Node item = ordered.get(i); if (item.equals(node)) { index = i; break; } } // find node if (index != -1) { try { target = ordered.get(index + 1); } catch (Throwable ignore) { //not found ignore target = null; } } return target; } /** * Build node path, parent, next, prev relation */ public static void buildNodeRelation(Node<? extends Node> root) { setNodePath(root); List<? extends Node> children = root.getChildren(); for (int i = 0; i < children.size(); i++) { Node childNode = children.get(i); childNode.setParent(root); if (i > 0) { childNode.setPrev(children.get(i - 1)); children.get(i - 1).setNext(childNode); } buildNodeRelation(childNode); } } private static void setNodePath(Node node) { if (node.getParent() == null) { node.setPath(PathUtil.build(node.getName())); return; } node.setPath(PathUtil.build(node.getParent().getPath(), node.getName())); } }
platform-api/src/main/java/com/flow/platform/api/util/NodeUtil.java
/* * Copyright 2017 flow.ci * * 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.flow.platform.api.util; import com.flow.platform.api.config.AppConfig; import com.flow.platform.api.domain.node.Flow; import com.flow.platform.api.domain.node.Node; import com.flow.platform.api.exception.YmlException; import com.flow.platform.yml.parser.YmlParser; import com.flow.platform.yml.parser.exception.YmlFormatException; import com.flow.platform.yml.parser.exception.YmlParseException; import com.google.common.io.Files; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; /** * @author yh@firim */ public class NodeUtil { /** * Get node workspace path */ public static Path workspacePath(Path base, Node node) { return Paths.get(base.toString(), node.getName()); } /** * Build node tree structure from yml file * * @param path file path * @return node tree */ public static Node buildFromYml(File path, String root) { try { String ymlString = Files.toString(path, AppConfig.DEFAULT_CHARSET); return buildFromYml(ymlString, root); } catch (YmlException e) { throw e; } catch (Throwable ignore) { return null; } } /** * Build node tree structure from yml string * * @param yml raw yml string * @return root node of yml * @throws YmlException if yml format is illegal */ public static Node buildFromYml(String yml, String root) { Flow[] flows; try { flows = YmlParser.fromYml(yml, Flow[].class); } catch (YmlParseException e) { throw new YmlException(e.getMessage()); } catch (YmlFormatException e) { throw new YmlException(e.getMessage()); } // current version only support single flow if (flows.length > 1) { throw new YmlException("Unsupported multiple flows definition"); } flows[0].setName(root); buildNodeRelation(flows[0]); return flows[0]; } /** * find all node */ public static void recurse(final Node root, final Consumer<Node> onNode) { for (Object child : root.getChildren()) { recurse((Node) child, onNode); } onNode.accept(root); } /** * get all nodes includes flow and steps * * @param node the parent node * @return List<Node> include parent node */ public static List<Node> flat(final Node node) { final List<Node> flatted = new LinkedList<>(); recurse(node, flatted::add); return flatted; } /** * find flow node */ public static Node findRootNode(Node node) { if (node.getParent() == null) { return node; } return findRootNode(node.getParent()); } /** * get prev node from flow */ public static Node prev(Node node, List<Node> ordered) { Integer index = -1; Node target = null; for (int i = 0; i < ordered.size(); i++) { Node item = ordered.get(i); if (item.equals(node)) { index = i; } } if (index >= 1 && index != -1 && index < ordered.size() - 1) { target = ordered.get(index - 1); } return target; } /** * get next node compare root * * @param node current node * @param ordered ordered and flatted node tree * @return next node of current */ public static Node next(Node node, List<Node> ordered) { Integer index = -1; Node target = null; //find node for (int i = 0; i < ordered.size(); i++) { Node item = ordered.get(i); if (item.equals(node)) { index = i; break; } } // find node if (index != -1) { try { target = ordered.get(index + 1); } catch (Throwable ignore) { //not found ignore target = null; } } return target; } /** * Build node path, parent, next, prev relation */ public static void buildNodeRelation(Node<? extends Node> root) { setNodePath(root); List<? extends Node> children = root.getChildren(); for (int i = 0; i < children.size(); i++) { Node childNode = children.get(i); childNode.setParent(root); if (i > 0) { childNode.setPrev(children.get(i - 1)); children.get(i - 1).setNext(childNode); } buildNodeRelation(childNode); } } private static void setNodePath(Node node) { if (node.getParent() == null) { node.setPath(PathUtil.build(node.getName())); return; } node.setPath(PathUtil.build(node.getParent().getPath(), node.getName())); } }
change code
platform-api/src/main/java/com/flow/platform/api/util/NodeUtil.java
change code
Java
apache-2.0
6551909a65df36c894c6b84034b7ed3b002fe1c3
0
google/error-prone,google/error-prone
/* * Copyright 2021 The Error Prone 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 com.google.errorprone.bugpatterns.inlineme; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.MoreAnnotations.asStringValue; import static com.google.errorprone.util.MoreAnnotations.getValue; import static com.google.errorprone.util.SideEffectAnalysis.hasSideEffect; import com.google.auto.value.AutoValue; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.parser.JavaTokenizer; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Token; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.nio.CharBuffer; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * Checker that performs the inlining at call-sites (where the invoked APIs are annotated as * {@code @InlineMe}). */ @BugPattern( name = "InlineMeInliner", summary = "Callers of this API should be inlined.", severity = WARNING, tags = Inliner.FINDING_TAG) public final class Inliner extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { public static final String FINDING_TAG = "JavaInlineMe"; static final String PREFIX_FLAG = "InlineMe:Prefix"; static final String SKIP_COMMENTS_FLAG = "InlineMe:SkipInliningsWithComments"; private static final Splitter PACKAGE_SPLITTER = Splitter.on('.'); private static final String INLINE_ME = "InlineMe"; private static final String VALIDATION_DISABLED = "InlineMeValidationDisabled"; private final ImmutableSet<String> apiPrefixes; private final boolean skipCallsitesWithComments; public Inliner(ErrorProneFlags flags) { this.apiPrefixes = ImmutableSet.copyOf(flags.getSet(PREFIX_FLAG).orElse(ImmutableSet.<String>of())); this.skipCallsitesWithComments = flags.getBoolean(SKIP_COMMENTS_FLAG).orElse(true); } // TODO(b/163596864): Add support for inlining fields @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = "new " + state.getSourceForNode(tree.getIdentifier()); return match(tree, symbol, callingVars, receiverString, null, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = ""; ExpressionTree receiver = getReceiver(tree); if (receiver != null) { receiverString = state.getSourceForNode(receiver); } ExpressionTree methodSelectTree = tree.getMethodSelect(); if (methodSelectTree != null) { String methodSelect = state.getSourceForNode(methodSelectTree); if ("super".equals(methodSelect)) { receiverString = methodSelect; } // TODO(kak): Can we omit the `this` case? The getReceiver() call above handles `this` if ("this".equals(methodSelect)) { receiverString = methodSelect; } } return match(tree, symbol, callingVars, receiverString, receiver, state); } private Description match( ExpressionTree tree, MethodSymbol symbol, ImmutableList<String> callingVars, String receiverString, ExpressionTree receiver, VisitorState state) { checkState(hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)); Api api = Api.create(symbol, state); if (!matchesApiPrefixes(api)) { return Description.NO_MATCH; } if (skipCallsitesWithComments && stringContainsComments(state.getSourceForNode(tree), state)) { return Description.NO_MATCH; } Attribute.Compound inlineMe = symbol.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(INLINE_ME)) .collect(onlyElement()); SuggestedFix.Builder builder = SuggestedFix.builder(); Map<String, String> typeNames = new HashMap<>(); for (String newImport : getStrings(inlineMe, "imports")) { String typeName = Iterables.getLast(PACKAGE_SPLITTER.split(newImport)); String qualifiedTypeName = SuggestedFixes.qualifyType(state, builder, newImport); typeNames.put(typeName, qualifiedTypeName); } for (String newStaticImport : getStrings(inlineMe, "staticImports")) { builder.addStaticImport(newStaticImport); } ImmutableList<String> varNames = symbol.getParameters().stream() .map(varSymbol -> varSymbol.getSimpleName().toString()) .collect(toImmutableList()); boolean varargsWithEmptyArguments = false; if (symbol.isVarArgs()) { // If we're calling a varargs method, its inlining *should* have the varargs parameter in a // reasonable position. If there are are 0 arguments, we'll need to do more surgery if (callingVars.size() == varNames.size() - 1) { varargsWithEmptyArguments = true; } else { ImmutableList<String> nonvarargs = callingVars.subList(0, varNames.size() - 1); String varargsJoined = Joiner.on(", ").join(callingVars.subList(varNames.size() - 1, callingVars.size())); callingVars = ImmutableList.<String>builderWithExpectedSize(varNames.size()) .addAll(nonvarargs) .add(varargsJoined) .build(); } } String replacement = trimTrailingSemicolons(asStringValue(getValue(inlineMe, "replacement").get()).get()); int replacementStart = ((DiagnosticPosition) tree).getStartPosition(); int replacementEnd = state.getEndPosition(tree); // Special case replacements starting with "this." so the receiver portion is not included in // the replacement. This avoids overlapping replacement regions for fluent chains. if (replacement.startsWith("this.") && receiver != null) { replacementStart = state.getEndPosition(receiver); replacement = replacement.substring("this".length()); } if (Strings.isNullOrEmpty(receiverString)) { replacement = replacement.replaceAll("\\bthis\\.\\b", ""); } else { if (replacement.equals("this")) { // e.g.: foo.b() -> foo Tree parent = state.getPath().getParentPath().getLeaf(); // If the receiver is a side-effect-free expression and the whole expression is standalone, // the receiver likely can't stand on its own (e.g.: "foo;" is not a valid statement while // "foo.noOpMethod();" is). if (parent instanceof ExpressionStatementTree && !hasSideEffect(receiver)) { return describe(parent, SuggestedFix.delete(parent), api); } } replacement = replacement.replaceAll("\\bthis\\b", receiverString); } // Qualify imports first, then replace parameter values to avoid clobbering source from the // inlined method. for (Map.Entry<String, String> typeName : typeNames.entrySet()) { // TODO(b/189535612): we'll need to be smarter about our replacements (to avoid clobbering // inline parameter comments like /* paramName= */ replacement = replacement.replaceAll( "\\b" + Pattern.quote(typeName.getKey()) + "\\b", Matcher.quoteReplacement(typeName.getValue())); } for (int i = 0; i < varNames.size(); i++) { // Ex: foo(int a, int... others) -> this.bar(a, others) // If caller passes 0 args in the varargs position, we want to remove the preceding comma to // make this.bar(a) (as opposed to "this.bar(a, )" boolean terminalVarargsReplacement = varargsWithEmptyArguments && i == varNames.size() - 1; String capturePrefixForVarargs = terminalVarargsReplacement ? "(?:,\\s*)?" : ""; // We want to avoid replacing a method invocation with the same name as the method. Pattern extractArgAndNextToken = Pattern.compile( "\\b" + capturePrefixForVarargs + Pattern.quote(varNames.get(i)) + "\\b([^(])"); String replacementResult = Matcher.quoteReplacement(terminalVarargsReplacement ? "" : callingVars.get(i)) + "$1"; Matcher matcher = extractArgAndNextToken.matcher(replacement); replacement = matcher.replaceAll(replacementResult); } builder.replace(replacementStart, replacementEnd, replacement); SuggestedFix fix = builder.build(); // If there are no imports to add, then there's no new dependencies, so we can verify that it // compilesWithFix(); if there are new imports to add, then we can't validate that it compiles. if (fix.getImportsToAdd().isEmpty()) { return SuggestedFixes.compilesWithFix(fix, state) ? describe(tree, fix, api) : Description.NO_MATCH; } return describe(tree, fix, api); } // Implementation borrowed from Refaster's comment-checking code. private static boolean stringContainsComments(String source, VisitorState state) { JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(state.context), CharBuffer.wrap(source)) {}; for (Token token = tokenizer.readToken(); token.kind != TokenKind.EOF; token = tokenizer.readToken()) { if (token.comments != null && !token.comments.isEmpty()) { return true; } } return false; } private static ImmutableList<String> getStrings(Attribute.Compound attribute, String name) { return getValue(attribute, name) .map(MoreAnnotations::asStrings) .orElse(Stream.empty()) .collect(toImmutableList()); } private Description describe(Tree tree, SuggestedFix fix, Api api) { return buildDescription(tree).setMessage(api.message()).addFix(fix).build(); } @AutoValue abstract static class Api { private static final Splitter CLASS_NAME_SPLITTER = Splitter.on('.'); static Api create(MethodSymbol method, VisitorState state) { String extraMessage = ""; if (hasDirectAnnotationWithSimpleName(method, VALIDATION_DISABLED)) { Attribute.Compound inlineMeValidationDisabled = method.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(VALIDATION_DISABLED)) .collect(onlyElement()); String reason = Iterables.getOnlyElement(getStrings(inlineMeValidationDisabled, "value")); extraMessage = " NOTE: this is an unvalidated inlining! Reasoning: " + reason; } return new AutoValue_Inliner_Api( method.owner.getQualifiedName().toString(), method.getSimpleName().toString(), method.isConstructor(), extraMessage); } abstract String className(); abstract String methodName(); abstract boolean isConstructor(); abstract String extraMessage(); final String message() { return shortName() + " should be inlined" + extraMessage(); } /** Returns {@code FullyQualifiedClassName#methodName}. */ final String methodId() { return String.format("%s#%s", className(), methodName()); } /** * Returns a short, human readable description of this API in markdown format (e.g., {@code * `ClassName.methodName()`}). */ final String shortName() { return String.format("`%s.%s()`", simpleClassName(), methodName()); } /** Returns the simple class name (e.g., {@code ClassName}). */ final String simpleClassName() { return Iterables.getLast(CLASS_NAME_SPLITTER.split(className())); } } private boolean matchesApiPrefixes(Api api) { if (apiPrefixes.isEmpty()) { return true; } for (String apiPrefix : apiPrefixes) { if (api.methodId().startsWith(apiPrefix)) { return true; } } return false; } private static final CharMatcher SEMICOLON = CharMatcher.is(';'); private static String trimTrailingSemicolons(String s) { return SEMICOLON.trimTrailingFrom(s); } }
core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Inliner.java
/* * Copyright 2021 The Error Prone 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 com.google.errorprone.bugpatterns.inlineme; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName; import static com.google.errorprone.util.MoreAnnotations.asStringValue; import static com.google.errorprone.util.MoreAnnotations.getValue; import static com.google.errorprone.util.SideEffectAnalysis.hasSideEffect; import com.google.auto.value.AutoValue; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * Checker that performs the inlining at call-sites (where the invoked APIs are annotated as * {@code @InlineMe}). */ @BugPattern( name = "InlineMeInliner", summary = "Callers of this API should be inlined.", severity = WARNING, tags = Inliner.FINDING_TAG) public final class Inliner extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { public static final String FINDING_TAG = "JavaInlineMe"; private static final Splitter PACKAGE_SPLITTER = Splitter.on('.'); static final String PREFIX_FLAG = "InlineMe:Prefix"; private static final String INLINE_ME = "InlineMe"; private static final String VALIDATION_DISABLED = "InlineMeValidationDisabled"; private final ImmutableSet<String> apiPrefixes; public Inliner(ErrorProneFlags flags) { this.apiPrefixes = ImmutableSet.copyOf(flags.getSet(PREFIX_FLAG).orElse(ImmutableSet.<String>of())); } // TODO(b/163596864): Add support for inlining fields @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = "new " + state.getSourceForNode(tree.getIdentifier()); return match(tree, symbol, callingVars, receiverString, null, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } ImmutableList<String> callingVars = tree.getArguments().stream().map(state::getSourceForNode).collect(toImmutableList()); String receiverString = ""; ExpressionTree receiver = getReceiver(tree); if (receiver != null) { receiverString = state.getSourceForNode(receiver); } ExpressionTree methodSelectTree = tree.getMethodSelect(); if (methodSelectTree != null) { String methodSelect = state.getSourceForNode(methodSelectTree); if ("super".equals(methodSelect)) { receiverString = methodSelect; } // TODO(kak): Can we omit the `this` case? The getReceiver() call above handles `this` if ("this".equals(methodSelect)) { receiverString = methodSelect; } } return match(tree, symbol, callingVars, receiverString, receiver, state); } private Description match( ExpressionTree tree, MethodSymbol symbol, ImmutableList<String> callingVars, String receiverString, ExpressionTree receiver, VisitorState state) { checkState(hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)); Api api = Api.create(symbol, state); if (!matchesApiPrefixes(api)) { return Description.NO_MATCH; } Attribute.Compound inlineMe = symbol.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(INLINE_ME)) .collect(onlyElement()); SuggestedFix.Builder builder = SuggestedFix.builder(); Map<String, String> typeNames = new HashMap<>(); for (String newImport : getStrings(inlineMe, "imports")) { String typeName = Iterables.getLast(PACKAGE_SPLITTER.split(newImport)); String qualifiedTypeName = SuggestedFixes.qualifyType(state, builder, newImport); typeNames.put(typeName, qualifiedTypeName); } for (String newStaticImport : getStrings(inlineMe, "staticImports")) { builder.addStaticImport(newStaticImport); } ImmutableList<String> varNames = symbol.getParameters().stream() .map(varSymbol -> varSymbol.getSimpleName().toString()) .collect(toImmutableList()); boolean varargsWithEmptyArguments = false; if (symbol.isVarArgs()) { // If we're calling a varargs method, its inlining *should* have the varargs parameter in a // reasonable position. If there are are 0 arguments, we'll need to do more surgery if (callingVars.size() == varNames.size() - 1) { varargsWithEmptyArguments = true; } else { ImmutableList<String> nonvarargs = callingVars.subList(0, varNames.size() - 1); String varargsJoined = Joiner.on(", ").join(callingVars.subList(varNames.size() - 1, callingVars.size())); callingVars = ImmutableList.<String>builderWithExpectedSize(varNames.size()) .addAll(nonvarargs) .add(varargsJoined) .build(); } } String replacement = trimTrailingSemicolons(asStringValue(getValue(inlineMe, "replacement").get()).get()); int replacementStart = ((DiagnosticPosition) tree).getStartPosition(); int replacementEnd = state.getEndPosition(tree); // Special case replacements starting with "this." so the receiver portion is not included in // the replacement. This avoids overlapping replacement regions for fluent chains. if (replacement.startsWith("this.") && receiver != null) { replacementStart = state.getEndPosition(receiver); replacement = replacement.substring("this".length()); } if (Strings.isNullOrEmpty(receiverString)) { replacement = replacement.replaceAll("\\bthis\\.\\b", ""); } else { if (replacement.equals("this")) { // e.g.: foo.b() -> foo Tree parent = state.getPath().getParentPath().getLeaf(); // If the receiver is a side-effect-free expression and the whole expression is standalone, // the receiver likely can't stand on its own (e.g.: "foo;" is not a valid statement while // "foo.noOpMethod();" is). if (parent instanceof ExpressionStatementTree && !hasSideEffect(receiver)) { return describe(parent, SuggestedFix.delete(parent), api); } } replacement = replacement.replaceAll("\\bthis\\b", receiverString); } // Qualify imports first, then replace parameter values to avoid clobbering source from the // inlined method. for (Map.Entry<String, String> typeName : typeNames.entrySet()) { // TODO(b/189535612): we'll need to be smarter about our replacements (to avoid clobbering // inline parameter comments like /* paramName= */ replacement = replacement.replaceAll( "\\b" + Pattern.quote(typeName.getKey()) + "\\b", Matcher.quoteReplacement(typeName.getValue())); } for (int i = 0; i < varNames.size(); i++) { // Ex: foo(int a, int... others) -> this.bar(a, others) // If caller passes 0 args in the varargs position, we want to remove the preceding comma to // make this.bar(a) (as opposed to "this.bar(a, )" boolean terminalVarargsReplacement = varargsWithEmptyArguments && i == varNames.size() - 1; String capturePrefixForVarargs = terminalVarargsReplacement ? "(?:,\\s*)?" : ""; // We want to avoid replacing a method invocation with the same name as the method. Pattern extractArgAndNextToken = Pattern.compile( "\\b" + capturePrefixForVarargs + Pattern.quote(varNames.get(i)) + "\\b([^(])"); String replacementResult = Matcher.quoteReplacement(terminalVarargsReplacement ? "" : callingVars.get(i)) + "$1"; Matcher matcher = extractArgAndNextToken.matcher(replacement); replacement = matcher.replaceAll(replacementResult); } builder.replace(replacementStart, replacementEnd, replacement); SuggestedFix fix = builder.build(); // If there are no imports to add, then there's no new dependencies, so we can verify that it // compilesWithFix(); if there are new imports to add, then we can't validate that it compiles. if (fix.getImportsToAdd().isEmpty()) { return SuggestedFixes.compilesWithFix(fix, state) ? describe(tree, fix, api) : Description.NO_MATCH; } return describe(tree, fix, api); } private static ImmutableList<String> getStrings(Attribute.Compound attribute, String name) { return getValue(attribute, name) .map(MoreAnnotations::asStrings) .orElse(Stream.empty()) .collect(toImmutableList()); } private Description describe(Tree tree, SuggestedFix fix, Api api) { return buildDescription(tree).setMessage(api.message()).addFix(fix).build(); } @AutoValue abstract static class Api { private static final Splitter CLASS_NAME_SPLITTER = Splitter.on('.'); static Api create(MethodSymbol method, VisitorState state) { String extraMessage = ""; if (hasDirectAnnotationWithSimpleName(method, VALIDATION_DISABLED)) { Attribute.Compound inlineMeValidationDisabled = method.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(VALIDATION_DISABLED)) .collect(onlyElement()); String reason = Iterables.getOnlyElement(getStrings(inlineMeValidationDisabled, "value")); extraMessage = " NOTE: this is an unvalidated inlining! Reasoning: " + reason; } return new AutoValue_Inliner_Api( method.owner.getQualifiedName().toString(), method.getSimpleName().toString(), method.isConstructor(), extraMessage); } abstract String className(); abstract String methodName(); abstract boolean isConstructor(); abstract String extraMessage(); final String message() { return shortName() + " should be inlined" + extraMessage(); } /** Returns {@code FullyQualifiedClassName#methodName}. */ final String methodId() { return String.format("%s#%s", className(), methodName()); } /** * Returns a short, human readable description of this API in markdown format (e.g., {@code * `ClassName.methodName()`}). */ final String shortName() { return String.format("`%s.%s()`", simpleClassName(), methodName()); } /** Returns the simple class name (e.g., {@code ClassName}). */ final String simpleClassName() { return Iterables.getLast(CLASS_NAME_SPLITTER.split(className())); } } private boolean matchesApiPrefixes(Api api) { if (apiPrefixes.isEmpty()) { return true; } for (String apiPrefix : apiPrefixes) { if (api.methodId().startsWith(apiPrefix)) { return true; } } return false; } private static final CharMatcher SEMICOLON = CharMatcher.is(';'); private static String trimTrailingSemicolons(String s) { return SEMICOLON.trimTrailingFrom(s); } }
For InlineMe - avoid rewriting callsites where there are interior comments, with a flag to revert the behavior if you don't care about removing comments. PiperOrigin-RevId: 405014564
core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Inliner.java
For InlineMe - avoid rewriting callsites where there are interior comments, with a flag to revert the behavior if you don't care about removing comments.
Java
apache-2.0
47391803e7824541790c194448f2ebacce454cd8
0
SIROK/growthbeat-java,growthbeat/growthbeat-java
package com.growthbeat.exception; import com.growthbeat.model.Error; public class ApiException extends GrowthbeatException { private static final long serialVersionUID = 1L; private int statusCode; private Error error; public ApiException(int statusCode) { super(String.format("Invalid status code %d", statusCode)); setStatusCode(statusCode); } public ApiException(int statusCode, Error error) { super(error != null ? error.getMessage() : String.format("Invalid status code %d", statusCode)); setStatusCode(statusCode); setError(error); } public Error getError() { return error; } public void setError(Error error) { this.error = error; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
src/main/java/com/growthbeat/exception/ApiException.java
package com.growthbeat.exception; import com.growthbeat.model.Error; public class ApiException extends GrowthbeatException { private static final long serialVersionUID = 1L; private int statusCode; private Error error; public ApiException(int statusCode) { super(); setStatusCode(statusCode); } public ApiException(int statusCode, Error error) { this(statusCode); setError(error); } public Error getError() { return error; } public void setError(Error error) { this.error = error; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
Add message in ApiException
src/main/java/com/growthbeat/exception/ApiException.java
Add message in ApiException
Java
apache-2.0
1889126a1cfacbeedea5f4a002a9ee77be20836d
0
Yannic/closure-compiler,google/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,vobruba-martin/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,google/closure-compiler,nawawi/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,google/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler
/* * Copyright 2008 The Closure Compiler 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 com.google.javascript.jscomp; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static com.google.javascript.jscomp.CompilerTypeTestCase.lines; import static com.google.javascript.jscomp.testing.ScopeSubject.assertScope; import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NO_RESOLVED_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE; import static com.google.javascript.rhino.testing.NodeSubject.assertNode; import static com.google.javascript.rhino.testing.TypeSubject.assertType; import static com.google.javascript.rhino.testing.TypeSubject.types; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Streams; import com.google.javascript.jscomp.CodingConvention.AssertionFunctionLookup; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.DataFlowAnalysis.BranchedFlowState; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode; import com.google.javascript.jscomp.modules.ModuleMapCreator; import com.google.javascript.jscomp.testing.ScopeSubject; import com.google.javascript.jscomp.type.FlowScope; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.rhino.ClosurePrimitive; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.StaticTypedRef; import com.google.javascript.rhino.jstype.StaticTypedScope; import com.google.javascript.rhino.jstype.StaticTypedSlot; import com.google.javascript.rhino.jstype.TemplateType; import com.google.javascript.rhino.testing.TypeSubject; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests {@link TypeInference}. * */ @RunWith(JUnit4.class) public final class TypeInferenceTest { private Compiler compiler; private JSTypeRegistry registry; private Map<String, JSType> assumptions; private JSType assumedThisType; private FlowScope returnScope; private static final AssertionFunctionLookup ASSERTION_FUNCTION_MAP = AssertionFunctionLookup.of(new ClosureCodingConvention().getAssertionFunctions()); /** * Maps a label name to information about the labeled statement. * * <p>This map is recreated each time parseAndRunTypeInference() is executed. */ private Map<String, LabeledStatement> labeledStatementMap; /** Stores information about a labeled statement and allows making assertions on it. */ static class LabeledStatement { final Node statementNode; final TypedScope enclosingScope; LabeledStatement(Node statementNode, TypedScope enclosingScope) { this.statementNode = checkNotNull(statementNode); this.enclosingScope = checkNotNull(enclosingScope); } } @Before public void setUp() { compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.setClosurePass(true); compiler.initOptions(options); options.setLanguageIn(LanguageMode.ECMASCRIPT_2018); registry = compiler.getTypeRegistry(); assumptions = new HashMap<>(); returnScope = null; } private void assumingThisType(JSType type) { assumedThisType = type; } private void assuming(String name, JSType type) { assumptions.put(name, type); } /** Declares a name with a given type in the parent scope of the test case code. */ private void assuming(String name, JSTypeNative type) { assuming(name, registry.getNativeType(type)); } private void inFunction(String js) { // Parse the body of the function. String thisBlock = assumedThisType == null ? "" : "/** @this {" + assumedThisType + "} */"; parseAndRunTypeInference("(" + thisBlock + " function() {" + js + "});"); } private void inModule(String js) { Node script = compiler.parseTestCode(js); assertWithMessage("parsing error: " + Joiner.on(", ").join(compiler.getErrors())) .that(compiler.getErrorCount()) .isEqualTo(0); Node root = IR.root(IR.root(), IR.root(script)); new GatherModuleMetadata(compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER) .process(root.getFirstChild(), root.getSecondChild()); new ModuleMapCreator(compiler, compiler.getModuleMetadataMap()) .process(root.getFirstChild(), root.getSecondChild()); // SCRIPT -> MODULE_BODY Node moduleBody = script.getFirstChild(); parseAndRunTypeInference(root, moduleBody); } private void inGenerator(String js) { checkState(assumedThisType == null); parseAndRunTypeInference("(function *() {" + js + "});"); } private void parseAndRunTypeInference(String js) { Node script = compiler.parseTestCode(js); Node root = IR.root(IR.root(), IR.root(script)); assertWithMessage("parsing error: " + Joiner.on(", ").join(compiler.getErrors())) .that(compiler.getErrorCount()) .isEqualTo(0); // SCRIPT -> EXPR_RESULT -> FUNCTION // `(function() { TEST CODE HERE });` Node function = script.getFirstFirstChild(); parseAndRunTypeInference(root, function); } private void parseAndRunTypeInference(Node root, Node cfgRoot) { // Create the scope with the assumptions. TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); // Also populate a map allowing us to look up labeled statements later. labeledStatementMap = new HashMap<>(); new NodeTraversal( compiler, new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { TypedScope scope = t.getTypedScope(); if (parent != null && parent.isLabel() && !n.isLabelName()) { // First child of a LABEL is a LABEL_NAME, n is the second child. Node labelNameNode = checkNotNull(n.getPrevious(), n); checkState(labelNameNode.isLabelName(), labelNameNode); String labelName = labelNameNode.getString(); assertWithMessage("Duplicate label name: %s", labelName) .that(labeledStatementMap) .doesNotContainKey(labelName); labeledStatementMap.put(labelName, new LabeledStatement(n, scope)); } } }, scopeCreator) .traverse(root); TypedScope assumedScope = scopeCreator.createScope(cfgRoot); for (Map.Entry<String,JSType> entry : assumptions.entrySet()) { assumedScope.declare(entry.getKey(), null, entry.getValue(), null, false); } // Create the control graph. ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false); cfa.process(null, cfgRoot); ControlFlowGraph<Node> cfg = cfa.getCfg(); // Create a simple reverse abstract interpreter. ReverseAbstractInterpreter rai = compiler.getReverseAbstractInterpreter(); // Do the type inference by data-flow analysis. TypeInference dfa = new TypeInference(compiler, cfg, rai, assumedScope, scopeCreator, ASSERTION_FUNCTION_MAP); dfa.analyze(); // Get the scope of the implicit return. BranchedFlowState<FlowScope> rtnState = cfg.getImplicitReturn().getAnnotation(); if (cfgRoot.isFunction()) { // Reset the flow scope's syntactic scope to the function block, rather than the function node // itself. This allows pulling out local vars from the function by name to verify their // types. returnScope = rtnState.getIn().withSyntacticScope(scopeCreator.createScope(cfgRoot.getLastChild())); } else { returnScope = rtnState.getIn(); } } private LabeledStatement getLabeledStatement(String label) { assertWithMessage("No statement found for label: %s", label) .that(labeledStatementMap) .containsKey(label); return labeledStatementMap.get(label); } /** * Returns a ScopeSubject for the scope containing the labeled statement. * * <p>Asserts that a statement with the given label existed in the code last passed to * parseAndRunTypeInference(). */ private ScopeSubject assertScopeEnclosing(String label) { return assertScope(getLabeledStatement(label).enclosingScope); } /** * Returns a TypeSubject for the JSType of the expression with the given label. * * <p>Asserts that a statement with the given label existed in the code last passed to * parseAndRunTypeInference(). Also asserts that the statement is an EXPR_RESULT whose expression * has a non-null JSType. */ private TypeSubject assertTypeOfExpression(String label) { Node statementNode = getLabeledStatement(label).statementNode; assertWithMessage("Not an expression statement.").that(statementNode.isExprResult()).isTrue(); JSType jsType = statementNode.getOnlyChild().getJSType(); assertWithMessage("Expression type is null").that(jsType).isNotNull(); return assertType(jsType); } private JSType getType(String name) { assertWithMessage("The return scope should not be null.").that(returnScope).isNotNull(); StaticTypedSlot var = returnScope.getSlot(name); assertWithMessage("The variable " + name + " is missing from the scope.").that(var).isNotNull(); return var.getType(); } /** Returns the NAME node {@code name} from the PARAM_LIST of the top level of type inference. */ private Node getParamNameNode(String name) { StaticTypedScope staticScope = checkNotNull(returnScope.getDeclarationScope(), returnScope); StaticTypedSlot slot = checkNotNull(staticScope.getSlot(name), staticScope); StaticTypedRef declaration = checkNotNull(slot.getDeclaration(), slot); Node node = checkNotNull(declaration.getNode(), declaration); assertNode(node).hasType(Token.NAME); Streams.stream(node.getAncestors()) .filter(Node::isParamList) .findFirst() .orElseThrow(AssertionError::new); return node; } private void verify(String name, JSType type) { assertWithMessage("Mismatch for " + name) .about(types()) .that(getType(name)) .isStructurallyEqualTo(type); } private void verify(String name, JSTypeNative type) { verify(name, registry.getNativeType(type)); } private void verifySubtypeOf(String name, JSType type) { JSType varType = getType(name); assertWithMessage("The variable " + name + " is missing a type.").that(varType).isNotNull(); assertWithMessage( "The type " + varType + " of variable " + name + " is not a subtype of " + type + ".") .that(varType.isSubtypeOf(type)) .isTrue(); } private void verifySubtypeOf(String name, JSTypeNative type) { verifySubtypeOf(name, registry.getNativeType(type)); } private EnumType createEnumType(String name, JSTypeNative elemType) { return createEnumType(name, registry.getNativeType(elemType)); } private EnumType createEnumType(String name, JSType elemType) { return registry.createEnumType(name, null, elemType); } private JSType createUndefinableType(JSTypeNative type) { return registry.createUnionType( registry.getNativeType(type), registry.getNativeType(VOID_TYPE)); } private JSType createNullableType(JSTypeNative type) { return createNullableType(registry.getNativeType(type)); } private JSType createNullableType(JSType type) { return registry.createNullableType(type); } private JSType createUnionType(JSTypeNative type1, JSTypeNative type2) { return registry.createUnionType( registry.getNativeType(type1), registry.getNativeType(type2)); } private JSType createMultiParamUnionType(JSTypeNative... variants) { return registry.createUnionType(variants); } @Test public void testAssumption() { assuming("x", NUMBER_TYPE); inFunction(""); verify("x", NUMBER_TYPE); } @Test public void testVar() { inFunction("var x = 1;"); verify("x", NUMBER_TYPE); } @Test public void testEmptyVar() { inFunction("var x;"); verify("x", VOID_TYPE); } @Test public void testAssignment() { assuming("x", OBJECT_TYPE); inFunction("x = 1;"); verify("x", NUMBER_TYPE); } @Test public void testExprWithinCast() { assuming("x", OBJECT_TYPE); inFunction("/** @type {string} */ (x = 1);"); verify("x", NUMBER_TYPE); } @Test public void testGetProp() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x.y();"); verify("x", OBJECT_TYPE); } @Test public void testGetElemDereference() { assuming("x", createUndefinableType(OBJECT_TYPE)); inFunction("x['z'] = 3;"); verify("x", OBJECT_TYPE); } @Test public void testIf1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {}; if (x) { y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf1a() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {}; if (x != null) { y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = x; if (x) { y = x; } else { y = {}; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf3() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 1; if (x) { y = x; }"); verify("y", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testPropertyInference1() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; if (this.foo) { y = this.foo; }"); verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testPropertyInference2() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; this.foo = 'x'; y = this.foo;"); verify("y", STRING_TYPE); } @Test public void testPropertyInference3() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; this.foo = x; y = this.foo;"); verify("y", createUndefinableType(STRING_TYPE)); } @Test public void testAssert1() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; goog.asserts.assert(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert1a() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; goog.asserts.assert(x !== null); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert2() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("goog.asserts.assert(1, x); out1 = x;"); verify("out1", startType); } @Test public void testAssert3() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("out1 = x; goog.asserts.assert(x && y); out2 = x; out3 = y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); verify("out3", OBJECT_TYPE); } @Test public void testAssert4() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("out1 = x; goog.asserts.assert(x && !y); out2 = x; out3 = y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); verify("out3", NULL_TYPE); } @Test public void testAssert5() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("goog.asserts.assert(x || y); out1 = x; out2 = y;"); verify("out1", startType); verify("out2", startType); } @Test public void testAssert6() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", getNativeType(UNKNOWN_TYPE)); // Only global qname roots can be undeclared assuming("x.y", startType); inFunction("out1 = x.y; goog.asserts.assert(x.y); out2 = x.y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert7() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(x);"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert8() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(x != null);"); verify("out1", startType); verify("out2", BOOLEAN_TYPE); } @Test public void testAssert9() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(y = x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssert11() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("var z = goog.asserts.assert(x || y);"); verify("x", startType); verify("y", startType); } @Test public void testPrimitiveAssertTruthy_narrowsNullableObjectToObject() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("out1 = x; assertTruthy(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testPrimitiveAssertTruthy_narrowsNullableObjectInNeqNullToObject() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("out1 = x; assertTruthy(x !== null); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testPrimitiveAssertTruthy_ignoresSecondArgumentEvenIfNullable() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("assertTruthy(1, x); out1 = x;"); verify("out1", startType); } @Test public void testAssertNumber_narrowsAllTypeToNumber() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertNumber(x); out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssertNumber_doesNotNarrowNamesInExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("goog.asserts.assertNumber(x + x); out1 = x;"); verify("out1", startType); } @Test public void testAssertNumber_returnsNumberGivenExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assertNumber(x + x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testPrimitiveAssertNumber_narrowsAllTypeToNumber() { JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; assertNumber(x); out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testPrimitiveAssertNumber_doesNotNarrowNamesInExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("assertNumber(x + x); out1 = x;"); verify("out1", startType); } @Test public void testPrimitiveAssertNumber_returnsNumberGivenExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; out2 = assertNumber(x + x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssertBoolean_narrowsAllTypeToBoolean() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertBoolean", getNativeType(BOOLEAN_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertBoolean(x); out2 = x;"); verify("out1", startType); verify("out2", BOOLEAN_TYPE); } @Test public void testAssertString_narrowsAllTypeToString() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertString", getNativeType(STRING_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertString(x); out2 = x;"); verify("out1", startType); verify("out2", STRING_TYPE); } @Test public void testAssertFunction_narrowsAllTypeToFunction() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertFunction", getNativeType(U2U_CONSTRUCTOR_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertFunction(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", U2U_CONSTRUCTOR_TYPE); } @Test public void testAssertElement_doesNotChangeElementType() { JSType elementType = registry.createObjectType("Element", registry.getNativeObjectType(OBJECT_TYPE)); includeGoogAssertionFn("assertElement", elementType); assuming("x", elementType); inFunction("out1 = x; goog.asserts.assertElement(x); out2 = x;"); verify("out1", elementType); verify("out2", elementType); } @Test public void testAssertObject_narrowsNullableArrayToArray() { JSType startType = createNullableType(ARRAY_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;"); verify("out1", startType); verify("out2", ARRAY_TYPE); } @Test public void testAssertObject_narrowsNullableObjectToObject() { JSType startType = createNullableType(OBJECT_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssertObject_narrowsQualifiedNameArgument() { JSType startType = createNullableType(OBJECT_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", getNativeType(UNKNOWN_TYPE)); // Only global qname roots can be undeclared assuming("x.y", startType); // test a property "x.y" instead of a simple name inFunction("out1 = x.y; goog.asserts.assertObject(x.y); out2 = x.y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssertObject_inCastToArray_returnsArray() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction( "out1 = x;" + "out2 = /** @type {!Array} */ (goog.asserts.assertObject(x));"); verify("out1", startType); verify("out2", ARRAY_TYPE); } @Test public void testAssertArray_narrowsNullableAllTypeToArray() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertArray", getNativeType(ARRAY_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", ARRAY_TYPE); } @Test public void testAssertArray_narrowsObjectTypeToArray() { JSType startType = getNativeType(OBJECT_TYPE); includeGoogAssertionFn("assertArray", getNativeType(ARRAY_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", ARRAY_TYPE); } @Test public void testAssertInstanceof_invalidCall_setsArgToUnknownType() { // Test invalid assert (2 params are required) JSType startType = createNullableType(ALL_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x); out2 = x;"); verify("out1", startType); verify("out2", UNKNOWN_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsAllTypeToString() { JSType startType = createNullableType(ALL_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_unknownCtor_setsStringToUnknown() { includeAssertInstanceof(); assuming("x", STRING_TYPE); assuming("Foo", UNKNOWN_TYPE); inFunction("out1 = x; goog.asserts.assertInstanceof(x, Foo); out2 = x;"); verify("out1", STRING_TYPE); verify("out2", UNKNOWN_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsUnknownToString() { JSType startType = registry.getNativeType(UNKNOWN_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_objectCtor_doesNotChangeStringType() { JSType startType = registry.getNativeType(STRING_OBJECT_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, Object); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsObjOrVoidToString() { JSType startType = createUnionType(OBJECT_TYPE, VOID_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); var r = x;"); verify("out1", startType); verify("x", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_stringCtor_returnsStringFromObjOrVoid() { JSType startType = createUnionType(OBJECT_TYPE, VOID_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; var y = goog.asserts.assertInstanceof(x, String);"); verify("out1", startType); verify("y", STRING_OBJECT_TYPE); } @Test public void testAssertWithIsDefAndNotNull() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "goog.asserts.assert(goog.isDefAndNotNull(x));" + "out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testIsDefAndNoResolvedType() { JSType startType = createUndefinableType(NO_RESOLVED_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "if (goog.isDef(x)) { out2a = x; out2b = x.length; out2c = x; }" + "out3 = x;" + "if (goog.isDef(x)) { out4 = x; }"); verify("out1", startType); verify("out2a", NO_RESOLVED_TYPE); verify("out2b", CHECKED_UNKNOWN_TYPE); verify("out2c", NO_RESOLVED_TYPE); verify("out3", startType); verify("out4", NO_RESOLVED_TYPE); } @Test public void testAssertWithNotIsNull() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "goog.asserts.assert(!goog.isNull(x));" + "out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testReturn1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("if (x) { return x; }\nx = {};\nreturn x;"); verify("x", OBJECT_TYPE); } @Test public void testReturn2() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("if (!x) { x = 0; }\nreturn x;"); verify("x", NUMBER_TYPE); } @Test public void testWhile1() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("while (!x) { if (x == null) { x = 0; } else { x = 1; } }"); verify("x", NUMBER_TYPE); } @Test public void testWhile2() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("while (!x) { x = {}; }"); verifySubtypeOf("x", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testDo() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("do { x = 1; } while (!x);"); verify("x", NUMBER_TYPE); } @Test public void testFor1() { assuming("y", NUMBER_TYPE); inFunction("var x = null; var i = null; for (i=y; !i; i=1) { x = 1; }"); verify("x", createNullableType(NUMBER_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testForInWithExistingVar() { assuming("y", OBJECT_TYPE); inFunction( lines( "var x = null;", "var i = null;", "for (i in y) {", " I_INSIDE_LOOP: i;", " X_AT_LOOP_START: x;", " x = 1;", " X_AT_LOOP_END: x;", "}", "X_AFTER_LOOP: x;", "I_AFTER_LOOP: i;")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onClosestHoistScope(); assertScopeEnclosing("I_INSIDE_LOOP").declares("x").onClosestHoistScope(); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertTypeOfExpression("I_AFTER_LOOP").toStringIsEqualTo("(null|string)"); assertTypeOfExpression("X_AT_LOOP_START").toStringIsEqualTo("(null|number)"); assertTypeOfExpression("X_AT_LOOP_END").toStringIsEqualTo("number"); assertTypeOfExpression("X_AFTER_LOOP").toStringIsEqualTo("(null|number)"); } @Test public void testForInWithRedeclaredVar() { assuming("y", OBJECT_TYPE); inFunction( lines( "var i = null;", "for (var i in y) {", // i redeclared here, but really the same variable " I_INSIDE_LOOP: i;", "}", "I_AFTER_LOOP: i;")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onClosestHoistScope(); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("I_AFTER_LOOP").declares("i").directly(); assertTypeOfExpression("I_AFTER_LOOP").toStringIsEqualTo("(null|string)"); } @Test public void testForInWithLet() { assuming("y", OBJECT_TYPE); inFunction( lines( "FOR_IN_LOOP: for (let i in y) {", // preserve newlines " I_INSIDE_LOOP: i;", "}", "AFTER_LOOP: 1;", "")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onScopeLabeled("FOR_IN_LOOP"); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("AFTER_LOOP").doesNotDeclare("i"); } @Test public void testForInWithConst() { assuming("y", OBJECT_TYPE); inFunction( lines( "FOR_IN_LOOP: for (const i in y) {", // preserve newlines " I_INSIDE_LOOP: i;", "}", "AFTER_LOOP: 1;", "")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onScopeLabeled("FOR_IN_LOOP"); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("AFTER_LOOP").doesNotDeclare("i"); } @Test public void testFor4() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {};\n" + "if (x) { for (var i = 0; i < 10; i++) { break; } y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testFor5() { assuming("y", templatize( getNativeObjectType(ARRAY_TYPE), ImmutableList.of(getNativeType(NUMBER_TYPE)))); inFunction( "var x = null; for (var i = 0; i < y.length; i++) { x = y[i]; }"); verify("x", createNullableType(NUMBER_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testFor6() { assuming("y", getNativeObjectType(ARRAY_TYPE)); inFunction( "var x = null;" + "for (var i = 0; i < y.length; i++) { " + " if (y[i] == 'z') { x = y[i]; } " + "}"); verify("x", getNativeType(UNKNOWN_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testSwitch1() { assuming("x", NUMBER_TYPE); inFunction("var y = null; switch(x) {\n" + "case 1: y = 1; break;\n" + "case 2: y = {};\n" + "case 3: y = {};\n" + "default: y = 0;}"); verify("y", NUMBER_TYPE); } @Test public void testSwitch2() { assuming("x", ALL_TYPE); inFunction("var y = null; switch (typeof x) {\n" + "case 'string':\n" + " y = x;\n" + " return;" + "default:\n" + " y = 'a';\n" + "}"); verify("y", STRING_TYPE); } @Test public void testSwitch3() { assuming("x", createNullableType(createUnionType(NUMBER_TYPE, STRING_TYPE))); inFunction("var y; var z; switch (typeof x) {\n" + "case 'string':\n" + " y = 1; z = null;\n" + " return;\n" + "case 'number':\n" + " y = x; z = null;\n" + " return;" + "default:\n" + " y = 1; z = x;\n" + "}"); verify("y", NUMBER_TYPE); verify("z", NULL_TYPE); } @Test public void testSwitch4() { assuming("x", ALL_TYPE); inFunction("var y = null; switch (typeof x) {\n" + "case 'string':\n" + "case 'number':\n" + " y = x;\n" + " return;\n" + "default:\n" + " y = 1;\n" + "}\n"); verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testCall1() { assuming("x", createNullableType( registry.createFunctionType(registry.getNativeType(NUMBER_TYPE)))); inFunction("var y = x();"); verify("y", NUMBER_TYPE); } @Test public void testNew1() { assuming("x", createNullableType( registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE))); inFunction("var y = new x();"); verify("y", UNKNOWN_TYPE); } @Test public void testNew2() { inFunction( "/**\n" + " * @constructor\n" + " * @param {T} x\n" + " * @template T\n" + " */" + "function F(x) {}\n" + "var x = /** @type {!Array<number>} */ ([]);\n" + "var result = new F(x);"); assertThat(getType("result").toString()).isEqualTo("F<Array<number>>"); } @Test public void testNew3() { inFunction( "/**\n" + " * @constructor\n" + " * @param {Array<T>} x\n" + " * @param {T} y\n" + " * @param {S} z\n" + " * @template T,S\n" + " */" + "function F(x,y,z) {}\n" + "var x = /** @type {!Array<number>} */ ([]);\n" + "var y = /** @type {string} */ ('foo');\n" + "var z = /** @type {boolean} */ (true);\n" + "var result = new F(x,y,z);"); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean>"); } @Test public void testNew4() { inFunction( lines( "/**", " * @constructor", " * @param {!Array<T>} x", " * @param {T} y", " * @param {S} z", " * @param {U} m", " * @template T,S,U", " */", "function F(x,y,z,m) {}", "var /** !Array<number> */ x = [];", "var y = 'foo';", "var z = true;", "var m = 9;", "var result = new F(x,y,z,m);")); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean,number>"); } @Test public void testNew_onCtor_instantiatingTemplatizedType_withNoTemplateInformation() { inFunction( lines( "/**", " * @constructor", " * @template T", " */", "function Foo() {}", "", "var result = new Foo();")); assertThat(getType("result").toString()).isEqualTo("Foo<?>"); } @Test public void testNew_onCtor_instantiatingTemplatizedType_specializedOnSecondaryTemplate() { inFunction( lines( "/**", " * @constructor", " * @template T", " */", "function Foo() {}", "", "/**", " * @template U", " * @param {function(new:Foo<U>)} ctor", " * @param {U} arg", " * @return {!Foo<U>}", " */", "function create(ctor, arg) {", " return new ctor(arg);", "}", "", "var result = create(Foo, 0);")); assertThat(getType("result").toString()).isEqualTo("Foo<number>"); } @Test public void testNewRest() { inFunction( lines( "/**", " * @constructor", " * @param {Array<T>} x", " * @param {T} y", " * @param {...S} rest", " * @template T,S", " */", "function F(x, y, ...rest) {}", "var x = /** @type {!Array<number>} */ ([]);", "var y = /** @type {string} */ ('foo');", "var z = /** @type {boolean} */ (true);", "var result = new F(x,y,z);")); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean>"); } @Test public void testParamNodeType_simpleName() { parseAndRunTypeInference("(/** @param {number} i */ function(i) {})"); assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_rest() { parseAndRunTypeInference("(/** @param {...number} i */ function(...i) {})"); assertNode(getParamNameNode("i")).hasJSTypeThat().toStringIsEqualTo("Array<number>"); } @Test public void testParamNodeType_arrayDestructuring() { parseAndRunTypeInference("(/** @param {!Iterable<number>} i */ function([i]) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_objectDestructuring() { parseAndRunTypeInference("(/** @param {{a: number}} i */ function({a: i}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_simpleName_withDefault() { parseAndRunTypeInference("(/** @param {number=} i */ function(i = 9) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_arrayDestructuring_withDefault() { parseAndRunTypeInference( lines( "(/** @param {!Iterable<number>=} unused */", "function([i] = /** @type ({!Array<number>} */ ([])) {})")); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. // TODO(b/122904530): `i` should be `number`. assertNode(getParamNameNode("i")).hasJSTypeThat().isUnknown(); } @Test public void testParamNodeType_objectDestructuring_withDefault() { parseAndRunTypeInference("(/** @param {{a: number}=} i */ function({a: i} = {a: 9}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_arrayDestructuring_withDefault_nestedInPattern() { parseAndRunTypeInference("(/** @param {!Iterable<number>} i */ function([i = 9]) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_objectDestructuring_withDefault_nestedInPattern() { parseAndRunTypeInference("(/** @param {{a: number}} i */ function({a: i = 9}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testInnerFunction1() { inFunction("var x = 1; function f() { x = null; };"); verify("x", NUMBER_TYPE); } @Test public void testInnerFunction2() { inFunction("var x = 1; var f = function() { x = null; };"); verify("x", NUMBER_TYPE); } @Test public void testFunctionDeclarationHasBlockScope() { inFunction( lines( "BLOCK_SCOPE: {", " BEFORE_DEFINITION: f;", " function f() {}", " AFTER_DEFINITION: f;", "}", "AFTER_BLOCK: f;")); // A block-scoped function declaration is hoisted to the beginning of its block, so it is always // defined within the block. assertScopeEnclosing("BEFORE_DEFINITION").declares("f").onScopeLabeled("BLOCK_SCOPE"); assertTypeOfExpression("BEFORE_DEFINITION").toStringIsEqualTo("function(): undefined"); assertTypeOfExpression("AFTER_DEFINITION").toStringIsEqualTo("function(): undefined"); assertScopeEnclosing("AFTER_BLOCK").doesNotDeclare("f"); } @Test public void testHook() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = x ? x : {};"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testThrow() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("var y = 1;\n" + "if (x == null) { throw new Error('x is null') }\n" + "y = x;"); verify("y", NUMBER_TYPE); } @Test public void testTry1() { assuming("x", NUMBER_TYPE); inFunction("var y = null; try { y = null; } finally { y = x; }"); verify("y", NUMBER_TYPE); } @Test public void testTry2() { assuming("x", NUMBER_TYPE); inFunction("var y = null;\n" + "try { } catch (e) { y = null; } finally { y = x; }"); verify("y", NUMBER_TYPE); } @Test public void testTry3() { assuming("x", NUMBER_TYPE); inFunction("var y = null; try { y = x; } catch (e) { }"); verify("y", NUMBER_TYPE); } @Test public void testCatch1() { inFunction("var y = null; try { foo(); } catch (e) { y = e; }"); verify("y", UNKNOWN_TYPE); } @Test public void testCatch2() { inFunction("var y = null; var e = 3; try { foo(); } catch (e) { y = e; }"); verify("y", UNKNOWN_TYPE); } @Test public void testUnknownType1() { inFunction("var y = 3; y = x;"); verify("y", UNKNOWN_TYPE); } @Test public void testUnknownType2() { assuming("x", ARRAY_TYPE); inFunction("var y = 5; y = x[0];"); verify("y", UNKNOWN_TYPE); } @Test public void testInfiniteLoop1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x = {}; while(x != null) { x = {}; }"); } @Test public void testInfiniteLoop2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x = {}; do { x = null; } while (x == null);"); } @Test public void testJoin1() { JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE); assuming("x", BOOLEAN_TYPE); assuming("unknownOrNull", unknownOrNull); inFunction("var y; if (x) y = unknownOrNull; else y = null;"); verify("y", unknownOrNull); } @Test public void testJoin2() { JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE); assuming("x", BOOLEAN_TYPE); assuming("unknownOrNull", unknownOrNull); inFunction("var y; if (x) y = null; else y = unknownOrNull;"); verify("y", unknownOrNull); } @Test public void testArrayLit() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 3; if (x) { x = [y = x]; }"); verify("x", createUnionType(NULL_TYPE, ARRAY_TYPE)); verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE)); } @Test public void testGetElem() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 3; if (x) { x = x[y = x]; }"); verify("x", UNKNOWN_TYPE); verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE)); } @Test public void testEnumRAI1() { JSType enumType = createEnumType("MyEnum", ARRAY_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (x) y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI2() { JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (typeof x == 'number') y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI3() { JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (x && typeof x == 'number') y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI4() { JSType enumType = createEnumType("MyEnum", createUnionType(STRING_TYPE, NUMBER_TYPE)).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (typeof x == 'number') y = x;"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingAnd() { assuming("x", NUMBER_TYPE); inFunction("var y = null; if (x && (y = 3)) { }"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingAnd2() { assuming("x", NUMBER_TYPE); inFunction("var y = null; var z = 4; if (x && (y = 3)) { z = y; }"); verify("z", NUMBER_TYPE); } @Test public void testShortCircuitingOr() { assuming("x", NUMBER_TYPE); inFunction("var y = null; if (x || (y = 3)) { }"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingOr2() { assuming("x", NUMBER_TYPE); inFunction("var y = null; var z = 4; if (x || (y = 3)) { z = y; }"); verify("z", createNullableType(NUMBER_TYPE)); } @Test public void testAssignInCondition() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("var y; if (!(y = x)) { y = 3; }"); verify("y", NUMBER_TYPE); } @Test public void testInstanceOf1() { assuming("x", OBJECT_TYPE); inFunction("var y = null; if (x instanceof String) y = x;"); verify("y", createNullableType(STRING_OBJECT_TYPE)); } @Test public void testInstanceOf2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 1; if (x instanceof String) y = x;"); verify("y", createUnionType(STRING_OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testInstanceOf3() { assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE)); inFunction("var y = null; if (x instanceof String) y = x;"); verify("y", createNullableType(STRING_OBJECT_TYPE)); } @Test public void testInstanceOf4() { assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE)); inFunction("var y = null; if (x instanceof String); else y = x;"); verify("y", createNullableType(NUMBER_OBJECT_TYPE)); } @Test public void testInstanceOf5() { assuming("x", OBJECT_TYPE); inFunction("var y = null; if (x instanceof String); else y = x;"); verify("y", createNullableType(OBJECT_TYPE)); } @Test public void testInstanceOf6() { // Here we are using "instanceof" to restrict the unknown type to // the type of the instance. This has the following problems: // 1) The type may actually be any sub-type // 2) The type may implement any interface // After the instanceof we will require casts for methods that require // sub-type or unrelated interfaces which would not have been required // before. JSType startType = registry.getNativeType(UNKNOWN_TYPE); assuming("x", startType); inFunction("out1 = x; if (x instanceof String) out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testUnary() { assuming("x", NUMBER_TYPE); inFunction("var y = +x;"); verify("y", NUMBER_TYPE); inFunction("var z = -x;"); verify("z", NUMBER_TYPE); } @Test public void testAdd1() { assuming("x", NUMBER_TYPE); inFunction("var y = x + 5;"); verify("y", NUMBER_TYPE); } @Test public void testAdd2() { assuming("x", NUMBER_TYPE); inFunction("var y = x + '5';"); verify("y", STRING_TYPE); } @Test public void testAdd3() { assuming("x", NUMBER_TYPE); inFunction("var y = '5' + x;"); verify("y", STRING_TYPE); } @Test public void testAssignAdd() { assuming("x", NUMBER_TYPE); inFunction("x += '5';"); verify("x", STRING_TYPE); } @Test public void testComparison() { inFunction("var x = 'foo'; var y = (x = 3) < 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) > 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) <= 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) >= 4;"); verify("x", NUMBER_TYPE); } @Test public void testThrownExpression() { inFunction("var x = 'foo'; " + "try { throw new Error(x = 3); } catch (ex) {}"); verify("x", NUMBER_TYPE); } @Test public void testObjectLit() { inFunction("var x = {}; var out = x.a;"); verify("out", UNKNOWN_TYPE); // Shouldn't this be 'undefined'? inFunction("var x = {a:1}; var out = x.a;"); verify("out", NUMBER_TYPE); inFunction("var x = {a:1}; var out = x.a; x.a = 'string'; var out2 = x.a;"); verify("out", NUMBER_TYPE); verify("out2", STRING_TYPE); inFunction("var x = { get a() {return 1} }; var out = x.a;"); verify("out", UNKNOWN_TYPE); inFunction( "var x = {" + " /** @return {number} */ get a() {return 1}" + "};" + "var out = x.a;"); verify("out", NUMBER_TYPE); inFunction("var x = { set a(b) {} }; var out = x.a;"); verify("out", UNKNOWN_TYPE); inFunction("var x = { " + "/** @param {number} b */ set a(b) {} };" + "var out = x.a;"); verify("out", NUMBER_TYPE); } @Test public void testObjectSpread_isInferredToBeObject() { // Given JSType recordType = registry.createRecordType( ImmutableMap.of( "x", getNativeType(STRING_TYPE), "y", getNativeType(NUMBER_TYPE))); assuming("obj", recordType); assuming("before", BOOLEAN_TYPE); assuming("after", NULL_TYPE); // When inFunction(lines("let spread = {before, ...obj, after};")); // Then // TODO(b/128355893): Do smarter inferrence. There are a lot of potential issues with // inference on object-rest, so for now we just give up and say `Object`. In theory we could // infer something like `{after: null, before: boolean, x: string, y: number}`. verify("spread", OBJECT_TYPE); } @Test public void testCast1() { inFunction("var x = /** @type {Object} */ (this);"); verify("x", createNullableType(OBJECT_TYPE)); } @Test public void testCast2() { inFunction( "/** @return {boolean} */" + "Object.prototype.method = function() { return true; };" + "var x = /** @type {Object} */ (this).method;"); verify( "x", registry.createFunctionTypeWithInstanceType( registry.getNativeObjectType(OBJECT_TYPE), registry.getNativeType(BOOLEAN_TYPE), ImmutableList.<JSType>of() /* params */)); } @Test public void testBackwardsInferenceCall() { inFunction( "/** @param {{foo: (number|undefined)}} x */" + "function f(x) {}" + "var y = {};" + "f(y);"); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testBackwardsInferenceCallRestParameter() { inFunction( lines( "/** @param {...{foo: (number|undefined)}} rest */", "function f(...rest) {}", "var y = {};", "f(y);")); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testBackwardsInferenceNew() { inFunction( "/**\n" + " * @constructor\n" + " * @param {{foo: (number|undefined)}} x\n" + " */" + "function F(x) {}" + "var y = {};" + "new F(y);"); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testNoThisInference() { JSType thisType = createNullableType(OBJECT_TYPE); assumingThisType(thisType); inFunction("var out = 3; if (goog.isNull(this)) out = this;"); verify("out", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testRecordInference() { inFunction( "/** @param {{a: boolean}|{b: string}} x */" + "function f(x) {}" + "var out = {};" + "f(out);"); assertThat(getType("out").toString()) .isEqualTo("{a: (boolean|undefined), b: (string|undefined)}"); } @Test public void testLotsOfBranchesGettingMerged() { String code = "var a = -1;\n"; code += "switch(foo()) { \n"; for (int i = 0; i < 100; i++) { code += "case " + i + ": a = " + i + "; break; \n"; } code += "default: a = undefined; break;\n"; code += "}\n"; inFunction(code); assertThat(getType("a").toString()).isEqualTo("(number|undefined)"); } @Test public void testIssue785() { inFunction("/** @param {string|{prop: (string|undefined)}} x */" + "function f(x) {}" + "var out = {};" + "f(out);"); assertThat(getType("out").toString()).isEqualTo("{prop: (string|undefined)}"); } @Test public void testFunctionTemplateType_literalParam() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(10);")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unionsPossibilities() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @param {T} b", " * @return {T}", " */", "function f(a, b){}", "", "var result = f(10, 'x');")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testFunctionTemplateType_willUseUnknown() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {?} */ ({}));")); verify("result", UNKNOWN_TYPE); } @Test public void testFunctionTemplateType_willUseUnknown_butPrefersTighterTypes() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @param {T} b", " * @param {T} c", " * @return {T}", " */", "function f(a, b, c){}", "", // Make sure `?` is dispreferred before *and* after a known type. "var result = f('x', /** @type {?} */ ({}), 5);")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testFunctionTemplateType_recursesIntoFunctionParams() { inFunction( lines( "/**", " * @template T", " * @param {function(T)} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(function(/** number */ a) { });")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_recursesIntoFunctionParams_throughUnknown() { inFunction( lines( "/**", " * @template T", " * @param {function(T)=} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {?} */ ({}));")); verify("result", UNKNOWN_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromParamType() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>|number} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {!Iterable<number>} */ ({}));")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromArgType() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>} a", " * @return {T}", " */", "function f(a){}", "", // The arg type is illegal, but the inference should still work. "var result = f(/** @type {!Iterable<number>|number} */ ({}));")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromArgType_acrossSubtypes() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {!Array<number>|!Generator<string>} */ ({}));")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testTypeTransformationTypePredicate() { inFunction( "/**\n" + " * @return {R}\n" + " * @template R := 'number' =:\n" + " */\n" + "function f(a){}\n" + "var result = f(10);"); verify("result", NUMBER_TYPE); } @Test public void testTypeTransformationConditional() { inFunction( "/**\n" + " * @param {T} a\n" + " * @param {N} b\n" + " * @return {R}\n" + " * @template T, N\n" + " * @template R := cond( eq(T, N), 'string', 'boolean' ) =:\n" + " */\n" + "function f(a, b){}\n" + "var result = f(1, 2);" + "var result2 = f(1, 'a');"); verify("result", STRING_TYPE); verify("result2", BOOLEAN_TYPE); } @Test public void testTypeTransformationNoneType() { inFunction( "/**\n" + " * @return {R}\n" + " * @template R := none() =:\n" + " */\n" + "function f(){}\n" + "var result = f(10);"); verify("result", JSTypeNative.UNKNOWN_TYPE); } @Test public void testTypeTransformationUnionType() { inFunction( "/**\n" + " * @param {S} a\n" + " * @param {N} b\n" + " * @return {R}\n" + " * @template S, N\n" + " * @template R := union(S, N) =:\n" + " */\n" + "function f(a, b) {}\n" + "var result = f(1, 'a');"); verify("result", createUnionType(STRING_TYPE, NUMBER_TYPE)); } @Test public void testTypeTransformationMapunion() { inFunction( "/**\n" + " * @param {U} a\n" + " * @return {R}\n" + " * @template U\n" + " * @template R :=\n" + " * mapunion(U, (x) => cond(eq(x, 'string'), 'boolean', 'null'))\n" + " * =:\n" + " */\n" + "function f(a) {}\n" + "/** @type {string|number} */ var x;" + "var result = f(x);"); verify("result", createUnionType(BOOLEAN_TYPE, NULL_TYPE)); } @Test public void testTypeTransformationObjectUseCase() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function Object(a) {}\n" + "/** @type {(string|number|boolean)} */\n" + "var o;\n" + "var r = Object(o);"); verify("r", createMultiParamUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE, JSTypeNative.BOOLEAN_OBJECT_TYPE)); } @Test public void testTypeTransformationObjectUseCase2() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function fn(a) {}\n" + "/** @type {(string|null|undefined)} */\n" + "var o;\n" + "var r = fn(o);"); verify("r", OBJECT_TYPE); } @Test public void testTypeTransformationObjectUseCase3() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function fn(a) {}\n" + "/** @type {(Array|undefined)} */\n" + "var o;\n" + "var r = fn(o);"); verify("r", OBJECT_TYPE); } @Test public void testTypeTransformationTypeOfVarWithInstanceOfConstructor() { inFunction("/** @constructor */\n" + "function Bar() {}" + "var b = new Bar();" + "/** \n" + " * @return {R}\n" + " * @template R := typeOfVar('b') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("b")); } @Test public void testTypeTransformationTypeOfVarWithConstructor() { inFunction("/** @constructor */\n" + "function Bar() {}" + "/** \n" + " * @return {R}\n" + " * @template R := typeOfVar('Bar') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("Bar")); } @Test public void testTypeTransformationTypeOfVarWithTypedef() { inFunction("/** @typedef {(string|number)} */\n" + "var NumberLike;" + "/** @type {!NumberLike} */" + "var x;" + "/**\n" + " * @return {R}\n" + " * @template R := typeOfVar('x') =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithTypeFromConstructor() { inFunction("/** @constructor */\n" + "function Bar(){}" + "var x = new Bar();" + "/** \n" + " * @return {R}\n" + " * @template R := 'Bar' =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithTypeFromTypedef() { inFunction("/** @typedef {(string|number)} */\n" + "var NumberLike;" + "/** @type {!NumberLike} */" + "var x;" + "/**\n" + " * @return {R}\n" + " * @template R := 'NumberLike' =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", createUnionType(STRING_TYPE, NUMBER_TYPE)); } @Test public void testTypeTransformationWithTypeFromNamespace() { inFunction( lines( "var wiz", "/** @constructor */", "wiz.async.Response = function() {};", "/**", " * @return {R}", " * @template R := typeOfVar('wiz.async.Response') =:", " */", "function f(){}", "var r = f();")); verify("r", getType("wiz.async.Response")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunction() { inFunction("/** @type {function(string, boolean)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(string, boolean)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionReturn() { inFunction("/** @type {function(): number} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(): number') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionThis() { inFunction("/** @type {function(this:boolean, string)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(this:boolean, string)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionVarargs() { inFunction("/** @type {function(string, ...number): number} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(string, ...number): number') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionOptional() { inFunction("/** @type {function(?string=, number=)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(?string=, number=)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationRecordFromObject() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := record(T) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:?}} */" + "var e;" + "/** @type {?} */" + "var bar;" + "var r = f({foo:bar});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationRecordFromObjectNested() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R :=\n" + " * maprecord(record(T), (k, v) => record({[k]:record(v)})) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:!Object, bar:!Object}} */" + "var e;" + "var r = f({foo:{}, bar:{}});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationRecordFromObjectWithTemplatizedType() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := record(T) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:!Array<number>}} */" + "var e;" + "/** @type {!Array<number>} */" + "var something;" + "var r = f({foo:something});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationIsTemplatizedPartially() { inFunction( Joiner.on('\n').join( "/**", " * @constructor", " * @template T, U", " */", "function Foo() {}", "/**", " * @template T := cond(isTemplatized(type('Foo', 'number')), 'number', 'string') =:", " * @return {T}", " */", "function f() { return 123; }", "var x = f();")); assertThat(getType("x").isNumber()).isTrue(); } @Test public void testAssertTypeofProp() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction( "goog.asserts.assert(typeof x.prop != 'undefined');" + "out = x.prop;"); verify("out", CHECKED_UNKNOWN_TYPE); } @Test public void testIsArray() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("goog.asserts.assert(Array.isArray(x));"); verify("x", ARRAY_TYPE); } @Test public void testNotIsArray() { assuming("x", createUnionType(ARRAY_TYPE, NUMBER_TYPE)); inFunction("goog.asserts.assert(!Array.isArray(x));"); verify("x", NUMBER_TYPE); } @Test public void testYield1() { inGenerator("var x = yield 3;"); verify("x", registry.getNativeType(UNKNOWN_TYPE)); } @Test public void testYield2() { // test that type inference happens inside the yield expression inGenerator( lines( "var obj;", "yield (obj = {a: 3, b: '4'});", "var a = obj.a;", "var b = obj.b;" )); verify("a", registry.getNativeType(NUMBER_TYPE)); verify("b", registry.getNativeType(STRING_TYPE)); } @Test public void testTemplateLiteral1() { inFunction("var x = `foobar`; X: x;"); assertTypeOfExpression("X").isString(); } @Test public void testSpreadExpression() { inFunction( lines( "let x = 1;", // x is initially a number "let y = [...[x = 'hi', 'there']];", // reassign x a string in the spread "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("string"); } @Test public void testTaggedTemplateLiteral1() { assuming("getNumber", registry.createFunctionType(registry.getNativeType(NUMBER_TYPE))); inFunction("var num = getNumber``; NUM: num;"); assertTypeOfExpression("NUM").isNumber(); } @Test public void testRestParamType() { parseAndRunTypeInference( lines( "(", "/**", // preserve newlines " * @param {...number} nums", " */", "function(str, ...nums) {", " NUMS: nums;", " let n = null;", " N_START: n;", " if (nums.length > 0) {", " n = nums[0];", " N_IF_TRUE: n;", " } else {", " N_IF_FALSE: n;", " }", " N_FINAL: n;", "}", ");")); assertTypeOfExpression("N_START").toStringIsEqualTo("null"); assertTypeOfExpression("N_IF_TRUE").toStringIsEqualTo("number"); assertTypeOfExpression("N_IF_FALSE").toStringIsEqualTo("null"); assertTypeOfExpression("N_FINAL").toStringIsEqualTo("(null|number)"); } @Test public void testObjectDestructuringDeclarationInference() { JSType recordType = registry.createRecordType( ImmutableMap.of( "x", getNativeType(STRING_TYPE), "y", getNativeType(NUMBER_TYPE))); assuming("obj", recordType); inFunction( lines( "let {x, y} = obj; ", // preserve newline "X: x;", "Y: y;")); assertTypeOfExpression("X").toStringIsEqualTo("string"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); assertScopeEnclosing("X").declares("x").withTypeThat().toStringIsEqualTo("string"); } @Test public void testObjectDestructuringDeclarationInferenceWithDefaultValue() { inFunction( lines( "var /** {x: (?string|undefined)} */ obj;", "let {x = 3} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("(null|number|string)"); } @Test public void testObjectDestructuringDeclarationInferenceWithUnnecessaryDefaultValue() { inFunction( lines( "var /** {x: string} */ obj;", "let {x = 3} = obj; ", // we ignore the default value's type "X: x;")); // TODO(b/77597706): should this just be `string`? // the legacy behavior (typechecking transpiled code) produces (number|string), but we should // possibly realize that the default value will never be evaluated. assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); } @Test public void testObjectDestructuringDeclarationInference_unknownRhsAndKnownDefaultValue() { inFunction( lines( "var /** ? */ obj;", "let {x = 3} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDeclarationInference_knownRhsAndUnknownDefaultValue() { inFunction( lines( "var /** {x: (string|undefined)} */ obj;", "let {x = someUnknown} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDeclaration_defaultValueEvaluatedAfterComputedProperty() { // contrived example to verify that we traverse the computed property before the default value. inFunction( lines( "var /** !Object<string, (number|undefined)> */ obj = {};", "var a = 1;", "const {[a = 'string']: b = a} = obj", "A: a", "B: b")); assertTypeOfExpression("A").toStringIsEqualTo("string"); assertTypeOfExpression("B").toStringIsEqualTo("(number|string)"); } @Test public void testObjectDestructuringDeclarationInferenceWithUnknownProperty() { JSType recordType = registry.createRecordType(ImmutableMap.of()); assuming("obj", recordType); inFunction( lines( "let {x} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDoesInferenceWithinComputedProp() { inFunction( lines( "let y = 'foobar'; ", // preserve newline "let {[y = 3]: z} = {};", "Y: y", "Z: z")); assertTypeOfExpression("Y").toStringIsEqualTo("number"); assertTypeOfExpression("Z").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringUsesIObjectTypeForComputedProp() { inFunction( lines( "let /** !IObject<string, number> */ myObj = {['foo']: 3}; ", // preserve newline "let {[42]: x} = myObj;", "X: x")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringDeclarationWithNestedPattern() { inFunction( lines( "let /** {a: {b: number}} */ obj = {a: {b: 3}};", // "let {a: {b: x}} = obj;", "X: x")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringAssignmentToQualifiedName() { inFunction( lines( "const ns = {};", // "({x: ns.x} = {x: 3});", "X: ns.x;")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringDeclarationInForOf() { inFunction( lines( "const /** !Iterable<{x: number}> */ data = [{x: 3}];", // "for (let {x} of data) {", " X: x;", "}")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringAssignInForOf() { inFunction( lines( "const /** !Iterable<{x: number}> */ data = [{x: 3}];", // "var x;", "for ({x} of data) {", " X: x;", "}")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringParameterWithDefaults() { parseAndRunTypeInference( "(/** @param {{x: (number|undefined)}} data */ function f({x = 3}) { X: x; });"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectRest_inferredGivenObjectLiteralType() { inFunction("var obj = {a: 1, b: 2, c: 3}; const {a, ...rest} = obj; A: a; REST: rest;"); assertTypeOfExpression("A").toStringIsEqualTo("number"); assertTypeOfExpression("REST").isEqualTo(registry.getNativeType(OBJECT_TYPE)); } @Test public void testArrayDestructuringDeclaration() { inFunction( lines( "const /** !Iterable<number> */ numbers = [1, 2, 3];", "let [x, y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringDeclarationWithDefaultValue() { inFunction( lines( "const /** !Iterable<(number|undefined)> */ numbers = [1, 2, 3];", "let [x = 'x', y = 'y'] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); assertTypeOfExpression("Y").toStringIsEqualTo("(number|string)"); } @Test public void testArrayDestructuringDeclarationWithDefaultValueForNestedPattern() { inFunction( lines( "const /** !Iterable<({x: number}|undefined)> */ xNumberObjs = [];", "let [{x = 'foo'} = {}] = xNumberObjs;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); } @Test public void testArrayDestructuringDeclarationWithRest() { inFunction( lines( "const /** !Iterable<number> */ numbers = [1, 2, 3];", "let [x, ...y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("Array<number>"); } @Test public void testArrayDestructuringDeclarationWithNestedArrayPattern() { inFunction( lines( "const /** !Iterable<!Iterable<number>> */ numbers = [[1, 2, 3]];", "let [[x], y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("Iterable<number>"); } @Test public void testArrayDestructuringDeclarationWithNestedObjectPattern() { inFunction( lines( "const /** !Iterable<{x: number}> */ numbers = [{x: 3}, {x: 4}];", "let [{x}, {x: y}] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringDeclarationWithNonIterableRhs() { // TODO(lharker): make sure TypeCheck warns on this inFunction("let [x] = 3; X: x;"); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testArrayDestructuringAssignWithGetProp() { inFunction( lines( "const ns = {};", // "const /** !Iterable<number> */ numbers = [1, 2, 3];", "[ns.x] = numbers;", "NSX: ns.x;")); assertTypeOfExpression("NSX").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringAssignWithGetElem() { // we don't update the scope on an assignment to a getelem, so this test just verifies that // a) type inference doesn't crash and b) type info validation passes. inFunction( lines( "const arr = [];", // "const /** !Iterable<number> */ numbers = [1, 2, 3];", "[arr[1]] = numbers;", "ARR1: arr[1];")); assertTypeOfExpression("ARR1").toStringIsEqualTo("?"); } @Test public void testDeclarationDoesntOverrideInferredTypeInDestructuringPattern() { inFunction("var [/** number */ x] = /** @type {?} */ ([null]); X: x"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testDeclarationDoesntOverrideInferredTypeInForOfLoop() { inFunction("for (var /** number */ x of /** @type {?} */ [null]) { X: x; }"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testTypeInferenceOccursInDestructuringCatch() { assuming("x", NUMBER_TYPE); inFunction( lines( "try {", " throw {err: 3}; ", "} catch ({[x = 'err']: /** number */ err}) {", " ERR: err;", " X: x;", "}")); assertTypeOfExpression("ERR").toStringIsEqualTo("number"); // verify we do inference on the assignment to `x` inside the computed property assertTypeOfExpression("X").toStringIsEqualTo("string"); } @Test public void testTypeInferenceOccursInDestructuringForIn() { assuming("x", NUMBER_TYPE); inFunction( lines( "/** @type {number} */", "String.prototype.length;", "", "var obj = {};", "for ({length: obj.length} in {'1': 1, '22': 22}) {", " LENGTH: obj.length;", // set to '1'.length and '22'.length "}")); assertTypeOfExpression("LENGTH").toStringIsEqualTo("number"); } @Test public void testInferringTypeInObjectPattern_fromTemplatizedProperty() { // create type Foo with one property templatized with type T TemplateType templateKey = registry.createTemplateType("T"); FunctionType fooCtor = registry.createConstructorType( "Foo", null, IR.paramList(), null, ImmutableList.of(templateKey), false); ObjectType fooInstanceType = fooCtor.getInstanceType(); fooInstanceType.defineDeclaredProperty("data", templateKey, null); // create a variable obj with type Foo<number> JSType fooOfNumber = templatize(fooInstanceType, ImmutableList.of(getNativeType(NUMBER_TYPE))); assuming("obj", fooOfNumber); inFunction( lines( "const {data} = obj;", // "OBJ: obj;", "DATA: data")); assertTypeOfExpression("OBJ").toStringIsEqualTo("Foo<number>"); assertTypeOfExpression("DATA").toStringIsEqualTo("number"); } @Test public void testTypeInferenceOccursInsideVoidOperator() { inFunction("var x; var y = void (x = 3); X: x; Y: y"); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("undefined"); } @Test public void constDeclarationWithReturnJSDoc_ignoresUnknownRhsType() { assuming("foo", UNKNOWN_TYPE); inFunction(lines("/** @return {number} */ const fn = foo;")); JSType fooWithInterfaceType = getType("fn"); assertType(fooWithInterfaceType).isFunctionTypeThat().hasReturnTypeThat().isNumber(); } @Test public void constDeclarationWithCtorJSDoc_ignoresKnownMixinReturnType() { // Create a function always returning a constructor for 'Foo' JSType fooType = FunctionType.builder(registry).forConstructor().withName("Foo").build(); assuming("Foo", fooType); FunctionType mixinType = FunctionType.builder(registry).withReturnType(fooType).build(); assuming("mixin", mixinType); // The @constructor JSDoc should declare a new type, and FooExtended should refer to that // type instead of the constructor for Foo inFunction(lines("/** @constructor @extends {Foo} */ const FooExtended = mixin();")); JSType fooWithInterfaceType = getType("FooExtended"); assertType(fooWithInterfaceType).isNotEqualTo(fooType); assertType(fooWithInterfaceType).toStringIsEqualTo("function(new:FooExtended): ?"); } @Test public void testSideEffectsInEsExportDefaultInferred() { assuming("foo", NUMBER_TYPE); assuming("bar", UNKNOWN_TYPE); inModule("export default (bar = foo, foo = 'not a number');"); assertType(getType("bar")).isNumber(); assertType(getType("foo")).isString(); } private ObjectType getNativeObjectType(JSTypeNative t) { return registry.getNativeObjectType(t); } private JSType getNativeType(JSTypeNative t) { return registry.getNativeType(t); } private JSType templatize(ObjectType objType, ImmutableList<JSType> t) { return registry.createTemplatizedType(objType, t); } /** Adds a goog.asserts.assert[name] function to the scope that asserts the given returnType */ private void includeGoogAssertionFn(String fnName, JSType returnType) { String fullName = "goog.asserts." + fnName; FunctionType fnType = FunctionType.builder(registry) .withReturnType(returnType) .withParamsNode(IR.paramList(IR.name("p"))) .withName(fullName) .build(); assuming(fullName, fnType); } /** Adds a function with {@link ClosurePrimitive#ASSERTS_TRUTHY} and the given name */ private void includePrimitiveTruthyAssertionFunction(String fnName) { TemplateType t = registry.createTemplateType("T"); FunctionType assertType = FunctionType.builder(registry) .withName(fnName) .withClosurePrimitiveId(ClosurePrimitive.ASSERTS_TRUTHY) .withReturnType(t) .withParamsNode(IR.paramList(IR.name("x").setJSType(t))) .withTemplateKeys(t) .build(); assuming(fnName, assertType); } /** * Adds a function with {@link ClosurePrimitive#ASSERTS_MATCHES_RETURN} that asserts the given * returnType */ private void includePrimitiveAssertionFn(String fullName, JSType returnType) { FunctionType fnType = FunctionType.builder(registry) .withReturnType(returnType) .withParamsNode(IR.paramList(IR.name("p"))) .withName(fullName) .withClosurePrimitiveId(ClosurePrimitive.ASSERTS_MATCHES_RETURN) .build(); assuming(fullName, fnType); } /** Adds goog.asserts.assertInstanceof to the scope, to do fine-grained assertion testing */ private void includeAssertInstanceof() { String fullName = "goog.asserts.assertInstanceof"; TemplateType templateType = registry.createTemplateType("T"); // Create the function type `function(new:T)` FunctionType templateTypeCtor = FunctionType.builder(registry).forConstructor().withTypeOfThis(templateType).build(); // Create the function type `function(?, function(new:T)): T` // This matches the JSDoc for goog.asserts.assertInstanceof: // /** // * @param {?} value The value to check // * @param {function(new:T)) type A user-defined ctor // * @return {T} // * @template T // */ FunctionType fnType = FunctionType.builder(registry) .withParamsNode( IR.paramList( IR.name("value").setJSType(getNativeType(UNKNOWN_TYPE)), IR.name("type").setJSType(templateTypeCtor))) .withTemplateKeys(templateType) .withReturnType(templateType) .withName(fullName) .build(); assuming(fullName, fnType); } }
test/com/google/javascript/jscomp/TypeInferenceTest.java
/* * Copyright 2008 The Closure Compiler 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 com.google.javascript.jscomp; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static com.google.javascript.jscomp.CompilerTypeTestCase.lines; import static com.google.javascript.jscomp.testing.ScopeSubject.assertScope; import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NO_RESOLVED_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE; import static com.google.javascript.rhino.testing.NodeSubject.assertNode; import static com.google.javascript.rhino.testing.TypeSubject.assertType; import static com.google.javascript.rhino.testing.TypeSubject.types; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Streams; import com.google.javascript.jscomp.CodingConvention.AssertionFunctionLookup; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.DataFlowAnalysis.BranchedFlowState; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode; import com.google.javascript.jscomp.modules.ModuleMapCreator; import com.google.javascript.jscomp.testing.ScopeSubject; import com.google.javascript.jscomp.type.FlowScope; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.rhino.ClosurePrimitive; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.StaticTypedRef; import com.google.javascript.rhino.jstype.StaticTypedScope; import com.google.javascript.rhino.jstype.StaticTypedSlot; import com.google.javascript.rhino.jstype.TemplateType; import com.google.javascript.rhino.testing.TypeSubject; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests {@link TypeInference}. * */ @RunWith(JUnit4.class) public final class TypeInferenceTest { private Compiler compiler; private JSTypeRegistry registry; private Map<String, JSType> assumptions; private JSType assumedThisType; private FlowScope returnScope; private static final AssertionFunctionLookup ASSERTION_FUNCTION_MAP = AssertionFunctionLookup.of(new ClosureCodingConvention().getAssertionFunctions()); /** * Maps a label name to information about the labeled statement. * * <p>This map is recreated each time parseAndRunTypeInference() is executed. */ private Map<String, LabeledStatement> labeledStatementMap; /** Stores information about a labeled statement and allows making assertions on it. */ static class LabeledStatement { final Node statementNode; final TypedScope enclosingScope; LabeledStatement(Node statementNode, TypedScope enclosingScope) { this.statementNode = checkNotNull(statementNode); this.enclosingScope = checkNotNull(enclosingScope); } } @Before public void setUp() { compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.setClosurePass(true); compiler.initOptions(options); options.setLanguageIn(LanguageMode.ECMASCRIPT_2018); registry = compiler.getTypeRegistry(); assumptions = new HashMap<>(); returnScope = null; } private void assumingThisType(JSType type) { assumedThisType = type; } private void assuming(String name, JSType type) { assumptions.put(name, type); } /** Declares a name with a given type in the parent scope of the test case code. */ private void assuming(String name, JSTypeNative type) { assuming(name, registry.getNativeType(type)); } private void inFunction(String js) { // Parse the body of the function. String thisBlock = assumedThisType == null ? "" : "/** @this {" + assumedThisType + "} */"; parseAndRunTypeInference("(" + thisBlock + " function() {" + js + "});"); } private void inModule(String js) { Node script = compiler.parseTestCode(js); assertWithMessage("parsing error: " + Joiner.on(", ").join(compiler.getErrors())) .that(compiler.getErrorCount()) .isEqualTo(0); Node root = IR.root(IR.root(), IR.root(script)); new GatherModuleMetadata(compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER) .process(root.getFirstChild(), root.getSecondChild()); new ModuleMapCreator(compiler, compiler.getModuleMetadataMap()) .process(root.getFirstChild(), root.getSecondChild()); // SCRIPT -> MODULE_BODY Node moduleBody = script.getFirstChild(); parseAndRunTypeInference(root, moduleBody); } private void inGenerator(String js) { checkState(assumedThisType == null); parseAndRunTypeInference("(function *() {" + js + "});"); } private void parseAndRunTypeInference(String js) { Node script = compiler.parseTestCode(js); Node root = IR.root(IR.root(), IR.root(script)); assertWithMessage("parsing error: " + Joiner.on(", ").join(compiler.getErrors())) .that(compiler.getErrorCount()) .isEqualTo(0); // SCRIPT -> EXPR_RESULT -> FUNCTION // `(function() { TEST CODE HERE });` Node function = script.getFirstFirstChild(); parseAndRunTypeInference(root, function); } private void parseAndRunTypeInference(Node root, Node cfgRoot) { // Create the scope with the assumptions. TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); // Also populate a map allowing us to look up labeled statements later. labeledStatementMap = new HashMap<>(); new NodeTraversal( compiler, new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { TypedScope scope = t.getTypedScope(); if (parent != null && parent.isLabel() && !n.isLabelName()) { // First child of a LABEL is a LABEL_NAME, n is the second child. Node labelNameNode = checkNotNull(n.getPrevious(), n); checkState(labelNameNode.isLabelName(), labelNameNode); String labelName = labelNameNode.getString(); assertWithMessage("Duplicate label name: %s", labelName) .that(labeledStatementMap) .doesNotContainKey(labelName); labeledStatementMap.put(labelName, new LabeledStatement(n, scope)); } } }, scopeCreator) .traverse(root); TypedScope assumedScope = scopeCreator.createScope(cfgRoot); for (Map.Entry<String,JSType> entry : assumptions.entrySet()) { assumedScope.declare(entry.getKey(), null, entry.getValue(), null, false); } // Create the control graph. ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false); cfa.process(null, cfgRoot); ControlFlowGraph<Node> cfg = cfa.getCfg(); // Create a simple reverse abstract interpreter. ReverseAbstractInterpreter rai = compiler.getReverseAbstractInterpreter(); // Do the type inference by data-flow analysis. TypeInference dfa = new TypeInference(compiler, cfg, rai, assumedScope, scopeCreator, ASSERTION_FUNCTION_MAP); dfa.analyze(); // Get the scope of the implicit return. BranchedFlowState<FlowScope> rtnState = cfg.getImplicitReturn().getAnnotation(); if (cfgRoot.isFunction()) { // Reset the flow scope's syntactic scope to the function block, rather than the function node // itself. This allows pulling out local vars from the function by name to verify their // types. returnScope = rtnState.getIn().withSyntacticScope(scopeCreator.createScope(cfgRoot.getLastChild())); } else { returnScope = rtnState.getIn(); } } private LabeledStatement getLabeledStatement(String label) { assertWithMessage("No statement found for label: %s", label) .that(labeledStatementMap) .containsKey(label); return labeledStatementMap.get(label); } /** * Returns a ScopeSubject for the scope containing the labeled statement. * * <p>Asserts that a statement with the given label existed in the code last passed to * parseAndRunTypeInference(). */ private ScopeSubject assertScopeEnclosing(String label) { return assertScope(getLabeledStatement(label).enclosingScope); } /** * Returns a TypeSubject for the JSType of the expression with the given label. * * <p>Asserts that a statement with the given label existed in the code last passed to * parseAndRunTypeInference(). Also asserts that the statement is an EXPR_RESULT whose expression * has a non-null JSType. */ private TypeSubject assertTypeOfExpression(String label) { Node statementNode = getLabeledStatement(label).statementNode; assertWithMessage("Not an expression statement.").that(statementNode.isExprResult()).isTrue(); JSType jsType = statementNode.getOnlyChild().getJSType(); assertWithMessage("Expression type is null").that(jsType).isNotNull(); return assertType(jsType); } private JSType getType(String name) { assertWithMessage("The return scope should not be null.").that(returnScope).isNotNull(); StaticTypedSlot var = returnScope.getSlot(name); assertWithMessage("The variable " + name + " is missing from the scope.").that(var).isNotNull(); return var.getType(); } /** Returns the NAME node {@code name} from the PARAM_LIST of the top level of type inference. */ private Node getParamNameNode(String name) { StaticTypedScope staticScope = checkNotNull(returnScope.getDeclarationScope(), returnScope); StaticTypedSlot slot = checkNotNull(staticScope.getSlot(name), staticScope); StaticTypedRef declaration = checkNotNull(slot.getDeclaration(), slot); Node node = checkNotNull(declaration.getNode(), declaration); assertNode(node).hasType(Token.NAME); Streams.stream(node.getAncestors()) .filter(Node::isParamList) .findFirst() .orElseThrow(AssertionError::new); return node; } private void verify(String name, JSType type) { assertWithMessage("Mismatch for " + name) .about(types()) .that(getType(name)) .isStructurallyEqualTo(type); } private void verify(String name, JSTypeNative type) { verify(name, registry.getNativeType(type)); } private void verifySubtypeOf(String name, JSType type) { JSType varType = getType(name); assertWithMessage("The variable " + name + " is missing a type.").that(varType).isNotNull(); assertWithMessage( "The type " + varType + " of variable " + name + " is not a subtype of " + type + ".") .that(varType.isSubtypeOf(type)) .isTrue(); } private void verifySubtypeOf(String name, JSTypeNative type) { verifySubtypeOf(name, registry.getNativeType(type)); } private EnumType createEnumType(String name, JSTypeNative elemType) { return createEnumType(name, registry.getNativeType(elemType)); } private EnumType createEnumType(String name, JSType elemType) { return registry.createEnumType(name, null, elemType); } private JSType createUndefinableType(JSTypeNative type) { return registry.createUnionType( registry.getNativeType(type), registry.getNativeType(VOID_TYPE)); } private JSType createNullableType(JSTypeNative type) { return createNullableType(registry.getNativeType(type)); } private JSType createNullableType(JSType type) { return registry.createNullableType(type); } private JSType createUnionType(JSTypeNative type1, JSTypeNative type2) { return registry.createUnionType( registry.getNativeType(type1), registry.getNativeType(type2)); } private JSType createMultiParamUnionType(JSTypeNative... variants) { return registry.createUnionType(variants); } @Test public void testAssumption() { assuming("x", NUMBER_TYPE); inFunction(""); verify("x", NUMBER_TYPE); } @Test public void testVar() { inFunction("var x = 1;"); verify("x", NUMBER_TYPE); } @Test public void testEmptyVar() { inFunction("var x;"); verify("x", VOID_TYPE); } @Test public void testAssignment() { assuming("x", OBJECT_TYPE); inFunction("x = 1;"); verify("x", NUMBER_TYPE); } @Test public void testExprWithinCast() { assuming("x", OBJECT_TYPE); inFunction("/** @type {string} */ (x = 1);"); verify("x", NUMBER_TYPE); } @Test public void testGetProp() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x.y();"); verify("x", OBJECT_TYPE); } @Test public void testGetElemDereference() { assuming("x", createUndefinableType(OBJECT_TYPE)); inFunction("x['z'] = 3;"); verify("x", OBJECT_TYPE); } @Test public void testIf1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {}; if (x) { y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf1a() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {}; if (x != null) { y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = x; if (x) { y = x; } else { y = {}; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testIf3() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 1; if (x) { y = x; }"); verify("y", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testPropertyInference1() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; if (this.foo) { y = this.foo; }"); verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testPropertyInference2() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; this.foo = 'x'; y = this.foo;"); verify("y", STRING_TYPE); } @Test public void testPropertyInference3() { ObjectType thisType = registry.createAnonymousObjectType(null); thisType.defineDeclaredProperty("foo", createUndefinableType(STRING_TYPE), null); assumingThisType(thisType); inFunction("var y = 1; this.foo = x; y = this.foo;"); verify("y", createUndefinableType(STRING_TYPE)); } @Test public void testAssert1() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; goog.asserts.assert(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert1a() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; goog.asserts.assert(x !== null); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert2() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("goog.asserts.assert(1, x); out1 = x;"); verify("out1", startType); } @Test public void testAssert3() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("out1 = x; goog.asserts.assert(x && y); out2 = x; out3 = y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); verify("out3", OBJECT_TYPE); } @Test public void testAssert4() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("out1 = x; goog.asserts.assert(x && !y); out2 = x; out3 = y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); verify("out3", NULL_TYPE); } @Test public void testAssert5() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("goog.asserts.assert(x || y); out1 = x; out2 = y;"); verify("out1", startType); verify("out2", startType); } @Test public void testAssert6() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", getNativeType(UNKNOWN_TYPE)); // Only global qname roots can be undeclared assuming("x.y", startType); inFunction("out1 = x.y; goog.asserts.assert(x.y); out2 = x.y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert7() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(x);"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssert8() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(x != null);"); verify("out1", startType); verify("out2", BOOLEAN_TYPE); } @Test public void testAssert9() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assert(y = x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssert11() { JSType startType = createNullableType(OBJECT_TYPE); assuming("x", startType); assuming("y", startType); inFunction("var z = goog.asserts.assert(x || y);"); verify("x", startType); verify("y", startType); } @Test public void testPrimitiveAssertTruthy_narrowsNullableObjectToObject() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("out1 = x; assertTruthy(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testPrimitiveAssertTruthy_narrowsNullableObjectInNeqNullToObject() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("out1 = x; assertTruthy(x !== null); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testPrimitiveAssertTruthy_ignoresSecondArgumentEvenIfNullable() { JSType startType = createNullableType(OBJECT_TYPE); includePrimitiveTruthyAssertionFunction("assertTruthy"); assuming("x", startType); inFunction("assertTruthy(1, x); out1 = x;"); verify("out1", startType); } @Test public void testAssertNumber_narrowsAllTypeToNumber() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertNumber(x); out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssertNumber_doesNotNarrowNamesInExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("goog.asserts.assertNumber(x + x); out1 = x;"); verify("out1", startType); } @Test public void testAssertNumber_returnsNumberGivenExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; out2 = goog.asserts.assertNumber(x + x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testPrimitiveAssertNumber_narrowsAllTypeToNumber() { JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; assertNumber(x); out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testPrimitiveAssertNumber_doesNotNarrowNamesInExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("assertNumber(x + x); out1 = x;"); verify("out1", startType); } @Test public void testPrimitiveAssertNumber_returnsNumberGivenExpression() { // Make sure it ignores expressions. JSType startType = createNullableType(ALL_TYPE); includePrimitiveAssertionFn("assertNumber", getNativeType(NUMBER_TYPE)); assuming("x", startType); inFunction("out1 = x; out2 = assertNumber(x + x);"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testAssertBoolean_narrowsAllTypeToBoolean() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertBoolean", getNativeType(BOOLEAN_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertBoolean(x); out2 = x;"); verify("out1", startType); verify("out2", BOOLEAN_TYPE); } @Test public void testAssertString_narrowsAllTypeToString() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertString", getNativeType(STRING_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertString(x); out2 = x;"); verify("out1", startType); verify("out2", STRING_TYPE); } @Test public void testAssertFunction_narrowsAllTypeToFunction() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertFunction", getNativeType(U2U_CONSTRUCTOR_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertFunction(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", U2U_CONSTRUCTOR_TYPE); } @Test public void testAssertElement_doesNotChangeElementType() { JSType elementType = registry.createObjectType("Element", registry.getNativeObjectType(OBJECT_TYPE)); includeGoogAssertionFn("assertElement", elementType); assuming("x", elementType); inFunction("out1 = x; goog.asserts.assertElement(x); out2 = x;"); verify("out1", elementType); verify("out2", elementType); } @Test public void testAssertObject_narrowsNullableArrayToArray() { JSType startType = createNullableType(ARRAY_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;"); verify("out1", startType); verify("out2", ARRAY_TYPE); } @Test public void testAssertObject_narrowsNullableObjectToObject() { JSType startType = createNullableType(OBJECT_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssertObject_narrowsQualifiedNameArgument() { JSType startType = createNullableType(OBJECT_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", getNativeType(UNKNOWN_TYPE)); // Only global qname roots can be undeclared assuming("x.y", startType); // test a property "x.y" instead of a simple name inFunction("out1 = x.y; goog.asserts.assertObject(x.y); out2 = x.y;"); verify("out1", startType); verify("out2", OBJECT_TYPE); } @Test public void testAssertObject_inCastToArray_returnsArray() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertObject", getNativeType(OBJECT_TYPE)); assuming("x", startType); inFunction( "out1 = x;" + "out2 = /** @type {!Array} */ (goog.asserts.assertObject(x));"); verify("out1", startType); verify("out2", ARRAY_TYPE); } @Test public void testAssertArray_narrowsNullableAllTypeToArray() { JSType startType = createNullableType(ALL_TYPE); includeGoogAssertionFn("assertArray", getNativeType(ARRAY_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", ARRAY_TYPE); } @Test public void testAssertArray_narrowsObjectTypeToArray() { JSType startType = getNativeType(OBJECT_TYPE); includeGoogAssertionFn("assertArray", getNativeType(ARRAY_TYPE)); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;"); verify("out1", startType); verifySubtypeOf("out2", ARRAY_TYPE); } @Test public void testAssertInstanceof_invalidCall_setsArgToUnknownType() { // Test invalid assert (2 params are required) JSType startType = createNullableType(ALL_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x); out2 = x;"); verify("out1", startType); verify("out2", UNKNOWN_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsAllTypeToString() { JSType startType = createNullableType(ALL_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_unknownCtor_setsStringToUnknown() { includeAssertInstanceof(); assuming("x", STRING_TYPE); assuming("Foo", UNKNOWN_TYPE); inFunction("out1 = x; goog.asserts.assertInstanceof(x, Foo); out2 = x;"); verify("out1", STRING_TYPE); verify("out2", UNKNOWN_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsUnknownToString() { JSType startType = registry.getNativeType(UNKNOWN_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_objectCtor_doesNotChangeStringType() { JSType startType = registry.getNativeType(STRING_OBJECT_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, Object); out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_stringCtor_narrowsObjOrVoidToString() { JSType startType = createUnionType(OBJECT_TYPE, VOID_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); var r = x;"); verify("out1", startType); verify("x", STRING_OBJECT_TYPE); } @Test public void testAssertInstanceof_stringCtor_returnsStringFromObjOrVoid() { JSType startType = createUnionType(OBJECT_TYPE, VOID_TYPE); includeAssertInstanceof(); assuming("x", startType); inFunction("out1 = x; var y = goog.asserts.assertInstanceof(x, String);"); verify("out1", startType); verify("y", STRING_OBJECT_TYPE); } @Test public void testAssertWithIsDefAndNotNull() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "goog.asserts.assert(goog.isDefAndNotNull(x));" + "out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testIsDefAndNoResolvedType() { JSType startType = createUndefinableType(NO_RESOLVED_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "if (goog.isDef(x)) { out2a = x; out2b = x.length; out2c = x; }" + "out3 = x;" + "if (goog.isDef(x)) { out4 = x; }"); verify("out1", startType); verify("out2a", NO_RESOLVED_TYPE); verify("out2b", CHECKED_UNKNOWN_TYPE); verify("out2c", NO_RESOLVED_TYPE); verify("out3", startType); verify("out4", NO_RESOLVED_TYPE); } @Test public void testAssertWithNotIsNull() { JSType startType = createNullableType(NUMBER_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "goog.asserts.assert(!goog.isNull(x));" + "out2 = x;"); verify("out1", startType); verify("out2", NUMBER_TYPE); } @Test public void testReturn1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("if (x) { return x; }\nx = {};\nreturn x;"); verify("x", OBJECT_TYPE); } @Test public void testReturn2() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("if (!x) { x = 0; }\nreturn x;"); verify("x", NUMBER_TYPE); } @Test public void testWhile1() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("while (!x) { if (x == null) { x = 0; } else { x = 1; } }"); verify("x", NUMBER_TYPE); } @Test public void testWhile2() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("while (!x) { x = {}; }"); verifySubtypeOf("x", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testDo() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("do { x = 1; } while (!x);"); verify("x", NUMBER_TYPE); } @Test public void testFor1() { assuming("y", NUMBER_TYPE); inFunction("var x = null; var i = null; for (i=y; !i; i=1) { x = 1; }"); verify("x", createNullableType(NUMBER_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testForInWithExistingVar() { assuming("y", OBJECT_TYPE); inFunction( lines( "var x = null;", "var i = null;", "for (i in y) {", " I_INSIDE_LOOP: i;", " X_AT_LOOP_START: x;", " x = 1;", " X_AT_LOOP_END: x;", "}", "X_AFTER_LOOP: x;", "I_AFTER_LOOP: i;")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onClosestHoistScope(); assertScopeEnclosing("I_INSIDE_LOOP").declares("x").onClosestHoistScope(); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertTypeOfExpression("I_AFTER_LOOP").toStringIsEqualTo("(null|string)"); assertTypeOfExpression("X_AT_LOOP_START").toStringIsEqualTo("(null|number)"); assertTypeOfExpression("X_AT_LOOP_END").toStringIsEqualTo("number"); assertTypeOfExpression("X_AFTER_LOOP").toStringIsEqualTo("(null|number)"); } @Test public void testForInWithRedeclaredVar() { assuming("y", OBJECT_TYPE); inFunction( lines( "var i = null;", "for (var i in y) {", // i redeclared here, but really the same variable " I_INSIDE_LOOP: i;", "}", "I_AFTER_LOOP: i;")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onClosestHoistScope(); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("I_AFTER_LOOP").declares("i").directly(); assertTypeOfExpression("I_AFTER_LOOP").toStringIsEqualTo("(null|string)"); } @Test public void testForInWithLet() { assuming("y", OBJECT_TYPE); inFunction( lines( "FOR_IN_LOOP: for (let i in y) {", // preserve newlines " I_INSIDE_LOOP: i;", "}", "AFTER_LOOP: 1;", "")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onScopeLabeled("FOR_IN_LOOP"); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("AFTER_LOOP").doesNotDeclare("i"); } @Test public void testForInWithConst() { assuming("y", OBJECT_TYPE); inFunction( lines( "FOR_IN_LOOP: for (const i in y) {", // preserve newlines " I_INSIDE_LOOP: i;", "}", "AFTER_LOOP: 1;", "")); assertScopeEnclosing("I_INSIDE_LOOP").declares("i").onScopeLabeled("FOR_IN_LOOP"); assertTypeOfExpression("I_INSIDE_LOOP").toStringIsEqualTo("string"); assertScopeEnclosing("AFTER_LOOP").doesNotDeclare("i"); } @Test public void testFor4() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = {};\n" + "if (x) { for (var i = 0; i < 10; i++) { break; } y = x; }"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testFor5() { assuming("y", templatize( getNativeObjectType(ARRAY_TYPE), ImmutableList.of(getNativeType(NUMBER_TYPE)))); inFunction( "var x = null; for (var i = 0; i < y.length; i++) { x = y[i]; }"); verify("x", createNullableType(NUMBER_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testFor6() { assuming("y", getNativeObjectType(ARRAY_TYPE)); inFunction( "var x = null;" + "for (var i = 0; i < y.length; i++) { " + " if (y[i] == 'z') { x = y[i]; } " + "}"); verify("x", getNativeType(UNKNOWN_TYPE)); verify("i", NUMBER_TYPE); } @Test public void testSwitch1() { assuming("x", NUMBER_TYPE); inFunction("var y = null; switch(x) {\n" + "case 1: y = 1; break;\n" + "case 2: y = {};\n" + "case 3: y = {};\n" + "default: y = 0;}"); verify("y", NUMBER_TYPE); } @Test public void testSwitch2() { assuming("x", ALL_TYPE); inFunction("var y = null; switch (typeof x) {\n" + "case 'string':\n" + " y = x;\n" + " return;" + "default:\n" + " y = 'a';\n" + "}"); verify("y", STRING_TYPE); } @Test public void testSwitch3() { assuming("x", createNullableType(createUnionType(NUMBER_TYPE, STRING_TYPE))); inFunction("var y; var z; switch (typeof x) {\n" + "case 'string':\n" + " y = 1; z = null;\n" + " return;\n" + "case 'number':\n" + " y = x; z = null;\n" + " return;" + "default:\n" + " y = 1; z = x;\n" + "}"); verify("y", NUMBER_TYPE); verify("z", NULL_TYPE); } @Test public void testSwitch4() { assuming("x", ALL_TYPE); inFunction("var y = null; switch (typeof x) {\n" + "case 'string':\n" + "case 'number':\n" + " y = x;\n" + " return;\n" + "default:\n" + " y = 1;\n" + "}\n"); verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testCall1() { assuming("x", createNullableType( registry.createFunctionType(registry.getNativeType(NUMBER_TYPE)))); inFunction("var y = x();"); verify("y", NUMBER_TYPE); } @Test public void testNew1() { assuming("x", createNullableType( registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE))); inFunction("var y = new x();"); verify("y", UNKNOWN_TYPE); } @Test public void testNew2() { inFunction( "/**\n" + " * @constructor\n" + " * @param {T} x\n" + " * @template T\n" + " */" + "function F(x) {}\n" + "var x = /** @type {!Array<number>} */ ([]);\n" + "var result = new F(x);"); assertThat(getType("result").toString()).isEqualTo("F<Array<number>>"); } @Test public void testNew3() { inFunction( "/**\n" + " * @constructor\n" + " * @param {Array<T>} x\n" + " * @param {T} y\n" + " * @param {S} z\n" + " * @template T,S\n" + " */" + "function F(x,y,z) {}\n" + "var x = /** @type {!Array<number>} */ ([]);\n" + "var y = /** @type {string} */ ('foo');\n" + "var z = /** @type {boolean} */ (true);\n" + "var result = new F(x,y,z);"); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean>"); } @Test public void testNew4() { inFunction( lines( "/**", " * @constructor", " * @param {!Array<T>} x", " * @param {T} y", " * @param {S} z", " * @param {U} m", " * @template T,S,U", " */", "function F(x,y,z,m) {}", "var /** !Array<number> */ x = [];", "var y = 'foo';", "var z = true;", "var m = 9;", "var result = new F(x,y,z,m);")); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean,number>"); } @Test public void testNewRest() { inFunction( lines( "/**", " * @constructor", " * @param {Array<T>} x", " * @param {T} y", " * @param {...S} rest", " * @template T,S", " */", "function F(x, y, ...rest) {}", "var x = /** @type {!Array<number>} */ ([]);", "var y = /** @type {string} */ ('foo');", "var z = /** @type {boolean} */ (true);", "var result = new F(x,y,z);")); assertThat(getType("result").toString()).isEqualTo("F<(number|string),boolean>"); } @Test public void testParamNodeType_simpleName() { parseAndRunTypeInference("(/** @param {number} i */ function(i) {})"); assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_rest() { parseAndRunTypeInference("(/** @param {...number} i */ function(...i) {})"); assertNode(getParamNameNode("i")).hasJSTypeThat().toStringIsEqualTo("Array<number>"); } @Test public void testParamNodeType_arrayDestructuring() { parseAndRunTypeInference("(/** @param {!Iterable<number>} i */ function([i]) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_objectDestructuring() { parseAndRunTypeInference("(/** @param {{a: number}} i */ function({a: i}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_simpleName_withDefault() { parseAndRunTypeInference("(/** @param {number=} i */ function(i = 9) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_arrayDestructuring_withDefault() { parseAndRunTypeInference( lines( "(/** @param {!Iterable<number>=} unused */", "function([i] = /** @type ({!Array<number>} */ ([])) {})")); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. // TODO(b/122904530): `i` should be `number`. assertNode(getParamNameNode("i")).hasJSTypeThat().isUnknown(); } @Test public void testParamNodeType_objectDestructuring_withDefault() { parseAndRunTypeInference("(/** @param {{a: number}=} i */ function({a: i} = {a: 9}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_arrayDestructuring_withDefault_nestedInPattern() { parseAndRunTypeInference("(/** @param {!Iterable<number>} i */ function([i = 9]) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testParamNodeType_objectDestructuring_withDefault_nestedInPattern() { parseAndRunTypeInference("(/** @param {{a: number}} i */ function({a: i = 9}) {})"); // TODO(nickreid): Also check the types of the other nodes in the PARAM_LIST tree. assertNode(getParamNameNode("i")).hasJSTypeThat().isNumber(); } @Test public void testInnerFunction1() { inFunction("var x = 1; function f() { x = null; };"); verify("x", NUMBER_TYPE); } @Test public void testInnerFunction2() { inFunction("var x = 1; var f = function() { x = null; };"); verify("x", NUMBER_TYPE); } @Test public void testFunctionDeclarationHasBlockScope() { inFunction( lines( "BLOCK_SCOPE: {", " BEFORE_DEFINITION: f;", " function f() {}", " AFTER_DEFINITION: f;", "}", "AFTER_BLOCK: f;")); // A block-scoped function declaration is hoisted to the beginning of its block, so it is always // defined within the block. assertScopeEnclosing("BEFORE_DEFINITION").declares("f").onScopeLabeled("BLOCK_SCOPE"); assertTypeOfExpression("BEFORE_DEFINITION").toStringIsEqualTo("function(): undefined"); assertTypeOfExpression("AFTER_DEFINITION").toStringIsEqualTo("function(): undefined"); assertScopeEnclosing("AFTER_BLOCK").doesNotDeclare("f"); } @Test public void testHook() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = x ? x : {};"); verifySubtypeOf("y", OBJECT_TYPE); } @Test public void testThrow() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("var y = 1;\n" + "if (x == null) { throw new Error('x is null') }\n" + "y = x;"); verify("y", NUMBER_TYPE); } @Test public void testTry1() { assuming("x", NUMBER_TYPE); inFunction("var y = null; try { y = null; } finally { y = x; }"); verify("y", NUMBER_TYPE); } @Test public void testTry2() { assuming("x", NUMBER_TYPE); inFunction("var y = null;\n" + "try { } catch (e) { y = null; } finally { y = x; }"); verify("y", NUMBER_TYPE); } @Test public void testTry3() { assuming("x", NUMBER_TYPE); inFunction("var y = null; try { y = x; } catch (e) { }"); verify("y", NUMBER_TYPE); } @Test public void testCatch1() { inFunction("var y = null; try { foo(); } catch (e) { y = e; }"); verify("y", UNKNOWN_TYPE); } @Test public void testCatch2() { inFunction("var y = null; var e = 3; try { foo(); } catch (e) { y = e; }"); verify("y", UNKNOWN_TYPE); } @Test public void testUnknownType1() { inFunction("var y = 3; y = x;"); verify("y", UNKNOWN_TYPE); } @Test public void testUnknownType2() { assuming("x", ARRAY_TYPE); inFunction("var y = 5; y = x[0];"); verify("y", UNKNOWN_TYPE); } @Test public void testInfiniteLoop1() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x = {}; while(x != null) { x = {}; }"); } @Test public void testInfiniteLoop2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("x = {}; do { x = null; } while (x == null);"); } @Test public void testJoin1() { JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE); assuming("x", BOOLEAN_TYPE); assuming("unknownOrNull", unknownOrNull); inFunction("var y; if (x) y = unknownOrNull; else y = null;"); verify("y", unknownOrNull); } @Test public void testJoin2() { JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE); assuming("x", BOOLEAN_TYPE); assuming("unknownOrNull", unknownOrNull); inFunction("var y; if (x) y = null; else y = unknownOrNull;"); verify("y", unknownOrNull); } @Test public void testArrayLit() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 3; if (x) { x = [y = x]; }"); verify("x", createUnionType(NULL_TYPE, ARRAY_TYPE)); verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE)); } @Test public void testGetElem() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 3; if (x) { x = x[y = x]; }"); verify("x", UNKNOWN_TYPE); verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE)); } @Test public void testEnumRAI1() { JSType enumType = createEnumType("MyEnum", ARRAY_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (x) y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI2() { JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (typeof x == 'number') y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI3() { JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (x && typeof x == 'number') y = x;"); verify("y", createNullableType(enumType)); } @Test public void testEnumRAI4() { JSType enumType = createEnumType("MyEnum", createUnionType(STRING_TYPE, NUMBER_TYPE)).getElementsType(); assuming("x", enumType); inFunction("var y = null; if (typeof x == 'number') y = x;"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingAnd() { assuming("x", NUMBER_TYPE); inFunction("var y = null; if (x && (y = 3)) { }"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingAnd2() { assuming("x", NUMBER_TYPE); inFunction("var y = null; var z = 4; if (x && (y = 3)) { z = y; }"); verify("z", NUMBER_TYPE); } @Test public void testShortCircuitingOr() { assuming("x", NUMBER_TYPE); inFunction("var y = null; if (x || (y = 3)) { }"); verify("y", createNullableType(NUMBER_TYPE)); } @Test public void testShortCircuitingOr2() { assuming("x", NUMBER_TYPE); inFunction("var y = null; var z = 4; if (x || (y = 3)) { z = y; }"); verify("z", createNullableType(NUMBER_TYPE)); } @Test public void testAssignInCondition() { assuming("x", createNullableType(NUMBER_TYPE)); inFunction("var y; if (!(y = x)) { y = 3; }"); verify("y", NUMBER_TYPE); } @Test public void testInstanceOf1() { assuming("x", OBJECT_TYPE); inFunction("var y = null; if (x instanceof String) y = x;"); verify("y", createNullableType(STRING_OBJECT_TYPE)); } @Test public void testInstanceOf2() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("var y = 1; if (x instanceof String) y = x;"); verify("y", createUnionType(STRING_OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testInstanceOf3() { assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE)); inFunction("var y = null; if (x instanceof String) y = x;"); verify("y", createNullableType(STRING_OBJECT_TYPE)); } @Test public void testInstanceOf4() { assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE)); inFunction("var y = null; if (x instanceof String); else y = x;"); verify("y", createNullableType(NUMBER_OBJECT_TYPE)); } @Test public void testInstanceOf5() { assuming("x", OBJECT_TYPE); inFunction("var y = null; if (x instanceof String); else y = x;"); verify("y", createNullableType(OBJECT_TYPE)); } @Test public void testInstanceOf6() { // Here we are using "instanceof" to restrict the unknown type to // the type of the instance. This has the following problems: // 1) The type may actually be any sub-type // 2) The type may implement any interface // After the instanceof we will require casts for methods that require // sub-type or unrelated interfaces which would not have been required // before. JSType startType = registry.getNativeType(UNKNOWN_TYPE); assuming("x", startType); inFunction("out1 = x; if (x instanceof String) out2 = x;"); verify("out1", startType); verify("out2", STRING_OBJECT_TYPE); } @Test public void testUnary() { assuming("x", NUMBER_TYPE); inFunction("var y = +x;"); verify("y", NUMBER_TYPE); inFunction("var z = -x;"); verify("z", NUMBER_TYPE); } @Test public void testAdd1() { assuming("x", NUMBER_TYPE); inFunction("var y = x + 5;"); verify("y", NUMBER_TYPE); } @Test public void testAdd2() { assuming("x", NUMBER_TYPE); inFunction("var y = x + '5';"); verify("y", STRING_TYPE); } @Test public void testAdd3() { assuming("x", NUMBER_TYPE); inFunction("var y = '5' + x;"); verify("y", STRING_TYPE); } @Test public void testAssignAdd() { assuming("x", NUMBER_TYPE); inFunction("x += '5';"); verify("x", STRING_TYPE); } @Test public void testComparison() { inFunction("var x = 'foo'; var y = (x = 3) < 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) > 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) <= 4;"); verify("x", NUMBER_TYPE); inFunction("var x = 'foo'; var y = (x = 3) >= 4;"); verify("x", NUMBER_TYPE); } @Test public void testThrownExpression() { inFunction("var x = 'foo'; " + "try { throw new Error(x = 3); } catch (ex) {}"); verify("x", NUMBER_TYPE); } @Test public void testObjectLit() { inFunction("var x = {}; var out = x.a;"); verify("out", UNKNOWN_TYPE); // Shouldn't this be 'undefined'? inFunction("var x = {a:1}; var out = x.a;"); verify("out", NUMBER_TYPE); inFunction("var x = {a:1}; var out = x.a; x.a = 'string'; var out2 = x.a;"); verify("out", NUMBER_TYPE); verify("out2", STRING_TYPE); inFunction("var x = { get a() {return 1} }; var out = x.a;"); verify("out", UNKNOWN_TYPE); inFunction( "var x = {" + " /** @return {number} */ get a() {return 1}" + "};" + "var out = x.a;"); verify("out", NUMBER_TYPE); inFunction("var x = { set a(b) {} }; var out = x.a;"); verify("out", UNKNOWN_TYPE); inFunction("var x = { " + "/** @param {number} b */ set a(b) {} };" + "var out = x.a;"); verify("out", NUMBER_TYPE); } @Test public void testObjectSpread_isInferredToBeObject() { // Given JSType recordType = registry.createRecordType( ImmutableMap.of( "x", getNativeType(STRING_TYPE), "y", getNativeType(NUMBER_TYPE))); assuming("obj", recordType); assuming("before", BOOLEAN_TYPE); assuming("after", NULL_TYPE); // When inFunction(lines("let spread = {before, ...obj, after};")); // Then // TODO(b/128355893): Do smarter inferrence. There are a lot of potential issues with // inference on object-rest, so for now we just give up and say `Object`. In theory we could // infer something like `{after: null, before: boolean, x: string, y: number}`. verify("spread", OBJECT_TYPE); } @Test public void testCast1() { inFunction("var x = /** @type {Object} */ (this);"); verify("x", createNullableType(OBJECT_TYPE)); } @Test public void testCast2() { inFunction( "/** @return {boolean} */" + "Object.prototype.method = function() { return true; };" + "var x = /** @type {Object} */ (this).method;"); verify( "x", registry.createFunctionTypeWithInstanceType( registry.getNativeObjectType(OBJECT_TYPE), registry.getNativeType(BOOLEAN_TYPE), ImmutableList.<JSType>of() /* params */)); } @Test public void testBackwardsInferenceCall() { inFunction( "/** @param {{foo: (number|undefined)}} x */" + "function f(x) {}" + "var y = {};" + "f(y);"); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testBackwardsInferenceCallRestParameter() { inFunction( lines( "/** @param {...{foo: (number|undefined)}} rest */", "function f(...rest) {}", "var y = {};", "f(y);")); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testBackwardsInferenceNew() { inFunction( "/**\n" + " * @constructor\n" + " * @param {{foo: (number|undefined)}} x\n" + " */" + "function F(x) {}" + "var y = {};" + "new F(y);"); assertThat(getType("y").toString()).isEqualTo("{foo: (number|undefined)}"); } @Test public void testNoThisInference() { JSType thisType = createNullableType(OBJECT_TYPE); assumingThisType(thisType); inFunction("var out = 3; if (goog.isNull(this)) out = this;"); verify("out", createUnionType(OBJECT_TYPE, NUMBER_TYPE)); } @Test public void testRecordInference() { inFunction( "/** @param {{a: boolean}|{b: string}} x */" + "function f(x) {}" + "var out = {};" + "f(out);"); assertThat(getType("out").toString()) .isEqualTo("{a: (boolean|undefined), b: (string|undefined)}"); } @Test public void testLotsOfBranchesGettingMerged() { String code = "var a = -1;\n"; code += "switch(foo()) { \n"; for (int i = 0; i < 100; i++) { code += "case " + i + ": a = " + i + "; break; \n"; } code += "default: a = undefined; break;\n"; code += "}\n"; inFunction(code); assertThat(getType("a").toString()).isEqualTo("(number|undefined)"); } @Test public void testIssue785() { inFunction("/** @param {string|{prop: (string|undefined)}} x */" + "function f(x) {}" + "var out = {};" + "f(out);"); assertThat(getType("out").toString()).isEqualTo("{prop: (string|undefined)}"); } @Test public void testFunctionTemplateType_literalParam() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(10);")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unionsPossibilities() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @param {T} b", " * @return {T}", " */", "function f(a, b){}", "", "var result = f(10, 'x');")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testFunctionTemplateType_willUseUnknown() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {?} */ ({}));")); verify("result", UNKNOWN_TYPE); } @Test public void testFunctionTemplateType_willUseUnknown_butPrefersTighterTypes() { inFunction( lines( "/**", " * @template T", " * @param {T} a", " * @param {T} b", " * @param {T} c", " * @return {T}", " */", "function f(a, b, c){}", "", // Make sure `?` is dispreferred before *and* after a known type. "var result = f('x', /** @type {?} */ ({}), 5);")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testFunctionTemplateType_recursesIntoFunctionParams() { inFunction( lines( "/**", " * @template T", " * @param {function(T)} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(function(/** number */ a) { });")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_recursesIntoFunctionParams_throughUnknown() { inFunction( lines( "/**", " * @template T", " * @param {function(T)=} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {?} */ ({}));")); verify("result", UNKNOWN_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromParamType() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>|number} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {!Iterable<number>} */ ({}));")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromArgType() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>} a", " * @return {T}", " */", "function f(a){}", "", // The arg type is illegal, but the inference should still work. "var result = f(/** @type {!Iterable<number>|number} */ ({}));")); verify("result", NUMBER_TYPE); } @Test public void testFunctionTemplateType_unpacksUnions_fromArgType_acrossSubtypes() { inFunction( lines( "/**", " * @template T", " * @param {!Iterable<T>} a", " * @return {T}", " */", "function f(a){}", "", "var result = f(/** @type {!Array<number>|!Generator<string>} */ ({}));")); verify("result", registry.createUnionType(NUMBER_TYPE, STRING_TYPE)); } @Test public void testTypeTransformationTypePredicate() { inFunction( "/**\n" + " * @return {R}\n" + " * @template R := 'number' =:\n" + " */\n" + "function f(a){}\n" + "var result = f(10);"); verify("result", NUMBER_TYPE); } @Test public void testTypeTransformationConditional() { inFunction( "/**\n" + " * @param {T} a\n" + " * @param {N} b\n" + " * @return {R}\n" + " * @template T, N\n" + " * @template R := cond( eq(T, N), 'string', 'boolean' ) =:\n" + " */\n" + "function f(a, b){}\n" + "var result = f(1, 2);" + "var result2 = f(1, 'a');"); verify("result", STRING_TYPE); verify("result2", BOOLEAN_TYPE); } @Test public void testTypeTransformationNoneType() { inFunction( "/**\n" + " * @return {R}\n" + " * @template R := none() =:\n" + " */\n" + "function f(){}\n" + "var result = f(10);"); verify("result", JSTypeNative.UNKNOWN_TYPE); } @Test public void testTypeTransformationUnionType() { inFunction( "/**\n" + " * @param {S} a\n" + " * @param {N} b\n" + " * @return {R}\n" + " * @template S, N\n" + " * @template R := union(S, N) =:\n" + " */\n" + "function f(a, b) {}\n" + "var result = f(1, 'a');"); verify("result", createUnionType(STRING_TYPE, NUMBER_TYPE)); } @Test public void testTypeTransformationMapunion() { inFunction( "/**\n" + " * @param {U} a\n" + " * @return {R}\n" + " * @template U\n" + " * @template R :=\n" + " * mapunion(U, (x) => cond(eq(x, 'string'), 'boolean', 'null'))\n" + " * =:\n" + " */\n" + "function f(a) {}\n" + "/** @type {string|number} */ var x;" + "var result = f(x);"); verify("result", createUnionType(BOOLEAN_TYPE, NULL_TYPE)); } @Test public void testTypeTransformationObjectUseCase() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function Object(a) {}\n" + "/** @type {(string|number|boolean)} */\n" + "var o;\n" + "var r = Object(o);"); verify("r", createMultiParamUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE, JSTypeNative.BOOLEAN_OBJECT_TYPE)); } @Test public void testTypeTransformationObjectUseCase2() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function fn(a) {}\n" + "/** @type {(string|null|undefined)} */\n" + "var o;\n" + "var r = fn(o);"); verify("r", OBJECT_TYPE); } @Test public void testTypeTransformationObjectUseCase3() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := \n" + " * mapunion(T, (x) => \n" + " * cond(eq(x, 'string'), 'String',\n" + " * cond(eq(x, 'number'), 'Number',\n" + " * cond(eq(x, 'boolean'), 'Boolean',\n" + " * cond(eq(x, 'null'), 'Object', \n" + " * cond(eq(x, 'undefined'), 'Object',\n" + " * x)))))) \n" + " * =:\n" + " */\n" + "function fn(a) {}\n" + "/** @type {(Array|undefined)} */\n" + "var o;\n" + "var r = fn(o);"); verify("r", OBJECT_TYPE); } @Test public void testTypeTransformationTypeOfVarWithInstanceOfConstructor() { inFunction("/** @constructor */\n" + "function Bar() {}" + "var b = new Bar();" + "/** \n" + " * @return {R}\n" + " * @template R := typeOfVar('b') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("b")); } @Test public void testTypeTransformationTypeOfVarWithConstructor() { inFunction("/** @constructor */\n" + "function Bar() {}" + "/** \n" + " * @return {R}\n" + " * @template R := typeOfVar('Bar') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("Bar")); } @Test public void testTypeTransformationTypeOfVarWithTypedef() { inFunction("/** @typedef {(string|number)} */\n" + "var NumberLike;" + "/** @type {!NumberLike} */" + "var x;" + "/**\n" + " * @return {R}\n" + " * @template R := typeOfVar('x') =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithTypeFromConstructor() { inFunction("/** @constructor */\n" + "function Bar(){}" + "var x = new Bar();" + "/** \n" + " * @return {R}\n" + " * @template R := 'Bar' =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithTypeFromTypedef() { inFunction("/** @typedef {(string|number)} */\n" + "var NumberLike;" + "/** @type {!NumberLike} */" + "var x;" + "/**\n" + " * @return {R}\n" + " * @template R := 'NumberLike' =:" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", createUnionType(STRING_TYPE, NUMBER_TYPE)); } @Test public void testTypeTransformationWithTypeFromNamespace() { inFunction( lines( "var wiz", "/** @constructor */", "wiz.async.Response = function() {};", "/**", " * @return {R}", " * @template R := typeOfVar('wiz.async.Response') =:", " */", "function f(){}", "var r = f();")); verify("r", getType("wiz.async.Response")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunction() { inFunction("/** @type {function(string, boolean)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(string, boolean)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionReturn() { inFunction("/** @type {function(): number} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(): number') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionThis() { inFunction("/** @type {function(this:boolean, string)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(this:boolean, string)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionVarargs() { inFunction("/** @type {function(string, ...number): number} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(string, ...number): number') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationWithNativeTypeExpressionFunctionOptional() { inFunction("/** @type {function(?string=, number=)} */\n" + "var x;\n" + "/**\n" + " * @return {R}\n" + " * @template R := typeExpr('function(?string=, number=)') =:\n" + " */\n" + "function f(){}\n" + "var r = f();"); verify("r", getType("x")); } @Test public void testTypeTransformationRecordFromObject() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := record(T) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:?}} */" + "var e;" + "/** @type {?} */" + "var bar;" + "var r = f({foo:bar});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationRecordFromObjectNested() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R :=\n" + " * maprecord(record(T), (k, v) => record({[k]:record(v)})) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:!Object, bar:!Object}} */" + "var e;" + "var r = f({foo:{}, bar:{}});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationRecordFromObjectWithTemplatizedType() { inFunction("/** \n" + " * @param {T} a\n" + " * @return {R}\n" + " * @template T \n" + " * @template R := record(T) =:" + " */\n" + "function f(a) {}\n" + "/** @type {{foo:!Array<number>}} */" + "var e;" + "/** @type {!Array<number>} */" + "var something;" + "var r = f({foo:something});"); assertThat(getType("r").isRecordType()).isTrue(); verify("r", getType("e")); } @Test public void testTypeTransformationIsTemplatizedPartially() { inFunction( Joiner.on('\n').join( "/**", " * @constructor", " * @template T, U", " */", "function Foo() {}", "/**", " * @template T := cond(isTemplatized(type('Foo', 'number')), 'number', 'string') =:", " * @return {T}", " */", "function f() { return 123; }", "var x = f();")); assertThat(getType("x").isNumber()).isTrue(); } @Test public void testAssertTypeofProp() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction( "goog.asserts.assert(typeof x.prop != 'undefined');" + "out = x.prop;"); verify("out", CHECKED_UNKNOWN_TYPE); } @Test public void testIsArray() { assuming("x", createNullableType(OBJECT_TYPE)); inFunction("goog.asserts.assert(Array.isArray(x));"); verify("x", ARRAY_TYPE); } @Test public void testNotIsArray() { assuming("x", createUnionType(ARRAY_TYPE, NUMBER_TYPE)); inFunction("goog.asserts.assert(!Array.isArray(x));"); verify("x", NUMBER_TYPE); } @Test public void testYield1() { inGenerator("var x = yield 3;"); verify("x", registry.getNativeType(UNKNOWN_TYPE)); } @Test public void testYield2() { // test that type inference happens inside the yield expression inGenerator( lines( "var obj;", "yield (obj = {a: 3, b: '4'});", "var a = obj.a;", "var b = obj.b;" )); verify("a", registry.getNativeType(NUMBER_TYPE)); verify("b", registry.getNativeType(STRING_TYPE)); } @Test public void testTemplateLiteral1() { inFunction("var x = `foobar`; X: x;"); assertTypeOfExpression("X").isString(); } @Test public void testSpreadExpression() { inFunction( lines( "let x = 1;", // x is initially a number "let y = [...[x = 'hi', 'there']];", // reassign x a string in the spread "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("string"); } @Test public void testTaggedTemplateLiteral1() { assuming("getNumber", registry.createFunctionType(registry.getNativeType(NUMBER_TYPE))); inFunction("var num = getNumber``; NUM: num;"); assertTypeOfExpression("NUM").isNumber(); } @Test public void testRestParamType() { parseAndRunTypeInference( lines( "(", "/**", // preserve newlines " * @param {...number} nums", " */", "function(str, ...nums) {", " NUMS: nums;", " let n = null;", " N_START: n;", " if (nums.length > 0) {", " n = nums[0];", " N_IF_TRUE: n;", " } else {", " N_IF_FALSE: n;", " }", " N_FINAL: n;", "}", ");")); assertTypeOfExpression("N_START").toStringIsEqualTo("null"); assertTypeOfExpression("N_IF_TRUE").toStringIsEqualTo("number"); assertTypeOfExpression("N_IF_FALSE").toStringIsEqualTo("null"); assertTypeOfExpression("N_FINAL").toStringIsEqualTo("(null|number)"); } @Test public void testObjectDestructuringDeclarationInference() { JSType recordType = registry.createRecordType( ImmutableMap.of( "x", getNativeType(STRING_TYPE), "y", getNativeType(NUMBER_TYPE))); assuming("obj", recordType); inFunction( lines( "let {x, y} = obj; ", // preserve newline "X: x;", "Y: y;")); assertTypeOfExpression("X").toStringIsEqualTo("string"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); assertScopeEnclosing("X").declares("x").withTypeThat().toStringIsEqualTo("string"); } @Test public void testObjectDestructuringDeclarationInferenceWithDefaultValue() { inFunction( lines( "var /** {x: (?string|undefined)} */ obj;", "let {x = 3} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("(null|number|string)"); } @Test public void testObjectDestructuringDeclarationInferenceWithUnnecessaryDefaultValue() { inFunction( lines( "var /** {x: string} */ obj;", "let {x = 3} = obj; ", // we ignore the default value's type "X: x;")); // TODO(b/77597706): should this just be `string`? // the legacy behavior (typechecking transpiled code) produces (number|string), but we should // possibly realize that the default value will never be evaluated. assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); } @Test public void testObjectDestructuringDeclarationInference_unknownRhsAndKnownDefaultValue() { inFunction( lines( "var /** ? */ obj;", "let {x = 3} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDeclarationInference_knownRhsAndUnknownDefaultValue() { inFunction( lines( "var /** {x: (string|undefined)} */ obj;", "let {x = someUnknown} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDeclaration_defaultValueEvaluatedAfterComputedProperty() { // contrived example to verify that we traverse the computed property before the default value. inFunction( lines( "var /** !Object<string, (number|undefined)> */ obj = {};", "var a = 1;", "const {[a = 'string']: b = a} = obj", "A: a", "B: b")); assertTypeOfExpression("A").toStringIsEqualTo("string"); assertTypeOfExpression("B").toStringIsEqualTo("(number|string)"); } @Test public void testObjectDestructuringDeclarationInferenceWithUnknownProperty() { JSType recordType = registry.createRecordType(ImmutableMap.of()); assuming("obj", recordType); inFunction( lines( "let {x} = obj; ", // preserve newline "X: x;")); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringDoesInferenceWithinComputedProp() { inFunction( lines( "let y = 'foobar'; ", // preserve newline "let {[y = 3]: z} = {};", "Y: y", "Z: z")); assertTypeOfExpression("Y").toStringIsEqualTo("number"); assertTypeOfExpression("Z").toStringIsEqualTo("?"); } @Test public void testObjectDestructuringUsesIObjectTypeForComputedProp() { inFunction( lines( "let /** !IObject<string, number> */ myObj = {['foo']: 3}; ", // preserve newline "let {[42]: x} = myObj;", "X: x")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringDeclarationWithNestedPattern() { inFunction( lines( "let /** {a: {b: number}} */ obj = {a: {b: 3}};", // "let {a: {b: x}} = obj;", "X: x")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringAssignmentToQualifiedName() { inFunction( lines( "const ns = {};", // "({x: ns.x} = {x: 3});", "X: ns.x;")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringDeclarationInForOf() { inFunction( lines( "const /** !Iterable<{x: number}> */ data = [{x: 3}];", // "for (let {x} of data) {", " X: x;", "}")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringAssignInForOf() { inFunction( lines( "const /** !Iterable<{x: number}> */ data = [{x: 3}];", // "var x;", "for ({x} of data) {", " X: x;", "}")); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectDestructuringParameterWithDefaults() { parseAndRunTypeInference( "(/** @param {{x: (number|undefined)}} data */ function f({x = 3}) { X: x; });"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testObjectRest_inferredGivenObjectLiteralType() { inFunction("var obj = {a: 1, b: 2, c: 3}; const {a, ...rest} = obj; A: a; REST: rest;"); assertTypeOfExpression("A").toStringIsEqualTo("number"); assertTypeOfExpression("REST").isEqualTo(registry.getNativeType(OBJECT_TYPE)); } @Test public void testArrayDestructuringDeclaration() { inFunction( lines( "const /** !Iterable<number> */ numbers = [1, 2, 3];", "let [x, y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringDeclarationWithDefaultValue() { inFunction( lines( "const /** !Iterable<(number|undefined)> */ numbers = [1, 2, 3];", "let [x = 'x', y = 'y'] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); assertTypeOfExpression("Y").toStringIsEqualTo("(number|string)"); } @Test public void testArrayDestructuringDeclarationWithDefaultValueForNestedPattern() { inFunction( lines( "const /** !Iterable<({x: number}|undefined)> */ xNumberObjs = [];", "let [{x = 'foo'} = {}] = xNumberObjs;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("(number|string)"); } @Test public void testArrayDestructuringDeclarationWithRest() { inFunction( lines( "const /** !Iterable<number> */ numbers = [1, 2, 3];", "let [x, ...y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("Array<number>"); } @Test public void testArrayDestructuringDeclarationWithNestedArrayPattern() { inFunction( lines( "const /** !Iterable<!Iterable<number>> */ numbers = [[1, 2, 3]];", "let [[x], y] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("Iterable<number>"); } @Test public void testArrayDestructuringDeclarationWithNestedObjectPattern() { inFunction( lines( "const /** !Iterable<{x: number}> */ numbers = [{x: 3}, {x: 4}];", "let [{x}, {x: y}] = numbers;", "X: x", "Y: y")); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringDeclarationWithNonIterableRhs() { // TODO(lharker): make sure TypeCheck warns on this inFunction("let [x] = 3; X: x;"); assertTypeOfExpression("X").toStringIsEqualTo("?"); } @Test public void testArrayDestructuringAssignWithGetProp() { inFunction( lines( "const ns = {};", // "const /** !Iterable<number> */ numbers = [1, 2, 3];", "[ns.x] = numbers;", "NSX: ns.x;")); assertTypeOfExpression("NSX").toStringIsEqualTo("number"); } @Test public void testArrayDestructuringAssignWithGetElem() { // we don't update the scope on an assignment to a getelem, so this test just verifies that // a) type inference doesn't crash and b) type info validation passes. inFunction( lines( "const arr = [];", // "const /** !Iterable<number> */ numbers = [1, 2, 3];", "[arr[1]] = numbers;", "ARR1: arr[1];")); assertTypeOfExpression("ARR1").toStringIsEqualTo("?"); } @Test public void testDeclarationDoesntOverrideInferredTypeInDestructuringPattern() { inFunction("var [/** number */ x] = /** @type {?} */ ([null]); X: x"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testDeclarationDoesntOverrideInferredTypeInForOfLoop() { inFunction("for (var /** number */ x of /** @type {?} */ [null]) { X: x; }"); assertTypeOfExpression("X").toStringIsEqualTo("number"); } @Test public void testTypeInferenceOccursInDestructuringCatch() { assuming("x", NUMBER_TYPE); inFunction( lines( "try {", " throw {err: 3}; ", "} catch ({[x = 'err']: /** number */ err}) {", " ERR: err;", " X: x;", "}")); assertTypeOfExpression("ERR").toStringIsEqualTo("number"); // verify we do inference on the assignment to `x` inside the computed property assertTypeOfExpression("X").toStringIsEqualTo("string"); } @Test public void testTypeInferenceOccursInDestructuringForIn() { assuming("x", NUMBER_TYPE); inFunction( lines( "/** @type {number} */", "String.prototype.length;", "", "var obj = {};", "for ({length: obj.length} in {'1': 1, '22': 22}) {", " LENGTH: obj.length;", // set to '1'.length and '22'.length "}")); assertTypeOfExpression("LENGTH").toStringIsEqualTo("number"); } @Test public void testInferringTypeInObjectPattern_fromTemplatizedProperty() { // create type Foo with one property templatized with type T TemplateType templateKey = registry.createTemplateType("T"); FunctionType fooCtor = registry.createConstructorType( "Foo", null, IR.paramList(), null, ImmutableList.of(templateKey), false); ObjectType fooInstanceType = fooCtor.getInstanceType(); fooInstanceType.defineDeclaredProperty("data", templateKey, null); // create a variable obj with type Foo<number> JSType fooOfNumber = templatize(fooInstanceType, ImmutableList.of(getNativeType(NUMBER_TYPE))); assuming("obj", fooOfNumber); inFunction( lines( "const {data} = obj;", // "OBJ: obj;", "DATA: data")); assertTypeOfExpression("OBJ").toStringIsEqualTo("Foo<number>"); assertTypeOfExpression("DATA").toStringIsEqualTo("number"); } @Test public void testTypeInferenceOccursInsideVoidOperator() { inFunction("var x; var y = void (x = 3); X: x; Y: y"); assertTypeOfExpression("X").toStringIsEqualTo("number"); assertTypeOfExpression("Y").toStringIsEqualTo("undefined"); } @Test public void constDeclarationWithReturnJSDoc_ignoresUnknownRhsType() { assuming("foo", UNKNOWN_TYPE); inFunction(lines("/** @return {number} */ const fn = foo;")); JSType fooWithInterfaceType = getType("fn"); assertType(fooWithInterfaceType).isFunctionTypeThat().hasReturnTypeThat().isNumber(); } @Test public void constDeclarationWithCtorJSDoc_ignoresKnownMixinReturnType() { // Create a function always returning a constructor for 'Foo' JSType fooType = FunctionType.builder(registry).forConstructor().withName("Foo").build(); assuming("Foo", fooType); FunctionType mixinType = FunctionType.builder(registry).withReturnType(fooType).build(); assuming("mixin", mixinType); // The @constructor JSDoc should declare a new type, and FooExtended should refer to that // type instead of the constructor for Foo inFunction(lines("/** @constructor @extends {Foo} */ const FooExtended = mixin();")); JSType fooWithInterfaceType = getType("FooExtended"); assertType(fooWithInterfaceType).isNotEqualTo(fooType); assertType(fooWithInterfaceType).toStringIsEqualTo("function(new:FooExtended): ?"); } @Test public void testSideEffectsInEsExportDefaultInferred() { assuming("foo", NUMBER_TYPE); assuming("bar", UNKNOWN_TYPE); inModule("export default (bar = foo, foo = 'not a number');"); assertType(getType("bar")).isNumber(); assertType(getType("foo")).isString(); } private ObjectType getNativeObjectType(JSTypeNative t) { return registry.getNativeObjectType(t); } private JSType getNativeType(JSTypeNative t) { return registry.getNativeType(t); } private JSType templatize(ObjectType objType, ImmutableList<JSType> t) { return registry.createTemplatizedType(objType, t); } /** Adds a goog.asserts.assert[name] function to the scope that asserts the given returnType */ private void includeGoogAssertionFn(String fnName, JSType returnType) { String fullName = "goog.asserts." + fnName; FunctionType fnType = FunctionType.builder(registry) .withReturnType(returnType) .withParamsNode(IR.paramList(IR.name("p"))) .withName(fullName) .build(); assuming(fullName, fnType); } /** Adds a function with {@link ClosurePrimitive#ASSERTS_TRUTHY} and the given name */ private void includePrimitiveTruthyAssertionFunction(String fnName) { TemplateType t = registry.createTemplateType("T"); FunctionType assertType = FunctionType.builder(registry) .withName(fnName) .withClosurePrimitiveId(ClosurePrimitive.ASSERTS_TRUTHY) .withReturnType(t) .withParamsNode(IR.paramList(IR.name("x").setJSType(t))) .withTemplateKeys(t) .build(); assuming(fnName, assertType); } /** * Adds a function with {@link ClosurePrimitive#ASSERTS_MATCHES_RETURN} that asserts the given * returnType */ private void includePrimitiveAssertionFn(String fullName, JSType returnType) { FunctionType fnType = FunctionType.builder(registry) .withReturnType(returnType) .withParamsNode(IR.paramList(IR.name("p"))) .withName(fullName) .withClosurePrimitiveId(ClosurePrimitive.ASSERTS_MATCHES_RETURN) .build(); assuming(fullName, fnType); } /** Adds goog.asserts.assertInstanceof to the scope, to do fine-grained assertion testing */ private void includeAssertInstanceof() { String fullName = "goog.asserts.assertInstanceof"; TemplateType templateType = registry.createTemplateType("T"); // Create the function type `function(new:T)` FunctionType templateTypeCtor = FunctionType.builder(registry).forConstructor().withTypeOfThis(templateType).build(); // Create the function type `function(?, function(new:T)): T` // This matches the JSDoc for goog.asserts.assertInstanceof: // /** // * @param {?} value The value to check // * @param {function(new:T)) type A user-defined ctor // * @return {T} // * @template T // */ FunctionType fnType = FunctionType.builder(registry) .withParamsNode( IR.paramList( IR.name("value").setJSType(getNativeType(UNKNOWN_TYPE)), IR.name("type").setJSType(templateTypeCtor))) .withTemplateKeys(templateType) .withReturnType(templateType) .withName(fullName) .build(); assuming(fullName, fnType); } }
Add tests that were supposed to be added in a previous commit. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=270074666
test/com/google/javascript/jscomp/TypeInferenceTest.java
Add tests that were supposed to be added in a previous commit.
Java
apache-2.0
e3e3ea204f3bbdff6d3461f5926abf23af54769f
0
HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity
package com.hubspot.singularity.data; import com.google.inject.Inject; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApiCache<K, V> { private static final Logger LOG = LoggerFactory.getLogger(ApiCache.class); public final boolean isEnabled; private final AtomicReference<Map<K, V>> zkValues; private final Supplier<Map<K, V>> supplyMap; @Inject public ApiCache( boolean isEnabled, int cacheTtl, Supplier<Map<K, V>> supplyMap, ScheduledExecutorService executor ) { this.isEnabled = isEnabled; this.supplyMap = supplyMap; this.zkValues = new AtomicReference<>(new HashMap<>()); if (this.isEnabled) { executor.scheduleAtFixedRate(this::reloadZkValues, 0, cacheTtl, TimeUnit.SECONDS); } } private void reloadZkValues() { LOG.debug("Reloading values for map from ZooKeeper"); try { Map<K, V> newZkValues = supplyMap.get(); zkValues.set(newZkValues); } catch (Exception e) { LOG.warn("Reloading ApiCache failed: {}", e.getMessage()); } } public V get(K key) { return this.zkValues.get().get(key); } public Map<K, V> getAll() { Map<K, V> allValues = this.zkValues.get(); if (allValues.isEmpty()) { LOG.debug("ApiCache getAll returned empty"); } return allValues; } public Map<K, V> getAll(Collection<K> keys) { Map<K, V> allValues = this.zkValues.get(); Map<K, V> filteredValues = keys .stream() .filter(allValues::containsKey) .collect(Collectors.toMap(Function.identity(), allValues::get)); if (filteredValues.isEmpty()) { LOG.debug("ApiCache getAll returned empty for {}", keys); } return filteredValues; } public boolean isEnabled() { return isEnabled; } }
SingularityService/src/main/java/com/hubspot/singularity/data/ApiCache.java
package com.hubspot.singularity.data; import com.google.inject.Inject; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApiCache<K, V> { private static final Logger LOG = LoggerFactory.getLogger(ApiCache.class); public final boolean isEnabled; private final AtomicReference<Map<K, V>> zkValues; private final Supplier<Map<K, V>> supplyMap; @Inject public ApiCache( boolean isEnabled, int cacheTtl, Supplier<Map<K, V>> supplyMap, ScheduledExecutorService executor ) { this.isEnabled = isEnabled; this.supplyMap = supplyMap; this.zkValues = new AtomicReference<>(new HashMap<>()); if (this.isEnabled) { executor.scheduleAtFixedRate(this::reloadZkValues, 0, cacheTtl, TimeUnit.SECONDS); } } private void reloadZkValues() { LOG.debug("Reloading values for map from ZooKeeper"); try { Map<K, V> newZkValues = supplyMap.get(); zkValues.set(newZkValues); } catch (Exception e) { LOG.warn("Reloading ApiCache failed: {}", e.getMessage()); } } public V get(K key) { return this.zkValues.get().get(key); } public Map<K, V> getAll() { Map<K, V> allValues = this.zkValues.get(); LOG.debug("Get all returned {}", allValues); return allValues; } public Map<K, V> getAll(Collection<K> keys) { Map<K, V> allValues = this.zkValues.get(); Map<K, V> filteredValues = keys .stream() .filter(allValues::containsKey) .collect(Collectors.toMap(Function.identity(), allValues::get)); LOG.debug("Get all from collection returned {}", filteredValues); return filteredValues; } public boolean isEnabled() { return isEnabled; } }
Be more selective with debug info
SingularityService/src/main/java/com/hubspot/singularity/data/ApiCache.java
Be more selective with debug info
Java
apache-2.0
e8ce8d698bea155d0846cce443cdf309c3bc63eb
0
ragerri/ixa-pipe-convert,ragerri/ixa-pipe-convert
/* * Copyright 2014 Rodrigo Agerri 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 eus.ixa.ixa.pipe.convert; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import eus.ixa.ixa.pipe.ml.tok.RuleBasedSegmenter; import ixa.kaflib.Entity; import ixa.kaflib.KAFDocument; import ixa.kaflib.Term; import ixa.kaflib.WF; import opennlp.tools.parser.Parse; import opennlp.tools.postag.POSDictionary; /** * Convert functions. * * @author ragerri * @version 2014-10-28 * */ public class Convert { private Convert() { } public static Pattern detokenizeTargets = Pattern.compile( "<\\s+START\\s+:\\s+target\\s+>", Pattern.UNICODE_CHARACTER_CLASS); public static Pattern detokenizeEnds = Pattern.compile("<\\s+END\\s+>"); /** * Process the ancora constituent XML annotation into Penn Treebank bracketing * style. * * @param inXML * the ancora xml constituent document * @return the ancora trees in penn treebank one line format * @throws IOException * if io exception */ public static void ancora2treebank(Path inXML) throws IOException { String filteredTrees = null; if (Files.isRegularFile(inXML)) { Path outfile = Paths.get(inXML.toString() + ".th"); System.err.println(">> Wrote XML ancora file to Penn Treebank in " + outfile); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); AncoraTreebank ancoraParser = new AncoraTreebank(); saxParser.parse(inXML.toFile(), ancoraParser); String trees = ancoraParser.getTrees(); // remove empty trees created by "missing" and "elliptic" attributes filteredTrees = trees.replaceAll("\\(\\SN\\)", ""); // format correctly closing brackets filteredTrees = filteredTrees.replace(") )", "))"); // remove double spaces filteredTrees = filteredTrees.replaceAll(" ", " "); // remove empty sentences created by <sentence title="yes"> elements filteredTrees = filteredTrees.replaceAll("\\(SENTENCE \\)\n", ""); Files.write(outfile, filteredTrees.getBytes(StandardCharsets.UTF_8)); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } else { System.out.println("Please choose a valid file as input"); } } /** * Calls the ancora2treebank function to generate Penn Treebank trees from * Ancora XML constituent parsing. * * @param dir * the directory containing the documents * @throws IOException * if io problems */ public static void processAncoraConstituentXMLCorpus(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { ancora2treebank(dir); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { processAncoraConstituentXMLCorpus(file); } else { ancora2treebank(file); } } } } } /** * Takes a file containing Penn Treebank oneline annotation and creates * tokenized sentences saving it to a file with the *.tok extension. * * @param treebankFile * the input file * @throws IOException */ public static void treebank2tokens(Path treebankFile) throws IOException { // process one file if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile, StandardCharsets.UTF_8); Path outfile = Files.createFile(Paths.get(treebankFile.toString() + ".tok")); String outFile = getTokensFromTree(inputTrees); Files.write(outfile, outFile.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote tokens to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Reads a list of Parse trees and calls {@code getTokens} to create tokenized * oneline text. * * @param inputTrees * the list of trees in penn treebank format * @return the tokenized document the document tokens */ private static String getTokensFromTree(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); StringBuilder sentBuilder = new StringBuilder(); getTokens(parse, sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * It converts a penn treebank constituent tree into tokens oneline form. * * @param parse * the parse tree * @param sb * the stringbuilder to add the trees */ private static void getTokens(Parse parse, StringBuilder sb) { if (parse.isPosTag()) { if (!parse.getType().equals("-NONE-")) { sb.append(parse.getCoveredText()).append(" "); } } else { Parse children[] = parse.getChildren(); for (int i = 0; i < children.length; i++) { getTokens(children[i], sb); } } } /** * Takes a file containing Penn Treebank oneline annotation and creates * Word_POS sentences for POS tagger training, saving it to a file with the * *.pos extension. * * @param treebankFile * the input file * @throws IOException */ public static void treebank2WordPos(Path treebankFile) throws IOException { // process one file if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile); Path outfile = Paths.get(treebankFile.toString() + ".pos"); String outFile = getPreTerminals(inputTrees); Files.write(outfile, outFile.getBytes()); System.err.println(">> Wrote Apache OpenNLP POS training format to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Reads a list of Parse trees and calls {@code getWordType} to create POS * training data in Word_POS form * * @param inputTrees * @return the document with Word_POS sentences */ private static String getPreTerminals(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); StringBuilder sentBuilder = new StringBuilder(); getWordType(parse, sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * It converts a penn treebank constituent tree into Word_POS form * * @param parse * @param sb */ private static void getWordType(Parse parse, StringBuilder sb) { if (parse.isPosTag()) { if (!parse.getType().equals("-NONE-")) { sb.append(parse.getCoveredText()).append("_").append(parse.getType()) .append(" "); } } else { Parse children[] = parse.getChildren(); for (int i = 0; i < children.length; i++) { getWordType(children[i], sb); } } } /** * It normalizes a oneline Penn treebank style tree removing trace nodes * (-NONE-) and pruning the empty trees created by removing the trace nodes. * * @param treebankFile * @throws IOException */ public static void getCleanPennTrees(Path treebankFile) throws IOException { if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile, StandardCharsets.UTF_8); Path outfile = Files.createFile(Paths.get(treebankFile.toString() + ".treeN")); String outFile = normalizeParse(inputTrees); Files.write(outfile, outFile.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote normalized parse to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * It takes as input a semi-pruned penn treebank tree (e.g., with -NONE- * traces removed) via sed 's/-NONE-\s[\*A-Za-z0-9]*[\*]*[\-]*[A-Za-z0-9]*' * * and prunes the empty trees remaining from the sed operation. The parseParse * function also removes function tags by default. * * @param inputTrees * @return */ // TODO add the sed regexp to this function private static String normalizeParse(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); Parse.pruneParse(parse); StringBuffer sentBuilder = new StringBuffer(); parse.show(sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * Remove named entity related layers in NAF. * * @param dir * the directory containing the documents * @throws IOException * if io problems */ public static void removeEntities(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { removeEntityLayer(dir); } // process one file else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { removeEntities(file); } else { removeEntityLayer(file); } } } } } /** * Remove the specified NAF layers. * * @param inFile * the NAF document * @throws IOException * if io problems */ private static void removeEntityLayer(Path inFile) { KAFDocument kaf = null; try { Path outfile = Files.createFile(Paths.get(inFile.toString() + ".tok.naf")); kaf = KAFDocument.createFromFile(inFile.toFile()); //kaf.removeLayer(Layer.entities); kaf.removeLayer(Layer.constituency); //kaf.removeLayer(Layer.coreferences); kaf.removeLayer(Layer.chunks); //kaf.removeLayer(Layer.deps); Files.write(outfile, kaf.toString().getBytes(StandardCharsets.UTF_8)); System.err .println(">> Wrote KAF document without entities to " + outfile); } catch (IOException e) { e.printStackTrace(); } } /** * Extract entities that contain a link to an external resource in NAF. * * @param dir * the directory containing the NAF documents * @throws IOException * if io problems */ public static void getNERFromNAF(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { printEntities(dir); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { getNERFromNAF(file); } else { printEntities(file); } } } } } /** * Print entities that contain an external resource link in NAF. * * @param inFile * the NAF document * @throws IOException * if io problems */ public static void printEntities(Path inFile) { KAFDocument kaf = null; try { kaf = KAFDocument.createFromFile(inFile.toFile()); } catch (IOException e) { e.printStackTrace(); } List<Entity> entityList = kaf.getEntities(); for (Entity entity : entityList) { System.out.println(entity.getStr() + "\t" + entity.getType()); } } /** * Extract entities that contain a link to an external resource in NAF. * * @param dir * the directory containing the NAF documents * @throws IOException * if io problems */ public static void getNEDFromNAF(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { printEntities(dir); } else { try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { getNEDFromNAF(file); } else { printEntities(file); } } } } } /** * Print entities that contain an external resource link in NAF. * * @param inFile * the NAF document * @throws IOException * if io problems */ public static void printNEDEntities(Path inFile) { KAFDocument kaf = null; try { kaf = KAFDocument.createFromFile(inFile.toFile()); } catch (IOException e) { e.printStackTrace(); } List<Entity> entityList = kaf.getEntities(); for (Entity entity : entityList) { if (entity.getExternalRefs().size() > 0) System.out.println(entity.getExternalRefs().get(0).getReference()); } } /** * Convert a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void createMonosemicDictionary(Path lemmaDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict)) { List<String> inputLines = Files.readAllLines(lemmaDict, StandardCharsets.UTF_8); getMonosemicDict(inputLines); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } private static void getMonosemicDict(List<String> inputLines) { Map<String, String> monosemicMap = new HashMap<String, String>(); ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split("\t"); if (lineArray.length == 3) { if (!lineArray[0].contains("<")) { dictMultiMap.put(lineArray[0], lineArray[2]); monosemicMap.put(lineArray[0], lineArray[1] + "\t" + lineArray[2]); } } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); // add only monosemic words if (tags.size() == 1) { System.out.println(token + "\t" + monosemicMap.get(token)); } } } /** * Convert a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. It saves the resulting file with the name of * the original dictionary changing the extension to .xml. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void convertLemmaToPOSDict(Path lemmaDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict)) { List<String> inputLines = Files.readAllLines(lemmaDict, StandardCharsets.UTF_8); Path outFile = Files.createFile(Paths.get(lemmaDict.toString() + ".xml")); POSDictionary posTagDict = getPOSTaggerDict(inputLines); OutputStream outputStream = Files.newOutputStream(outFile); posTagDict.serialize(outputStream); outputStream.close(); System.err .println(">> Serialized Apache OpenNLP POSDictionary format to " + outFile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Generates {@code POSDictionary} from a list of monosemic words and its * postag. form\tab\lemma\tabpostag * * @param inputLines * the list of words and postag per line * @return the POSDictionary */ private static POSDictionary getPOSTaggerDict(List<String> inputLines) { POSDictionary posTaggerDict = new POSDictionary(); ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split("\t"); if (lineArray.length == 3) { if (!lineArray[0].contains("<")) { dictMultiMap.put(lineArray[0], lineArray[2]); } } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); // add only monosemic words if (tags.size() == 1) { posTaggerDict.put(token, tags.toArray(new String[tags.size()])); } } return posTaggerDict; } /** * Aggregates a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. It saves the resulting file with the name of * the original lemma dictionary changing the extension to .xml. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void addLemmaToPOSDict(Path lemmaDict, Path posTaggerDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict) && Files.isRegularFile(posTaggerDict)) { InputStream posDictInputStream = Files.newInputStream(posTaggerDict); POSDictionary posDict = POSDictionary.create(posDictInputStream); List<String> inputLines = Files.readAllLines(lemmaDict); Path outFile = Paths.get(lemmaDict.toString() + ".xml"); addPOSTaggerDict(inputLines, posDict); OutputStream outputStream = Files.newOutputStream(outFile); posDict.serialize(outputStream); outputStream.close(); System.err .println(">> Serialized Apache OpenNLP POSDictionary format to " + outFile); } else { System.out.println("Please choose a valid files as input."); System.exit(1); } } /** * Aggregates {@code POSDictionary} from a list of words and its postag. * * @param inputLines * the list of words and postag per line * @param tagDict * the POSDictionary to which the lemma dictionary will be added */ private static void addPOSTaggerDict(List<String> inputLines, POSDictionary tagDict) { ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split(" "); if (lineArray.length == 2) { dictMultiMap.put(lineArray[0], lineArray[1]); } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); if (tags.size() == 1) { tagDict.put(token, tags.toArray(new String[tags.size()])); } } } public static void nafToCoNLL2002(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); Path outfile = Files.createFile(Paths.get(dir.toString() + ".conll02")); String outKAF = nafToCoNLLConvert2002(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL document to " + outfile); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { nafToCoNLL2002(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = nafToCoNLLConvert2002(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL02 document to " + outfile); } } } } } /** * Output Conll2002 format. * * @param kaf * the kaf document * @return the annotated named entities in conll02 format */ public static String nafToCoNLLConvert2002(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { Term neTerm = spanTerm.getFirstTarget(); entityToSpanSize.put(neTerm.getId(), spanTerm.size()); entityToType.put(neTerm.getId(), ne.getType()); } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); //System.err.println("--> thisterm: " + thisTerm.getForm() + " " + thisTerm.getId()); if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); //System.err.println("--> neSpanSize: " + neSpanSize); String neClass = entityToType.get(thisTerm.getId()); //String neType = convertToConLLTypes(neClass); if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neClass); sb.append("\n"); } } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.BEGIN.toString()); sb.append(neClass); sb.append("\n"); } i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); } } sb.append("\n");// end of sentence } return sb.toString(); } public static void nafToCoNLL2003(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); Path outfile = Files.createFile(Paths.get(dir.toString() + ".conll03")); String outKAF = nafToCoNLLConvert2003(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL document to " + outfile); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { nafToCoNLL2003(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = nafToCoNLLConvert2003(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL03 document to " + outfile); } } } } } /** * Output Conll2003 format. * * @param kaf * the kaf document * @return the annotated named entities in conll03 format */ public static String nafToCoNLLConvert2003(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { Term neTerm = spanTerm.getFirstTarget(); // create map from term Id to Entity span size entityToSpanSize.put(neTerm.getId(), spanTerm.size()); // create map from term Id to Entity type entityToType.put(neTerm.getId(), ne.getType()); } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); boolean previousIsEntity = false; String previousType = null; for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); // if term is inside an entity span then annotate B-I entities if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); String neClass = entityToType.get(thisTerm.getId()); String neType = Convert.convertToConLLTypes(neClass); // if Entity span is multi token if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0 && previousIsEntity && previousType.equalsIgnoreCase(neType)) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neType); sb.append("\n"); } previousType = neType; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (previousIsEntity && previousType.equalsIgnoreCase(neType)) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neType); sb.append("\n"); } previousIsEntity = true; previousType = neType; i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); previousIsEntity = false; previousType = BIO.OUT.toString(); } } sb.append("\n");// end of sentence } return sb.toString(); } public static void trivagoAspectsToCoNLL02(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); System.err.println(">> Processing " + dir.toString()); Path outfile = Paths.get(dir.toString() + ".conll02"); String outKAF = trivagoAspectsToCoNLLConvert02(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL document to " + outfile); } else { try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { trivagoAspectsToCoNLL02(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = trivagoAspectsToCoNLLConvert02(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL2002 to " + outfile); } } } } } /** * Output Conll2002 format. * * @param kaf * the kaf document * @return the annotated named entities in conll02 format */ public static String trivagoAspectsToCoNLLConvert02(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { List<Term> neTerms = spanTerm.getTargets(); for (Term neTerm: neTerms) { if (!entityToSpanSize.containsKey(neTerm.getId())) { entityToSpanSize.put(neTerm.getId(), spanTerm.size()); entityToType.put(neTerm.getId(), ne.getType()); } else { //TODO this is not ideal, but these overlappings spans here are a mess break; } } } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); String neClass = entityToType.get(thisTerm.getId()); if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neClass); sb.append("\n"); } } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.BEGIN.toString()); sb.append(neClass); sb.append("\n"); } i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); } } sb.append("\n");// end of sentence } return sb.toString(); } /** * Convert Entity class annotation to CoNLL formats. * * @param neType * named entity class * @return the converted string */ public static String convertToConLLTypes(String neType) { String conllType = null; if (neType.startsWith("PER") || neType.startsWith("ORG") || neType.startsWith("LOC") || neType.startsWith("GPE") || neType.length() == 3) { conllType = neType.substring(0, 3); } else { conllType = neType; } return conllType; } /** * Enumeration class for CoNLL 2003 BIO format */ private static enum BIO { BEGIN("B-"), IN("I-"), OUT("O"); String tag; BIO(String tag) { this.tag = tag; } public String toString() { return this.tag; } } public static void brownClusterClean(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir) && !dir.toString().endsWith(".clean")) { brownCleanUpperCase(dir); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { brownClusterClean(file); } else { if (!file.toString().endsWith(".clean")) { brownCleanUpperCase(file); } } } } } } /** * Do not print a sentence if is less than 90% lowercase. * * @param sentences * the list of sentences * @throws IOException */ private static void brownCleanUpperCase(Path inFile) throws IOException { StringBuilder precleantext = new StringBuilder(); BufferedReader breader = Files.newBufferedReader(inFile, StandardCharsets.ISO_8859_1); String line; while ((line = breader.readLine()) != null) { double lowercaseCounter = 0; StringBuilder sb = new StringBuilder(); String[] lineArray = line.split(" "); for (String word : lineArray) { if (lineArray.length > 0) { sb.append(word); } } char[] lineCharArray = sb.toString().toCharArray(); for (char lineArr : lineCharArray) { if (Character.isLowerCase(lineArr)) { lowercaseCounter++; } } double percent = lowercaseCounter / (double) lineCharArray.length; if (percent >= 0.90) { precleantext.append(line).append("\n"); } } Path outfile = Files.createFile(Paths.get(inFile.toRealPath().toString() + ".clean")); Files.write(outfile, precleantext.toString().getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote clean document to " + outfile); breader.close(); } /** * Takes a text file and put the contents in a NAF document. * It creates the WF elements. * @param inputFile * @throws IOException */ public static void textToNAF(final Path inputFile) throws IOException { KAFDocument kaf = new KAFDocument("en", "v1.naf"); int noSents = 0; int noParas = 1; final List<String> sentences = Files.readAllLines(inputFile); for (final String sentence : sentences) { noSents = noSents + 1; final String[] tokens = sentence.split(" "); for (final String token : tokens) { if (token.equals(RuleBasedSegmenter.PARAGRAPH)) { ++noParas; // TODO sentences without end markers; // crap rule while (noParas > noSents) { ++noSents; } } else { // TODO add offset final WF wf = kaf.newWF(0, token, noSents); wf.setPara(noParas); //wf.setSent(noSents); } } } } }
src/main/java/eus/ixa/ixa/pipe/convert/Convert.java
/* * Copyright 2014 Rodrigo Agerri 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 eus.ixa.ixa.pipe.convert; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import eus.ixa.ixa.pipe.ml.tok.RuleBasedSegmenter; import ixa.kaflib.Entity; import ixa.kaflib.KAFDocument; import ixa.kaflib.Term; import ixa.kaflib.WF; import opennlp.tools.parser.Parse; import opennlp.tools.postag.POSDictionary; /** * Convert functions. * * @author ragerri * @version 2014-10-28 * */ public class Convert { private Convert() { } public static Pattern detokenizeTargets = Pattern.compile( "<\\s+START\\s+:\\s+target\\s+>", Pattern.UNICODE_CHARACTER_CLASS); public static Pattern detokenizeEnds = Pattern.compile("<\\s+END\\s+>"); /** * Process the ancora constituent XML annotation into Penn Treebank bracketing * style. * * @param inXML * the ancora xml constituent document * @return the ancora trees in penn treebank one line format * @throws IOException * if io exception */ public static void ancora2treebank(Path inXML) throws IOException { String filteredTrees = null; if (Files.isRegularFile(inXML)) { Path outfile = Paths.get(inXML.toString() + ".th"); System.err.println(">> Wrote XML ancora file to Penn Treebank in " + outfile); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); AncoraTreebank ancoraParser = new AncoraTreebank(); saxParser.parse(inXML.toFile(), ancoraParser); String trees = ancoraParser.getTrees(); // remove empty trees created by "missing" and "elliptic" attributes filteredTrees = trees.replaceAll("\\(\\SN\\)", ""); // format correctly closing brackets filteredTrees = filteredTrees.replace(") )", "))"); // remove double spaces filteredTrees = filteredTrees.replaceAll(" ", " "); // remove empty sentences created by <sentence title="yes"> elements filteredTrees = filteredTrees.replaceAll("\\(SENTENCE \\)\n", ""); Files.write(outfile, filteredTrees.getBytes(StandardCharsets.UTF_8)); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } else { System.out.println("Please choose a valid file as input"); } } /** * Calls the ancora2treebank function to generate Penn Treebank trees from * Ancora XML constituent parsing. * * @param dir * the directory containing the documents * @throws IOException * if io problems */ public static void processAncoraConstituentXMLCorpus(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { ancora2treebank(dir); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { processAncoraConstituentXMLCorpus(file); } else { ancora2treebank(file); } } } } } /** * Takes a file containing Penn Treebank oneline annotation and creates * tokenized sentences saving it to a file with the *.tok extension. * * @param treebankFile * the input file * @throws IOException */ public static void treebank2tokens(Path treebankFile) throws IOException { // process one file if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile, StandardCharsets.UTF_8); Path outfile = Files.createFile(Paths.get(treebankFile.toString() + ".tok")); String outFile = getTokensFromTree(inputTrees); Files.write(outfile, outFile.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote tokens to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Reads a list of Parse trees and calls {@code getTokens} to create tokenized * oneline text. * * @param inputTrees * the list of trees in penn treebank format * @return the tokenized document the document tokens */ private static String getTokensFromTree(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); StringBuilder sentBuilder = new StringBuilder(); getTokens(parse, sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * It converts a penn treebank constituent tree into tokens oneline form. * * @param parse * the parse tree * @param sb * the stringbuilder to add the trees */ private static void getTokens(Parse parse, StringBuilder sb) { if (parse.isPosTag()) { if (!parse.getType().equals("-NONE-")) { sb.append(parse.getCoveredText()).append(" "); } } else { Parse children[] = parse.getChildren(); for (int i = 0; i < children.length; i++) { getTokens(children[i], sb); } } } /** * Takes a file containing Penn Treebank oneline annotation and creates * Word_POS sentences for POS tagger training, saving it to a file with the * *.pos extension. * * @param treebankFile * the input file * @throws IOException */ public static void treebank2WordPos(Path treebankFile) throws IOException { // process one file if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile); Path outfile = Paths.get(treebankFile.toString() + ".pos"); String outFile = getPreTerminals(inputTrees); Files.write(outfile, outFile.getBytes()); System.err.println(">> Wrote Apache OpenNLP POS training format to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Reads a list of Parse trees and calls {@code getWordType} to create POS * training data in Word_POS form * * @param inputTrees * @return the document with Word_POS sentences */ private static String getPreTerminals(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); StringBuilder sentBuilder = new StringBuilder(); getWordType(parse, sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * It converts a penn treebank constituent tree into Word_POS form * * @param parse * @param sb */ private static void getWordType(Parse parse, StringBuilder sb) { if (parse.isPosTag()) { if (!parse.getType().equals("-NONE-")) { sb.append(parse.getCoveredText()).append("_").append(parse.getType()) .append(" "); } } else { Parse children[] = parse.getChildren(); for (int i = 0; i < children.length; i++) { getWordType(children[i], sb); } } } /** * It normalizes a oneline Penn treebank style tree removing trace nodes * (-NONE-) and pruning the empty trees created by removing the trace nodes. * * @param treebankFile * @throws IOException */ public static void getCleanPennTrees(Path treebankFile) throws IOException { if (Files.isRegularFile(treebankFile)) { List<String> inputTrees = Files.readAllLines(treebankFile, StandardCharsets.UTF_8); Path outfile = Files.createFile(Paths.get(treebankFile.toString() + ".treeN")); String outFile = normalizeParse(inputTrees); Files.write(outfile, outFile.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote normalized parse to " + outfile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * It takes as input a semi-pruned penn treebank tree (e.g., with -NONE- * traces removed) via sed 's/-NONE-\s[\*A-Za-z0-9]*[\*]*[\-]*[A-Za-z0-9]*' * * and prunes the empty trees remaining from the sed operation. The parseParse * function also removes function tags by default. * * @param inputTrees * @return */ // TODO add the sed regexp to this function private static String normalizeParse(List<String> inputTrees) { StringBuilder parsedDoc = new StringBuilder(); for (String parseSent : inputTrees) { Parse parse = Parse.parseParse(parseSent); Parse.pruneParse(parse); StringBuffer sentBuilder = new StringBuffer(); parse.show(sentBuilder); parsedDoc.append(sentBuilder.toString()).append("\n"); } return parsedDoc.toString(); } /** * Remove named entity related layers in NAF. * * @param dir * the directory containing the documents * @throws IOException * if io problems */ public static void removeEntities(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { removeEntityLayer(dir); } // process one file else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { removeEntities(file); } else { removeEntityLayer(file); } } } } } /** * Remove the specified NAF layers. * * @param inFile * the NAF document * @throws IOException * if io problems */ private static void removeEntityLayer(Path inFile) { KAFDocument kaf = null; try { Path outfile = Files.createFile(Paths.get(inFile.toString() + ".tok.naf")); kaf = KAFDocument.createFromFile(inFile.toFile()); //kaf.removeLayer(Layer.entities); kaf.removeLayer(Layer.constituency); //kaf.removeLayer(Layer.coreferences); kaf.removeLayer(Layer.chunks); //kaf.removeLayer(Layer.deps); Files.write(outfile, kaf.toString().getBytes(StandardCharsets.UTF_8)); System.err .println(">> Wrote KAF document without entities to " + outfile); } catch (IOException e) { e.printStackTrace(); } } /** * Extract entities that contain a link to an external resource in NAF. * * @param dir * the directory containing the NAF documents * @throws IOException * if io problems */ public static void getNERFromNAF(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { printEntities(dir); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { getNERFromNAF(file); } else { printEntities(file); } } } } } /** * Print entities that contain an external resource link in NAF. * * @param inFile * the NAF document * @throws IOException * if io problems */ public static void printEntities(Path inFile) { KAFDocument kaf = null; try { kaf = KAFDocument.createFromFile(inFile.toFile()); } catch (IOException e) { e.printStackTrace(); } List<Entity> entityList = kaf.getEntities(); for (Entity entity : entityList) { System.out.println(entity.getStr() + "\t" + entity.getType()); } } /** * Extract entities that contain a link to an external resource in NAF. * * @param dir * the directory containing the NAF documents * @throws IOException * if io problems */ public static void getNEDFromNAF(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { printEntities(dir); } else { try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { getNEDFromNAF(file); } else { printEntities(file); } } } } } /** * Print entities that contain an external resource link in NAF. * * @param inFile * the NAF document * @throws IOException * if io problems */ public static void printNEDEntities(Path inFile) { KAFDocument kaf = null; try { kaf = KAFDocument.createFromFile(inFile.toFile()); } catch (IOException e) { e.printStackTrace(); } List<Entity> entityList = kaf.getEntities(); for (Entity entity : entityList) { if (entity.getExternalRefs().size() > 0) System.out.println(entity.getExternalRefs().get(0).getReference()); } } /** * Convert a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void createMonosemicDictionary(Path lemmaDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict)) { List<String> inputLines = Files.readAllLines(lemmaDict, StandardCharsets.UTF_8); getMonosemicDict(inputLines); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } private static void getMonosemicDict(List<String> inputLines) { Map<String, String> monosemicMap = new HashMap<String, String>(); ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split("\t"); if (lineArray.length == 3) { if (!lineArray[0].contains("<")) { dictMultiMap.put(lineArray[0], lineArray[2]); monosemicMap.put(lineArray[0], lineArray[1] + "\t" + lineArray[2]); } } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); // add only monosemic words if (tags.size() == 1) { System.out.println(token + "\t" + monosemicMap.get(token)); } } } /** * Convert a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. It saves the resulting file with the name of * the original dictionary changing the extension to .xml. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void convertLemmaToPOSDict(Path lemmaDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict)) { List<String> inputLines = Files.readAllLines(lemmaDict, StandardCharsets.UTF_8); Path outFile = Files.createFile(Paths.get(lemmaDict.toString() + ".xml")); POSDictionary posTagDict = getPOSTaggerDict(inputLines); OutputStream outputStream = Files.newOutputStream(outFile); posTagDict.serialize(outputStream); outputStream.close(); System.err .println(">> Serialized Apache OpenNLP POSDictionary format to " + outFile); } else { System.out.println("Please choose a valid file as input."); System.exit(1); } } /** * Generates {@code POSDictionary} from a list of monosemic words and its * postag. form\tab\lemma\tabpostag * * @param inputLines * the list of words and postag per line * @return the POSDictionary */ private static POSDictionary getPOSTaggerDict(List<String> inputLines) { POSDictionary posTaggerDict = new POSDictionary(); ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split("\t"); if (lineArray.length == 3) { if (!lineArray[0].contains("<")) { dictMultiMap.put(lineArray[0], lineArray[2]); } } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); // add only monosemic words if (tags.size() == 1) { posTaggerDict.put(token, tags.toArray(new String[tags.size()])); } } return posTaggerDict; } /** * Aggregates a lemma dictionary (word lemma postag) into a * {@code POSTaggerDictionary}. It saves the resulting file with the name of * the original lemma dictionary changing the extension to .xml. * * @param lemmaDict * the input file * @throws IOException * if io problems */ public static void addLemmaToPOSDict(Path lemmaDict, Path posTaggerDict) throws IOException { // process one file if (Files.isRegularFile(lemmaDict) && Files.isRegularFile(posTaggerDict)) { InputStream posDictInputStream = Files.newInputStream(posTaggerDict); POSDictionary posDict = POSDictionary.create(posDictInputStream); List<String> inputLines = Files.readAllLines(lemmaDict); Path outFile = Paths.get(lemmaDict.toString() + ".xml"); addPOSTaggerDict(inputLines, posDict); OutputStream outputStream = Files.newOutputStream(outFile); posDict.serialize(outputStream); outputStream.close(); System.err .println(">> Serialized Apache OpenNLP POSDictionary format to " + outFile); } else { System.out.println("Please choose a valid files as input."); System.exit(1); } } /** * Aggregates {@code POSDictionary} from a list of words and its postag. * * @param inputLines * the list of words and postag per line * @param tagDict * the POSDictionary to which the lemma dictionary will be added */ private static void addPOSTaggerDict(List<String> inputLines, POSDictionary tagDict) { ListMultimap<String, String> dictMultiMap = ArrayListMultimap.create(); for (String line : inputLines) { String[] lineArray = line.split(" "); if (lineArray.length == 2) { dictMultiMap.put(lineArray[0], lineArray[1]); } } for (String token : dictMultiMap.keySet()) { List<String> tags = dictMultiMap.get(token); if (tags.size() == 1) { tagDict.put(token, tags.toArray(new String[tags.size()])); } } } public static void nafToCoNLL2002(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); Path outfile = Files.createFile(Paths.get(dir.toString() + ".conll02")); String outKAF = nafToCoNLLConvert2002(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL document to " + outfile); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { nafToCoNLL2002(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = nafToCoNLLConvert2002(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL02 document to " + outfile); } } } } } /** * Output Conll2002 format. * * @param kaf * the kaf document * @return the annotated named entities in conll02 format */ public static String nafToCoNLLConvert2002(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { Term neTerm = spanTerm.getFirstTarget(); entityToSpanSize.put(neTerm.getId(), spanTerm.size()); entityToType.put(neTerm.getId(), ne.getType()); } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); //System.err.println("--> thisterm: " + thisTerm.getForm() + " " + thisTerm.getId()); if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); //System.err.println("--> neSpanSize: " + neSpanSize); String neClass = entityToType.get(thisTerm.getId()); //String neType = convertToConLLTypes(neClass); if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neClass); sb.append("\n"); } } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.BEGIN.toString()); sb.append(neClass); sb.append("\n"); } i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); } } sb.append("\n");// end of sentence } return sb.toString(); } public static void nafToCoNLL2003(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); Path outfile = Files.createFile(Paths.get(dir.toString() + ".conll03")); String outKAF = nafToCoNLLConvert2003(kaf); Files.write(outfile, outKAF.getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote CoNLL document to " + outfile); } else { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { nafToCoNLL2003(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = nafToCoNLLConvert2003(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL03 document to " + outfile); } } } } } /** * Output Conll2003 format. * * @param kaf * the kaf document * @return the annotated named entities in conll03 format */ public static String nafToCoNLLConvert2003(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { Term neTerm = spanTerm.getFirstTarget(); // create map from term Id to Entity span size entityToSpanSize.put(neTerm.getId(), spanTerm.size()); // create map from term Id to Entity type entityToType.put(neTerm.getId(), ne.getType()); } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); boolean previousIsEntity = false; String previousType = null; for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); // if term is inside an entity span then annotate B-I entities if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); String neClass = entityToType.get(thisTerm.getId()); String neType = Convert.convertToConLLTypes(neClass); // if Entity span is multi token if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0 && previousIsEntity && previousType.equalsIgnoreCase(neType)) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neType); sb.append("\n"); } previousType = neType; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (previousIsEntity && previousType.equalsIgnoreCase(neType)) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neType); sb.append("\n"); } previousIsEntity = true; previousType = neType; i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); previousIsEntity = false; previousType = BIO.OUT.toString(); } } sb.append("\n");// end of sentence } return sb.toString(); } public static void trivagoAspectsToCoNLL02(Path dir) throws IOException { // process one file if (Files.isRegularFile(dir)) { KAFDocument kaf = KAFDocument.createFromFile(dir.toFile()); System.err.println(">> Processing " + dir.toString()); Path outfile = Paths.get(dir.toString() + ".conll02"); String outKAF = trivagoAspectsToCoNLLConvert02(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL document to " + outfile); } else { try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { trivagoAspectsToCoNLL02(file); } else { Path outfile = Files.createFile(Paths.get(file.toString() + ".conll02")); KAFDocument kaf = KAFDocument.createFromFile(file.toFile()); String outKAF = trivagoAspectsToCoNLLConvert02(kaf); Files.write(outfile, outKAF.getBytes()); System.err.println(">> Wrote CoNLL2002 to " + outfile); } } } } } /** * Output Conll2002 format. * * @param kaf * the kaf document * @return the annotated named entities in conll02 format */ public static String trivagoAspectsToCoNLLConvert02(KAFDocument kaf) { List<Entity> namedEntityList = kaf.getEntities(); Map<String, Integer> entityToSpanSize = new HashMap<String, Integer>(); Map<String, String> entityToType = new HashMap<String, String>(); for (Entity ne : namedEntityList) { List<ixa.kaflib.Span<Term>> entitySpanList = ne.getSpans(); for (ixa.kaflib.Span<Term> spanTerm : entitySpanList) { List<Term> neTerms = spanTerm.getTargets(); for (Term neTerm: neTerms) { if (!entityToSpanSize.containsKey(neTerm.getId())) { entityToSpanSize.put(neTerm.getId(), spanTerm.size()); entityToType.put(neTerm.getId(), ne.getType()); } else { //TODO this is not ideal, but these overlappings spans here are a mess break; } } } } List<List<WF>> sentences = kaf.getSentences(); StringBuilder sb = new StringBuilder(); for (List<WF> sentence : sentences) { int sentNumber = sentence.get(0).getSent(); List<Term> sentenceTerms = kaf.getSentenceTerms(sentNumber); for (int i = 0; i < sentenceTerms.size(); i++) { Term thisTerm = sentenceTerms.get(i); if (entityToSpanSize.get(thisTerm.getId()) != null) { int neSpanSize = entityToSpanSize.get(thisTerm.getId()); String neClass = entityToType.get(thisTerm.getId()); if (neSpanSize > 1) { for (int j = 0; j < neSpanSize; j++) { thisTerm = sentenceTerms.get(i + j); sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); if (j == 0) { sb.append(BIO.BEGIN.toString()); } else { sb.append(BIO.IN.toString()); } sb.append(neClass); sb.append("\n"); } } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.BEGIN.toString()); sb.append(neClass); sb.append("\n"); } i += neSpanSize - 1; } else { sb.append(thisTerm.getForm()); sb.append("\t"); sb.append(thisTerm.getLemma()); sb.append("\t"); sb.append(thisTerm.getMorphofeat()); sb.append("\t"); sb.append(BIO.OUT); sb.append("\n"); } } sb.append("\n");// end of sentence } return sb.toString(); } /** * Convert Entity class annotation to CoNLL formats. * * @param neType * named entity class * @return the converted string */ public static String convertToConLLTypes(String neType) { String conllType = null; if (neType.startsWith("PER") || neType.startsWith("ORG") || neType.startsWith("LOC") || neType.startsWith("GPE") || neType.length() == 3) { conllType = neType.substring(0, 3); } else { conllType = neType; } return conllType; } /** * Enumeration class for CoNLL 2003 BIO format */ private static enum BIO { BEGIN("B-"), IN("I-"), OUT("O"); String tag; BIO(String tag) { this.tag = tag; } public String toString() { return this.tag; } } public static void brownClusterClean(Path dir) throws IOException { if (Files.isDirectory(dir)) { // recursively process directories try (DirectoryStream<Path> filesDir = Files.newDirectoryStream(dir)) { for (Path file : filesDir) { if (Files.isDirectory(file)) { brownClusterClean(file); } else { brownCleanUpperCase(file); } } filesDir.close(); } } else { if (Files.isRegularFile(dir)) { brownCleanUpperCase(dir); } } } /** * Do not print a sentence if is less than 90% lowercase. * * @param sentences * the list of sentences * @throws IOException */ private static void brownCleanUpperCase(Path inFile) throws IOException { StringBuilder precleantext = new StringBuilder(); BufferedReader breader = Files.newBufferedReader(inFile, StandardCharsets.ISO_8859_1); String line; while ((line = breader.readLine()) != null) { double lowercaseCounter = 0; StringBuilder sb = new StringBuilder(); String[] lineArray = line.split(" "); for (String word : lineArray) { if (lineArray.length > 0) { sb.append(word); } } char[] lineCharArray = sb.toString().toCharArray(); for (char lineArr : lineCharArray) { if (Character.isLowerCase(lineArr)) { lowercaseCounter++; } } double percent = lowercaseCounter / (double) lineCharArray.length; if (percent >= 0.90) { precleantext.append(line).append("\n"); } } Path outfile = Files.createFile(Paths.get(inFile.toString() + ".clean")); Files.write(outfile, precleantext.toString().getBytes(StandardCharsets.UTF_8)); System.err.println(">> Wrote clean document to " + outfile); breader.close(); } /** * Takes a text file and put the contents in a NAF document. * It creates the WF elements. * @param inputFile * @throws IOException */ public static void textToNAF(final Path inputFile) throws IOException { KAFDocument kaf = new KAFDocument("en", "v1.naf"); int noSents = 0; int noParas = 1; final List<String> sentences = Files.readAllLines(inputFile); for (final String sentence : sentences) { noSents = noSents + 1; final String[] tokens = sentence.split(" "); for (final String token : tokens) { if (token.equals(RuleBasedSegmenter.PARAGRAPH)) { ++noParas; // TODO sentences without end markers; // crap rule while (noParas > noSents) { ++noSents; } } else { // TODO add offset final WF wf = kaf.newWF(0, token, noSents); wf.setPara(noParas); //wf.setSent(noSents); } } } } }
more tests
src/main/java/eus/ixa/ixa/pipe/convert/Convert.java
more tests
Java
apache-2.0
c327c5b20033d7b53bf108eb3f264799c147d65f
0
tomakehurst/wiremock,tomakehurst/wiremock,Mahoney/wiremock,Mahoney/wiremock,dlaha21/wiremock,tomakehurst/wiremock,dlaha21/wiremock,dlaha21/wiremock,dlaha21/wiremock,dlaha21/wiremock,tomakehurst/wiremock,Mahoney/wiremock,Mahoney/wiremock,tomakehurst/wiremock,Mahoney/wiremock
/* * Copyright (C) 2011 Thomas Akehurst * * 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.github.tomakehurst.wiremock.matching; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.tomakehurst.wiremock.common.xml.Xml; import com.google.common.base.Joiner; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xmlunit.XMLUnitException; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.*; import org.xmlunit.placeholder.PlaceholderDifferenceEvaluator; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Strings.isNullOrEmpty; import static org.xmlunit.diff.ComparisonType.*; public class EqualToXmlPattern extends MemoizingStringValuePattern { private static Set<ComparisonType> COUNTED_COMPARISONS = ImmutableSet.of( ELEMENT_TAG_NAME, SCHEMA_LOCATION, NO_NAMESPACE_SCHEMA_LOCATION, NODE_TYPE, NAMESPACE_URI, TEXT_VALUE, PROCESSING_INSTRUCTION_TARGET, PROCESSING_INSTRUCTION_DATA, ELEMENT_NUM_ATTRIBUTES, ATTR_VALUE, CHILD_NODELIST_LENGTH, CHILD_LOOKUP, ATTR_NAME_LOOKUP ); private final Boolean enablePlaceholders; private final String placeholderOpeningDelimiterRegex; private final String placeholderClosingDelimiterRegex; private final DifferenceEvaluator diffEvaluator; private final Set<ComparisonType> exemptedComparisons; private final Document expectedXmlDoc; public EqualToXmlPattern(@JsonProperty("equalToXml") String expectedValue) { this(expectedValue, null, null, null, null); } public EqualToXmlPattern(@JsonProperty("equalToXml") String expectedValue, @JsonProperty("enablePlaceholders") Boolean enablePlaceholders, @JsonProperty("placeholderOpeningDelimiterRegex") String placeholderOpeningDelimiterRegex, @JsonProperty("placeholderClosingDelimiterRegex") String placeholderClosingDelimiterRegex, @JsonProperty("exemptedComparisons") Set<ComparisonType> exemptedComparisons) { super(expectedValue); expectedXmlDoc = Xml.read(expectedValue); // Throw an exception if we can't parse the document this.enablePlaceholders = enablePlaceholders; this.placeholderOpeningDelimiterRegex = placeholderOpeningDelimiterRegex; this.placeholderClosingDelimiterRegex = placeholderClosingDelimiterRegex; this.exemptedComparisons = exemptedComparisons; IgnoreUncountedDifferenceEvaluator baseDifferenceEvaluator = new IgnoreUncountedDifferenceEvaluator(exemptedComparisons); if (enablePlaceholders != null && enablePlaceholders) { diffEvaluator = DifferenceEvaluators.chain(baseDifferenceEvaluator, new PlaceholderDifferenceEvaluator(placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex)); } else { diffEvaluator = baseDifferenceEvaluator; } } public String getEqualToXml() { return expectedValue; } @Override public String getExpected() { return Xml.prettyPrint(getValue()); } public Boolean isEnablePlaceholders() { return enablePlaceholders; } public String getPlaceholderOpeningDelimiterRegex() { return placeholderOpeningDelimiterRegex; } public String getPlaceholderClosingDelimiterRegex() { return placeholderClosingDelimiterRegex; } public Set<ComparisonType> getExemptedComparisons() { return exemptedComparisons; } @Override protected MatchResult calculateMatch(final String value) { return new MatchResult() { @Override public boolean isExactMatch() { if (isNullOrEmpty(value)) { return false; } try { Diff diff = DiffBuilder.compare(Input.from(expectedXmlDoc)) .withTest(value) .withComparisonController(ComparisonControllers.StopWhenDifferent) .ignoreWhitespace() .ignoreComments() .withDifferenceEvaluator(diffEvaluator) .withNodeMatcher(new OrderInvariantNodeMatcher()) .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory()) .build(); return !diff.hasDifferences(); } catch (XMLUnitException e) { notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue + "\n\nActual:\n" + value); return false; } } @Override public double getDistance() { if (isNullOrEmpty(value)) { return 1.0; } final AtomicInteger totalComparisons = new AtomicInteger(0); final AtomicInteger differences = new AtomicInteger(0); Diff diff; try { diff = DiffBuilder.compare(Input.from(expectedValue)) .withTest(value) .ignoreWhitespace() .ignoreComments() .withDifferenceEvaluator(diffEvaluator) .withComparisonListeners(new ComparisonListener() { @Override public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) { if (COUNTED_COMPARISONS.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) { totalComparisons.incrementAndGet(); if (outcome == ComparisonResult.DIFFERENT) { differences.incrementAndGet(); } } } }) .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory()) .build(); } catch (XMLUnitException e) { notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue + "\n\nActual:\n" + value); return 1.0; } notifier().info( Joiner.on("\n").join(diff.getDifferences()) ); return differences.doubleValue() / totalComparisons.doubleValue(); } }; } private static class IgnoreUncountedDifferenceEvaluator implements DifferenceEvaluator { private final Set<ComparisonType> finalCountedComparisons; public IgnoreUncountedDifferenceEvaluator(Set<ComparisonType> exemptedComparisons) { finalCountedComparisons = exemptedComparisons != null ? Sets.difference(COUNTED_COMPARISONS, exemptedComparisons) : COUNTED_COMPARISONS; } @Override public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) { if (finalCountedComparisons.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) { return outcome; } return ComparisonResult.EQUAL; } } public EqualToXmlPattern exemptingComparisons(ComparisonType... comparisons) { return new EqualToXmlPattern( expectedValue, enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, ImmutableSet.copyOf(comparisons)); } private static final class OrderInvariantNodeMatcher extends DefaultNodeMatcher { @Override public Iterable<Map.Entry<Node, Node>> match(Iterable<Node> controlNodes, Iterable<Node> testNodes) { return super.match( sort(controlNodes), sort(testNodes) ); } private static Iterable<Node> sort(Iterable<Node> nodes) { return FluentIterable.from(nodes).toSortedList(COMPARATOR); } private static final Comparator<Node> COMPARATOR = new Comparator<Node>() { @Override public int compare(Node node1, Node node2) { return node1.getLocalName().compareTo(node2.getLocalName()); } }; } }
src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java
/* * Copyright (C) 2011 Thomas Akehurst * * 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.github.tomakehurst.wiremock.matching; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.tomakehurst.wiremock.common.xml.Xml; import com.google.common.base.Joiner; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.w3c.dom.Node; import org.xmlunit.XMLUnitException; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.*; import org.xmlunit.placeholder.PlaceholderDifferenceEvaluator; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Strings.isNullOrEmpty; import static org.xmlunit.diff.ComparisonType.*; public class EqualToXmlPattern extends MemoizingStringValuePattern { private static Set<ComparisonType> COUNTED_COMPARISONS = ImmutableSet.of( ELEMENT_TAG_NAME, SCHEMA_LOCATION, NO_NAMESPACE_SCHEMA_LOCATION, NODE_TYPE, NAMESPACE_URI, TEXT_VALUE, PROCESSING_INSTRUCTION_TARGET, PROCESSING_INSTRUCTION_DATA, ELEMENT_NUM_ATTRIBUTES, ATTR_VALUE, CHILD_NODELIST_LENGTH, CHILD_LOOKUP, ATTR_NAME_LOOKUP ); private final Boolean enablePlaceholders; private final String placeholderOpeningDelimiterRegex; private final String placeholderClosingDelimiterRegex; private final DifferenceEvaluator diffEvaluator; private final Set<ComparisonType> exemptedComparisons; public EqualToXmlPattern(@JsonProperty("equalToXml") String expectedValue) { this(expectedValue, null, null, null, null); } public EqualToXmlPattern(@JsonProperty("equalToXml") String expectedValue, @JsonProperty("enablePlaceholders") Boolean enablePlaceholders, @JsonProperty("placeholderOpeningDelimiterRegex") String placeholderOpeningDelimiterRegex, @JsonProperty("placeholderClosingDelimiterRegex") String placeholderClosingDelimiterRegex, @JsonProperty("exemptedComparisons") Set<ComparisonType> exemptedComparisons) { super(expectedValue); Xml.read(expectedValue); // Throw an exception if we can't parse the document this.enablePlaceholders = enablePlaceholders; this.placeholderOpeningDelimiterRegex = placeholderOpeningDelimiterRegex; this.placeholderClosingDelimiterRegex = placeholderClosingDelimiterRegex; this.exemptedComparisons = exemptedComparisons; IgnoreUncountedDifferenceEvaluator baseDifferenceEvaluator = new IgnoreUncountedDifferenceEvaluator(exemptedComparisons); if (enablePlaceholders != null && enablePlaceholders) { diffEvaluator = DifferenceEvaluators.chain(baseDifferenceEvaluator, new PlaceholderDifferenceEvaluator(placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex)); } else { diffEvaluator = baseDifferenceEvaluator; } } public String getEqualToXml() { return expectedValue; } @Override public String getExpected() { return Xml.prettyPrint(getValue()); } public Boolean isEnablePlaceholders() { return enablePlaceholders; } public String getPlaceholderOpeningDelimiterRegex() { return placeholderOpeningDelimiterRegex; } public String getPlaceholderClosingDelimiterRegex() { return placeholderClosingDelimiterRegex; } public Set<ComparisonType> getExemptedComparisons() { return exemptedComparisons; } @Override protected MatchResult calculateMatch(final String value) { return new MatchResult() { @Override public boolean isExactMatch() { if (isNullOrEmpty(value)) { return false; } try { Diff diff = DiffBuilder.compare(Input.from(expectedValue)) .withTest(value) .withComparisonController(ComparisonControllers.StopWhenDifferent) .ignoreWhitespace() .ignoreComments() .withDifferenceEvaluator(diffEvaluator) .withNodeMatcher(new OrderInvariantNodeMatcher()) .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory()) .build(); return !diff.hasDifferences(); } catch (XMLUnitException e) { notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue + "\n\nActual:\n" + value); return false; } } @Override public double getDistance() { if (isNullOrEmpty(value)) { return 1.0; } final AtomicInteger totalComparisons = new AtomicInteger(0); final AtomicInteger differences = new AtomicInteger(0); Diff diff; try { diff = DiffBuilder.compare(Input.from(expectedValue)) .withTest(value) .ignoreWhitespace() .ignoreComments() .withDifferenceEvaluator(diffEvaluator) .withComparisonListeners(new ComparisonListener() { @Override public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) { if (COUNTED_COMPARISONS.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) { totalComparisons.incrementAndGet(); if (outcome == ComparisonResult.DIFFERENT) { differences.incrementAndGet(); } } } }) .withDocumentBuilderFactory(Xml.newDocumentBuilderFactory()) .build(); } catch (XMLUnitException e) { notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue + "\n\nActual:\n" + value); return 1.0; } notifier().info( Joiner.on("\n").join(diff.getDifferences()) ); return differences.doubleValue() / totalComparisons.doubleValue(); } }; } private static class IgnoreUncountedDifferenceEvaluator implements DifferenceEvaluator { private final Set<ComparisonType> finalCountedComparisons; public IgnoreUncountedDifferenceEvaluator(Set<ComparisonType> exemptedComparisons) { finalCountedComparisons = exemptedComparisons != null ? Sets.difference(COUNTED_COMPARISONS, exemptedComparisons) : COUNTED_COMPARISONS; } @Override public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) { if (finalCountedComparisons.contains(comparison.getType()) && comparison.getControlDetails().getValue() != null) { return outcome; } return ComparisonResult.EQUAL; } } public EqualToXmlPattern exemptingComparisons(ComparisonType... comparisons) { return new EqualToXmlPattern( expectedValue, enablePlaceholders, placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, ImmutableSet.copyOf(comparisons)); } private static final class OrderInvariantNodeMatcher extends DefaultNodeMatcher { @Override public Iterable<Map.Entry<Node, Node>> match(Iterable<Node> controlNodes, Iterable<Node> testNodes) { return super.match( sort(controlNodes), sort(testNodes) ); } private static Iterable<Node> sort(Iterable<Node> nodes) { return FluentIterable.from(nodes).toSortedList(COMPARATOR); } private static final Comparator<Node> COMPARATOR = new Comparator<Node>() { @Override public int compare(Node node1, Node node2) { return node1.getLocalName().compareTo(node2.getLocalName()); } }; } }
Started caching expected XML in EqualToXmlPattern as a Document to reduce repeated parsing
src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java
Started caching expected XML in EqualToXmlPattern as a Document to reduce repeated parsing
Java
apache-2.0
d8cf8d7639278bec909c722ef172830fa1db2f65
0
ivan-fedorov/intellij-community,fitermay/intellij-community,robovm/robovm-studio,amith01994/intellij-community,signed/intellij-community,vladmm/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,izonder/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,signed/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,jagguli/intellij-community,samthor/intellij-community,petteyg/intellij-community,robovm/robovm-studio,supersven/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,fnouama/intellij-community,jagguli/intellij-community,blademainer/intellij-community,diorcety/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,hurricup/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,blademainer/intellij-community,clumsy/intellij-community,kdwink/intellij-community,diorcety/intellij-community,semonte/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,slisson/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,slisson/intellij-community,robovm/robovm-studio,fnouama/intellij-community,slisson/intellij-community,kdwink/intellij-community,hurricup/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,slisson/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,caot/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,amith01994/intellij-community,caot/intellij-community,retomerz/intellij-community,FHannes/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,hurricup/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,kool79/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,jagguli/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,holmes/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,da1z/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,kool79/intellij-community,ryano144/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,caot/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,caot/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,asedunov/intellij-community,supersven/intellij-community,slisson/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,semonte/intellij-community,vvv1559/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,supersven/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,holmes/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,izonder/intellij-community,caot/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ryano144/intellij-community,kool79/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,signed/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,clumsy/intellij-community,samthor/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,izonder/intellij-community,signed/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,kool79/intellij-community,da1z/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,kool79/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,petteyg/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,signed/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,samthor/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,signed/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,signed/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,signed/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vladmm/intellij-community,fnouama/intellij-community,allotria/intellij-community,hurricup/intellij-community,caot/intellij-community,clumsy/intellij-community,dslomov/intellij-community,supersven/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,izonder/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,hurricup/intellij-community,caot/intellij-community,allotria/intellij-community,supersven/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,tmpgit/intellij-community,holmes/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,caot/intellij-community,allotria/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,kool79/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,caot/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,amith01994/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,izonder/intellij-community,asedunov/intellij-community,clumsy/intellij-community,kool79/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ibinti/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,samthor/intellij-community,jagguli/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,hurricup/intellij-community,retomerz/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,asedunov/intellij-community,da1z/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,semonte/intellij-community,ryano144/intellij-community,signed/intellij-community,adedayo/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ibinti/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,diorcety/intellij-community,semonte/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,adedayo/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,kdwink/intellij-community,holmes/intellij-community,signed/intellij-community,caot/intellij-community,slisson/intellij-community,signed/intellij-community,jagguli/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,kdwink/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,fnouama/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,holmes/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,samthor/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,xfournet/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,supersven/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,allotria/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,hurricup/intellij-community,diorcety/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,clumsy/intellij-community,da1z/intellij-community,semonte/intellij-community,vladmm/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,Distrotech/intellij-community
package com.jetbrains.python.codeInsight.imports; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.lang.ImportOptimizer; import com.intellij.psi.PsiFile; import com.jetbrains.python.inspections.PyUnresolvedReferencesInspection; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyRecursiveElementVisitor; import org.jetbrains.annotations.NotNull; import java.util.Collections; /** * @author yole */ public class PyImportOptimizer implements ImportOptimizer { public boolean supports(PsiFile file) { return true; } @NotNull public Runnable processFile(@NotNull PsiFile file) { final LocalInspectionToolSession session = new LocalInspectionToolSession(file, 0, file.getTextLength()); final PyUnresolvedReferencesInspection.Visitor visitor = new PyUnresolvedReferencesInspection.Visitor(null, session, Collections.<String>emptyList()); file.accept(new PyRecursiveElementVisitor() { @Override public void visitPyElement(PyElement node) { super.visitPyElement(node); node.accept(visitor); } }); return new Runnable() { public void run() { visitor.optimizeImports(); } }; } }
python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java
package com.jetbrains.python.codeInsight.imports; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.lang.ImportOptimizer; import com.intellij.psi.PsiFile; import com.jetbrains.python.inspections.PyUnresolvedReferencesInspection; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyRecursiveElementVisitor; import org.jetbrains.annotations.NotNull; import java.util.Collections; /** * @author yole */ public class PyImportOptimizer implements ImportOptimizer { public boolean supports(PsiFile file) { return true; } @NotNull public Runnable processFile(PsiFile file) { final LocalInspectionToolSession session = new LocalInspectionToolSession(file, 0, file.getTextLength()); final PyUnresolvedReferencesInspection.Visitor visitor = new PyUnresolvedReferencesInspection.Visitor(null, session, Collections.<String>emptyList()); file.accept(new PyRecursiveElementVisitor() { @Override public void visitPyElement(PyElement node) { super.visitPyElement(node); node.accept(visitor); } }); return new Runnable() { public void run() { visitor.optimizeImports(); } }; } }
@NotNull
python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java
@NotNull
Java
apache-2.0
58952909ddb6f9ffbad23f295cd21c1f785eac6f
0
gtison/kf,gtison/kf,gtison/kf
src/main/java/com/ukefu/webim/web/handler/admin/webim/WebIMController.java
package com.ukefu.webim.web.handler.admin.webim; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.ukefu.util.Menu; import com.ukefu.webim.service.repository.ConsultInviteRepository; import com.ukefu.webim.service.repository.OrganRepository; import com.ukefu.webim.service.repository.UserRepository; import com.ukefu.webim.web.handler.Handler; import com.ukefu.webim.web.model.CousultInvite; @Controller @RequestMapping("/admin/webim") public class WebIMController extends Handler{ @Autowired private ConsultInviteRepository invite; @Autowired private OrganRepository organRes ; @Autowired private UserRepository userRes ; @Value("${web.upload-path}") private String path; @RequestMapping("/index") @Menu(type = "admin" , subtype = "webim" , admin= true) public ModelAndView index(ModelMap map , HttpServletRequest request) { List<CousultInvite> settingList = invite.findByOrgi(super.getUser(request).getOrgi()) ; if(settingList.size() > 0){ map.addAttribute("inviteData", settingList.get(0)); } map.addAttribute("skillList", organRes.findByOrgiAndSkill(super.getOrgi(request), true)) ; map.addAttribute("agentList", userRes.findByOrgiAndAgent(super.getOrgi(request), true , new PageRequest(0, super.getPs(request)))) ; map.addAttribute("import", request.getServerPort()) ; return request(super.createAdminTempletResponse("/admin/webim/index")); } @RequestMapping("/save") @Menu(type = "admin" , subtype = "webim" , admin= true) public ModelAndView save(HttpServletRequest request , @Valid CousultInvite inviteData , @RequestParam(value = "webimlogo", required = false) MultipartFile webimlogo,@RequestParam(value = "agentheadimg", required = false) MultipartFile agentheadimg) throws IOException { if(!StringUtils.isBlank(inviteData.getSnsaccountid())){ CousultInvite tempData = invite.findBySnsaccountidAndOrgi(inviteData.getSnsaccountid() , super.getOrgi(request)) ; if(tempData!=null){ tempData.setConsult_vsitorbtn_model(inviteData.getConsult_vsitorbtn_model()); tempData.setConsult_vsitorbtn_color(inviteData.getConsult_vsitorbtn_color()); tempData.setConsult_vsitorbtn_position(inviteData.getConsult_vsitorbtn_position()); tempData.setConsult_vsitorbtn_content(inviteData.getConsult_vsitorbtn_content()); tempData.setConsult_vsitorbtn_display(inviteData.getConsult_vsitorbtn_display()); tempData.setConsult_dialog_color(inviteData.getConsult_dialog_color()); inviteData = tempData ; } }else{ inviteData.setSnsaccountid(super.getUser(request).getId()); } inviteData.setOrgi(super.getUser(request).getOrgi()); if(webimlogo!=null && webimlogo.getOriginalFilename().lastIndexOf(".") > 0){ File logoDir = new File(path , "logo"); if(!logoDir.exists()){ logoDir.mkdirs() ; } String fileName = "logo/"+inviteData.getId()+webimlogo.getOriginalFilename().substring(webimlogo.getOriginalFilename().lastIndexOf(".")) ; FileCopyUtils.copy(webimlogo.getBytes(), new File(path , fileName)); inviteData.setConsult_dialog_logo(fileName); } if(agentheadimg!=null && agentheadimg.getOriginalFilename().lastIndexOf(".") > 0){ File headimgDir = new File(path , "headimg"); if(!headimgDir.exists()){ headimgDir.mkdirs() ; } String fileName = "headimg/"+inviteData.getId()+agentheadimg.getOriginalFilename().substring(agentheadimg.getOriginalFilename().lastIndexOf(".")) ; FileCopyUtils.copy(agentheadimg.getBytes(), new File(path , fileName)); inviteData.setConsult_dialog_headimg(fileName); } invite.save(inviteData) ; return request(super.createRequestPageTempletResponse("redirect:/admin/webim/index.html")); } @RequestMapping("/profile") @Menu(type = "admin" , subtype = "profile" , admin= true) public ModelAndView profile(ModelMap map , HttpServletRequest request) { List<CousultInvite> settingList = invite.findByOrgi(super.getUser(request).getOrgi()) ; if(settingList.size() > 0){ map.addAttribute("inviteData", settingList.get(0)); } map.addAttribute("import", request.getServerPort()) ; return request(super.createAdminTempletResponse("/admin/webim/profile")); } @RequestMapping("/profile/save") @Menu(type = "admin" , subtype = "profile" , admin= true) public ModelAndView saveprofile(HttpServletRequest request , @Valid CousultInvite inviteData, @RequestParam(value = "dialogad", required = false) MultipartFile dialogad) throws IOException { CousultInvite tempInviteData ; if(inviteData!=null && !StringUtils.isBlank(inviteData.getId())){ tempInviteData = invite.findOne(inviteData.getId()) ; if(tempInviteData!=null){ tempInviteData.setDialog_name(inviteData.getDialog_name()); tempInviteData.setDialog_address(inviteData.getDialog_address()); tempInviteData.setDialog_phone(inviteData.getDialog_phone()); tempInviteData.setDialog_mail(inviteData.getDialog_mail()); tempInviteData.setDialog_introduction(inviteData.getDialog_introduction()); tempInviteData.setDialog_message(inviteData.getDialog_message()); tempInviteData.setLeavemessage(inviteData.isLeavemessage()) ; tempInviteData.setLvmopentype(inviteData.getLvmopentype()); tempInviteData.setLvmname(inviteData.isLvmname()); tempInviteData.setLvmphone(inviteData.isLvmphone()); tempInviteData.setLvmemail(inviteData.isLvmemail()); tempInviteData.setLvmaddress(inviteData.isLvmaddress()); tempInviteData.setLvmqq(inviteData.isLvmqq()); tempInviteData.setSkill(inviteData.isSkill()); tempInviteData.setConsult_skill_title(inviteData.getConsult_skill_title()); tempInviteData.setConsult_skill_msg(inviteData.getConsult_skill_msg()); tempInviteData.setConsult_skill_bottomtitle(inviteData.getConsult_skill_bottomtitle()); tempInviteData.setConsult_skill_maxagent(inviteData.getConsult_skill_maxagent()); tempInviteData.setConsult_skill_numbers(inviteData.getConsult_skill_numbers()); tempInviteData.setConsult_info(inviteData.isConsult_info()); tempInviteData.setConsult_info_email(inviteData.isConsult_info_email()); tempInviteData.setConsult_info_name(inviteData.isConsult_info_name()); tempInviteData.setConsult_info_phone(inviteData.isConsult_info_phone()); tempInviteData.setConsult_info_resion(inviteData.isConsult_info_resion()); tempInviteData.setConsult_info_message(inviteData.getConsult_info_message()); tempInviteData.setConsult_info_cookies(inviteData.isConsult_info_cookies()); tempInviteData.setAi(inviteData.isAi()); tempInviteData.setAifirst(inviteData.isAifirst()); tempInviteData.setAimsg(inviteData.getAimsg()); tempInviteData.setAisuccesstip(inviteData.getAisuccesstip()); tempInviteData.setAiname(inviteData.getAiname()); if(dialogad!=null && !StringUtils.isBlank(dialogad.getName()) && dialogad.getBytes()!=null && dialogad.getBytes().length >0){ String fileName = "ad/"+inviteData.getId()+dialogad.getOriginalFilename().substring(dialogad.getOriginalFilename().lastIndexOf(".")) ; File file = new File(path , fileName) ; if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } FileCopyUtils.copy(dialogad.getBytes(), file); tempInviteData.setDialog_ad(fileName); } invite.save(tempInviteData) ; } }else{ invite.save(inviteData) ; } return request(super.createRequestPageTempletResponse("redirect:/admin/webim/profile.html")); } @RequestMapping("/invote") @Menu(type = "admin" , subtype = "invote" , admin= true) public ModelAndView invote(ModelMap map , HttpServletRequest request) { List<CousultInvite> settingList = invite.findByOrgi(super.getUser(request).getOrgi()) ; if(settingList.size() > 0){ map.addAttribute("inviteData", settingList.get(0)); } map.addAttribute("import", request.getServerPort()) ; return request(super.createAdminTempletResponse("/admin/webim/invote")); } @RequestMapping("/invote/save") @Menu(type = "admin" , subtype = "profile" , admin= true) public ModelAndView saveinvote(HttpServletRequest request , @Valid CousultInvite inviteData, @RequestParam(value = "invotebg", required = false) MultipartFile invotebg) throws IOException { CousultInvite tempInviteData ; if(inviteData!=null && !StringUtils.isBlank(inviteData.getId())){ tempInviteData = invite.findOne(inviteData.getId()) ; if(tempInviteData!=null){ tempInviteData.setConsult_invite_enable(inviteData.isConsult_invite_enable()); tempInviteData.setConsult_invite_content(inviteData.getConsult_invite_content()); tempInviteData.setConsult_invite_accept(inviteData.getConsult_invite_accept()); tempInviteData.setConsult_invite_later(inviteData.getConsult_invite_later()); tempInviteData.setConsult_invite_delay(inviteData.getConsult_invite_delay()); tempInviteData.setConsult_invite_color(inviteData.getConsult_invite_color()); if(invotebg!=null && !StringUtils.isBlank(invotebg.getName()) && invotebg.getBytes()!=null && invotebg.getBytes().length >0){ String fileName = "invote/"+inviteData.getId()+invotebg.getOriginalFilename().substring(invotebg.getOriginalFilename().lastIndexOf(".")) ; File file = new File(path , fileName) ; if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } FileCopyUtils.copy(invotebg.getBytes(), file); tempInviteData.setConsult_invite_bg(fileName); } invite.save(tempInviteData) ; } }else{ invite.save(inviteData) ; } return request(super.createRequestPageTempletResponse("redirect:/admin/webim/invote.html")); } }
no commit message
src/main/java/com/ukefu/webim/web/handler/admin/webim/WebIMController.java
no commit message
Java
apache-2.0
4abd4802e8560d916f1c0f73f3ba98f87d9a56ac
0
Nanoware/Terasology,MovingBlocks/Terasology,Nanoware/Terasology,MovingBlocks/Terasology,Malanius/Terasology,MovingBlocks/Terasology,Nanoware/Terasology,Malanius/Terasology
/* * Copyright 2017 MovingBlocks * * 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.terasology.rendering.dag.gsoc; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.assets.ResourceUrn; import org.terasology.context.Context; import org.terasology.engine.SimpleUri; import org.terasology.engine.module.ModuleManager; import org.terasology.naming.Name; import org.terasology.rendering.assets.material.Material; import org.terasology.rendering.dag.StateChange; import org.terasology.rendering.opengl.BaseFboManager; import org.terasology.rendering.opengl.FBO; import org.terasology.rendering.opengl.FboConfig; import org.terasology.utilities.Assets; import javax.annotation.Nullable; import java.util.*; /** * This class implements a number of default methods for the convenience of classes * wishing to implement the Node interface. * <p> * It provides the default functionality to identify a node, handle its status (enabled/disabled), * deal with StateChange objects and Frame Buffer objects. */ public abstract class NewAbstractNode implements NewNode { protected static final Logger logger = LoggerFactory.getLogger(NewAbstractNode.class); protected boolean enabled = true; // protected BufferPairConnection bufferPairConnection; private Set<StateChange> desiredStateChanges = Sets.newLinkedHashSet(); private Map<SimpleUri, BaseFboManager> fboUsages = Maps.newHashMap(); private Map<String, DependencyConnection> inputConnections = Maps.newHashMap(); private Map<String, DependencyConnection> outputConnections = Maps.newHashMap(); private final SimpleUri nodeUri; private final Name nodeAka; private Context context; /** * Constructor to be used by inheriting classes. * <p> * The nodeId provided in input will become part of the nodeUri uniquely identifying the node in the RenderGraph, * i.e. "engine:hazeNode". * * @param nodeId a String representing the id of the node, namespace -excluded-: that's added automatically. * @param context a Context object. */ protected NewAbstractNode(String nodeId, String nodeAka, Name providingModule, Context context) { String newNodeAka = nodeAka; ModuleManager moduleManager = context.get(ModuleManager.class); // Name providingModule = moduleManager.getEnvironment().getModuleProviding(this.getClass()); this.context = context; this.nodeUri = new SimpleUri(providingModule.toString(), nodeId); if (nodeAka.endsWith("Node")) { newNodeAka = nodeAka.substring(0, nodeAka.length() - "Node".length()); } this.nodeAka = new Name(newNodeAka); addOutputBufferPairConnection(1); } protected NewAbstractNode(String nodeId, Name providingModule, Context context) { this(nodeId, nodeId, providingModule, context); } public Map<String, DependencyConnection> getInputConnections() { return inputConnections; } public Map<String, DependencyConnection> getOutputConnections() { return outputConnections; } public void setInputConnections(Map<String, DependencyConnection> inputConnections) { this.inputConnections = inputConnections; } public void setOutputConnections(Map<String, DependencyConnection> outputConnections) { this.outputConnections = outputConnections; } public final void postInit(Context context) { tryBufferPairPass(); setDependencies(context); } public void tryBufferPairPass() { BufferPairConnection bufferPairConnection = getInputBufferPairConnection(1); if (bufferPairConnection != null) { if (bufferPairConnection.getData() != null) { addOutputBufferPairConnection(1, bufferPairConnection); } } } /** * Each node must implement this method to be called when the node is fully connected. * This method should call other private node methods to use dependencies. */ public abstract void setDependencies(Context context); /** * * @param input * @return true if successful insertion, false otherwise */ private boolean addInputConnection(DependencyConnection input) { return (this.inputConnections.putIfAbsent(input.getName(), input) == null); } /** * * @param output * @return true if successful insertion, false otherwise */ private boolean addOutputConnection(DependencyConnection output) { return (this.outputConnections.putIfAbsent(output.getName(), output) == null); } /** * TODO String to SimpleUri or make ConnectionUri and change Strings for names to ConnectionUris */ @Nullable protected FBO getInputFboData(int number) { return ((FboConnection) this.inputConnections.get(FboConnection.getConnectionName(number, this.nodeUri))).getData(); } @Nullable protected FBO getOutputFboData(int number) { return ((FboConnection) this.outputConnections.get(FboConnection.getConnectionName(number, this.nodeUri))).getData(); } public boolean addInputConnection(int id, DependencyConnection connection) { if (connection instanceof FboConnection) { return addInputFboConnection(id, (FboConnection) connection); } if (connection instanceof BufferPairConnection) { return addInputBufferPairConnection(id, (BufferPairConnection) connection); } else { throw new RuntimeException("addInputConnection failed on unknown connection type"); } } public boolean addInputRunOrderConnection(RunOrderConnection from, int inputId) { DependencyConnection runOrderconnection = new RunOrderConnection(RunOrderConnection.getConnectionName(inputId, this.nodeUri), DependencyConnection.Type.INPUT, this.getUri()); runOrderconnection.setConnectedConnection(from); return addInputConnection(runOrderconnection); } public boolean addOutputRunOrderConnection(int outputId) { DependencyConnection runOrderConnection = new RunOrderConnection(RunOrderConnection.getConnectionName(outputId, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(runOrderConnection); } public boolean addInputBufferPairConnection(int id, BufferPairConnection from) { DependencyConnection bufferPairConenction = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, from.getData(), this.getUri()); bufferPairConenction.setConnectedConnection(from); return addInputConnection(bufferPairConenction); } public boolean addInputBufferPairConnection(int id, BufferPair bufferPair) { BufferPairConnection bufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, bufferPair, this.getUri()); return addInputConnection(bufferPairConnection); } /** * TODO do something if could not insert * @param id * @param bufferPair * @return true if inserted, false otherwise */ public boolean addOutputBufferPairConnection(int id, BufferPair bufferPair) { boolean success = false; String connectionUri = BufferPairConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { BufferPairConnection localBufferPairConnection = (BufferPairConnection) outputConnections.get(connectionUri); // set data for all connected connections if (!localBufferPairConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating bufferPair data to all connected connections of " + localBufferPairConnection + ": "); localBufferPairConnection.getConnectedConnections().forEach((k, v) -> { logger.info("setting data for: " + v.toString() + " ,"); v.setData(bufferPair); }); logger.info("data propagated.\n"); } if(localBufferPairConnection.getData() != null) { logger.warn("Adding output buffer pair to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + localBufferPairConnection.toString()); } localBufferPairConnection.setData(bufferPair); success = true; } else { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, bufferPair, this.getUri()); success = addOutputConnection(localBufferPairConnection); } return success; } /** * TODO do something if could not insert * @param id * @param from * @return true if inserted, false otherwise */ public boolean addOutputBufferPairConnection(int id, BufferPairConnection from) { boolean success = false; String connectionUri = BufferPairConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { BufferPairConnection localBufferPairConnection = (BufferPairConnection) outputConnections.get(connectionUri); // set data for all connected connections if (!localBufferPairConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating data from " + from.toString() + " to all connected connections of " + localBufferPairConnection + ": "); localBufferPairConnection.getConnectedConnections().forEach((k, v) -> { logger.info("setting data for: " + v.toString() + " ,"); v.setData(from.getData()); }); logger.info("data propagated.\n"); } if(localBufferPairConnection.getData() != null) { logger.warn("Adding output buffer pair connection " + from.toString() + "\n to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + localBufferPairConnection.toString()); } localBufferPairConnection.setData(from.getData()); success = true; } else { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, from.getData(), this.getUri()); success = addOutputConnection(localBufferPairConnection); } return success; } public boolean addOutputBufferPairConnection(int id) { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(localBufferPairConnection); } /** * * @param id * @param from * @return true if inserted, false otherwise */ protected boolean addInputFboConnection(int id, FboConnection from) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, from.getData(), this.getUri()); fboConnection.setConnectedConnection(from); // must remember where I'm connected from return addInputConnection(fboConnection); } /** * This connection must be getting a NEW FBO which is not from another node otherwise it's going to break things! * This is going to be private : TODO WHEN #3680 IS DONE, MUST BE PRIVATE ONLY !!! * @param fboData * @return true if inserted, false otherwise */ public boolean addInputFboConnection(int id, FBO fboData) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, fboData, this.getUri()); return addInputConnection(fboConnection); } /** * TODO do something if could not insert * @param id * @param fboData * @return true if inserted, false otherwise */ protected boolean addOutputFboConnection(int id, FBO fboData) { boolean success = false; String connectionUri = FboConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { FboConnection fboConnection = (FboConnection) outputConnections.get(connectionUri); if(fboConnection.getData() != null) { logger.warn("Adding output fbo data to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + fboConnection.toString()); } fboConnection.setData(fboData); // set data for all connected connections if (!fboConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating fbo data to all connected connections of " + fboConnection + ": "); fboConnection.getConnectedConnections().forEach((k, v) -> { logger.info("setting data for: " + v.toString() + " ,"); v.setData(fboData); }); logger.info("data propagated.\n"); } success = true; } else { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, fboData, this.getUri()); success = addOutputConnection(fboConnection); } return success; } public boolean addOutputFboConnection(int id) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(fboConnection); } /** * Is {@code thisNode} dependent on {@param anotherNode}? * @param anotherNode * @return If this node has at least one {@param anotherNode}'s connection on input - true. Otherwise false. */ public boolean isDependentOn(NewNode anotherNode) { boolean isDependent = false; // for all my input connections for (DependencyConnection connection: inputConnections.values()) { if (!connection.getConnectedConnections().isEmpty()) { HashMap<String, DependencyConnection> connectedConnections = connection.getConnectedConnections(); SimpleUri anotherNodeUri = anotherNode.getUri(); // SimpleUri connectedNodeUri; // for all connection's connected connections get parent node and see if it matches anotherNode for (DependencyConnection connectedConnection: connectedConnections.values()) { if (connectedConnection.getParentNode().equals(anotherNodeUri)) { isDependent = true; } } } } return isDependent; } @Nullable public FboConnection getOutputFboConnection(int outputFboId) { return (FboConnection) getOutputConnection(FboConnection.getConnectionName(outputFboId, this.nodeUri)); } @Nullable public FboConnection getInputFboConnection(int inputFboId) { return (FboConnection) getInputConnection(FboConnection.getConnectionName(inputFboId, this.nodeUri)); } @Nullable public BufferPairConnection getOutputBufferPairConnection(int outputBufferPairId) { return (BufferPairConnection) getOutputConnection(BufferPairConnection.getConnectionName(outputBufferPairId, this.nodeUri)); } @Nullable public BufferPairConnection getInputBufferPairConnection(int inputBufferPairId) { return (BufferPairConnection) getInputConnection(BufferPairConnection.getConnectionName(inputBufferPairId, this.nodeUri)); } @Nullable public RunOrderConnection getOutputRunOrderConnection(int outputRunOrderConnectionId) { return (RunOrderConnection) getOutputConnection(RunOrderConnection.getConnectionName(outputRunOrderConnectionId, this.nodeUri)); } @Nullable public RunOrderConnection getInputRunOrderConnection(int inputRunOrderConnectionId) { return (RunOrderConnection) getInputConnection(RunOrderConnection.getConnectionName(inputRunOrderConnectionId, this.nodeUri)); } protected void removeInputConnection(String name) { // TODO add check - what do if connected inputConnections.remove(name); } protected void removeOutputConnection(String name) { // TODO add check - what do if connected outputConnections.remove(name); } /** * Remove said connection. * @param id * @param type */ public void removeFboConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { // remove output outputConnections.remove(FboConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { // remove input connection inputConnections.remove(FboConnection.getConnectionName(id, getUri())); } } public void removeBufferPairConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { outputConnections.remove(BufferPairConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { inputConnections.remove(BufferPairConnection.getConnectionName(id, getUri())); } } public void removeRunOrderConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { outputConnections.remove(RunOrderConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { inputConnections.remove(RunOrderConnection.getConnectionName(id, getUri())); } } public int getNumberOfInputConnections() { return this.inputConnections.size(); } public int getNumberOfOutputConnections() { return this.outputConnections.size(); } @Nullable public DependencyConnection getInputConnection(String name) { DependencyConnection connection = inputConnections.get(name); if (connection == null) { String errorMessage = String.format("Getting input connection named %s returned null." + " No such input connection in %s", name, this.toString()); logger.error(errorMessage); // throw new NullPointerException(errorMessage); } return connection; } @Nullable public DependencyConnection getOutputConnection(String name) { DependencyConnection connection = outputConnections.get(name); if (connection == null) { String errorMessage = String.format("Getting output connection named %s returned null." + " No such output connection in %s", name, this.toString()); logger.error(errorMessage); // throw new NullPointerException(errorMessage); } return connection; } public List<String> getInputConnectionsList() { List<String> inputConnectionNameList = new ArrayList<>(); this.inputConnections.forEach((name, connection) -> inputConnectionNameList.add(name)); return inputConnectionNameList; } public List<String> getOutputConnectionsList() { List<String> outputConnectionNameList = new ArrayList<>(); this.inputConnections.forEach((name, connection) -> outputConnectionNameList.add(name)); return outputConnectionNameList; } public void disconnectInputFbo(int inputId) { logger.info("Disconnecting" + this.getUri() + " input Fbo number " + inputId); DependencyConnection connectionToDisconnect = this.inputConnections.get(FboConnection.getConnectionName(inputId, this.nodeUri)); if (connectionToDisconnect != null) { // TODO make it reconnectInputFboToOutput if (!connectionToDisconnect.getConnectedConnections().isEmpty()) { connectionToDisconnect.disconnect(); } else { logger.warn("Connection was not connected, it probably originated in this node. (Support FBOs can be created inside nodes)"); } } else { logger.error("No such connection"); } } /** * Used by inheriting classes to declare the need for a specific Frame Buffer Object and obtain it. * * The characteristics of the required FBO are described in the fboConfig provided in input. * Within the context of the given fboManager an fboConfig uniquely identifies the FBO: * if the FBO exists already it is returned, if it doesn't, the FBO is first created and then returned. * * If the fboManager already contains an FBO with the same fboUri but different characteristics from * those described in the fboConfig object, an IllegalArgumentException is thrown. * * @param fboConfig an FboConfig object describing the required FBO. * @param fboManager a BaseFboManager object from which to obtain the FBO. * @return the requested FBO object, either newly created or a pre-existing one. * @throws IllegalArgumentException if the fboUri in fboConfig already in use by FBO with different characteristics. */ protected FBO requiresFbo(FboConfig fboConfig, BaseFboManager fboManager) { SimpleUri fboName = fboConfig.getName(); FBO fbo; if (!fboUsages.containsKey(fboName)) { fboUsages.put(fboName, fboManager); } else { logger.warn("FBO " + fboName + " is already requested."); fbo = fboManager.get(fboName); this.addInputFboConnection(inputConnections.size() + 1, fbo); return fbo; } fbo = fboManager.request(fboConfig); return fbo; } /** * Inheriting classes must call this method to ensure that any FBO requested and acquired by a node * is automatically released upon the node's disposal. This way FBOs that aren't used by any node * are also disposed. */ @Override public void dispose() { for (Map.Entry<SimpleUri, BaseFboManager> entry : fboUsages.entrySet()) { SimpleUri fboName = entry.getKey(); BaseFboManager baseFboManager = entry.getValue(); baseFboManager.release(fboName); } fboUsages.clear(); } /** * Adds a StateChange object to the set of state changes desired by a node. * <p> * This method is normally used within the constructor of a concrete node class, to set the OpenGL state * a node requires. However, it can also be used when runtime conditions change, i.e. a switch from * a normal rendering style to wireframe and viceversa. * <p> * Only StateChange objects that are in the set and are not redundant make it into the TaskList * and actually modify the OpenGL state every frame. * * @param stateChange a StateChange object used by the node to modify the OpenGL state in which it operates. */ protected void addDesiredStateChange(StateChange stateChange) { if (stateChange.isTheDefaultInstance()) { logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})", stateChange.getClass().getSimpleName(), this.toString()); } desiredStateChanges.add(stateChange); } /** * Removes a StateChange object from the set of desired state changes. * * @param stateChange a StateChange object representing a state change no longer required by the node. */ protected void removeDesiredStateChange(StateChange stateChange) { desiredStateChanges.remove(stateChange); } public Set<StateChange> getDesiredStateChanges() { return desiredStateChanges; } /** * Deletes all desired state changes for the node and adds them all again. * Must call after changing dependency connections. */ public void resetDesiredStateChanges() { desiredStateChanges.clear(); setDependencies(context); } public void clearDesiredStateChanges() { desiredStateChanges.clear(); } @Override public String toString() { return String.format("%s (%s)", getUri(), this.getClass().getSimpleName()); } @Override public boolean isEnabled() { return enabled; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public void handleCommand(String command, String... arguments) { } @Override public SimpleUri getUri() { return nodeUri; } @Override public Name getAka() { return nodeAka; } /** * Utility method to conveniently retrieve materials from the Assets system, * hiding the relative complexity of the exception handling. * * @param materialUrn a ResourceUrn instance providing the name of the material to be obtained. * @return a Material instance * @throws RuntimeException if the material couldn't be resolved through the asset system. */ public static Material getMaterial(ResourceUrn materialUrn) { String materialName = materialUrn.toString(); return Assets.getMaterial(materialName).orElseThrow(() -> new RuntimeException("Failed to resolve required asset: '" + materialName + "'")); } }
engine/src/main/java/org/terasology/rendering/dag/gsoc/NewAbstractNode.java
/* * Copyright 2017 MovingBlocks * * 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.terasology.rendering.dag.gsoc; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.assets.ResourceUrn; import org.terasology.context.Context; import org.terasology.engine.SimpleUri; import org.terasology.engine.module.ModuleManager; import org.terasology.naming.Name; import org.terasology.rendering.assets.material.Material; import org.terasology.rendering.dag.StateChange; import org.terasology.rendering.opengl.BaseFboManager; import org.terasology.rendering.opengl.FBO; import org.terasology.rendering.opengl.FboConfig; import org.terasology.utilities.Assets; import javax.annotation.Nullable; import java.util.*; /** * This class implements a number of default methods for the convenience of classes * wishing to implement the Node interface. * <p> * It provides the default functionality to identify a node, handle its status (enabled/disabled), * deal with StateChange objects and Frame Buffer objects. */ public abstract class NewAbstractNode implements NewNode { protected static final Logger logger = LoggerFactory.getLogger(NewAbstractNode.class); protected boolean enabled = true; // protected BufferPairConnection bufferPairConnection; private Set<StateChange> desiredStateChanges = Sets.newLinkedHashSet(); private Map<SimpleUri, BaseFboManager> fboUsages = Maps.newHashMap(); private Map<String, DependencyConnection> inputConnections = Maps.newHashMap(); private Map<String, DependencyConnection> outputConnections = Maps.newHashMap(); private final SimpleUri nodeUri; private final Name nodeAka; private Context context; /** * Constructor to be used by inheriting classes. * <p> * The nodeId provided in input will become part of the nodeUri uniquely identifying the node in the RenderGraph, * i.e. "engine:hazeNode". * * @param nodeId a String representing the id of the node, namespace -excluded-: that's added automatically. * @param context a Context object. */ protected NewAbstractNode(String nodeId, String nodeAka, Name providingModule, Context context) { String newNodeAka = nodeAka; ModuleManager moduleManager = context.get(ModuleManager.class); // Name providingModule = moduleManager.getEnvironment().getModuleProviding(this.getClass()); this.context = context; this.nodeUri = new SimpleUri(providingModule.toString(), nodeId); if (nodeAka.endsWith("Node")) { newNodeAka = nodeAka.substring(0, nodeAka.length() - "Node".length()); } this.nodeAka = new Name(newNodeAka); addOutputBufferPairConnection(1); } protected NewAbstractNode(String nodeId, Name providingModule, Context context) { this(nodeId, nodeId, providingModule, context); } public Map<String, DependencyConnection> getInputConnections() { return inputConnections; } public Map<String, DependencyConnection> getOutputConnections() { return outputConnections; } public void setInputConnections(Map<String, DependencyConnection> inputConnections) { this.inputConnections = inputConnections; } public void setOutputConnections(Map<String, DependencyConnection> outputConnections) { this.outputConnections = outputConnections; } public final void postInit(Context context) { tryBufferPairPass(); setDependencies(context); } public void tryBufferPairPass() { BufferPairConnection bufferPairConnection = getInputBufferPairConnection(1); if (bufferPairConnection != null) { if (bufferPairConnection.getData() != null) { addOutputBufferPairConnection(1, bufferPairConnection); } } } /** * Each node must implement this method to be called when the node is fully connected. * This method should call other private node methods to use dependencies. */ public abstract void setDependencies(Context context); /** * * @param input * @return true if successful insertion, false otherwise */ private boolean addInputConnection(DependencyConnection input) { return (this.inputConnections.putIfAbsent(input.getName(), input) == null); } /** * * @param output * @return true if successful insertion, false otherwise */ private boolean addOutputConnection(DependencyConnection output) { return (this.outputConnections.putIfAbsent(output.getName(), output) == null); } /** * TODO String to SimpleUri or make ConnectionUri and change Strings for names to ConnectionUris */ @Nullable protected FBO getInputFboData(int number) { return ((FboConnection) this.inputConnections.get(FboConnection.getConnectionName(number, this.nodeUri))).getData(); } @Nullable protected FBO getOutputFboData(int number) { return ((FboConnection) this.outputConnections.get(FboConnection.getConnectionName(number, this.nodeUri))).getData(); } public boolean addInputConnection(int id, DependencyConnection connection) { if (connection instanceof FboConnection) { return addInputFboConnection(id, (FboConnection) connection); } if (connection instanceof BufferPairConnection) { return addInputBufferPairConnection(id, (BufferPairConnection) connection); } else { throw new RuntimeException("addInputConnection failed on unknown connection type"); } } public boolean addInputRunOrderConnection(RunOrderConnection from, int inputId) { DependencyConnection runOrderconnection = new RunOrderConnection(RunOrderConnection.getConnectionName(inputId, this.nodeUri), DependencyConnection.Type.INPUT, this.getUri()); runOrderconnection.setConnectedConnection(from); return addInputConnection(runOrderconnection); } public boolean addOutputRunOrderConnection(int outputId) { DependencyConnection runOrderConnection = new RunOrderConnection(RunOrderConnection.getConnectionName(outputId, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(runOrderConnection); } public boolean addInputBufferPairConnection(int id, BufferPairConnection from) { DependencyConnection bufferPairConenction = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, from.getData(), this.getUri()); bufferPairConenction.setConnectedConnection(from); return addInputConnection(bufferPairConenction); } public boolean addInputBufferPairConnection(int id, BufferPair bufferPair) { BufferPairConnection bufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, bufferPair, this.getUri()); return addInputConnection(bufferPairConnection); } /** * TODO do something if could not insert * @param id * @param bufferPair * @return true if inserted, false otherwise */ public boolean addOutputBufferPairConnection(int id, BufferPair bufferPair) { boolean success = false; String connectionUri = BufferPairConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { BufferPairConnection localBufferPairConnection = (BufferPairConnection) outputConnections.get(connectionUri); // set data for all connected connections if (!localBufferPairConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating bufferPair data to all connected connections of " + localBufferPairConnection + ": "); localBufferPairConnection.getConnectedConnections().forEach((k, v) -> { v.setData(bufferPair); }); logger.info("data propagated.\n"); } if(localBufferPairConnection.getData() != null) { logger.warn("Adding output buffer pair to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + localBufferPairConnection.toString()); } localBufferPairConnection.setData(bufferPair); success = true; } else { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, bufferPair, this.getUri()); success = addOutputConnection(localBufferPairConnection); } return success; } /** * TODO do something if could not insert * @param id * @param from * @return true if inserted, false otherwise */ public boolean addOutputBufferPairConnection(int id, BufferPairConnection from) { boolean success = false; String connectionUri = BufferPairConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { BufferPairConnection localBufferPairConnection = (BufferPairConnection) outputConnections.get(connectionUri); // set data for all connected connections if (!localBufferPairConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating data from " + from.toString() + " to all connected connections of " + localBufferPairConnection + ": "); localBufferPairConnection.getConnectedConnections().forEach((k, v) -> { logger.info("setting data for: " + v.toString() + " ,"); v.setData(from.getData()); }); logger.info("data propagated.\n"); } if(localBufferPairConnection.getData() != null) { logger.warn("Adding output buffer pair connection " + from.toString() + "\n to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + localBufferPairConnection.toString()); } localBufferPairConnection.setData(from.getData()); success = true; } else { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, from.getData(), this.getUri()); success = addOutputConnection(localBufferPairConnection); } return success; } public boolean addOutputBufferPairConnection(int id) { DependencyConnection localBufferPairConnection = new BufferPairConnection(BufferPairConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(localBufferPairConnection); } /** * * @param id * @param from * @return true if inserted, false otherwise */ protected boolean addInputFboConnection(int id, FboConnection from) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, from.getData(), this.getUri()); fboConnection.setConnectedConnection(from); // must remember where I'm connected from return addInputConnection(fboConnection); } /** * This connection must be getting a NEW FBO which is not from another node otherwise it's going to break things! * This is going to be private : TODO WHEN #3680 IS DONE, MUST BE PRIVATE ONLY !!! * @param fboData * @return true if inserted, false otherwise */ public boolean addInputFboConnection(int id, FBO fboData) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.INPUT, fboData, this.getUri()); return addInputConnection(fboConnection); } /** * TODO do something if could not insert * @param id * @param fboData * @return true if inserted, false otherwise */ protected boolean addOutputFboConnection(int id, FBO fboData) { boolean success = false; String connectionUri = FboConnection.getConnectionName(id, this.nodeUri); if (outputConnections.containsKey(connectionUri)) { FboConnection fboConnection = (FboConnection) outputConnections.get(connectionUri); if(fboConnection.getData() != null) { logger.warn("Adding output fbo data to slot id " + id + " of " + this.nodeUri + "node overwrites data of existing connection: " + fboConnection.toString()); } fboConnection.setData(fboData); // set data for all connected connections if (!fboConnection.getConnectedConnections().isEmpty()) { logger.info("Propagating fbo data to all connected connections of " + fboConnection + ": "); fboConnection.getConnectedConnections().forEach((k, v) -> { v.setData(fboData); }); logger.info("data propagated.\n"); } success = true; } else { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, fboData, this.getUri()); success = addOutputConnection(fboConnection); } return success; } public boolean addOutputFboConnection(int id) { DependencyConnection fboConnection = new FboConnection(FboConnection.getConnectionName(id, this.nodeUri), DependencyConnection.Type.OUTPUT, this.getUri()); return addOutputConnection(fboConnection); } /** * Is {@code thisNode} dependent on {@param anotherNode}? * @param anotherNode * @return If this node has at least one {@param anotherNode}'s connection on input - true. Otherwise false. */ public boolean isDependentOn(NewNode anotherNode) { boolean isDependent = false; // for all my input connections for (DependencyConnection connection: inputConnections.values()) { if (!connection.getConnectedConnections().isEmpty()) { HashMap<String, DependencyConnection> connectedConnections = connection.getConnectedConnections(); SimpleUri anotherNodeUri = anotherNode.getUri(); // SimpleUri connectedNodeUri; // for all connection's connected connections get parent node and see if it matches anotherNode for (DependencyConnection connectedConnection: connectedConnections.values()) { if (connectedConnection.getParentNode().equals(anotherNodeUri)) { isDependent = true; } } } } return isDependent; } @Nullable public FboConnection getOutputFboConnection(int outputFboId) { return (FboConnection) getOutputConnection(FboConnection.getConnectionName(outputFboId, this.nodeUri)); } @Nullable public FboConnection getInputFboConnection(int inputFboId) { return (FboConnection) getInputConnection(FboConnection.getConnectionName(inputFboId, this.nodeUri)); } @Nullable public BufferPairConnection getOutputBufferPairConnection(int outputBufferPairId) { return (BufferPairConnection) getOutputConnection(BufferPairConnection.getConnectionName(outputBufferPairId, this.nodeUri)); } @Nullable public BufferPairConnection getInputBufferPairConnection(int inputBufferPairId) { return (BufferPairConnection) getInputConnection(BufferPairConnection.getConnectionName(inputBufferPairId, this.nodeUri)); } @Nullable public RunOrderConnection getOutputRunOrderConnection(int outputRunOrderConnectionId) { return (RunOrderConnection) getOutputConnection(RunOrderConnection.getConnectionName(outputRunOrderConnectionId, this.nodeUri)); } @Nullable public RunOrderConnection getInputRunOrderConnection(int inputRunOrderConnectionId) { return (RunOrderConnection) getInputConnection(RunOrderConnection.getConnectionName(inputRunOrderConnectionId, this.nodeUri)); } protected void removeInputConnection(String name) { // TODO add check - what do if connected inputConnections.remove(name); } protected void removeOutputConnection(String name) { // TODO add check - what do if connected outputConnections.remove(name); } /** * Remove said connection. * @param id * @param type */ public void removeFboConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { // remove output outputConnections.remove(FboConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { // remove input connection inputConnections.remove(FboConnection.getConnectionName(id, getUri())); } } public void removeBufferPairConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { outputConnections.remove(BufferPairConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { inputConnections.remove(BufferPairConnection.getConnectionName(id, getUri())); } } public void removeRunOrderConnection(int id, DependencyConnection.Type type) { if (type.equals(DependencyConnection.Type.OUTPUT)) { outputConnections.remove(RunOrderConnection.getConnectionName(id, getUri())); } else if (type.equals(DependencyConnection.Type.INPUT)) { inputConnections.remove(RunOrderConnection.getConnectionName(id, getUri())); } } public int getNumberOfInputConnections() { return this.inputConnections.size(); } public int getNumberOfOutputConnections() { return this.outputConnections.size(); } @Nullable public DependencyConnection getInputConnection(String name) { DependencyConnection connection = inputConnections.get(name); if (connection == null) { String errorMessage = String.format("Getting input connection named %s returned null." + " No such input connection in %s", name, this.toString()); logger.error(errorMessage); // throw new NullPointerException(errorMessage); } return connection; } @Nullable public DependencyConnection getOutputConnection(String name) { DependencyConnection connection = outputConnections.get(name); if (connection == null) { String errorMessage = String.format("Getting output connection named %s returned null." + " No such output connection in %s", name, this.toString()); logger.error(errorMessage); // throw new NullPointerException(errorMessage); } return connection; } public List<String> getInputConnectionsList() { List<String> inputConnectionNameList = new ArrayList<>(); this.inputConnections.forEach((name, connection) -> inputConnectionNameList.add(name)); return inputConnectionNameList; } public List<String> getOutputConnectionsList() { List<String> outputConnectionNameList = new ArrayList<>(); this.inputConnections.forEach((name, connection) -> outputConnectionNameList.add(name)); return outputConnectionNameList; } public void disconnectInputFbo(int inputId) { logger.info("Disconnecting" + this.getUri() + " input Fbo number " + inputId); DependencyConnection connectionToDisconnect = this.inputConnections.get(FboConnection.getConnectionName(inputId, this.nodeUri)); if (connectionToDisconnect != null) { // TODO make it reconnectInputFboToOutput if (!connectionToDisconnect.getConnectedConnections().isEmpty()) { connectionToDisconnect.disconnect(); } else { logger.warn("Connection was not connected, it probably originated in this node. (Support FBOs can be created inside nodes)"); } } else { logger.error("No such connection"); } } /** * Used by inheriting classes to declare the need for a specific Frame Buffer Object and obtain it. * * The characteristics of the required FBO are described in the fboConfig provided in input. * Within the context of the given fboManager an fboConfig uniquely identifies the FBO: * if the FBO exists already it is returned, if it doesn't, the FBO is first created and then returned. * * If the fboManager already contains an FBO with the same fboUri but different characteristics from * those described in the fboConfig object, an IllegalArgumentException is thrown. * * @param fboConfig an FboConfig object describing the required FBO. * @param fboManager a BaseFboManager object from which to obtain the FBO. * @return the requested FBO object, either newly created or a pre-existing one. * @throws IllegalArgumentException if the fboUri in fboConfig already in use by FBO with different characteristics. */ protected FBO requiresFbo(FboConfig fboConfig, BaseFboManager fboManager) { SimpleUri fboName = fboConfig.getName(); FBO fbo; if (!fboUsages.containsKey(fboName)) { fboUsages.put(fboName, fboManager); } else { logger.warn("FBO " + fboName + " is already requested."); fbo = fboManager.get(fboName); this.addInputFboConnection(inputConnections.size() + 1, fbo); return fbo; } fbo = fboManager.request(fboConfig); return fbo; } /** * Inheriting classes must call this method to ensure that any FBO requested and acquired by a node * is automatically released upon the node's disposal. This way FBOs that aren't used by any node * are also disposed. */ @Override public void dispose() { for (Map.Entry<SimpleUri, BaseFboManager> entry : fboUsages.entrySet()) { SimpleUri fboName = entry.getKey(); BaseFboManager baseFboManager = entry.getValue(); baseFboManager.release(fboName); } fboUsages.clear(); } /** * Adds a StateChange object to the set of state changes desired by a node. * <p> * This method is normally used within the constructor of a concrete node class, to set the OpenGL state * a node requires. However, it can also be used when runtime conditions change, i.e. a switch from * a normal rendering style to wireframe and viceversa. * <p> * Only StateChange objects that are in the set and are not redundant make it into the TaskList * and actually modify the OpenGL state every frame. * * @param stateChange a StateChange object used by the node to modify the OpenGL state in which it operates. */ protected void addDesiredStateChange(StateChange stateChange) { if (stateChange.isTheDefaultInstance()) { logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})", stateChange.getClass().getSimpleName(), this.toString()); } desiredStateChanges.add(stateChange); } /** * Removes a StateChange object from the set of desired state changes. * * @param stateChange a StateChange object representing a state change no longer required by the node. */ protected void removeDesiredStateChange(StateChange stateChange) { desiredStateChanges.remove(stateChange); } public Set<StateChange> getDesiredStateChanges() { return desiredStateChanges; } /** * Deletes all desired state changes for the node and adds them all again. * Must call after changing dependency connections. */ public void resetDesiredStateChanges() { desiredStateChanges.clear(); setDependencies(context); } public void clearDesiredStateChanges() { desiredStateChanges.clear(); } @Override public String toString() { return String.format("%s (%s)", getUri(), this.getClass().getSimpleName()); } @Override public boolean isEnabled() { return enabled; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public void handleCommand(String command, String... arguments) { } @Override public SimpleUri getUri() { return nodeUri; } @Override public Name getAka() { return nodeAka; } /** * Utility method to conveniently retrieve materials from the Assets system, * hiding the relative complexity of the exception handling. * * @param materialUrn a ResourceUrn instance providing the name of the material to be obtained. * @return a Material instance * @throws RuntimeException if the material couldn't be resolved through the asset system. */ public static Material getMaterial(ResourceUrn materialUrn) { String materialName = materialUrn.toString(); return Assets.getMaterial(materialName).orElseThrow(() -> new RuntimeException("Failed to resolve required asset: '" + materialName + "'")); } }
NewAbstractNode.java add logger.info for propagating data to output connections back
engine/src/main/java/org/terasology/rendering/dag/gsoc/NewAbstractNode.java
NewAbstractNode.java add logger.info for propagating data to output connections back
Java
apache-2.0
b4eff4ab99c02dbce890cadb2b7e93a91ac274cf
0
DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.function; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.core.position.PositionSource; import com.opengamma.core.position.impl.PositionAccumulator; import com.opengamma.id.UniqueId; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.PublicAPI; /** * Service to interrogate the portfolio structure. * <p> * The {@link PortfolioNode} object only contains the unique identifier of its parent * nodes, requiring additional resolution steps and queries to a {@link PositionSource}. * This is exposed to functions as part of the {@link FunctionExecutionContext} to * allow such queries. At function execution, all child nodes, positions, trades and * referenced securities will be resolved and can be queried directly from the node * object or using utility methods from {@link PositionAccumulator}. */ @PublicAPI public class PortfolioStructure { /** * The portfolio source. */ private final PositionSource _positionSource; /** * Constructs a portfolio structure querying service using the underlying position * source for portfolio information. * * @param positionSource the underlying position source, not null */ public PortfolioStructure(final PositionSource positionSource) { ArgumentChecker.notNull(positionSource, "positionSource"); _positionSource = positionSource; } /** * Returns the position source used by the querying service. * * @return the position source */ public PositionSource getPositionSource() { return _positionSource; } //------------------------------------------------------------------------- /** * Returns the portfolio node that is the immediate parent of the given node. * This is equivalent to resolving the unique identifier reported by a portfolio node as its parent. * * @param node the node to search for, not null * @return the parent node, null if the parent cannot be resolved or the node is a root node */ public PortfolioNode getParentNode(final PortfolioNode node) { ArgumentChecker.notNull(node, "node"); return getParentNodeImpl(node); } private PortfolioNode getParentNodeImpl(final PortfolioNode node) { final UniqueId parent = node.getParentNodeId(); if (parent == null) { return null; } return getPositionSource().getPortfolioNode(parent); } /** * Returns the portfolio node that a position is underneath. * This is equivalent to resolving the unique identifier reported by the position object. * * @param position the position to search for, not null * @return the portfolio node, null if the node cannot be resolved */ public PortfolioNode getParentNode(final Position position) { ArgumentChecker.notNull(position, "position"); final UniqueId parent = position.getParentNodeId(); if (parent == null) { return null; } return getPositionSource().getPortfolioNode(parent); } //------------------------------------------------------------------------- /** * Returns the root node for the portfolio containing the given node. * This is equivalent to traversing up the tree until the root is found. * * @param node the node to search for, not null * @return the root node, null if parent node hierarchy incomplete */ public PortfolioNode getRootPortfolioNode(final PortfolioNode node) { ArgumentChecker.notNull(node, "node"); return getRootPortfolioNodeImpl(node); } /** * Returns the root node for the portfolio containing the given position. * This is equivalent to traversing up the tree from the position's portfolio node until the root is found. * * @param position the position to search for, not null * @return the root node, null if parent node hierarchy incomplete */ public PortfolioNode getRootPortfolioNode(final Position position) { final PortfolioNode node = getParentNode(position); if (node == null) { return null; } return getRootPortfolioNodeImpl(node); } private PortfolioNode getRootPortfolioNodeImpl(PortfolioNode node) { UniqueId parent = node.getParentNodeId(); while (parent != null) { node = getPositionSource().getPortfolioNode(parent); if (node == null) { // Position source is broken return null; } parent = node.getParentNodeId(); } return node; } }
projects/OG-Engine/src/com/opengamma/engine/function/PortfolioStructure.java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.function; import com.opengamma.DataNotFoundException; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.core.position.PositionSource; import com.opengamma.core.position.impl.PositionAccumulator; import com.opengamma.id.UniqueId; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.PublicAPI; /** * Service to interrogate the portfolio structure. * <p> * The {@link PortfolioNode} object only contains the unique identifier of its parent * nodes, requiring additional resolution steps and queries to a {@link PositionSource}. * This is exposed to functions as part of the {@link FunctionExecutionContext} to * allow such queries. At function execution, all child nodes, positions, trades and * referenced securities will be resolved and can be queried directly from the node * object or using utility methods from {@link PositionAccumulator}. */ @PublicAPI public class PortfolioStructure { /** * The portfolio source. */ private final PositionSource _positionSource; /** * Constructs a portfolio structure querying service using the underlying position * source for portfolio information. * * @param positionSource the underlying position source, not null */ public PortfolioStructure(final PositionSource positionSource) { ArgumentChecker.notNull(positionSource, "positionSource"); _positionSource = positionSource; } /** * Returns the position source used by the querying service. * * @return the position source */ public PositionSource getPositionSource() { return _positionSource; } //------------------------------------------------------------------------- /** * Returns the portfolio node that is the immediate parent of the given node. * This is equivalent to resolving the unique identifier reported by a portfolio node as its parent. * * @param node the node to search for, not null * @return the parent node, null if the parent cannot be resolved or the node is a root node */ public PortfolioNode getParentNode(final PortfolioNode node) { ArgumentChecker.notNull(node, "node"); return getParentNodeImpl(node); } private PortfolioNode getParentNodeImpl(final PortfolioNode node) { final UniqueId parent = node.getParentNodeId(); if (parent == null) { return null; } try { return getPositionSource().getPortfolioNode(parent); } catch (DataNotFoundException ex) { return null; } } /** * Returns the portfolio node that a position is underneath. * This is equivalent to resolving the unique identifier reported by the position object. * * @param position the position to search for, not null * @return the portfolio node, null if the node cannot be resolved */ public PortfolioNode getParentNode(final Position position) { ArgumentChecker.notNull(position, "position"); final UniqueId parent = position.getParentNodeId(); if (parent == null) { return null; } try { return getPositionSource().getPortfolioNode(parent); } catch (DataNotFoundException ex) { return null; } } //------------------------------------------------------------------------- /** * Returns the root node for the portfolio containing the given node. * This is equivalent to traversing up the tree until the root is found. * * @param node the node to search for, not null * @return the root node, null if parent node hierarchy incomplete */ public PortfolioNode getRootPortfolioNode(final PortfolioNode node) { ArgumentChecker.notNull(node, "node"); return getRootPortfolioNodeImpl(node); } /** * Returns the root node for the portfolio containing the given position. * This is equivalent to traversing up the tree from the position's portfolio node until the root is found. * * @param position the position to search for, not null * @return the root node, null if parent node hierarchy incomplete */ public PortfolioNode getRootPortfolioNode(final Position position) { final PortfolioNode node = getParentNode(position); if (node == null) { return null; } return getRootPortfolioNodeImpl(node); } private PortfolioNode getRootPortfolioNodeImpl(PortfolioNode node) { UniqueId parent = node.getParentNodeId(); while (parent != null) { node = getPositionSource().getPortfolioNode(parent); if (node == null) { // Position source is broken return null; } parent = node.getParentNodeId(); } return node; } }
[PLAT-1925] Change PositionSource to throw DataNotFoundException Adjust class to match test
projects/OG-Engine/src/com/opengamma/engine/function/PortfolioStructure.java
[PLAT-1925] Change PositionSource to throw DataNotFoundException
Java
apache-2.0
27c7d9ddfcbc00512dbdcaf4d82914f7d1cc16ca
0
HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar
package com.hubspot.blazar.util; import com.google.common.base.Optional; import com.hubspot.blazar.base.CommitInfo; import com.hubspot.blazar.base.DiscoveryResult; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.base.Module; import com.hubspot.blazar.base.RepositoryBuild; import com.hubspot.blazar.base.RepositoryBuild.State; import com.hubspot.blazar.data.service.BranchService; import com.hubspot.blazar.data.service.DependenciesService; import com.hubspot.blazar.data.service.ModuleDiscoveryService; import com.hubspot.blazar.data.service.ModuleService; import com.hubspot.blazar.data.service.RepositoryBuildService; import com.hubspot.blazar.discovery.ModuleDiscovery; import com.hubspot.blazar.exception.NonRetryableBuildException; import com.hubspot.blazar.github.GitHubProtos.Commit; import org.kohsuke.github.GHRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Set; @Singleton public class RepositoryBuildLauncher { private static final Logger LOG = LoggerFactory.getLogger(RepositoryBuildLauncher.class); private final RepositoryBuildService repositoryBuildService; private final BranchService branchService; private final ModuleService moduleService; private final DependenciesService dependenciesService; private final ModuleDiscoveryService moduleDiscoveryService; private final ModuleDiscovery moduleDiscovery; private final GitHubHelper gitHubHelper; @Inject public RepositoryBuildLauncher(RepositoryBuildService repositoryBuildService, BranchService branchService, ModuleService moduleService, DependenciesService dependenciesService, ModuleDiscoveryService moduleDiscoveryService, ModuleDiscovery moduleDiscovery, GitHubHelper gitHubHelper) { this.repositoryBuildService = repositoryBuildService; this.branchService = branchService; this.moduleService = moduleService; this.dependenciesService = dependenciesService; this.moduleDiscoveryService = moduleDiscoveryService; this.moduleDiscovery = moduleDiscovery; this.gitHubHelper = gitHubHelper; } public void launch(RepositoryBuild queued, Optional<RepositoryBuild> previous) throws Exception { GitInfo gitInfo = branchService.get(queued.getBranchId()).get();; CommitInfo commitInfo = commitInfo(gitInfo, commit(previous)); Set<Module> modules = updateModules(gitInfo, commitInfo); RepositoryBuild launching = queued.withStartTimestamp(System.currentTimeMillis()) .withState(State.LAUNCHING) .withCommitInfo(commitInfo) .withDependencyGraph(dependenciesService.buildDependencyGraph(gitInfo, modules)); LOG.info("Updating status of build {} to {}", launching.getId().get(), launching.getState()); repositoryBuildService.begin(launching); } Set<Module> updateModules(GitInfo gitInfo, CommitInfo commitInfo) throws IOException { if (commitInfo.isTruncated() || moduleDiscovery.shouldRediscover(gitInfo, commitInfo)) { DiscoveryResult result = moduleDiscovery.discover(gitInfo); return moduleDiscoveryService.handleDiscoveryResult(gitInfo, result); } else { return moduleService.getByBranch(gitInfo.getId().get()); } } private CommitInfo commitInfo(GitInfo gitInfo, Optional<Commit> previousCommit) throws IOException, NonRetryableBuildException { LOG.info("Trying to fetch current sha for branch {}/{}", gitInfo.getRepository(), gitInfo.getBranch()); final GHRepository repository; try { repository = gitHubHelper.repositoryFor(gitInfo); } catch (FileNotFoundException e) { throw new NonRetryableBuildException("Couldn't find repository " + gitInfo.getFullRepositoryName(), e); } Optional<String> sha = gitHubHelper.shaFor(repository, gitInfo); if (!sha.isPresent()) { String message = String.format("Couldn't find branch %s for repository %s", gitInfo.getBranch(), gitInfo.getFullRepositoryName()); throw new NonRetryableBuildException(message); } else { LOG.info("Found sha {} for branch {}/{}", sha.get(), gitInfo.getRepository(), gitInfo.getBranch()); Commit currentCommit = gitHubHelper.toCommit(repository.getCommit(sha.get())); return gitHubHelper.commitInfoFor(repository, currentCommit, previousCommit); } } private static Optional<Commit> commit(Optional<RepositoryBuild> build) { if (build.isPresent() && build.get().getCommitInfo() != null && build.get().getCommitInfo().isPresent()) { return Optional.of(build.get().getCommitInfo().get().getCurrent()); } else { return Optional.absent(); } } }
BlazarService/src/main/java/com/hubspot/blazar/util/RepositoryBuildLauncher.java
package com.hubspot.blazar.util; import com.google.common.base.Optional; import com.hubspot.blazar.base.CommitInfo; import com.hubspot.blazar.base.DiscoveryResult; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.base.Module; import com.hubspot.blazar.base.RepositoryBuild; import com.hubspot.blazar.base.RepositoryBuild.State; import com.hubspot.blazar.data.service.BranchService; import com.hubspot.blazar.data.service.DependenciesService; import com.hubspot.blazar.data.service.ModuleDiscoveryService; import com.hubspot.blazar.data.service.ModuleService; import com.hubspot.blazar.data.service.RepositoryBuildService; import com.hubspot.blazar.discovery.ModuleDiscovery; import com.hubspot.blazar.exception.NonRetryableBuildException; import com.hubspot.blazar.github.GitHubProtos.Commit; import org.kohsuke.github.GHRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Set; @Singleton public class RepositoryBuildLauncher { private static final Logger LOG = LoggerFactory.getLogger(RepositoryBuildLauncher.class); private final RepositoryBuildService repositoryBuildService; private final BranchService branchService; private final ModuleService moduleService; private final DependenciesService dependenciesService; private final ModuleDiscoveryService moduleDiscoveryService; private final ModuleDiscovery moduleDiscovery; private final GitHubHelper gitHubHelper; @Inject public RepositoryBuildLauncher(RepositoryBuildService repositoryBuildService, BranchService branchService, ModuleService moduleService, DependenciesService dependenciesService, ModuleDiscoveryService moduleDiscoveryService, ModuleDiscovery moduleDiscovery, GitHubHelper gitHubHelper) { this.repositoryBuildService = repositoryBuildService; this.branchService = branchService; this.moduleService = moduleService; this.dependenciesService = dependenciesService; this.moduleDiscoveryService = moduleDiscoveryService; this.moduleDiscovery = moduleDiscovery; this.gitHubHelper = gitHubHelper; } public void launch(RepositoryBuild queued, Optional<RepositoryBuild> previous) throws Exception { GitInfo gitInfo = branchService.get(queued.getBranchId()).get();; CommitInfo commitInfo = commitInfo(gitInfo, commit(previous)); Set<Module> modules = updateModules(gitInfo, commitInfo); RepositoryBuild launching = queued.withStartTimestamp(System.currentTimeMillis()) .withState(State.LAUNCHING) .withCommitInfo(commitInfo) .withDependencyGraph(dependenciesService.buildDependencyGraph(gitInfo, modules)); LOG.info("Updating status of build {} to {}", launching.getId().get(), launching.getState()); repositoryBuildService.begin(launching); } Set<Module> updateModules(GitInfo gitInfo, CommitInfo commitInfo) throws IOException { if (commitInfo.isTruncated() || moduleDiscovery.shouldRediscover(gitInfo, commitInfo)) { DiscoveryResult result = moduleDiscovery.discover(gitInfo); return moduleDiscoveryService.handleDiscoveryResult(gitInfo, result); } else { return moduleService.getByBranch(gitInfo.getId().get()); } } private CommitInfo commitInfo(GitInfo gitInfo, Optional<Commit> previousCommit) throws IOException, NonRetryableBuildException { LOG.info("Trying to fetch current sha for branch {}/{}", gitInfo.getRepository(), gitInfo.getBranch()); final GHRepository repository; try { repository = gitHubHelper.repositoryFor(gitInfo); } catch (FileNotFoundException e) { throw new NonRetryableBuildException("Couldn't find repository " + gitInfo.getFullRepositoryName(), e); } Optional<String> sha = gitHubHelper.shaFor(repository, gitInfo); if (!sha.isPresent()) { String message = String.format("Couldn't find branch %s for repository %s", gitInfo.getBranch(), gitInfo.getFullRepositoryName()); throw new NonRetryableBuildException(message); } else { LOG.info("Found sha {} for branch {}/{}", sha.get(), gitInfo.getRepository(), gitInfo.getBranch()); Commit currentCommit = gitHubHelper.toCommit(repository.getCommit(sha.get())); return gitHubHelper.commitInfoFor(repository, currentCommit, previousCommit); } } private static Optional<Commit> commit(Optional<RepositoryBuild> build) { if (build.isPresent() && build.get().getCommitInfo() != null) { return Optional.of(build.get().getCommitInfo().get().getCurrent()); } else { return Optional.absent(); } } }
Check for null as well
BlazarService/src/main/java/com/hubspot/blazar/util/RepositoryBuildLauncher.java
Check for null as well
Java
apache-2.0
38e3cf508e738c7696731cacc32e1cb957537d21
0
clumsy/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,samthor/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,signed/intellij-community,holmes/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,signed/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,FHannes/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,kool79/intellij-community,blademainer/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,samthor/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,adedayo/intellij-community,semonte/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,semonte/intellij-community,FHannes/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,suncycheng/intellij-community,slisson/intellij-community,caot/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,diorcety/intellij-community,supersven/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vladmm/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,kdwink/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,samthor/intellij-community,semonte/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,da1z/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ryano144/intellij-community,caot/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,allotria/intellij-community,vvv1559/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,amith01994/intellij-community,da1z/intellij-community,kdwink/intellij-community,fitermay/intellij-community,izonder/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,allotria/intellij-community,tmpgit/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,blademainer/intellij-community,holmes/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,fitermay/intellij-community,xfournet/intellij-community,slisson/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,orekyuu/intellij-community,slisson/intellij-community,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,da1z/intellij-community,caot/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,consulo/consulo,suncycheng/intellij-community,asedunov/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,caot/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,fitermay/intellij-community,signed/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,consulo/consulo,youdonghai/intellij-community,hurricup/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,adedayo/intellij-community,vladmm/intellij-community,consulo/consulo,ol-loginov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,supersven/intellij-community,xfournet/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,vladmm/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,caot/intellij-community,salguarnieri/intellij-community,caot/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,kool79/intellij-community,izonder/intellij-community,orekyuu/intellij-community,holmes/intellij-community,slisson/intellij-community,allotria/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,kdwink/intellij-community,fnouama/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,da1z/intellij-community,tmpgit/intellij-community,caot/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,supersven/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,jagguli/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fitermay/intellij-community,allotria/intellij-community,jagguli/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ibinti/intellij-community,consulo/consulo,adedayo/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,supersven/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,supersven/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,signed/intellij-community,adedayo/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,izonder/intellij-community,semonte/intellij-community,kool79/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,apixandru/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,samthor/intellij-community,hurricup/intellij-community,vladmm/intellij-community,slisson/intellij-community,holmes/intellij-community,ernestp/consulo,slisson/intellij-community,dslomov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,caot/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,apixandru/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,kool79/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,diorcety/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ernestp/consulo,robovm/robovm-studio,amith01994/intellij-community,retomerz/intellij-community,apixandru/intellij-community,apixandru/intellij-community,hurricup/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ernestp/consulo,allotria/intellij-community,retomerz/intellij-community,clumsy/intellij-community,slisson/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,nicolargo/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,consulo/consulo,samthor/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,apixandru/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,hurricup/intellij-community,da1z/intellij-community,semonte/intellij-community,dslomov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,izonder/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,fitermay/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,diorcety/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,semonte/intellij-community,caot/intellij-community,da1z/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,supersven/intellij-community,ernestp/consulo,wreckJ/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ernestp/consulo,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,allotria/intellij-community,asedunov/intellij-community,xfournet/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,signed/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,samthor/intellij-community,supersven/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,kool79/intellij-community,signed/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.util.ui.table; import com.intellij.ui.table.JBTable; import com.intellij.util.ui.AbstractTableCellEditor; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.KeyEvent; /** * @author Konstantin Bulenkov */ public abstract class JBListTable extends JPanel { protected final JTable myInternalTable; private final JBTable mainTable; public JBListTable(@NotNull final JTable t) { super(new BorderLayout()); myInternalTable = t; final JBListTableModel model = new JBListTableModel(t) { @Override public JBTableRow getRow(int index) { return getRowAt(index); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return isRowEditable(rowIndex); } }; mainTable = new JBTable(model) { @Override protected void processKeyEvent(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER && e.getModifiers() == 0) { if (!isEditing() && e.getID() == KeyEvent.KEY_PRESSED) { editCellAt(getSelectedRow(), getSelectedColumn()); } e.consume(); } //todo[kb] JBTabsImpl breaks focus traversal policy. Need a workaround here //else if (e.getKeyCode() == KeyEvent.VK_TAB) { // final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); // if (e.isShiftDown()) { // keyboardFocusManager.focusPreviousComponent(this); // } else { // keyboardFocusManager.focusNextComponent(this); // } //} else { super.processKeyEvent(e); } } @Override public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus, int row, int col) { return getRowRenderer(t, row, selected, hasFocus); } }; } @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { //be careful. hardcore!!! if (isEditing() && e.getKeyCode() == KeyEvent.VK_TAB) { if (pressed) { final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); if (e.isShiftDown()) { mgr.focusPreviousComponent(); } else { mgr.focusNextComponent(); } } return true; } return super.processKeyBinding(ks, e, condition, pressed); } @Override public TableCellEditor getCellEditor(final int row, int column) { final JBTableRowEditor editor = getRowEditor(row); if (editor != null) { editor.prepareEditor(t, row); editor.setFocusCycleRoot(true); editor.setFocusTraversalPolicy(new JBListTableFocusTraversalPolicy(editor)); return new AbstractTableCellEditor() { JTable curTable = null; @Override public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected, final int row, int column) { curTable = table; final JPanel p = new JPanel(new BorderLayout()) { @Override public void addNotify() { super.addNotify(); final int height = (int)getPreferredSize().getHeight(); if (height > table.getRowHeight(row)) { new RowResizeAnimator(table, row, height).start(); } } public void removeNotify() { super.removeNotify(); new RowResizeAnimator(table, row, table.getRowHeight()).start(); } }; p.add(editor, BorderLayout.CENTER); return p; } @Override public Object getCellEditorValue() { return editor.getValue(); } @Override public boolean stopCellEditing() { return super.stopCellEditing(); } @Override public void cancelCellEditing() { super.cancelCellEditing(); } }; } return null; } @Override public Component prepareEditor(TableCellEditor editor, int row, int column) { Object value = getValueAt(row, column); boolean isSelected = isCellSelected(row, column); return editor.getTableCellEditorComponent(this, value, isSelected, row, column); } }; mainTable.setStriped(true); } public final JBTable getTable() { return mainTable; } protected abstract JComponent getRowRenderer(JTable table, int row, boolean selected, boolean focused); protected abstract JBTableRowEditor getRowEditor(int row); protected abstract JBTableRow getRowAt(int row); protected boolean isRowEditable(int row) { return true; } private static class RowResizeAnimator extends Thread { private final JTable myTable; private final int myRow; private int neededHeight; private int step = 5; private int currentHeight; private RowResizeAnimator(JTable table, int row, int height) { super("Row Animator"); myTable = table; myRow = row; neededHeight = height; currentHeight = myTable.getRowHeight(myRow); } @Override public void run() { try { sleep(50); while (currentHeight != neededHeight) { if (Math.abs(currentHeight - neededHeight) < step) { currentHeight = neededHeight; } else { currentHeight += currentHeight < neededHeight ? step : -step; } SwingUtilities.invokeLater(new Runnable() { public void run() { myTable.setRowHeight(myRow, currentHeight); } }); sleep(15); } } catch (InterruptedException e) { } } } }
platform/platform-api/src/com/intellij/util/ui/table/JBListTable.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.util.ui.table; import com.intellij.ui.table.JBTable; import com.intellij.util.ui.AbstractTableCellEditor; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.KeyEvent; /** * @author Konstantin Bulenkov */ public abstract class JBListTable extends JPanel { protected final JTable myInternalTable; private final JBTable mainTable; public JBListTable(@NotNull final JTable t) { super(new BorderLayout()); myInternalTable = t; final JBListTableModel model = new JBListTableModel(t) { @Override public JBTableRow getRow(int index) { return getRowAt(index); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return isRowEditable(rowIndex); } }; mainTable = new JBTable(model) { @Override protected void processKeyEvent(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER && e.getModifiers() == 0) { editCellAt(getSelectedRow(), getSelectedColumn()); } //todo[kb] JBTabsImpl breaks focus traversal policy. Need a workaround here //else if (e.getKeyCode() == KeyEvent.VK_TAB) { // final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); // if (e.isShiftDown()) { // keyboardFocusManager.focusPreviousComponent(this); // } else { // keyboardFocusManager.focusNextComponent(this); // } //} else { super.processKeyEvent(e); } } @Override public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus, int row, int col) { return getRowRenderer(t, row, selected, hasFocus); } }; } @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { //be careful. hardcore!!! if (isEditing() && e.getKeyCode() == KeyEvent.VK_TAB) { if (pressed) { final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); if (e.isShiftDown()) { mgr.focusPreviousComponent(); } else { mgr.focusNextComponent(); } } return true; } return super.processKeyBinding(ks, e, condition, pressed); } @Override public TableCellEditor getCellEditor(final int row, int column) { final JBTableRowEditor editor = getRowEditor(row); if (editor != null) { editor.prepareEditor(t, row); editor.setFocusCycleRoot(true); editor.setFocusTraversalPolicy(new JBListTableFocusTraversalPolicy(editor)); return new AbstractTableCellEditor() { JTable curTable = null; @Override public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected, final int row, int column) { curTable = table; final JPanel p = new JPanel(new BorderLayout()) { @Override public void addNotify() { super.addNotify(); final int height = (int)getPreferredSize().getHeight(); if (height > table.getRowHeight(row)) { new RowResizeAnimator(table, row, height).start(); } } public void removeNotify() { super.removeNotify(); new RowResizeAnimator(table, row, table.getRowHeight()).start(); } }; p.add(editor, BorderLayout.CENTER); return p; } @Override public Object getCellEditorValue() { return editor.getValue(); } @Override public boolean stopCellEditing() { return super.stopCellEditing(); } @Override public void cancelCellEditing() { super.cancelCellEditing(); } }; } return null; } @Override public Component prepareEditor(TableCellEditor editor, int row, int column) { Object value = getValueAt(row, column); boolean isSelected = isCellSelected(row, column); return editor.getTableCellEditorComponent(this, value, isSelected, row, column); } }; mainTable.setStriped(true); } public final JBTable getTable() { return mainTable; } protected abstract JComponent getRowRenderer(JTable table, int row, boolean selected, boolean focused); protected abstract JBTableRowEditor getRowEditor(int row); protected abstract JBTableRow getRowAt(int row); protected boolean isRowEditable(int row) { return true; } private static class RowResizeAnimator extends Thread { private final JTable myTable; private final int myRow; private int neededHeight; private int step = 5; private int currentHeight; private RowResizeAnimator(JTable table, int row, int height) { super("Row Animator"); myTable = table; myRow = row; neededHeight = height; currentHeight = myTable.getRowHeight(myRow); } @Override public void run() { try { sleep(50); while (currentHeight != neededHeight) { if (Math.abs(currentHeight - neededHeight) < step) { currentHeight = neededHeight; } else { currentHeight += currentHeight < neededHeight ? step : -step; } SwingUtilities.invokeLater(new Runnable() { public void run() { myTable.setRowHeight(myRow, currentHeight); } }); sleep(15); } } catch (InterruptedException e) { } } } }
fix Enter in cell editor
platform/platform-api/src/com/intellij/util/ui/table/JBListTable.java
fix Enter in cell editor
Java
apache-2.0
c4d71466b2f06e6557a822140229ed96fbf05b33
0
apache/logging-log4j2,apache/logging-log4j2,apache/logging-log4j2
/* * 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.log4j.config; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.LogManager; import org.apache.log4j.PatternLayout; import org.apache.log4j.bridge.AppenderAdapter; import org.apache.log4j.bridge.AppenderWrapper; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.Filter; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.status.StatusConfiguration; import org.apache.logging.log4j.util.LoaderUtil; /** * Constructs a configuration based on Log4j 1 properties. */ public class PropertiesConfiguration extends Log4j1Configuration { private static final String CATEGORY_PREFIX = "log4j.category."; private static final String LOGGER_PREFIX = "log4j.logger."; private static final String ADDITIVITY_PREFIX = "log4j.additivity."; private static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory"; private static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger"; private static final String APPENDER_PREFIX = "log4j.appender."; private static final String LOGGER_REF = "logger-ref"; private static final String ROOT_REF = "root-ref"; private static final String APPENDER_REF_TAG = "appender-ref"; public static final long DEFAULT_DELAY = 60000; public static final String DEBUG_KEY="log4j.debug"; private static final String INTERNAL_ROOT_NAME = "root"; private final Map<String, Appender> registry = new HashMap<>(); /** * Constructs a new instance. * * @param loggerContext The LoggerContext. * @param source The ConfigurationSource. * @param monitorIntervalSeconds The monitoring interval in seconds. */ public PropertiesConfiguration(final LoggerContext loggerContext, final ConfigurationSource source, final int monitorIntervalSeconds) { super(loggerContext, source, monitorIntervalSeconds); } @Override public void doConfigure() { final InputStream inputStream = getConfigurationSource().getInputStream(); final Properties properties = new Properties(); try { properties.load(inputStream); } catch (final Exception e) { LOGGER.error("Could not read configuration file [{}].", getConfigurationSource().toString(), e); return; } // If we reach here, then the config file is alright. doConfigure(properties); } @Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } final Configuration config = new PropertiesConfigurationFactory().getConfiguration(getLoggerContext(), source); return config == null || config.getState() != State.INITIALIZING ? null : config; } catch (final IOException ex) { LOGGER.error("Cannot locate file {}: {}", getConfigurationSource(), ex); } return null; } /** * Reads a configuration from a file. <b>The existing configuration is * not cleared nor reset.</b> If you require a different behavior, * then call {@link LogManager#resetConfiguration * resetConfiguration} method before calling * <code>doConfigure</code>. * * <p>The configuration file consists of statements in the format * <code>key=value</code>. The syntax of different configuration * elements are discussed below. * * <p>The level value can consist of the string values OFF, FATAL, * ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A * custom level value can be specified in the form * level#classname. By default the repository-wide threshold is set * to the lowest possible value, namely the level <code>ALL</code>. * </p> * * * <h3>Appender configuration</h3> * * <p>Appender configuration syntax is: * <pre> * # For appender named <i>appenderName</i>, set its class. * # Note: The appender name can contain dots. * log4j.appender.appenderName=fully.qualified.name.of.appender.class * * # Set appender specific options. * log4j.appender.appenderName.option1=value1 * ... * log4j.appender.appenderName.optionN=valueN * </pre> * <p> * For each named appender you can configure its {@link Layout}. The * syntax for configuring an appender's layout is: * <pre> * log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class * log4j.appender.appenderName.layout.option1=value1 * .... * log4j.appender.appenderName.layout.optionN=valueN * </pre> * <p> * The syntax for adding {@link Filter}s to an appender is: * <pre> * log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class * log4j.appender.appenderName.filter.ID.option1=value1 * ... * log4j.appender.appenderName.filter.ID.optionN=valueN * </pre> * The first line defines the class name of the filter identified by ID; * subsequent lines with the same ID specify filter option - value * pairs. Multiple filters are added to the appender in the lexicographic * order of IDs. * <p> * The syntax for adding an {@link ErrorHandler} to an appender is: * <pre> * log4j.appender.appenderName.errorhandler=fully.qualified.name.of.errorhandler.class * log4j.appender.appenderName.errorhandler.appender-ref=appenderName * log4j.appender.appenderName.errorhandler.option1=value1 * ... * log4j.appender.appenderName.errorhandler.optionN=valueN * </pre> * * <h3>Configuring loggers</h3> * * <p>The syntax for configuring the root logger is: * <pre> * log4j.rootLogger=[level], appenderName, appenderName, ... * </pre> * * <p>This syntax means that an optional <em>level</em> can be * supplied followed by appender names separated by commas. * * <p>The level value can consist of the string values OFF, FATAL, * ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A * custom level value can be specified in the form * <code>level#classname</code>. * * <p>If a level value is specified, then the root level is set * to the corresponding level. If no level value is specified, * then the root level remains untouched. * * <p>The root logger can be assigned multiple appenders. * * <p>Each <i>appenderName</i> (separated by commas) will be added to * the root logger. The named appender is defined using the * appender syntax defined above. * * <p>For non-root categories the syntax is almost the same: * <pre> * log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName, ... * </pre> * * <p>The meaning of the optional level value is discussed above * in relation to the root logger. In addition however, the value * INHERITED can be specified meaning that the named logger should * inherit its level from the logger hierarchy. * * <p>If no level value is supplied, then the level of the * named logger remains untouched. * * <p>By default categories inherit their level from the * hierarchy. However, if you set the level of a logger and later * decide that that logger should inherit its level, then you should * specify INHERITED as the value for the level value. NULL is a * synonym for INHERITED. * * <p>Similar to the root logger syntax, each <i>appenderName</i> * (separated by commas) will be attached to the named logger. * * <p>See the <a href="../../../../manual.html#additivity">appender * additivity rule</a> in the user manual for the meaning of the * <code>additivity</code> flag. * * * # Set options for appender named "A1". * # Appender "A1" will be a SyslogAppender * log4j.appender.A1=org.apache.log4j.net.SyslogAppender * * # The syslog daemon resides on www.abc.net * log4j.appender.A1.SyslogHost=www.abc.net * * # A1's layout is a PatternLayout, using the conversion pattern * # <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will * # include # the relative time since the start of the application in * # milliseconds, followed by the level of the log request, * # followed by the two rightmost components of the logger name, * # followed by the callers method name, followed by the line number, * # the nested diagnostic context and finally the message itself. * # Refer to the documentation of {@link PatternLayout} for further information * # on the syntax of the ConversionPattern key. * log4j.appender.A1.layout=org.apache.log4j.PatternLayout * log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n * * # Set options for appender named "A2" * # A2 should be a RollingFileAppender, with maximum file size of 10 MB * # using at most one backup file. A2's layout is TTCC, using the * # ISO8061 date format with context printing enabled. * log4j.appender.A2=org.apache.log4j.RollingFileAppender * log4j.appender.A2.MaxFileSize=10MB * log4j.appender.A2.MaxBackupIndex=1 * log4j.appender.A2.layout=org.apache.log4j.TTCCLayout * log4j.appender.A2.layout.ContextPrinting=enabled * log4j.appender.A2.layout.DateFormat=ISO8601 * * # Root logger set to DEBUG using the A2 appender defined above. * log4j.rootLogger=DEBUG, A2 * * # Logger definitions: * # The SECURITY logger inherits is level from root. However, it's output * # will go to A1 appender defined above. It's additivity is non-cumulative. * log4j.logger.SECURITY=INHERIT, A1 * log4j.additivity.SECURITY=false * * # Only warnings or above will be logged for the logger "SECURITY.access". * # Output will go to A1. * log4j.logger.SECURITY.access=WARN * * * # The logger "class.of.the.day" inherits its level from the * # logger hierarchy. Output will go to the appender's of the root * # logger, A2 in this case. * log4j.logger.class.of.the.day=INHERIT * </pre> * * <p>Refer to the <b>setOption</b> method in each Appender and * Layout for class specific options. * * <p>Use the <code>#</code> or <code>!</code> characters at the * beginning of a line for comments. * * <p> */ private void doConfigure(final Properties properties) { String status = "error"; String value = properties.getProperty(DEBUG_KEY); if (value == null) { value = properties.getProperty("log4j.configDebug"); if (value != null) { LOGGER.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead."); } } if (value != null) { status = OptionConverter.toBoolean(value, false) ? "debug" : "error"; } final StatusConfiguration statusConfig = new StatusConfiguration().withStatus(status); statusConfig.initialize(); configureRoot(properties); parseLoggers(properties); LOGGER.debug("Finished configuring."); } // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- private void configureRoot(final Properties props) { String effectiveFrefix = ROOT_LOGGER_PREFIX; String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props); if (value == null) { value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props); effectiveFrefix = ROOT_CATEGORY_PREFIX; } if (value == null) { LOGGER.debug("Could not find root logger information. Is this OK?"); } else { final LoggerConfig root = getRootLogger(); parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value); } } /** * Parses non-root elements, such non-root categories and renderers. */ private void parseLoggers(final Properties props) { final Enumeration<?> enumeration = props.propertyNames(); while (enumeration.hasMoreElements()) { final String key = Objects.toString(enumeration.nextElement(), null); if (key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) { String loggerName = null; if (key.startsWith(CATEGORY_PREFIX)) { loggerName = key.substring(CATEGORY_PREFIX.length()); } else if (key.startsWith(LOGGER_PREFIX)) { loggerName = key.substring(LOGGER_PREFIX.length()); } final String value = OptionConverter.findAndSubst(key, props); LoggerConfig loggerConfig = getLogger(loggerName); if (loggerConfig == null) { final boolean additivity = getAdditivityForLogger(props, loggerName); loggerConfig = new LoggerConfig(loggerName, org.apache.logging.log4j.Level.ERROR, additivity); addLogger(loggerName, loggerConfig); } parseLogger(props, loggerConfig, key, loggerName, value); } } } /** * Parses the additivity option for a non-root category. */ private boolean getAdditivityForLogger(final Properties props, final String loggerName) { boolean additivity = true; final String key = ADDITIVITY_PREFIX + loggerName; final String value = OptionConverter.findAndSubst(key, props); LOGGER.debug("Handling {}=[{}]", key, value); // touch additivity only if necessary if ((value != null) && (!value.equals(""))) { additivity = OptionConverter.toBoolean(value, true); } return additivity; } /** * This method must work for the root category as well. */ private void parseLogger(final Properties props, final LoggerConfig logger, final String optionKey, final String loggerName, final String value) { LOGGER.debug("Parsing for [{}] with value=[{}].", loggerName, value); // We must skip over ',' but not white space final StringTokenizer st = new StringTokenizer(value, ","); // If value is not in the form ", appender.." or "", then we should set the level of the logger. if (!(value.startsWith(",") || value.equals(""))) { // just to be on the safe side... if (!st.hasMoreTokens()) { return; } final String levelStr = st.nextToken(); LOGGER.debug("Level token is [{}].", levelStr); final org.apache.logging.log4j.Level level = levelStr == null ? org.apache.logging.log4j.Level.ERROR : OptionConverter.convertLevel(levelStr, org.apache.logging.log4j.Level.DEBUG); logger.setLevel(level); LOGGER.debug("Logger {} level set to {}", loggerName, level); } Appender appender; String appenderName; while (st.hasMoreTokens()) { appenderName = st.nextToken().trim(); if (appenderName == null || appenderName.equals(",")) { continue; } LOGGER.debug("Parsing appender named \"{}\".", appenderName); appender = parseAppender(props, appenderName); if (appender != null) { LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", appenderName, logger.getName()); logger.addAppender(getAppender(appenderName), null, null); } else { LOGGER.debug("Appender named [{}] not found.", appenderName); } } } public Appender parseAppender(final Properties props, final String appenderName) { Appender appender = registry.get(appenderName); if ((appender != null)) { LOGGER.debug("Appender \"" + appenderName + "\" was already parsed."); return appender; } // Appender was not previously initialized. final String prefix = APPENDER_PREFIX + appenderName; final String layoutPrefix = prefix + ".layout"; final String filterPrefix = APPENDER_PREFIX + appenderName + ".filter."; final String className = OptionConverter.findAndSubst(prefix, props); appender = manager.parseAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props, this); if (appender == null) { appender = buildAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props); } else { registry.put(appenderName, appender); if (appender instanceof AppenderWrapper) { addAppender(((AppenderWrapper) appender).getAppender()); } else { addAppender(new AppenderAdapter(appender).getAdapter()); } } return appender; } private Appender buildAppender(final String appenderName, final String className, final String prefix, final String layoutPrefix, final String filterPrefix, final Properties props) { final Appender appender = newInstanceOf(className, "Appender"); if (appender == null) { return null; } appender.setName(appenderName); appender.setLayout(parseLayout(layoutPrefix, appenderName, props)); final String errorHandlerPrefix = prefix + ".errorhandler"; final String errorHandlerClass = OptionConverter.findAndSubst(errorHandlerPrefix, props); if (errorHandlerClass != null) { final ErrorHandler eh = parseErrorHandler(props, errorHandlerPrefix, errorHandlerClass, appender); if (eh != null) { appender.setErrorHandler(eh); } } appender.addFilter(parseAppenderFilters(props, filterPrefix, appenderName)); final String[] keys = new String[] { layoutPrefix }; addProperties(appender, keys, props, prefix); if (appender instanceof AppenderWrapper) { addAppender(((AppenderWrapper) appender).getAppender()); } else { addAppender(new AppenderAdapter(appender).getAdapter()); } registry.put(appenderName, appender); return appender; } public Layout parseLayout(final String layoutPrefix, final String appenderName, final Properties props) { final String layoutClass = OptionConverter.findAndSubst(layoutPrefix, props); if (layoutClass == null) { return null; } Layout layout = manager.parseLayout(layoutClass, layoutPrefix, props, this); if (layout == null) { layout = buildLayout(layoutPrefix, layoutClass, appenderName, props); } return layout; } private Layout buildLayout(final String layoutPrefix, final String className, final String appenderName, final Properties props) { final Layout layout = newInstanceOf(className, "Layout"); if (layout == null) { return null; } LOGGER.debug("Parsing layout options for \"{}\".", appenderName); PropertySetter.setProperties(layout, props, layoutPrefix + "."); LOGGER.debug("End of parsing for \"{}\".", appenderName); return layout; } public ErrorHandler parseErrorHandler(final Properties props, final String errorHandlerPrefix, final String errorHandlerClass, final Appender appender) { final ErrorHandler eh = newInstanceOf(errorHandlerClass, "ErrorHandler"); final String[] keys = new String[] { errorHandlerPrefix + "." + ROOT_REF, errorHandlerPrefix + "." + LOGGER_REF, errorHandlerPrefix + "." + APPENDER_REF_TAG }; addProperties(eh, keys, props, errorHandlerPrefix); return eh; } public void addProperties(final Object obj, final String[] keys, final Properties props, final String prefix) { final Properties edited = new Properties(); props.stringPropertyNames().stream().filter(name -> { if (name.startsWith(prefix)) { for (final String key : keys) { if (name.equals(key)) { return false; } } return true; } return false; }).forEach(name -> edited.put(name, props.getProperty(name))); PropertySetter.setProperties(obj, edited, prefix + "."); } public Filter parseAppenderFilters(final Properties props, final String filterPrefix, final String appenderName) { // extract filters and filter options from props into a hashtable mapping // the property name defining the filter class to a list of pre-parsed // name-value pairs associated to that filter final int fIdx = filterPrefix.length(); final SortedMap<String, List<NameValue>> filters = new TreeMap<>(); final Enumeration<?> e = props.keys(); String name = ""; while (e.hasMoreElements()) { final String key = (String) e.nextElement(); if (key.startsWith(filterPrefix)) { final int dotIdx = key.indexOf('.', fIdx); String filterKey = key; if (dotIdx != -1) { filterKey = key.substring(0, dotIdx); name = key.substring(dotIdx + 1); } final List<NameValue> filterOpts = filters.computeIfAbsent(filterKey, k -> new ArrayList<>()); if (dotIdx != -1) { final String value = OptionConverter.findAndSubst(key, props); filterOpts.add(new NameValue(name, value)); } } } Filter head = null; Filter next = null; for (final Map.Entry<String, List<NameValue>> entry : filters.entrySet()) { final String clazz = props.getProperty(entry.getKey()); Filter filter = null; if (clazz != null) { filter = manager.parseFilter(clazz, entry.getKey(), props, this); if (filter == null) { LOGGER.debug("Filter key: [{}] class: [{}] props: {}", entry.getKey(), clazz, entry.getValue()); filter = buildFilter(clazz, appenderName, entry.getValue()); } } if (filter != null) { if (head == null) { head = filter; } else { next.setNext(filter); } next = filter; } } return head; } private Filter buildFilter(final String className, final String appenderName, final List<NameValue> props) { final Filter filter = newInstanceOf(className, "Filter"); if (filter != null) { final PropertySetter propSetter = new PropertySetter(filter); for (final NameValue property : props) { propSetter.setProperty(property.key, property.value); } propSetter.activate(); } return filter; } private static <T> T newInstanceOf(final String className, final String type) { try { return LoaderUtil.newInstanceOf(className); } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException ex) { LOGGER.error("Unable to create {} {} due to {}:{}", type, className, ex.getClass().getSimpleName(), ex.getMessage()); return null; } } private static class NameValue { String key, value; NameValue(final String key, final String value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } } }
log4j-1.2-api/src/main/java/org/apache/log4j/config/PropertiesConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.log4j.config; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.LogManager; import org.apache.log4j.PatternLayout; import org.apache.log4j.bridge.AppenderAdapter; import org.apache.log4j.bridge.AppenderWrapper; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.Filter; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.status.StatusConfiguration; import org.apache.logging.log4j.util.LoaderUtil; /** * Constructs a configuration based on Log4j 1 properties. */ public class PropertiesConfiguration extends Log4j1Configuration { private static final String CATEGORY_PREFIX = "log4j.category."; private static final String LOGGER_PREFIX = "log4j.logger."; private static final String ADDITIVITY_PREFIX = "log4j.additivity."; private static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory"; private static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger"; private static final String APPENDER_PREFIX = "log4j.appender."; private static final String LOGGER_REF = "logger-ref"; private static final String ROOT_REF = "root-ref"; private static final String APPENDER_REF_TAG = "appender-ref"; public static final long DEFAULT_DELAY = 60000; public static final String DEBUG_KEY="log4j.debug"; private static final String INTERNAL_ROOT_NAME = "root"; private final Map<String, Appender> registry = new HashMap<>(); /** * Constructs a new instance. * * @param loggerContext The LoggerContext. * @param source The ConfigurationSource. * @param monitorIntervalSeconds The monitoring interval in seconds. */ public PropertiesConfiguration(final LoggerContext loggerContext, final ConfigurationSource source, final int monitorIntervalSeconds) { super(loggerContext, source, monitorIntervalSeconds); } @Override public void doConfigure() { final InputStream inputStream = getConfigurationSource().getInputStream(); final Properties properties = new Properties(); try { properties.load(inputStream); } catch (final Exception e) { LOGGER.error("Could not read configuration file [{}].", getConfigurationSource().toString(), e); return; } // If we reach here, then the config file is alright. doConfigure(properties); } @Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory(); final PropertiesConfiguration config = (PropertiesConfiguration) factory.getConfiguration(getLoggerContext(), source); return config == null || config.getState() != State.INITIALIZING ? null : config; } catch (final IOException ex) { LOGGER.error("Cannot locate file {}: {}", getConfigurationSource(), ex); } return null; } /** * Reads a configuration from a file. <b>The existing configuration is * not cleared nor reset.</b> If you require a different behavior, * then call {@link LogManager#resetConfiguration * resetConfiguration} method before calling * <code>doConfigure</code>. * * <p>The configuration file consists of statements in the format * <code>key=value</code>. The syntax of different configuration * elements are discussed below. * * <p>The level value can consist of the string values OFF, FATAL, * ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A * custom level value can be specified in the form * level#classname. By default the repository-wide threshold is set * to the lowest possible value, namely the level <code>ALL</code>. * </p> * * * <h3>Appender configuration</h3> * * <p>Appender configuration syntax is: * <pre> * # For appender named <i>appenderName</i>, set its class. * # Note: The appender name can contain dots. * log4j.appender.appenderName=fully.qualified.name.of.appender.class * * # Set appender specific options. * log4j.appender.appenderName.option1=value1 * ... * log4j.appender.appenderName.optionN=valueN * </pre> * <p> * For each named appender you can configure its {@link Layout}. The * syntax for configuring an appender's layout is: * <pre> * log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class * log4j.appender.appenderName.layout.option1=value1 * .... * log4j.appender.appenderName.layout.optionN=valueN * </pre> * <p> * The syntax for adding {@link Filter}s to an appender is: * <pre> * log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class * log4j.appender.appenderName.filter.ID.option1=value1 * ... * log4j.appender.appenderName.filter.ID.optionN=valueN * </pre> * The first line defines the class name of the filter identified by ID; * subsequent lines with the same ID specify filter option - value * pairs. Multiple filters are added to the appender in the lexicographic * order of IDs. * <p> * The syntax for adding an {@link ErrorHandler} to an appender is: * <pre> * log4j.appender.appenderName.errorhandler=fully.qualified.name.of.errorhandler.class * log4j.appender.appenderName.errorhandler.appender-ref=appenderName * log4j.appender.appenderName.errorhandler.option1=value1 * ... * log4j.appender.appenderName.errorhandler.optionN=valueN * </pre> * * <h3>Configuring loggers</h3> * * <p>The syntax for configuring the root logger is: * <pre> * log4j.rootLogger=[level], appenderName, appenderName, ... * </pre> * * <p>This syntax means that an optional <em>level</em> can be * supplied followed by appender names separated by commas. * * <p>The level value can consist of the string values OFF, FATAL, * ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A * custom level value can be specified in the form * <code>level#classname</code>. * * <p>If a level value is specified, then the root level is set * to the corresponding level. If no level value is specified, * then the root level remains untouched. * * <p>The root logger can be assigned multiple appenders. * * <p>Each <i>appenderName</i> (separated by commas) will be added to * the root logger. The named appender is defined using the * appender syntax defined above. * * <p>For non-root categories the syntax is almost the same: * <pre> * log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName, ... * </pre> * * <p>The meaning of the optional level value is discussed above * in relation to the root logger. In addition however, the value * INHERITED can be specified meaning that the named logger should * inherit its level from the logger hierarchy. * * <p>If no level value is supplied, then the level of the * named logger remains untouched. * * <p>By default categories inherit their level from the * hierarchy. However, if you set the level of a logger and later * decide that that logger should inherit its level, then you should * specify INHERITED as the value for the level value. NULL is a * synonym for INHERITED. * * <p>Similar to the root logger syntax, each <i>appenderName</i> * (separated by commas) will be attached to the named logger. * * <p>See the <a href="../../../../manual.html#additivity">appender * additivity rule</a> in the user manual for the meaning of the * <code>additivity</code> flag. * * * # Set options for appender named "A1". * # Appender "A1" will be a SyslogAppender * log4j.appender.A1=org.apache.log4j.net.SyslogAppender * * # The syslog daemon resides on www.abc.net * log4j.appender.A1.SyslogHost=www.abc.net * * # A1's layout is a PatternLayout, using the conversion pattern * # <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will * # include # the relative time since the start of the application in * # milliseconds, followed by the level of the log request, * # followed by the two rightmost components of the logger name, * # followed by the callers method name, followed by the line number, * # the nested diagnostic context and finally the message itself. * # Refer to the documentation of {@link PatternLayout} for further information * # on the syntax of the ConversionPattern key. * log4j.appender.A1.layout=org.apache.log4j.PatternLayout * log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n * * # Set options for appender named "A2" * # A2 should be a RollingFileAppender, with maximum file size of 10 MB * # using at most one backup file. A2's layout is TTCC, using the * # ISO8061 date format with context printing enabled. * log4j.appender.A2=org.apache.log4j.RollingFileAppender * log4j.appender.A2.MaxFileSize=10MB * log4j.appender.A2.MaxBackupIndex=1 * log4j.appender.A2.layout=org.apache.log4j.TTCCLayout * log4j.appender.A2.layout.ContextPrinting=enabled * log4j.appender.A2.layout.DateFormat=ISO8601 * * # Root logger set to DEBUG using the A2 appender defined above. * log4j.rootLogger=DEBUG, A2 * * # Logger definitions: * # The SECURITY logger inherits is level from root. However, it's output * # will go to A1 appender defined above. It's additivity is non-cumulative. * log4j.logger.SECURITY=INHERIT, A1 * log4j.additivity.SECURITY=false * * # Only warnings or above will be logged for the logger "SECURITY.access". * # Output will go to A1. * log4j.logger.SECURITY.access=WARN * * * # The logger "class.of.the.day" inherits its level from the * # logger hierarchy. Output will go to the appender's of the root * # logger, A2 in this case. * log4j.logger.class.of.the.day=INHERIT * </pre> * * <p>Refer to the <b>setOption</b> method in each Appender and * Layout for class specific options. * * <p>Use the <code>#</code> or <code>!</code> characters at the * beginning of a line for comments. * * <p> */ private void doConfigure(final Properties properties) { String status = "error"; String value = properties.getProperty(DEBUG_KEY); if (value == null) { value = properties.getProperty("log4j.configDebug"); if (value != null) { LOGGER.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead."); } } if (value != null) { status = OptionConverter.toBoolean(value, false) ? "debug" : "error"; } final StatusConfiguration statusConfig = new StatusConfiguration().withStatus(status); statusConfig.initialize(); configureRoot(properties); parseLoggers(properties); LOGGER.debug("Finished configuring."); } // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- private void configureRoot(final Properties props) { String effectiveFrefix = ROOT_LOGGER_PREFIX; String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props); if (value == null) { value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props); effectiveFrefix = ROOT_CATEGORY_PREFIX; } if (value == null) { LOGGER.debug("Could not find root logger information. Is this OK?"); } else { final LoggerConfig root = getRootLogger(); parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value); } } /** * Parses non-root elements, such non-root categories and renderers. */ private void parseLoggers(final Properties props) { final Enumeration<?> enumeration = props.propertyNames(); while (enumeration.hasMoreElements()) { final String key = Objects.toString(enumeration.nextElement(), null); if (key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) { String loggerName = null; if (key.startsWith(CATEGORY_PREFIX)) { loggerName = key.substring(CATEGORY_PREFIX.length()); } else if (key.startsWith(LOGGER_PREFIX)) { loggerName = key.substring(LOGGER_PREFIX.length()); } final String value = OptionConverter.findAndSubst(key, props); LoggerConfig loggerConfig = getLogger(loggerName); if (loggerConfig == null) { final boolean additivity = getAdditivityForLogger(props, loggerName); loggerConfig = new LoggerConfig(loggerName, org.apache.logging.log4j.Level.ERROR, additivity); addLogger(loggerName, loggerConfig); } parseLogger(props, loggerConfig, key, loggerName, value); } } } /** * Parses the additivity option for a non-root category. */ private boolean getAdditivityForLogger(final Properties props, final String loggerName) { boolean additivity = true; final String key = ADDITIVITY_PREFIX + loggerName; final String value = OptionConverter.findAndSubst(key, props); LOGGER.debug("Handling {}=[{}]", key, value); // touch additivity only if necessary if ((value != null) && (!value.equals(""))) { additivity = OptionConverter.toBoolean(value, true); } return additivity; } /** * This method must work for the root category as well. */ private void parseLogger(final Properties props, final LoggerConfig logger, final String optionKey, final String loggerName, final String value) { LOGGER.debug("Parsing for [{}] with value=[{}].", loggerName, value); // We must skip over ',' but not white space final StringTokenizer st = new StringTokenizer(value, ","); // If value is not in the form ", appender.." or "", then we should set the level of the logger. if (!(value.startsWith(",") || value.equals(""))) { // just to be on the safe side... if (!st.hasMoreTokens()) { return; } final String levelStr = st.nextToken(); LOGGER.debug("Level token is [{}].", levelStr); final org.apache.logging.log4j.Level level = levelStr == null ? org.apache.logging.log4j.Level.ERROR : OptionConverter.convertLevel(levelStr, org.apache.logging.log4j.Level.DEBUG); logger.setLevel(level); LOGGER.debug("Logger {} level set to {}", loggerName, level); } Appender appender; String appenderName; while (st.hasMoreTokens()) { appenderName = st.nextToken().trim(); if (appenderName == null || appenderName.equals(",")) { continue; } LOGGER.debug("Parsing appender named \"{}\".", appenderName); appender = parseAppender(props, appenderName); if (appender != null) { LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", appenderName, logger.getName()); logger.addAppender(getAppender(appenderName), null, null); } else { LOGGER.debug("Appender named [{}] not found.", appenderName); } } } public Appender parseAppender(final Properties props, final String appenderName) { Appender appender = registry.get(appenderName); if ((appender != null)) { LOGGER.debug("Appender \"" + appenderName + "\" was already parsed."); return appender; } // Appender was not previously initialized. final String prefix = APPENDER_PREFIX + appenderName; final String layoutPrefix = prefix + ".layout"; final String filterPrefix = APPENDER_PREFIX + appenderName + ".filter."; final String className = OptionConverter.findAndSubst(prefix, props); appender = manager.parseAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props, this); if (appender == null) { appender = buildAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props); } else { registry.put(appenderName, appender); if (appender instanceof AppenderWrapper) { addAppender(((AppenderWrapper) appender).getAppender()); } else { addAppender(new AppenderAdapter(appender).getAdapter()); } } return appender; } private Appender buildAppender(final String appenderName, final String className, final String prefix, final String layoutPrefix, final String filterPrefix, final Properties props) { final Appender appender = newInstanceOf(className, "Appender"); if (appender == null) { return null; } appender.setName(appenderName); appender.setLayout(parseLayout(layoutPrefix, appenderName, props)); final String errorHandlerPrefix = prefix + ".errorhandler"; final String errorHandlerClass = OptionConverter.findAndSubst(errorHandlerPrefix, props); if (errorHandlerClass != null) { final ErrorHandler eh = parseErrorHandler(props, errorHandlerPrefix, errorHandlerClass, appender); if (eh != null) { appender.setErrorHandler(eh); } } appender.addFilter(parseAppenderFilters(props, filterPrefix, appenderName)); final String[] keys = new String[] { layoutPrefix }; addProperties(appender, keys, props, prefix); if (appender instanceof AppenderWrapper) { addAppender(((AppenderWrapper) appender).getAppender()); } else { addAppender(new AppenderAdapter(appender).getAdapter()); } registry.put(appenderName, appender); return appender; } public Layout parseLayout(final String layoutPrefix, final String appenderName, final Properties props) { final String layoutClass = OptionConverter.findAndSubst(layoutPrefix, props); if (layoutClass == null) { return null; } Layout layout = manager.parseLayout(layoutClass, layoutPrefix, props, this); if (layout == null) { layout = buildLayout(layoutPrefix, layoutClass, appenderName, props); } return layout; } private Layout buildLayout(final String layoutPrefix, final String className, final String appenderName, final Properties props) { final Layout layout = newInstanceOf(className, "Layout"); if (layout == null) { return null; } LOGGER.debug("Parsing layout options for \"{}\".", appenderName); PropertySetter.setProperties(layout, props, layoutPrefix + "."); LOGGER.debug("End of parsing for \"{}\".", appenderName); return layout; } public ErrorHandler parseErrorHandler(final Properties props, final String errorHandlerPrefix, final String errorHandlerClass, final Appender appender) { final ErrorHandler eh = newInstanceOf(errorHandlerClass, "ErrorHandler"); final String[] keys = new String[] { errorHandlerPrefix + "." + ROOT_REF, errorHandlerPrefix + "." + LOGGER_REF, errorHandlerPrefix + "." + APPENDER_REF_TAG }; addProperties(eh, keys, props, errorHandlerPrefix); return eh; } public void addProperties(final Object obj, final String[] keys, final Properties props, final String prefix) { final Properties edited = new Properties(); props.stringPropertyNames().stream().filter(name -> { if (name.startsWith(prefix)) { for (final String key : keys) { if (name.equals(key)) { return false; } } return true; } return false; }).forEach(name -> edited.put(name, props.getProperty(name))); PropertySetter.setProperties(obj, edited, prefix + "."); } public Filter parseAppenderFilters(final Properties props, final String filterPrefix, final String appenderName) { // extract filters and filter options from props into a hashtable mapping // the property name defining the filter class to a list of pre-parsed // name-value pairs associated to that filter final int fIdx = filterPrefix.length(); final SortedMap<String, List<NameValue>> filters = new TreeMap<>(); final Enumeration<?> e = props.keys(); String name = ""; while (e.hasMoreElements()) { final String key = (String) e.nextElement(); if (key.startsWith(filterPrefix)) { final int dotIdx = key.indexOf('.', fIdx); String filterKey = key; if (dotIdx != -1) { filterKey = key.substring(0, dotIdx); name = key.substring(dotIdx + 1); } final List<NameValue> filterOpts = filters.computeIfAbsent(filterKey, k -> new ArrayList<>()); if (dotIdx != -1) { final String value = OptionConverter.findAndSubst(key, props); filterOpts.add(new NameValue(name, value)); } } } Filter head = null; Filter next = null; for (final Map.Entry<String, List<NameValue>> entry : filters.entrySet()) { final String clazz = props.getProperty(entry.getKey()); Filter filter = null; if (clazz != null) { filter = manager.parseFilter(clazz, entry.getKey(), props, this); if (filter == null) { LOGGER.debug("Filter key: [{}] class: [{}] props: {}", entry.getKey(), clazz, entry.getValue()); filter = buildFilter(clazz, appenderName, entry.getValue()); } } if (filter != null) { if (head == null) { head = filter; } else { next.setNext(filter); } next = filter; } } return head; } private Filter buildFilter(final String className, final String appenderName, final List<NameValue> props) { final Filter filter = newInstanceOf(className, "Filter"); if (filter != null) { final PropertySetter propSetter = new PropertySetter(filter); for (final NameValue property : props) { propSetter.setProperty(property.key, property.value); } propSetter.activate(); } return filter; } private static <T> T newInstanceOf(final String className, final String type) { try { return LoaderUtil.newInstanceOf(className); } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException ex) { LOGGER.error("Unable to create {} {} due to {}:{}", type, className, ex.getClass().getSimpleName(), ex.getMessage()); return null; } } private static class NameValue { String key, value; NameValue(final String key, final String value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } } }
Type as interface instead of concrete class, no type-cast needed. Drop single us local variable.
log4j-1.2-api/src/main/java/org/apache/log4j/config/PropertiesConfiguration.java
Type as interface instead of concrete class, no type-cast needed.
Java
apache-2.0
10ea1af8a550b34b461f263c813f66129e691d35
0
ewjmulder/keycloak,ewjmulder/keycloak,darranl/keycloak,srose/keycloak,mhajas/keycloak,cfsnyder/keycloak,stianst/keycloak,wildfly-security-incubator/keycloak,ssilvert/keycloak,keycloak/keycloak,lkubik/keycloak,gregjones60/keycloak,dylanplecki/keycloak,pfiled/keycloak,eugene-chow/keycloak,stianst/keycloak,girirajsharma/keycloak,jean-merelis/keycloak,hmlnarik/keycloak,cmoulliard/keycloak,arivanajoki/keycloak,vmuzikar/keycloak,manuel-palacio/keycloak,pedroigor/keycloak,mposolda/keycloak,chameleon82/keycloak,keycloak/keycloak,j-bore/keycloak,AOEpeople/keycloak,didiez/keycloak,iperdomo/keycloak,grange74/keycloak,iperdomo/keycloak,mhajas/keycloak,srose/keycloak,mbaluch/keycloak,reneploetz/keycloak,vmuzikar/keycloak,wildfly-security-incubator/keycloak,mbaluch/keycloak,jean-merelis/keycloak,dylanplecki/keycloak,stianst/keycloak,grange74/keycloak,wildfly-security-incubator/keycloak,mposolda/keycloak,thomasdarimont/keycloak,manuel-palacio/keycloak,ahus1/keycloak,agolPL/keycloak,dylanplecki/keycloak,eugene-chow/keycloak,cfsnyder/keycloak,grange74/keycloak,hmlnarik/keycloak,dbarentine/keycloak,chameleon82/keycloak,thomasdarimont/keycloak,j-bore/keycloak,reneploetz/keycloak,srose/keycloak,pedroigor/keycloak,hmlnarik/keycloak,ssilvert/keycloak,reneploetz/keycloak,ppolavar/keycloak,brat000012001/keycloak,anaerobic/keycloak,jpkrohling/keycloak,raehalme/keycloak,amalalex/keycloak,mposolda/keycloak,amalalex/keycloak,j-bore/keycloak,gregjones60/keycloak,jean-merelis/keycloak,eugene-chow/keycloak,ssilvert/keycloak,lennartj/keycloak,pedroigor/keycloak,cmoulliard/keycloak,amalalex/keycloak,amalalex/keycloak,ssilvert/keycloak,matzew/keycloak,cfsnyder/keycloak,mposolda/keycloak,darranl/keycloak,jean-merelis/keycloak,ahus1/keycloak,VihreatDeGrona/keycloak,pfiled/keycloak,mbaluch/keycloak,abstractj/keycloak,almighty/keycloak,matzew/keycloak,dbarentine/keycloak,hmlnarik/keycloak,lennartj/keycloak,ppolavar/keycloak,vmuzikar/keycloak,brat000012001/keycloak,WebJustDevelopment/keycloak,keycloak/keycloak,hmlnarik/keycloak,mbaluch/keycloak,jpkrohling/keycloak,mposolda/keycloak,thomasdarimont/keycloak,abstractj/keycloak,lkubik/keycloak,girirajsharma/keycloak,girirajsharma/keycloak,thomasdarimont/keycloak,lkubik/keycloak,anaerobic/keycloak,dbarentine/keycloak,girirajsharma/keycloak,ahus1/keycloak,brat000012001/keycloak,vmuzikar/keycloak,didiez/keycloak,brat000012001/keycloak,arivanajoki/keycloak,raehalme/keycloak,cmoulliard/keycloak,didiez/keycloak,anaerobic/keycloak,keycloak/keycloak,ahus1/keycloak,j-bore/keycloak,dylanplecki/keycloak,ahus1/keycloak,raehalme/keycloak,stianst/keycloak,stianst/keycloak,WebJustDevelopment/keycloak,cfsnyder/keycloak,manuel-palacio/keycloak,matzew/keycloak,mhajas/keycloak,agolPL/keycloak,agolPL/keycloak,VihreatDeGrona/keycloak,gregjones60/keycloak,ppolavar/keycloak,lennartj/keycloak,lennartj/keycloak,mhajas/keycloak,eugene-chow/keycloak,ewjmulder/keycloak,almighty/keycloak,pfiled/keycloak,agolPL/keycloak,VihreatDeGrona/keycloak,dbarentine/keycloak,pfiled/keycloak,raehalme/keycloak,almighty/keycloak,jpkrohling/keycloak,abstractj/keycloak,AOEpeople/keycloak,chameleon82/keycloak,ssilvert/keycloak,keycloak/keycloak,brat000012001/keycloak,mhajas/keycloak,manuel-palacio/keycloak,vmuzikar/keycloak,thomasdarimont/keycloak,almighty/keycloak,pedroigor/keycloak,matzew/keycloak,anaerobic/keycloak,vmuzikar/keycloak,mposolda/keycloak,iperdomo/keycloak,darranl/keycloak,grange74/keycloak,lkubik/keycloak,didiez/keycloak,ahus1/keycloak,arivanajoki/keycloak,cmoulliard/keycloak,ppolavar/keycloak,raehalme/keycloak,ewjmulder/keycloak,AOEpeople/keycloak,hmlnarik/keycloak,VihreatDeGrona/keycloak,WebJustDevelopment/keycloak,srose/keycloak,abstractj/keycloak,pedroigor/keycloak,reneploetz/keycloak,jpkrohling/keycloak,thomasdarimont/keycloak,srose/keycloak,WebJustDevelopment/keycloak,chameleon82/keycloak,wildfly-security-incubator/keycloak,AOEpeople/keycloak,reneploetz/keycloak,raehalme/keycloak,pedroigor/keycloak,abstractj/keycloak,iperdomo/keycloak,jpkrohling/keycloak,gregjones60/keycloak,darranl/keycloak,arivanajoki/keycloak
package org.keycloak.services.models.picketlink; import org.bouncycastle.openssl.PEMWriter; import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.security.PemUtils; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.models.KeycloakSession; import org.keycloak.services.models.RealmModel; import org.keycloak.services.models.RequiredCredentialModel; import org.keycloak.services.models.ApplicationModel; import org.keycloak.services.models.RoleModel; import org.keycloak.services.models.SocialLinkModel; import org.keycloak.services.models.UserCredentialModel; import org.keycloak.services.models.UserModel; import org.keycloak.services.models.picketlink.mappings.RealmData; import org.keycloak.services.models.picketlink.mappings.ApplicationData; import org.keycloak.services.models.picketlink.relationships.*; import org.keycloak.services.models.picketlink.relationships.RequiredApplicationCredentialRelationship; import org.picketlink.idm.IdentityManager; import org.picketlink.idm.PartitionManager; import org.picketlink.idm.RelationshipManager; import org.picketlink.idm.credential.Credentials; import org.picketlink.idm.credential.Password; import org.picketlink.idm.credential.TOTPCredential; import org.picketlink.idm.credential.TOTPCredentials; import org.picketlink.idm.credential.UsernamePasswordCredentials; import org.picketlink.idm.credential.X509CertificateCredentials; import org.picketlink.idm.model.IdentityType; import org.picketlink.idm.model.sample.Grant; import org.picketlink.idm.model.sample.Role; import org.picketlink.idm.model.sample.SampleModel; import org.picketlink.idm.model.sample.User; import org.picketlink.idm.query.IdentityQuery; import org.picketlink.idm.query.RelationshipQuery; import java.io.IOException; import java.io.StringWriter; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Meant to be a per-request object * * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class RealmAdapter implements RealmModel { protected static final Logger logger = Logger.getLogger(RealmManager.class); protected RealmData realm; protected volatile transient PublicKey publicKey; protected volatile transient PrivateKey privateKey; protected IdentityManager idm; protected PartitionManager partitionManager; protected RelationshipManager relationshipManager; protected KeycloakSession session; public RealmAdapter(KeycloakSession session, RealmData realm, PartitionManager partitionManager) { this.session = session; this.realm = realm; this.partitionManager = partitionManager; } protected IdentityManager getIdm() { if (idm == null) idm = partitionManager.createIdentityManager(realm); return idm; } protected RelationshipManager getRelationshipManager() { if (relationshipManager == null) relationshipManager = partitionManager.createRelationshipManager(); return relationshipManager; } protected void updateRealm() { partitionManager.update(realm); } @Override public String getId() { // for some reason picketlink queries by name when finding partition, don't know what ID is used for now return realm.getName(); } @Override public String getName() { return realm.getRealmName(); } @Override public void setName(String name) { realm.setRealmName(name); updateRealm(); } @Override public boolean isEnabled() { return realm.isEnabled(); } @Override public void setEnabled(boolean enabled) { realm.setEnabled(enabled); updateRealm(); } @Override public boolean isSocial() { return realm.isSocial(); } @Override public void setSocial(boolean social) { realm.setSocial(social); updateRealm(); } @Override public boolean isAutomaticRegistrationAfterSocialLogin() { return realm.isAutomaticRegistrationAfterSocialLogin(); } @Override public void setAutomaticRegistrationAfterSocialLogin(boolean automaticRegistrationAfterSocialLogin) { realm.setAutomaticRegistrationAfterSocialLogin(automaticRegistrationAfterSocialLogin); updateRealm(); } @Override public boolean isSslNotRequired() { return realm.isSslNotRequired(); } @Override public void setSslNotRequired(boolean sslNotRequired) { realm.setSslNotRequired(sslNotRequired); updateRealm(); } @Override public boolean isCookieLoginAllowed() { return realm.isCookieLoginAllowed(); } @Override public void setCookieLoginAllowed(boolean cookieLoginAllowed) { realm.setCookieLoginAllowed(cookieLoginAllowed); updateRealm(); } @Override public boolean isRegistrationAllowed() { return realm.isRegistrationAllowed(); } @Override public void setRegistrationAllowed(boolean registrationAllowed) { realm.setRegistrationAllowed(registrationAllowed); updateRealm(); } @Override public boolean isVerifyEmail() { return realm.isVerifyEmail(); } @Override public void setVerifyEmail(boolean verifyEmail) { realm.setVerifyEmail(verifyEmail); updateRealm(); } @Override public boolean isResetPasswordAllowed() { return realm.isResetPasswordAllowed(); } @Override public void setResetPasswordAllowed(boolean resetPassword) { realm.setResetPasswordAllowed(resetPassword); updateRealm(); } @Override public int getTokenLifespan() { return realm.getTokenLifespan(); } @Override public void setTokenLifespan(int tokenLifespan) { realm.setTokenLifespan(tokenLifespan); updateRealm(); } @Override public int getAccessCodeLifespan() { return realm.getAccessCodeLifespan(); } @Override public void setAccessCodeLifespan(int accessCodeLifespan) { realm.setAccessCodeLifespan(accessCodeLifespan); updateRealm(); } @Override public int getAccessCodeLifespanUserAction() { return realm.getAccessCodeLifespanUserAction(); } @Override public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { realm.setAccessCodeLifespanUserAction(accessCodeLifespanUserAction); updateRealm(); } @Override public String getPublicKeyPem() { return realm.getPublicKeyPem(); } @Override public void setPublicKeyPem(String publicKeyPem) { realm.setPublicKeyPem(publicKeyPem); this.publicKey = null; updateRealm(); } @Override public String getPrivateKeyPem() { return realm.getPrivateKeyPem(); } @Override public void setPrivateKeyPem(String privateKeyPem) { realm.setPrivateKeyPem(privateKeyPem); this.privateKey = null; updateRealm(); } @Override public PublicKey getPublicKey() { if (publicKey != null) return publicKey; String pem = getPublicKeyPem(); if (pem != null) { try { publicKey = PemUtils.decodePublicKey(pem); } catch (Exception e) { throw new RuntimeException(e); } } return publicKey; } @Override public void setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(publicKey); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); setPublicKeyPem(PemUtils.removeBeginEnd(s)); } @Override public PrivateKey getPrivateKey() { if (privateKey != null) return privateKey; String pem = getPrivateKeyPem(); if (pem != null) { try { privateKey = PemUtils.decodePrivateKey(pem); } catch (Exception e) { throw new RuntimeException(e); } } return privateKey; } @Override public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(privateKey); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); setPrivateKeyPem(PemUtils.removeBeginEnd(s)); } @Override public List<RequiredCredentialModel> getRequiredCredentials() { List<RequiredCredentialRelationship> results = getRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<RequiredCredentialRelationship> getRequiredCredentialRelationships() { RelationshipQuery<RequiredCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(RequiredCredentialRelationship.class); query.setParameter(RequiredCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredApplicationCredential(RequiredCredentialModel cred) { RequiredApplicationCredentialRelationship relationship = new RequiredApplicationCredentialRelationship(); addRequiredCredential(cred, relationship); } @Override public List<RequiredCredentialModel> getRequiredApplicationCredentials() { List<RequiredApplicationCredentialRelationship> results = getResourceRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<RequiredApplicationCredentialRelationship> getResourceRequiredCredentialRelationships() { RelationshipQuery<RequiredApplicationCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(RequiredApplicationCredentialRelationship.class); query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredOAuthClientCredential(RequiredCredentialModel cred) { OAuthClientRequiredCredentialRelationship relationship = new OAuthClientRequiredCredentialRelationship(); addRequiredCredential(cred, relationship); } @Override public List<RequiredCredentialModel> getRequiredOAuthClientCredentials() { List<OAuthClientRequiredCredentialRelationship> results = getOAuthClientRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<OAuthClientRequiredCredentialRelationship> getOAuthClientRequiredCredentialRelationships() { RelationshipQuery<OAuthClientRequiredCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(OAuthClientRequiredCredentialRelationship.class); query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredCredential(RequiredCredentialModel cred) { RequiredCredentialRelationship relationship = new RequiredCredentialRelationship(); addRequiredCredential(cred, relationship); } protected List<RequiredCredentialModel> getRequiredCredentialModels(List<? extends RequiredCredentialRelationship> results) { List<RequiredCredentialModel> rtn = new ArrayList<RequiredCredentialModel>(); for (RequiredCredentialRelationship relationship : results) { RequiredCredentialModel model = new RequiredCredentialModel(); model.setInput(relationship.isInput()); model.setSecret(relationship.isSecret()); model.setType(relationship.getCredentialType()); model.setFormLabel(relationship.getFormLabel()); rtn.add(model); } return rtn; } protected void addRequiredCredential(RequiredCredentialModel cred, RequiredCredentialRelationship relationship) { relationship.setCredentialType(cred.getType()); relationship.setInput(cred.isInput()); relationship.setSecret(cred.isSecret()); relationship.setRealm(realm.getName()); relationship.setFormLabel(cred.getFormLabel()); getRelationshipManager().add(relationship); } @Override public void updateRequiredCredentials(Set<String> creds) { List<RequiredCredentialRelationship> relationships = getRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { logger.info("updating cred: " + cred); if (!already.contains(cred)) { addRequiredCredential(cred); } } } @Override public void updateRequiredOAuthClientCredentials(Set<String> creds) { List<OAuthClientRequiredCredentialRelationship> relationships = getOAuthClientRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { if (!already.contains(cred)) { addRequiredOAuthClientCredential(cred); } } } @Override public void updateRequiredApplicationCredentials(Set<String> creds) { List<RequiredApplicationCredentialRelationship> relationships = getResourceRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { if (!already.contains(cred)) { addRequiredResourceCredential(cred); } } } @Override public void addRequiredCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredCredential(model); } @Override public void addRequiredOAuthClientCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredOAuthClientCredential(model); } @Override public void addRequiredResourceCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredApplicationCredential(model); } protected RequiredCredentialModel initRequiredCredentialModel(String type) { RequiredCredentialModel model = RequiredCredentialModel.BUILT_IN.get(type); if (model == null) { throw new RuntimeException("Unknown credential type " + type); } return model; } @Override public boolean validatePassword(UserModel user, String password) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getLoginName(), new Password(password)); getIdm().validateCredentials(creds); return creds.getStatus() == Credentials.Status.VALID; } @Override public boolean validateTOTP(UserModel user, String password, String token) { TOTPCredentials creds = new TOTPCredentials(); creds.setToken(token); creds.setUsername(user.getLoginName()); creds.setPassword(new Password(password)); getIdm().validateCredentials(creds); return creds.getStatus() == Credentials.Status.VALID; } @Override public void updateCredential(UserModel user, UserCredentialModel cred) { IdentityManager idm = getIdm(); if (cred.getType().equals(CredentialRepresentation.PASSWORD)) { Password password = new Password(cred.getValue()); idm.updateCredential(((UserAdapter)user).getUser(), password); } else if (cred.getType().equals(CredentialRepresentation.TOTP)) { TOTPCredential totp = new TOTPCredential(cred.getValue()); totp.setDevice(cred.getDevice()); idm.updateCredential(((UserAdapter)user).getUser(), totp); } else if (cred.getType().equals(CredentialRepresentation.CLIENT_CERT)) { X509Certificate cert = null; try { cert = org.keycloak.PemUtils.decodeCertificate(cred.getValue()); } catch (Exception e) { throw new RuntimeException(e); } X509CertificateCredentials creds = new X509CertificateCredentials(cert); idm.updateCredential(((UserAdapter)user).getUser(), creds); } } @Override public UserAdapter getUser(String name) { User user = findPicketlinkUser(name); if (user == null) return null; return new UserAdapter(user, getIdm()); } protected User findPicketlinkUser(String name) { return SampleModel.getUser(getIdm(), name); } @Override public UserAdapter addUser(String username) { User user = findPicketlinkUser(username); if (user != null) throw new IllegalStateException("User already exists"); user = new User(username); getIdm().add(user); return new UserAdapter(user, getIdm()); } @Override public RoleAdapter getRole(String name) { Role role = SampleModel.getRole(getIdm(), name); if (role == null) return null; return new RoleAdapter(role, getIdm()); } @Override public RoleModel getRoleById(String id) { IdentityQuery<Role> query = getIdm().createIdentityQuery(Role.class); query.setParameter(IdentityType.ID, id); List<Role> roles = query.getResultList(); if (roles.size() == 0) return null; return new RoleAdapter(roles.get(0), getIdm()); } @Override public RoleAdapter addRole(String name) { Role role = new Role(name); getIdm().add(role); return new RoleAdapter(role, getIdm()); } @Override public List<RoleModel> getRoles() { IdentityManager idm = getIdm(); IdentityQuery<Role> query = idm.createIdentityQuery(Role.class); query.setParameter(Role.PARTITION, realm); List<Role> roles = query.getResultList(); List<RoleModel> roleModels = new ArrayList<RoleModel>(); for (Role role : roles) { roleModels.add(new RoleAdapter(role, idm)); } return roleModels; } /** * Key name, value resource * * @return */ @Override public Map<String, ApplicationModel> getResourceNameMap() { Map<String, ApplicationModel> resourceMap = new HashMap<String, ApplicationModel>(); for (ApplicationModel resource : getApplications()) { resourceMap.put(resource.getName(), resource); } return resourceMap; } /** * Makes sure that the resource returned is owned by the realm * * @return */ @Override public ApplicationModel getApplicationById(String id) { RelationshipQuery<ResourceRelationship> query = getRelationshipManager().createRelationshipQuery(ResourceRelationship.class); query.setParameter(ResourceRelationship.REALM, realm.getName()); query.setParameter(ResourceRelationship.RESOURCE, id); List<ResourceRelationship> results = query.getResultList(); if (results.size() == 0) return null; ApplicationData resource = partitionManager.getPartition(ApplicationData.class, id); ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); return model; } @Override public List<ApplicationModel> getApplications() { RelationshipQuery<ResourceRelationship> query = getRelationshipManager().createRelationshipQuery(ResourceRelationship.class); query.setParameter(ResourceRelationship.REALM, realm.getName()); List<ResourceRelationship> results = query.getResultList(); List<ApplicationModel> resources = new ArrayList<ApplicationModel>(); for (ResourceRelationship relationship : results) { ApplicationData resource = partitionManager.getPartition(ApplicationData.class, relationship.getResource()); ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); resources.add(model); } return resources; } @Override public ApplicationModel addApplication(String name) { ApplicationData applicationData = new ApplicationData(RealmManager.generateId()); User resourceUser = new User(name); idm.add(resourceUser); applicationData.setResourceUser(resourceUser); applicationData.setResourceName(name); applicationData.setResourceUser(resourceUser); partitionManager.add(applicationData); ResourceRelationship resourceRelationship = new ResourceRelationship(); resourceRelationship.setRealm(realm.getName()); resourceRelationship.setResource(applicationData.getName()); getRelationshipManager().add(resourceRelationship); ApplicationModel resource = new ApplicationAdapter(applicationData, this, partitionManager); resource.addRole("*"); resource.addScope(new UserAdapter(resourceUser, idm), "*"); return resource; } @Override public boolean hasRole(UserModel user, RoleModel role) { return SampleModel.hasRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); } @Override public boolean hasRole(UserModel user, String role) { RoleModel roleModel = getRole(role); return hasRole(user, roleModel); } @Override public void grantRole(UserModel user, RoleModel role) { SampleModel.grantRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); } @Override public void deleteRoleMapping(UserModel user, RoleModel role) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); query.setParameter(Grant.ROLE, ((RoleAdapter)role).getRole()); List<Grant> grants = query.getResultList(); for (Grant grant : grants) { getRelationshipManager().remove(grant); } } @Override public Set<String> getRoleMappingValues(UserModel user) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); List<Grant> grants = query.getResultList(); HashSet<String> set = new HashSet<String>(); for (Grant grant : grants) { if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(grant.getRole().getName()); } return set; } @Override public List<RoleModel> getRoleMappings(UserModel user) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); List<Grant> grants = query.getResultList(); List<RoleModel> set = new ArrayList<RoleModel>(); for (Grant grant : grants) { if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(new RoleAdapter(grant.getRole(), getIdm())); } return set; } @Override public void addScope(UserModel agent, String roleName) { IdentityManager idm = getIdm(); Role role = SampleModel.getRole(idm, roleName); if (role == null) throw new RuntimeException("role not found"); ScopeRelationship scope = new ScopeRelationship(); scope.setClient(((UserAdapter)agent).getUser()); scope.setScope(role); getRelationshipManager().add(scope); } @Override public Set<String> getScope(UserModel agent) { RelationshipQuery<ScopeRelationship> query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); List<ScopeRelationship> scope = query.getResultList(); HashSet<String> set = new HashSet<String>(); for (ScopeRelationship rel : scope) { if (rel.getScope().getPartition().getId().equals(realm.getId())) set.add(rel.getScope().getName()); } return set; } @Override public boolean isRealmAdmin(UserModel agent) { RealmAdapter realmModel = (RealmAdapter)new RealmManager(session).defaultRealm(); RelationshipQuery<RealmAdminRelationship> query = getRelationshipManager().createRelationshipQuery(RealmAdminRelationship.class); query.setParameter(RealmAdminRelationship.REALM, realm.getName()); query.setParameter(RealmAdminRelationship.ADMIN, ((UserAdapter)agent).getUser()); List<RealmAdminRelationship> results = query.getResultList(); return results.size() > 0; } @Override public void addRealmAdmin(UserModel agent) { RealmAdminRelationship relationship = new RealmAdminRelationship(); relationship.setAdmin(((UserAdapter)agent).getUser()); relationship.setRealm(realm.getName()); getRelationshipManager().add(relationship); } @Override public List<RoleModel> getDefaultRoles() { List<RoleModel> defaultRoleModels = new ArrayList<RoleModel>(); if (realm.getDefaultRoles() != null) { for (String name : realm.getDefaultRoles()) { RoleAdapter role = getRole(name); if (role != null) { defaultRoleModels.add(role); } } } return defaultRoleModels; } @Override public void addDefaultRole(String name) { if (getRole(name) == null) { addRole(name); } String[] defaultRoles = realm.getDefaultRoles(); if (defaultRoles == null) { defaultRoles = new String[1]; } else { defaultRoles = Arrays.copyOf(defaultRoles, defaultRoles.length + 1); } defaultRoles[defaultRoles.length - 1] = name; realm.setDefaultRoles(defaultRoles); updateRealm(); } @Override public void updateDefaultRoles(String[] defaultRoles) { for (String name : defaultRoles) { if (getRole(name) == null) { addRole(name); } } realm.setDefaultRoles(defaultRoles); updateRealm(); } @Override public UserModel getUserBySocialLink(SocialLinkModel socialLink) { RelationshipQuery<SocialLinkRelationship> query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); query.setParameter(SocialLinkRelationship.SOCIAL_PROVIDER, socialLink.getSocialProvider()); query.setParameter(SocialLinkRelationship.SOCIAL_USERNAME, socialLink.getSocialUsername()); List<SocialLinkRelationship> results = query.getResultList(); if (results.isEmpty()) { return null; } else if (results.size() > 1) { throw new IllegalStateException("More results found for socialProvider=" + socialLink.getSocialProvider() + ", socialUsername=" + socialLink.getSocialUsername() + ", results=" + results); } else { User user = results.get(0).getUser(); return new UserAdapter(user, getIdm()); } } @Override public Set<SocialLinkModel> getSocialLinks(UserModel user) { RelationshipQuery<SocialLinkRelationship> query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); query.setParameter(SocialLinkRelationship.USER, ((UserAdapter)user).getUser()); List<SocialLinkRelationship> plSocialLinks = query.getResultList(); Set<SocialLinkModel> results = new HashSet<SocialLinkModel>(); for (SocialLinkRelationship relationship : plSocialLinks) { results.add(new SocialLinkModel(relationship.getSocialProvider(), relationship.getSocialUsername())); } return results; } @Override public void addSocialLink(UserModel user, SocialLinkModel socialLink) { SocialLinkRelationship relationship = new SocialLinkRelationship(); relationship.setUser(((UserAdapter)user).getUser()); relationship.setSocialProvider(socialLink.getSocialProvider()); relationship.setSocialUsername(socialLink.getSocialUsername()); getRelationshipManager().add(relationship); } @Override public void removeSocialLink(UserModel user, SocialLinkModel socialLink) { SocialLinkRelationship relationship = new SocialLinkRelationship(); relationship.setUser(((UserAdapter)user).getUser()); relationship.setSocialProvider(socialLink.getSocialProvider()); relationship.setSocialUsername(socialLink.getSocialUsername()); getRelationshipManager().remove(relationship); } @Override public List<UserModel> searchForUserByAttributes(Map<String, String> attributes) { IdentityQuery<User> query = getIdm().createIdentityQuery(User.class); for (Map.Entry<String, String> entry : attributes.entrySet()) { if (entry.getKey().equals(UserModel.LOGIN_NAME)) { query.setParameter(User.LOGIN_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) { query.setParameter(User.FIRST_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) { query.setParameter(User.LAST_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) { query.setParameter(User.EMAIL, entry.getValue()); } } List<User> users = query.getResultList(); List<UserModel> userModels = new ArrayList<UserModel>(); for (User user : users) { userModels.add(new UserAdapter(user, idm)); } return userModels; } }
services/src/main/java/org/keycloak/services/models/picketlink/RealmAdapter.java
package org.keycloak.services.models.picketlink; import org.bouncycastle.openssl.PEMWriter; import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.security.PemUtils; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.models.KeycloakSession; import org.keycloak.services.models.RealmModel; import org.keycloak.services.models.RequiredCredentialModel; import org.keycloak.services.models.ApplicationModel; import org.keycloak.services.models.RoleModel; import org.keycloak.services.models.SocialLinkModel; import org.keycloak.services.models.UserCredentialModel; import org.keycloak.services.models.UserModel; import org.keycloak.services.models.picketlink.mappings.RealmData; import org.keycloak.services.models.picketlink.mappings.ApplicationData; import org.keycloak.services.models.picketlink.relationships.*; import org.keycloak.services.models.picketlink.relationships.RequiredApplicationCredentialRelationship; import org.picketlink.idm.IdentityManager; import org.picketlink.idm.PartitionManager; import org.picketlink.idm.RelationshipManager; import org.picketlink.idm.credential.Credentials; import org.picketlink.idm.credential.Password; import org.picketlink.idm.credential.TOTPCredential; import org.picketlink.idm.credential.TOTPCredentials; import org.picketlink.idm.credential.UsernamePasswordCredentials; import org.picketlink.idm.credential.X509CertificateCredentials; import org.picketlink.idm.model.IdentityType; import org.picketlink.idm.model.sample.Grant; import org.picketlink.idm.model.sample.Role; import org.picketlink.idm.model.sample.SampleModel; import org.picketlink.idm.model.sample.User; import org.picketlink.idm.query.IdentityQuery; import org.picketlink.idm.query.RelationshipQuery; import java.io.IOException; import java.io.StringWriter; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Meant to be a per-request object * * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class RealmAdapter implements RealmModel { protected static final Logger logger = Logger.getLogger(RealmManager.class); protected RealmData realm; protected volatile transient PublicKey publicKey; protected volatile transient PrivateKey privateKey; protected IdentityManager idm; protected PartitionManager partitionManager; protected RelationshipManager relationshipManager; protected KeycloakSession session; public RealmAdapter(KeycloakSession session, RealmData realm, PartitionManager partitionManager) { this.session = session; this.realm = realm; this.partitionManager = partitionManager; } protected IdentityManager getIdm() { if (idm == null) idm = partitionManager.createIdentityManager(realm); return idm; } protected RelationshipManager getRelationshipManager() { if (relationshipManager == null) relationshipManager = partitionManager.createRelationshipManager(); return relationshipManager; } protected void updateRealm() { partitionManager.update(realm); } @Override public String getId() { // for some reason picketlink queries by name when finding partition, don't know what ID is used for now return realm.getName(); } @Override public String getName() { return realm.getRealmName(); } @Override public void setName(String name) { realm.setRealmName(name); updateRealm(); } @Override public boolean isEnabled() { return realm.isEnabled(); } @Override public void setEnabled(boolean enabled) { realm.setEnabled(enabled); updateRealm(); } @Override public boolean isSocial() { return realm.isSocial(); } @Override public void setSocial(boolean social) { realm.setSocial(social); } @Override public boolean isAutomaticRegistrationAfterSocialLogin() { return realm.isAutomaticRegistrationAfterSocialLogin(); } @Override public void setAutomaticRegistrationAfterSocialLogin(boolean automaticRegistrationAfterSocialLogin) { realm.setAutomaticRegistrationAfterSocialLogin(automaticRegistrationAfterSocialLogin); updateRealm(); } @Override public boolean isSslNotRequired() { return realm.isSslNotRequired(); } @Override public void setSslNotRequired(boolean sslNotRequired) { realm.setSslNotRequired(sslNotRequired); updateRealm(); } @Override public boolean isCookieLoginAllowed() { return realm.isCookieLoginAllowed(); } @Override public void setCookieLoginAllowed(boolean cookieLoginAllowed) { realm.setCookieLoginAllowed(cookieLoginAllowed); updateRealm(); } @Override public boolean isRegistrationAllowed() { return realm.isRegistrationAllowed(); } @Override public void setRegistrationAllowed(boolean registrationAllowed) { realm.setRegistrationAllowed(registrationAllowed); updateRealm(); } @Override public boolean isVerifyEmail() { return realm.isVerifyEmail(); } @Override public void setVerifyEmail(boolean verifyEmail) { realm.setVerifyEmail(verifyEmail); updateRealm(); } @Override public boolean isResetPasswordAllowed() { return realm.isResetPasswordAllowed(); } @Override public void setResetPasswordAllowed(boolean resetPassword) { realm.setResetPasswordAllowed(resetPassword); updateRealm(); } @Override public int getTokenLifespan() { return realm.getTokenLifespan(); } @Override public void setTokenLifespan(int tokenLifespan) { realm.setTokenLifespan(tokenLifespan); updateRealm(); } @Override public int getAccessCodeLifespan() { return realm.getAccessCodeLifespan(); } @Override public void setAccessCodeLifespan(int accessCodeLifespan) { realm.setAccessCodeLifespan(accessCodeLifespan); updateRealm(); } @Override public int getAccessCodeLifespanUserAction() { return realm.getAccessCodeLifespanUserAction(); } @Override public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { realm.setAccessCodeLifespanUserAction(accessCodeLifespanUserAction); updateRealm(); } @Override public String getPublicKeyPem() { return realm.getPublicKeyPem(); } @Override public void setPublicKeyPem(String publicKeyPem) { realm.setPublicKeyPem(publicKeyPem); this.publicKey = null; updateRealm(); } @Override public String getPrivateKeyPem() { return realm.getPrivateKeyPem(); } @Override public void setPrivateKeyPem(String privateKeyPem) { realm.setPrivateKeyPem(privateKeyPem); this.privateKey = null; updateRealm(); } @Override public PublicKey getPublicKey() { if (publicKey != null) return publicKey; String pem = getPublicKeyPem(); if (pem != null) { try { publicKey = PemUtils.decodePublicKey(pem); } catch (Exception e) { throw new RuntimeException(e); } } return publicKey; } @Override public void setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(publicKey); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); setPublicKeyPem(PemUtils.removeBeginEnd(s)); } @Override public PrivateKey getPrivateKey() { if (privateKey != null) return privateKey; String pem = getPrivateKeyPem(); if (pem != null) { try { privateKey = PemUtils.decodePrivateKey(pem); } catch (Exception e) { throw new RuntimeException(e); } } return privateKey; } @Override public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; StringWriter writer = new StringWriter(); PEMWriter pemWriter = new PEMWriter(writer); try { pemWriter.writeObject(privateKey); pemWriter.flush(); } catch (IOException e) { throw new RuntimeException(e); } String s = writer.toString(); setPrivateKeyPem(PemUtils.removeBeginEnd(s)); } @Override public List<RequiredCredentialModel> getRequiredCredentials() { List<RequiredCredentialRelationship> results = getRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<RequiredCredentialRelationship> getRequiredCredentialRelationships() { RelationshipQuery<RequiredCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(RequiredCredentialRelationship.class); query.setParameter(RequiredCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredApplicationCredential(RequiredCredentialModel cred) { RequiredApplicationCredentialRelationship relationship = new RequiredApplicationCredentialRelationship(); addRequiredCredential(cred, relationship); } @Override public List<RequiredCredentialModel> getRequiredApplicationCredentials() { List<RequiredApplicationCredentialRelationship> results = getResourceRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<RequiredApplicationCredentialRelationship> getResourceRequiredCredentialRelationships() { RelationshipQuery<RequiredApplicationCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(RequiredApplicationCredentialRelationship.class); query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredOAuthClientCredential(RequiredCredentialModel cred) { OAuthClientRequiredCredentialRelationship relationship = new OAuthClientRequiredCredentialRelationship(); addRequiredCredential(cred, relationship); } @Override public List<RequiredCredentialModel> getRequiredOAuthClientCredentials() { List<OAuthClientRequiredCredentialRelationship> results = getOAuthClientRequiredCredentialRelationships(); return getRequiredCredentialModels(results); } protected List<OAuthClientRequiredCredentialRelationship> getOAuthClientRequiredCredentialRelationships() { RelationshipQuery<OAuthClientRequiredCredentialRelationship> query = getRelationshipManager().createRelationshipQuery(OAuthClientRequiredCredentialRelationship.class); query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); return query.getResultList(); } public void addRequiredCredential(RequiredCredentialModel cred) { RequiredCredentialRelationship relationship = new RequiredCredentialRelationship(); addRequiredCredential(cred, relationship); } protected List<RequiredCredentialModel> getRequiredCredentialModels(List<? extends RequiredCredentialRelationship> results) { List<RequiredCredentialModel> rtn = new ArrayList<RequiredCredentialModel>(); for (RequiredCredentialRelationship relationship : results) { RequiredCredentialModel model = new RequiredCredentialModel(); model.setInput(relationship.isInput()); model.setSecret(relationship.isSecret()); model.setType(relationship.getCredentialType()); model.setFormLabel(relationship.getFormLabel()); rtn.add(model); } return rtn; } protected void addRequiredCredential(RequiredCredentialModel cred, RequiredCredentialRelationship relationship) { relationship.setCredentialType(cred.getType()); relationship.setInput(cred.isInput()); relationship.setSecret(cred.isSecret()); relationship.setRealm(realm.getName()); relationship.setFormLabel(cred.getFormLabel()); getRelationshipManager().add(relationship); } @Override public void updateRequiredCredentials(Set<String> creds) { List<RequiredCredentialRelationship> relationships = getRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { logger.info("updating cred: " + cred); if (!already.contains(cred)) { addRequiredCredential(cred); } } } @Override public void updateRequiredOAuthClientCredentials(Set<String> creds) { List<OAuthClientRequiredCredentialRelationship> relationships = getOAuthClientRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { if (!already.contains(cred)) { addRequiredOAuthClientCredential(cred); } } } @Override public void updateRequiredApplicationCredentials(Set<String> creds) { List<RequiredApplicationCredentialRelationship> relationships = getResourceRequiredCredentialRelationships(); RelationshipManager rm = getRelationshipManager(); Set<String> already = new HashSet<String>(); for (RequiredCredentialRelationship rel : relationships) { if (!creds.contains(rel.getCredentialType())) { rm.remove(rel); } else { already.add(rel.getCredentialType()); } } for (String cred : creds) { if (!already.contains(cred)) { addRequiredResourceCredential(cred); } } } @Override public void addRequiredCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredCredential(model); } @Override public void addRequiredOAuthClientCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredOAuthClientCredential(model); } @Override public void addRequiredResourceCredential(String type) { RequiredCredentialModel model = initRequiredCredentialModel(type); addRequiredApplicationCredential(model); } protected RequiredCredentialModel initRequiredCredentialModel(String type) { RequiredCredentialModel model = RequiredCredentialModel.BUILT_IN.get(type); if (model == null) { throw new RuntimeException("Unknown credential type " + type); } return model; } @Override public boolean validatePassword(UserModel user, String password) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getLoginName(), new Password(password)); getIdm().validateCredentials(creds); return creds.getStatus() == Credentials.Status.VALID; } @Override public boolean validateTOTP(UserModel user, String password, String token) { TOTPCredentials creds = new TOTPCredentials(); creds.setToken(token); creds.setUsername(user.getLoginName()); creds.setPassword(new Password(password)); getIdm().validateCredentials(creds); return creds.getStatus() == Credentials.Status.VALID; } @Override public void updateCredential(UserModel user, UserCredentialModel cred) { IdentityManager idm = getIdm(); if (cred.getType().equals(CredentialRepresentation.PASSWORD)) { Password password = new Password(cred.getValue()); idm.updateCredential(((UserAdapter)user).getUser(), password); } else if (cred.getType().equals(CredentialRepresentation.TOTP)) { TOTPCredential totp = new TOTPCredential(cred.getValue()); totp.setDevice(cred.getDevice()); idm.updateCredential(((UserAdapter)user).getUser(), totp); } else if (cred.getType().equals(CredentialRepresentation.CLIENT_CERT)) { X509Certificate cert = null; try { cert = org.keycloak.PemUtils.decodeCertificate(cred.getValue()); } catch (Exception e) { throw new RuntimeException(e); } X509CertificateCredentials creds = new X509CertificateCredentials(cert); idm.updateCredential(((UserAdapter)user).getUser(), creds); } } @Override public UserAdapter getUser(String name) { User user = findPicketlinkUser(name); if (user == null) return null; return new UserAdapter(user, getIdm()); } protected User findPicketlinkUser(String name) { return SampleModel.getUser(getIdm(), name); } @Override public UserAdapter addUser(String username) { User user = findPicketlinkUser(username); if (user != null) throw new IllegalStateException("User already exists"); user = new User(username); getIdm().add(user); return new UserAdapter(user, getIdm()); } @Override public RoleAdapter getRole(String name) { Role role = SampleModel.getRole(getIdm(), name); if (role == null) return null; return new RoleAdapter(role, getIdm()); } @Override public RoleModel getRoleById(String id) { IdentityQuery<Role> query = getIdm().createIdentityQuery(Role.class); query.setParameter(IdentityType.ID, id); List<Role> roles = query.getResultList(); if (roles.size() == 0) return null; return new RoleAdapter(roles.get(0), getIdm()); } @Override public RoleAdapter addRole(String name) { Role role = new Role(name); getIdm().add(role); return new RoleAdapter(role, getIdm()); } @Override public List<RoleModel> getRoles() { IdentityManager idm = getIdm(); IdentityQuery<Role> query = idm.createIdentityQuery(Role.class); query.setParameter(Role.PARTITION, realm); List<Role> roles = query.getResultList(); List<RoleModel> roleModels = new ArrayList<RoleModel>(); for (Role role : roles) { roleModels.add(new RoleAdapter(role, idm)); } return roleModels; } /** * Key name, value resource * * @return */ @Override public Map<String, ApplicationModel> getResourceNameMap() { Map<String, ApplicationModel> resourceMap = new HashMap<String, ApplicationModel>(); for (ApplicationModel resource : getApplications()) { resourceMap.put(resource.getName(), resource); } return resourceMap; } /** * Makes sure that the resource returned is owned by the realm * * @return */ @Override public ApplicationModel getApplicationById(String id) { RelationshipQuery<ResourceRelationship> query = getRelationshipManager().createRelationshipQuery(ResourceRelationship.class); query.setParameter(ResourceRelationship.REALM, realm.getName()); query.setParameter(ResourceRelationship.RESOURCE, id); List<ResourceRelationship> results = query.getResultList(); if (results.size() == 0) return null; ApplicationData resource = partitionManager.getPartition(ApplicationData.class, id); ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); return model; } @Override public List<ApplicationModel> getApplications() { RelationshipQuery<ResourceRelationship> query = getRelationshipManager().createRelationshipQuery(ResourceRelationship.class); query.setParameter(ResourceRelationship.REALM, realm.getName()); List<ResourceRelationship> results = query.getResultList(); List<ApplicationModel> resources = new ArrayList<ApplicationModel>(); for (ResourceRelationship relationship : results) { ApplicationData resource = partitionManager.getPartition(ApplicationData.class, relationship.getResource()); ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); resources.add(model); } return resources; } @Override public ApplicationModel addApplication(String name) { ApplicationData applicationData = new ApplicationData(RealmManager.generateId()); User resourceUser = new User(name); idm.add(resourceUser); applicationData.setResourceUser(resourceUser); applicationData.setResourceName(name); applicationData.setResourceUser(resourceUser); partitionManager.add(applicationData); ResourceRelationship resourceRelationship = new ResourceRelationship(); resourceRelationship.setRealm(realm.getName()); resourceRelationship.setResource(applicationData.getName()); getRelationshipManager().add(resourceRelationship); ApplicationModel resource = new ApplicationAdapter(applicationData, this, partitionManager); resource.addRole("*"); resource.addScope(new UserAdapter(resourceUser, idm), "*"); return resource; } @Override public boolean hasRole(UserModel user, RoleModel role) { return SampleModel.hasRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); } @Override public boolean hasRole(UserModel user, String role) { RoleModel roleModel = getRole(role); return hasRole(user, roleModel); } @Override public void grantRole(UserModel user, RoleModel role) { SampleModel.grantRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); } @Override public void deleteRoleMapping(UserModel user, RoleModel role) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); query.setParameter(Grant.ROLE, ((RoleAdapter)role).getRole()); List<Grant> grants = query.getResultList(); for (Grant grant : grants) { getRelationshipManager().remove(grant); } } @Override public Set<String> getRoleMappingValues(UserModel user) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); List<Grant> grants = query.getResultList(); HashSet<String> set = new HashSet<String>(); for (Grant grant : grants) { if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(grant.getRole().getName()); } return set; } @Override public List<RoleModel> getRoleMappings(UserModel user) { RelationshipQuery<Grant> query = getRelationshipManager().createRelationshipQuery(Grant.class); query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); List<Grant> grants = query.getResultList(); List<RoleModel> set = new ArrayList<RoleModel>(); for (Grant grant : grants) { if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(new RoleAdapter(grant.getRole(), getIdm())); } return set; } @Override public void addScope(UserModel agent, String roleName) { IdentityManager idm = getIdm(); Role role = SampleModel.getRole(idm, roleName); if (role == null) throw new RuntimeException("role not found"); ScopeRelationship scope = new ScopeRelationship(); scope.setClient(((UserAdapter)agent).getUser()); scope.setScope(role); getRelationshipManager().add(scope); } @Override public Set<String> getScope(UserModel agent) { RelationshipQuery<ScopeRelationship> query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); List<ScopeRelationship> scope = query.getResultList(); HashSet<String> set = new HashSet<String>(); for (ScopeRelationship rel : scope) { if (rel.getScope().getPartition().getId().equals(realm.getId())) set.add(rel.getScope().getName()); } return set; } @Override public boolean isRealmAdmin(UserModel agent) { RealmAdapter realmModel = (RealmAdapter)new RealmManager(session).defaultRealm(); RelationshipQuery<RealmAdminRelationship> query = getRelationshipManager().createRelationshipQuery(RealmAdminRelationship.class); query.setParameter(RealmAdminRelationship.REALM, realm.getName()); query.setParameter(RealmAdminRelationship.ADMIN, ((UserAdapter)agent).getUser()); List<RealmAdminRelationship> results = query.getResultList(); return results.size() > 0; } @Override public void addRealmAdmin(UserModel agent) { RealmAdminRelationship relationship = new RealmAdminRelationship(); relationship.setAdmin(((UserAdapter)agent).getUser()); relationship.setRealm(realm.getName()); getRelationshipManager().add(relationship); } @Override public List<RoleModel> getDefaultRoles() { List<RoleModel> defaultRoleModels = new ArrayList<RoleModel>(); if (realm.getDefaultRoles() != null) { for (String name : realm.getDefaultRoles()) { RoleAdapter role = getRole(name); if (role != null) { defaultRoleModels.add(role); } } } return defaultRoleModels; } @Override public void addDefaultRole(String name) { if (getRole(name) == null) { addRole(name); } String[] defaultRoles = realm.getDefaultRoles(); if (defaultRoles == null) { defaultRoles = new String[1]; } else { defaultRoles = Arrays.copyOf(defaultRoles, defaultRoles.length + 1); } defaultRoles[defaultRoles.length - 1] = name; realm.setDefaultRoles(defaultRoles); updateRealm(); } @Override public void updateDefaultRoles(String[] defaultRoles) { for (String name : defaultRoles) { if (getRole(name) == null) { addRole(name); } } realm.setDefaultRoles(defaultRoles); updateRealm(); } @Override public UserModel getUserBySocialLink(SocialLinkModel socialLink) { RelationshipQuery<SocialLinkRelationship> query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); query.setParameter(SocialLinkRelationship.SOCIAL_PROVIDER, socialLink.getSocialProvider()); query.setParameter(SocialLinkRelationship.SOCIAL_USERNAME, socialLink.getSocialUsername()); List<SocialLinkRelationship> results = query.getResultList(); if (results.isEmpty()) { return null; } else if (results.size() > 1) { throw new IllegalStateException("More results found for socialProvider=" + socialLink.getSocialProvider() + ", socialUsername=" + socialLink.getSocialUsername() + ", results=" + results); } else { User user = results.get(0).getUser(); return new UserAdapter(user, getIdm()); } } @Override public Set<SocialLinkModel> getSocialLinks(UserModel user) { RelationshipQuery<SocialLinkRelationship> query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); query.setParameter(SocialLinkRelationship.USER, ((UserAdapter)user).getUser()); List<SocialLinkRelationship> plSocialLinks = query.getResultList(); Set<SocialLinkModel> results = new HashSet<SocialLinkModel>(); for (SocialLinkRelationship relationship : plSocialLinks) { results.add(new SocialLinkModel(relationship.getSocialProvider(), relationship.getSocialUsername())); } return results; } @Override public void addSocialLink(UserModel user, SocialLinkModel socialLink) { SocialLinkRelationship relationship = new SocialLinkRelationship(); relationship.setUser(((UserAdapter)user).getUser()); relationship.setSocialProvider(socialLink.getSocialProvider()); relationship.setSocialUsername(socialLink.getSocialUsername()); getRelationshipManager().add(relationship); } @Override public void removeSocialLink(UserModel user, SocialLinkModel socialLink) { SocialLinkRelationship relationship = new SocialLinkRelationship(); relationship.setUser(((UserAdapter)user).getUser()); relationship.setSocialProvider(socialLink.getSocialProvider()); relationship.setSocialUsername(socialLink.getSocialUsername()); getRelationshipManager().remove(relationship); } @Override public List<UserModel> searchForUserByAttributes(Map<String, String> attributes) { IdentityQuery<User> query = getIdm().createIdentityQuery(User.class); for (Map.Entry<String, String> entry : attributes.entrySet()) { if (entry.getKey().equals(UserModel.LOGIN_NAME)) { query.setParameter(User.LOGIN_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) { query.setParameter(User.FIRST_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) { query.setParameter(User.LAST_NAME, entry.getValue()); } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) { query.setParameter(User.EMAIL, entry.getValue()); } } List<User> users = query.getResultList(); List<UserModel> userModels = new ArrayList<UserModel>(); for (User user : users) { userModels.add(new UserAdapter(user, idm)); } return userModels; } }
Realm not updated after setting social enabled
services/src/main/java/org/keycloak/services/models/picketlink/RealmAdapter.java
Realm not updated after setting social enabled
Java
apache-2.0
d7f7e6eeea7bf39841f11a554edabce946a9a25a
0
bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm
// Copyright 2017 The Bazel Authors. 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 build.buildfarm.instance.shard; import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; import build.buildfarm.common.DigestUtil; import build.buildfarm.common.DigestUtil.ActionKey; import build.buildfarm.common.ShardBackplane; import build.buildfarm.v1test.CompletedOperationMetadata; import build.buildfarm.v1test.QueuedOperationMetadata; import build.buildfarm.v1test.RedisShardBackplaneConfig; import build.buildfarm.v1test.ShardDispatchedOperation; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.devtools.remoteexecution.v1test.ActionResult; import com.google.devtools.remoteexecution.v1test.Digest; import com.google.devtools.remoteexecution.v1test.Directory; import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata; import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata.Stage; import com.google.devtools.remoteexecution.v1test.GetTreeResponse; import com.google.longrunning.Operation; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import io.grpc.Status; import io.grpc.Status.Code; import java.io.IOException; import java.net.ConnectException; import java.net.URI; import java.net.URISyntaxException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.naming.ConfigurationException; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; import redis.clients.util.Pool; public class RedisShardBackplane implements ShardBackplane { private final RedisShardBackplaneConfig config; private final Function<Operation, Operation> onPublish; private final Function<Operation, Operation> onComplete; private final Predicate<Operation> isPrequeued; private final Predicate<Operation> isDispatched; private final Pool<Jedis> pool; private @Nullable Runnable onUnsubscribe = null; private Thread subscriptionThread = null; private Thread failsafeOperationThread = null; private Set<String> previousPrequeued = ImmutableSet.of(); private Set<String> previousDispatched = ImmutableSet.of(); private OperationSubscriber operationSubscriber = null; private RedisShardSubscription operationSubscription = null; private boolean poolStarted = false; private Set<String> workerSet = null; private long workerSetExpiresAt = 0; private static final JsonFormat.Printer operationPrinter = JsonFormat.printer().usingTypeRegistry( JsonFormat.TypeRegistry.newBuilder() .add(CompletedOperationMetadata.getDescriptor()) .add(ExecuteOperationMetadata.getDescriptor()) .add(QueuedOperationMetadata.getDescriptor()) .build()); private static class JedisMisconfigurationException extends JedisDataException { public JedisMisconfigurationException(final String message) { super(message); } public JedisMisconfigurationException(final Throwable cause) { super(cause); } public JedisMisconfigurationException(final String message, final Throwable cause) { super(message, cause); } } private static JedisPoolConfig createJedisPoolConfig(RedisShardBackplaneConfig config) { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(config.getJedisPoolMaxTotal()); return jedisPoolConfig; } private static URI parseRedisURI(String redisURI) throws ConfigurationException { try { return new URI(redisURI); } catch (URISyntaxException e) { throw new ConfigurationException(e.getMessage()); } } public RedisShardBackplane( RedisShardBackplaneConfig config, Function<Operation, Operation> onPublish, Function<Operation, Operation> onComplete, Predicate<Operation> isPrequeued, Predicate<Operation> isDispatched) throws ConfigurationException { this( config, onPublish, onComplete, isPrequeued, isDispatched, new JedisPool(createJedisPoolConfig(config), parseRedisURI(config.getRedisUri()), /* connectionTimeout=*/ 30000, /* soTimeout=*/ 30000)); } public RedisShardBackplane( RedisShardBackplaneConfig config, Function<Operation, Operation> onPublish, Function<Operation, Operation> onComplete, Predicate<Operation> isPrequeued, Predicate<Operation> isDispatched, JedisPool pool) { this.config = config; this.onPublish = onPublish; this.onComplete = onComplete; this.isPrequeued = isPrequeued; this.isDispatched = isDispatched; this.pool = pool; } @Override public Runnable setOnUnsubscribe(Runnable onUnsubscribe) { Runnable oldOnUnsubscribe = this.onUnsubscribe; this.onUnsubscribe = onUnsubscribe; return oldOnUnsubscribe; } public void updateWatchedIfDone(Jedis jedis) { List<String> operationChannels = operationSubscriber.watchedOperationChannels(); if (operationChannels.isEmpty()) { previousPrequeued = ImmutableSet.of(); previousDispatched = ImmutableSet.of(); return; } System.out.println("RedisShardBackplane::updateWatchedIfDone: Checking on open watches"); List<Map.Entry<String, Response<String>>> operations = new ArrayList(operationChannels.size()); Pipeline p = jedis.pipelined(); for (String operationName : Iterables.transform(operationChannels, RedisShardBackplane::parseOperationChannel)) { operations.add(new AbstractMap.SimpleEntry<>( operationName, p.get(operationKey(operationName)))); } Response<List<String>> queuedResponse = p.lrange(config.getQueuedOperationsListName(), 0, -1); Response<List<String>> prequeuedResponse = p.lrange(config.getPreQueuedOperationsListName(), 0, -1); Response<Set<String>> dispatchedResponse = p.hkeys(config.getDispatchedOperationsHashName()); p.sync(); Set<String> queued = new HashSet(queuedResponse.get()); Set<String> prequeued = new HashSet(prequeuedResponse.get()); Set<String> dispatched = dispatchedResponse.get(); ImmutableSet.Builder<String> previousPrequeuedBuilder = ImmutableSet.builder(); ImmutableSet.Builder<String> previousDispatchedBuilder = ImmutableSet.builder(); int iRemainingIncomplete = 20; for (Map.Entry<String, Response<String>> entry : operations) { String json = entry.getValue().get(); Operation operation = json == null ? null : RedisShardBackplane.parseOperationJson(json); String operationName = entry.getKey(); if (operation == null || operation.getDone()) { operationSubscriber.onOperation(operationChannel(operationName), operation); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " done due to " + (operation == null ? "null" : "completed")); } else if (!prequeued.contains(operationName) && isPrequeued.test(operation)) { if (previousPrequeued.contains(operationName)) { prequeueOperation(jedis, operationName); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " reprequeued..."); } else { previousPrequeuedBuilder.add(operationName); } } else if (!dispatched.contains(operationName) && !queued.contains(operationName) && isDispatched.test(operation)) { if (previousDispatched.contains(operationName)) { dispatchOperation(jedis, operationName, /* requeueAt=*/ 0); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " redispatched..."); } else { previousDispatchedBuilder.add(operationName); } } else if (iRemainingIncomplete > 0) { System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName); iRemainingIncomplete--; } } previousPrequeued = previousPrequeuedBuilder.build(); previousDispatched = previousDispatchedBuilder.build(); } private void startSubscriptionThread() { operationSubscriber = new OperationSubscriber(); operationSubscription = new RedisShardSubscription( operationSubscriber, /* onUnsubscribe=*/ () -> { subscriptionThread = null; if (onUnsubscribe != null) { onUnsubscribe.run(); } }, /* onReset=*/ this::updateWatchedIfDone, /* subscriptions=*/ operationSubscriber::watchedOperationChannels, this::getJedis); // use Executors... subscriptionThread = new Thread(operationSubscription); subscriptionThread.start(); failsafeOperationThread = new Thread(() -> { while (true) { try { TimeUnit.SECONDS.sleep(30); try (Jedis jedis = getJedis()) { updateWatchedIfDone(jedis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Exception e) { e.printStackTrace(); } } }); failsafeOperationThread.start(); } @Override public void start() { poolStarted = true; if (config.getSubscribeToOperation()) { startSubscriptionThread(); } } @Override public void stop() { if (subscriptionThread != null) { subscriptionThread.stop(); // subscriptionThread.join(); failsafeOperationThread.stop(); // failsafeOperationThread.join(); } if (pool != null) { poolStarted = false; pool.close(); } } @Override public boolean watchOperation(String operationName, Predicate<Operation> watcher) throws IOException { operationSubscriber.watch(operationChannel(operationName), watcher); return true; } @Override public boolean addWorker(String workerName) throws IOException { return withBackplaneException((jedis) -> jedis.sadd(config.getWorkersSetName(), workerName) == 1); } private static final String MISCONF_RESPONSE = "MISCONF"; @FunctionalInterface private static interface JedisContext<T> { T run(Jedis jedis) throws JedisException; } @VisibleForTesting public void withVoidBackplaneException(Consumer<Jedis> withJedis) throws IOException { withBackplaneException(new JedisContext<Void>() { @Override public Void run(Jedis jedis) throws JedisException { withJedis.accept(jedis); return null; } }); } @VisibleForTesting public <T> T withBackplaneException(JedisContext<T> withJedis) throws IOException { try (Jedis jedis = getJedis()) { try { return withJedis.run(jedis); } catch (JedisDataException e) { if (e.getMessage().startsWith(MISCONF_RESPONSE)) { throw new JedisMisconfigurationException(e.getMessage()); } throw e; } } catch (JedisMisconfigurationException e) { // the backplane is configured not to accept writes currently // as a result of an error. The error is meant to indicate // that substantial resources were unavailable. // we must throw an IOException which indicates as much // this looks simply to me like a good opportunity to use FAILED_PRECONDITION // we are technically not at RESOURCE_EXHAUSTED, this is a // persistent state which can exist long past the error throw new IOException(Status.FAILED_PRECONDITION.withCause(e).asRuntimeException()); } catch (JedisConnectionException e) { if ((e.getMessage() != null && e.getMessage().equals("Unexpected end of stream.")) || e.getCause() instanceof ConnectException) { throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException()); } Throwable cause = e; Status status = Status.UNKNOWN; while (status.getCode() == Code.UNKNOWN && cause != null) { String message = cause.getMessage() == null ? "" : cause.getMessage(); if ((cause instanceof SocketException && cause.getMessage().equals("Connection reset")) || cause instanceof ConnectException || message.equals("Unexpected end of stream.")) { status = Status.UNAVAILABLE; } else if (cause instanceof SocketTimeoutException) { status = Status.DEADLINE_EXCEEDED; } else if (cause instanceof IOException) { throw (IOException) cause; } else { cause = cause.getCause(); } } throw new IOException(status.withCause(cause == null ? e : cause).asRuntimeException()); } } @Override public void removeWorker(String workerName) throws IOException { if (workerSet != null) { workerSet.remove(workerName); } withVoidBackplaneException((jedis) -> jedis.srem(config.getWorkersSetName(), workerName)); } @Override public String getRandomWorker() throws IOException { return withBackplaneException((jedis) -> jedis.srandmember(config.getWorkersSetName())); } @Override public Set<String> getWorkerSet() throws IOException { long now = System.currentTimeMillis(); if (now < workerSetExpiresAt) { return workerSet; } workerSet = withBackplaneException((jedis) -> jedis.smembers(config.getWorkersSetName())); // fetch every 3 seconds workerSetExpiresAt = now + 3000; return workerSet; } @Override public boolean isWorker(String workerName) throws IOException { return withBackplaneException((jedis) -> jedis.sismember(config.getWorkersSetName(), workerName)); } private static ActionResult parseActionResult(String json) { try { ActionResult.Builder builder = ActionResult.newBuilder(); JsonFormat.parser().merge(json, builder); return builder.build(); } catch (InvalidProtocolBufferException e) { return null; } } @Override public ActionResult getActionResult(ActionKey actionKey) throws IOException { String json = withBackplaneException((jedis) -> jedis.get(acKey(actionKey))); if (json == null) { return null; } ActionResult actionResult = parseActionResult(json); if (actionResult == null) { withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey)); } return actionResult; } @Override public void putActionResult(ActionKey actionKey, ActionResult actionResult) throws IOException { String json = JsonFormat.printer().print(actionResult); withVoidBackplaneException((jedis) -> jedis.setex(acKey(actionKey), config.getActionCacheExpire(), json)); } private void removeActionResult(Jedis jedis, ActionKey actionKey) { jedis.del(acKey(actionKey)); } @Override public void removeActionResult(ActionKey actionKey) throws IOException { withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey)); } @Override public void removeActionResults(Iterable<ActionKey> actionKeys) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (ActionKey actionKey : actionKeys) { p.del(acKey(actionKey)); } p.sync(); }); } @Override public ActionCacheScanResult scanActionCache(String scanToken, int count) throws IOException { final String jedisScanToken = scanToken == null ? SCAN_POINTER_START : scanToken; ImmutableList.Builder<Map.Entry<ActionKey, String>> results = new ImmutableList.Builder<>(); ScanParams scanParams = new ScanParams() .match(config.getActionCachePrefix() + ":*") .count(count); String token = withBackplaneException((jedis) -> { ScanResult<String> scanResult = jedis.scan(jedisScanToken, scanParams); List<String> keyResults = scanResult.getResult(); List<Response<String>> actionResults = new ArrayList<>(keyResults.size()); Pipeline p = jedis.pipelined(); for (int i = 0; i < keyResults.size(); i++) { actionResults.add(p.get(keyResults.get(i))); } p.sync(); for (int i = 0; i < keyResults.size(); i++) { String json = actionResults.get(i).get(); if (json == null) { continue; } String key = keyResults.get(i); results.add(new AbstractMap.SimpleEntry<>( DigestUtil.asActionKey(DigestUtil.parseDigest(key.split(":")[1])), json)); } return scanResult.getStringCursor().equals(SCAN_POINTER_START) ? null : scanResult.getStringCursor(); }); return new ActionCacheScanResult( token, Iterables.transform( results.build(), (entry) -> new AbstractMap.SimpleEntry<>( entry.getKey(), parseActionResult(entry.getValue())))); } @Override public void adjustBlobLocations(Digest blobDigest, Set<String> addWorkers, Set<String> removeWorkers) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); for (String workerName : addWorkers) { t.sadd(key, workerName); } for (String workerName : removeWorkers) { t.srem(key, workerName); } t.expire(key, config.getCasExpire()); t.exec(); }); } @Override public void addBlobLocation(Digest blobDigest, String workerName) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); t.sadd(key, workerName); t.expire(key, config.getCasExpire()); t.exec(); }); } @Override public void addBlobsLocation(Iterable<Digest> blobDigests, String workerName) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (Digest blobDigest : blobDigests) { String key = casKey(blobDigest); p.sadd(key, workerName); p.expire(key, config.getCasExpire()); } p.sync(); }); } @Override public void removeBlobLocation(Digest blobDigest, String workerName) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> jedis.srem(key, workerName)); } @Override public void removeBlobsLocation(Iterable<Digest> blobDigests, String workerName) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (Digest blobDigest : blobDigests) { p.srem(casKey(blobDigest), workerName); } p.sync(); }); } @Override public String getBlobLocation(Digest blobDigest) throws IOException { return withBackplaneException((jedis) -> jedis.srandmember(casKey(blobDigest))); } @Override public Set<String> getBlobLocationSet(Digest blobDigest) throws IOException { return withBackplaneException((jedis) -> jedis.smembers(casKey(blobDigest))); } @Override public Map<Digest, Set<String>> getBlobDigestsWorkers(Iterable<Digest> blobDigests) throws IOException { // FIXME pipeline ImmutableMap.Builder<Digest, Set<String>> blobDigestsWorkers = new ImmutableMap.Builder<>(); withVoidBackplaneException((jedis) -> { for (Digest blobDigest : blobDigests) { Set<String> workers = jedis.smembers(casKey(blobDigest)); if (workers.isEmpty()) { continue; } blobDigestsWorkers.put(blobDigest, workers); } }); return blobDigestsWorkers.build(); } public static Operation parseOperationJson(String operationJson) { if (operationJson == null) { return null; } try { Operation.Builder operationBuilder = Operation.newBuilder(); getOperationParser().merge(operationJson, operationBuilder); return operationBuilder.build(); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return null; } } private static JsonFormat.Parser getOperationParser() { return JsonFormat.parser().usingTypeRegistry( JsonFormat.TypeRegistry.newBuilder() .add(CompletedOperationMetadata.getDescriptor()) .add(ExecuteOperationMetadata.getDescriptor()) .add(QueuedOperationMetadata.getDescriptor()) .build()); } private String getOperation(Jedis jedis, String operationName) { String json = jedis.get(operationKey(operationName)); if (json == null) { return null; } return json; } @Override public Operation getOperation(String operationName) throws IOException { String json = withBackplaneException((jedis) -> getOperation(jedis, operationName)); return parseOperationJson(json); } @Override public boolean putOperation(Operation operation, Stage stage) throws IOException { boolean prequeue = stage == Stage.UNKNOWN && !operation.getDone(); boolean queue = stage == Stage.QUEUED; boolean complete = !queue && operation.getDone(); boolean publish = !queue && stage != Stage.UNKNOWN; if (complete) { // for filtering anything that shouldn't be stored operation = onComplete.apply(operation); } String json; try { json = operationPrinter.print(operation); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } String publishOperation; if (publish) { publishOperation = operationPrinter.print(onPublish.apply(operation)); } else { publishOperation = null; } String name = operation.getName(); withVoidBackplaneException((jedis) -> { if (complete) { completeOperation(jedis, name); } jedis.setex(operationKey(name), config.getOperationExpire(), json); if (queue) { queueOperation(jedis, name); } if (prequeue) { prequeueOperation(jedis, name); } if (publish) { jedis.publish(operationChannel(name), publishOperation); } }); return true; } private void prequeueOperation(Jedis jedis, String operationName) { jedis.lpush(config.getPreQueuedOperationsListName(), operationName); } private void queueOperation(Jedis jedis, String operationName) { if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) == 1) { System.err.println("RedisShardBackplane::queueOperation: WARNING Removed dispatched operation"); } jedis.lpush(config.getQueuedOperationsListName(), operationName); } public Map<String, Operation> getOperationsMap() throws IOException { ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>(); withVoidBackplaneException((jedis) -> { for (Map.Entry<String, String> entry : jedis.hgetAll(config.getDispatchedOperationsHashName()).entrySet()) { builder.put(entry.getKey(), entry.getValue()); } }); return Maps.transformValues(builder.build(), RedisShardBackplane::parseOperationJson); } @Override public Iterable<String> getOperations() throws IOException { throw new UnsupportedOperationException(); /* return withVoidBackplaneException((jedis) -> { Iterable<String> dispatchedOperations = jedis.hkeys(config.getDispatchedOperationsHashName()); Iterable<String> queuedOperations = jedis.lrange(config.getQueuedOperationsListName(), 0, -1); return Iterables.concat(queuedOperations, dispatchedOperations, getCompletedOperations(jedis)); }); */ } @Override public ImmutableList<ShardDispatchedOperation> getDispatchedOperations() throws IOException { ImmutableList.Builder<ShardDispatchedOperation> builder = new ImmutableList.Builder<>(); Map<String, String> dispatchedOperations = withBackplaneException((jedis) -> jedis.hgetAll(config.getDispatchedOperationsHashName())); ImmutableList.Builder<String> invalidOperationNames = new ImmutableList.Builder<>(); boolean hasInvalid = false; // executor work queue? for (Map.Entry<String, String> entry : dispatchedOperations.entrySet()) { try { ShardDispatchedOperation.Builder dispatchedOperationBuilder = ShardDispatchedOperation.newBuilder(); JsonFormat.parser().merge(entry.getValue(), dispatchedOperationBuilder); builder.add(dispatchedOperationBuilder.build()); } catch (InvalidProtocolBufferException e) { System.err.println("RedisShardBackplane::getDispatchedOperations: removing invalid operation " + entry.getKey()); e.printStackTrace(); /* guess we don't want to spin on this */ invalidOperationNames.add(entry.getKey()); hasInvalid = true; } } if (hasInvalid) { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (String invalidOperationName : invalidOperationNames.build()) { p.hdel(config.getDispatchedOperationsHashName(), invalidOperationName); } p.sync(); }); } return builder.build(); } @Override public String deprequeueOperation() throws IOException, InterruptedException { String operationName = withBackplaneException((jedis) -> { List<String> result; do { result = jedis.brpop(1, config.getPreQueuedOperationsListName()); if (Thread.currentThread().isInterrupted()) { return null; } } while (result == null || result.isEmpty()); if (result.size() == 2 && result.get(0).equals(config.getPreQueuedOperationsListName())) { return result.get(1); } return null; }); if (Thread.interrupted()) { throw new InterruptedException(); } return operationName; } @Override public String dispatchOperation() throws IOException, InterruptedException { String operationName = withBackplaneException((jedis) -> { List<String> result; do { /* maybe we should really have a dispatch queue per registered worker */ result = jedis.brpop(1, config.getQueuedOperationsListName()); if (Thread.currentThread().isInterrupted()) { return null; } } while (result == null || result.isEmpty()); if (result.size() == 2 && result.get(0).equals(config.getQueuedOperationsListName())) { return result.get(1); } return null; }); if (operationName == null) { if (Thread.interrupted()) { throw new InterruptedException(); } return null; } // right here is an operation loss risk long requeueAt = System.currentTimeMillis() + 30 * 1000; if (!withBackplaneException((jedis) -> dispatchOperation(jedis, operationName, requeueAt))) { return null; } return operationName; } private boolean dispatchOperation(Jedis jedis, String operationName, long requeueAt) { ShardDispatchedOperation o = ShardDispatchedOperation.newBuilder() .setName(operationName) .setRequeueAt(requeueAt) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } /* if the operation is already in the dispatch list, fail the dispatch */ return jedis.hsetnx(config.getDispatchedOperationsHashName(), operationName, json) == 1; } @Override public boolean pollOperation(String operationName, Stage stage, long requeueAt) throws IOException { ShardDispatchedOperation o = ShardDispatchedOperation.newBuilder() .setName(operationName) .setRequeueAt(requeueAt) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } return withBackplaneException((jedis) -> { if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) { if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) { return true; } /* someone else beat us to the punch, delete our incorrectly added key */ jedis.hdel(config.getDispatchedOperationsHashName(), operationName); } return false; }); } @Override public void prequeueOperation(String operationName) throws IOException { withVoidBackplaneException((jedis) -> prequeueOperation(jedis, operationName)); } @Override public void requeueDispatchedOperation(Operation operation) throws IOException { withVoidBackplaneException((jedis) -> queueOperation(jedis, operation.getName())); } private void completeOperation(Jedis jedis, String operationName) { if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) != 1) { System.err.println("RedisShardBackplane::completeOperation: WARNING " + operationName + " was not in dispatched list"); } } @Override public void completeOperation(String operationName) throws IOException { withVoidBackplaneException((jedis) -> completeOperation(jedis, operationName)); } @Override public void deleteOperation(String operationName) throws IOException { Operation o = Operation.newBuilder() .setName(operationName) .setDone(true) .setError(com.google.rpc.Status.newBuilder() .setCode(Code.UNAVAILABLE.value()) .build()) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { json = null; e.printStackTrace(); } final String publishOperation = json; withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); t.hdel(config.getDispatchedOperationsHashName(), operationName); t.lrem(config.getQueuedOperationsListName(), 0, operationName); t.del(operationKey(operationName)); t.exec(); jedis.publish(operationChannel(operationName), publishOperation); }); } private Jedis getJedis() { if (!poolStarted) { throw Status.FAILED_PRECONDITION.withDescription("pool is not started").asRuntimeException(); } return pool.getResource(); } private String casKey(Digest blobDigest) { return config.getCasPrefix() + ":" + DigestUtil.toString(blobDigest); } private String treeKey(Digest blobDigest) { return config.getTreePrefix() + ":" + DigestUtil.toString(blobDigest); } private String acKey(ActionKey actionKey) { return config.getActionCachePrefix() + ":" + DigestUtil.toString(actionKey.getDigest()); } private String operationKey(String operationName) { return config.getOperationPrefix() + ":" + operationName; } private String operationChannel(String operationName) { return config.getOperationChannelPrefix() + ":" + operationName; } public static String parseOperationChannel(String channel) { return channel.split(":")[1]; } @Override public void putTree(Digest inputRoot, Iterable<Directory> directories) throws IOException { String treeValue = JsonFormat.printer().print(GetTreeResponse.newBuilder() .addAllDirectories(directories) .build()); withVoidBackplaneException((jedis) -> jedis.setex(treeKey(inputRoot), config.getTreeExpire(), treeValue)); } @Override public Iterable<Directory> getTree(Digest inputRoot) throws IOException { String json = withBackplaneException((jedis) -> jedis.get(treeKey(inputRoot))); if (json == null) { return null; } try { GetTreeResponse.Builder builder = GetTreeResponse.newBuilder(); JsonFormat.parser().merge(json, builder); return builder.build().getDirectoriesList(); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return null; } } @Override public void removeTree(Digest inputRoot) throws IOException { withVoidBackplaneException((jedis) -> jedis.del(treeKey(inputRoot))); } @Override public boolean canQueue() throws IOException { int maxQueueDepth = config.getMaxQueueDepth(); return maxQueueDepth < 0 || withBackplaneException((jedis) -> jedis.llen(config.getQueuedOperationsListName()) < maxQueueDepth); } @Override public boolean canPrequeue() throws IOException { int maxPreQueueDepth = config.getMaxPreQueueDepth(); return maxPreQueueDepth < 0 || withBackplaneException((jedis) -> jedis.llen(config.getPreQueuedOperationsListName()) < maxPreQueueDepth); } }
src/main/java/build/buildfarm/instance/shard/RedisShardBackplane.java
// Copyright 2017 The Bazel Authors. 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 build.buildfarm.instance.shard; import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; import build.buildfarm.common.DigestUtil; import build.buildfarm.common.DigestUtil.ActionKey; import build.buildfarm.common.ShardBackplane; import build.buildfarm.v1test.CompletedOperationMetadata; import build.buildfarm.v1test.QueuedOperationMetadata; import build.buildfarm.v1test.RedisShardBackplaneConfig; import build.buildfarm.v1test.ShardDispatchedOperation; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.devtools.remoteexecution.v1test.ActionResult; import com.google.devtools.remoteexecution.v1test.Digest; import com.google.devtools.remoteexecution.v1test.Directory; import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata; import com.google.devtools.remoteexecution.v1test.ExecuteOperationMetadata.Stage; import com.google.devtools.remoteexecution.v1test.GetTreeResponse; import com.google.longrunning.Operation; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import io.grpc.Status; import io.grpc.Status.Code; import java.io.IOException; import java.net.ConnectException; import java.net.URI; import java.net.URISyntaxException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.naming.ConfigurationException; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; import redis.clients.util.Pool; public class RedisShardBackplane implements ShardBackplane { private final RedisShardBackplaneConfig config; private final Function<Operation, Operation> onPublish; private final Function<Operation, Operation> onComplete; private final Predicate<Operation> isPrequeued; private final Predicate<Operation> isDispatched; private final Pool<Jedis> pool; private @Nullable Runnable onUnsubscribe = null; private Thread subscriptionThread = null; private Thread failsafeOperationThread = null; private Set<String> previousPrequeued = ImmutableSet.of(); private Set<String> previousDispatched = ImmutableSet.of(); private OperationSubscriber operationSubscriber = null; private RedisShardSubscription operationSubscription = null; private boolean poolStarted = false; private Set<String> workerSet = null; private long workerSetExpiresAt = 0; private static final JsonFormat.Printer operationPrinter = JsonFormat.printer().usingTypeRegistry( JsonFormat.TypeRegistry.newBuilder() .add(CompletedOperationMetadata.getDescriptor()) .add(ExecuteOperationMetadata.getDescriptor()) .add(QueuedOperationMetadata.getDescriptor()) .build()); private static class JedisMisconfigurationException extends JedisDataException { public JedisMisconfigurationException(final String message) { super(message); } public JedisMisconfigurationException(final Throwable cause) { super(cause); } public JedisMisconfigurationException(final String message, final Throwable cause) { super(message, cause); } } private static JedisPoolConfig createJedisPoolConfig(RedisShardBackplaneConfig config) { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(config.getJedisPoolMaxTotal()); return jedisPoolConfig; } private static URI parseRedisURI(String redisURI) throws ConfigurationException { try { return new URI(redisURI); } catch (URISyntaxException e) { throw new ConfigurationException(e.getMessage()); } } public RedisShardBackplane( RedisShardBackplaneConfig config, Function<Operation, Operation> onPublish, Function<Operation, Operation> onComplete, Predicate<Operation> isPrequeued, Predicate<Operation> isDispatched) throws ConfigurationException { this( config, onPublish, onComplete, isPrequeued, isDispatched, new JedisPool(createJedisPoolConfig(config), parseRedisURI(config.getRedisUri()), /* connectionTimeout=*/ 30000, /* soTimeout=*/ 30000)); } public RedisShardBackplane( RedisShardBackplaneConfig config, Function<Operation, Operation> onPublish, Function<Operation, Operation> onComplete, Predicate<Operation> isPrequeued, Predicate<Operation> isDispatched, JedisPool pool) { this.config = config; this.onPublish = onPublish; this.onComplete = onComplete; this.isPrequeued = isPrequeued; this.isDispatched = isDispatched; this.pool = pool; } @Override public Runnable setOnUnsubscribe(Runnable onUnsubscribe) { Runnable oldOnUnsubscribe = this.onUnsubscribe; this.onUnsubscribe = onUnsubscribe; return oldOnUnsubscribe; } public void updateWatchedIfDone(Jedis jedis) { List<String> operationChannels = operationSubscriber.watchedOperationChannels(); if (operationChannels.isEmpty()) { previousPrequeued = ImmutableSet.of(); previousDispatched = ImmutableSet.of(); return; } System.out.println("RedisShardBackplane::updateWatchedIfDone: Checking on open watches"); List<Map.Entry<String, Response<String>>> operations = new ArrayList(operationChannels.size()); Pipeline p = jedis.pipelined(); for (String operationName : Iterables.transform(operationChannels, RedisShardBackplane::parseOperationChannel)) { operations.add(new AbstractMap.SimpleEntry<>( operationName, p.get(operationKey(operationName)))); } Response<List<String>> queuedResponse = p.lrange(config.getQueuedOperationsListName(), 0, -1); Response<List<String>> prequeuedResponse = p.lrange(config.getPreQueuedOperationsListName(), 0, -1); Response<Set<String>> dispatchedResponse = p.hkeys(config.getDispatchedOperationsHashName()); p.sync(); Set<String> queued = new HashSet(queuedResponse.get()); Set<String> prequeued = new HashSet(prequeuedResponse.get()); Set<String> dispatched = dispatchedResponse.get(); ImmutableSet.Builder<String> previousPrequeuedBuilder = ImmutableSet.builder(); ImmutableSet.Builder<String> previousDispatchedBuilder = ImmutableSet.builder(); int iRemainingIncomplete = 20; for (Map.Entry<String, Response<String>> entry : operations) { String json = entry.getValue().get(); Operation operation = json == null ? null : RedisShardBackplane.parseOperationJson(json); String operationName = entry.getKey(); if (operation == null || operation.getDone()) { operationSubscriber.onOperation(operationChannel(operationName), operation); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " done due to " + (operation == null ? "null" : "completed")); } else if (!prequeued.contains(operationName) && isPrequeued.test(operation)) { if (previousPrequeued.contains(operationName)) { prequeueOperation(jedis, operationName); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " reprequeued..."); } else { previousPrequeuedBuilder.add(operationName); } } else if (!dispatched.contains(operationName) && !queued.contains(operationName) && isDispatched.test(operation)) { if (previousDispatched.contains(operationName)) { dispatchOperation(jedis, operationName, /* requeueAt=*/ 0); System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName + " redispatched..."); } else { previousDispatchedBuilder.add(operationName); } } else if (iRemainingIncomplete > 0) { System.out.println("RedisShardBackplane::updateWatchedIfDone: Operation " + operationName); iRemainingIncomplete--; } } previousPrequeued = previousPrequeuedBuilder.build(); previousDispatched = previousDispatchedBuilder.build(); } private void startSubscriptionThread() { operationSubscriber = new OperationSubscriber(); operationSubscription = new RedisShardSubscription( operationSubscriber, /* onUnsubscribe=*/ () -> { subscriptionThread = null; if (onUnsubscribe != null) { onUnsubscribe.run(); } }, /* onReset=*/ this::updateWatchedIfDone, /* subscriptions=*/ operationSubscriber::watchedOperationChannels, this::getJedis); // use Executors... subscriptionThread = new Thread(operationSubscription); subscriptionThread.start(); failsafeOperationThread = new Thread(() -> { while (true) { try { TimeUnit.SECONDS.sleep(30); try (Jedis jedis = getJedis()) { updateWatchedIfDone(jedis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } catch (Exception e) { e.printStackTrace(); } } }); failsafeOperationThread.start(); } @Override public void start() { poolStarted = true; if (config.getSubscribeToOperation()) { startSubscriptionThread(); } } @Override public void stop() { if (subscriptionThread != null) { subscriptionThread.stop(); // subscriptionThread.join(); failsafeOperationThread.stop(); // failsafeOperationThread.join(); } if (pool != null) { poolStarted = false; pool.close(); } } @Override public boolean watchOperation(String operationName, Predicate<Operation> watcher) throws IOException { operationSubscriber.watch(operationChannel(operationName), watcher); return true; } @Override public boolean addWorker(String workerName) throws IOException { return withBackplaneException((jedis) -> jedis.sadd(config.getWorkersSetName(), workerName) == 1); } private static final String MISCONF_RESPONSE = "MISCONF"; @FunctionalInterface private static interface JedisContext<T> { T run(Jedis jedis) throws JedisException; } @VisibleForTesting public void withVoidBackplaneException(Consumer<Jedis> withJedis) throws IOException { withBackplaneException(new JedisContext<Void>() { @Override public Void run(Jedis jedis) throws JedisException { withJedis.accept(jedis); return null; } }); } @VisibleForTesting public <T> T withBackplaneException(JedisContext<T> withJedis) throws IOException { try (Jedis jedis = getJedis()) { try { return withJedis.run(jedis); } catch (JedisDataException e) { if (e.getMessage().startsWith(MISCONF_RESPONSE)) { throw new JedisMisconfigurationException(e.getMessage()); } throw e; } } catch (JedisMisconfigurationException e) { // the backplane is configured not to accept writes currently // as a result of an error. The error is meant to indicate // that substantial resources were unavailable. // we must throw an IOException which indicates as much // this looks simply to me like a good opportunity to use FAILED_PRECONDITION // we are technically not at RESOURCE_EXHAUSTED, this is a // persistent state which can exist long past the error throw new IOException(Status.FAILED_PRECONDITION.withCause(e).asRuntimeException()); } catch (JedisConnectionException e) { if ((e.getMessage() != null && e.getMessage().equals("Unexpected end of stream.")) || e.getCause() instanceof ConnectException) { throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException()); } Throwable cause = e; Status status = Status.UNKNOWN; while (status.getCode() == Code.UNKNOWN && cause != null) { String message = cause.getMessage() == null ? "" : cause.getMessage(); if ((cause instanceof SocketException && cause.getMessage().equals("Connection reset")) || cause instanceof ConnectException || message.equals("Unexpected end of stream.")) { status = Status.UNAVAILABLE; } else if (cause instanceof SocketTimeoutException) { status = Status.DEADLINE_EXCEEDED; } else if (cause instanceof IOException) { throw (IOException) cause; } else { cause = cause.getCause(); } } throw new IOException(status.withCause(cause == null ? e : cause).asRuntimeException()); } } @Override public void removeWorker(String workerName) throws IOException { if (workerSet != null) { workerSet.remove(workerName); } withVoidBackplaneException((jedis) -> jedis.srem(config.getWorkersSetName(), workerName)); } @Override public String getRandomWorker() throws IOException { return withBackplaneException((jedis) -> jedis.srandmember(config.getWorkersSetName())); } @Override public Set<String> getWorkerSet() throws IOException { if (System.nanoTime() < workerSetExpiresAt) { return workerSet; } workerSet = withBackplaneException((jedis) -> jedis.smembers(config.getWorkersSetName())); // fetch every 3 seconds workerSetExpiresAt = System.nanoTime() + 3000000000l; return workerSet; } @Override public boolean isWorker(String workerName) throws IOException { return withBackplaneException((jedis) -> jedis.sismember(config.getWorkersSetName(), workerName)); } private static ActionResult parseActionResult(String json) { try { ActionResult.Builder builder = ActionResult.newBuilder(); JsonFormat.parser().merge(json, builder); return builder.build(); } catch (InvalidProtocolBufferException e) { return null; } } @Override public ActionResult getActionResult(ActionKey actionKey) throws IOException { String json = withBackplaneException((jedis) -> jedis.get(acKey(actionKey))); if (json == null) { return null; } ActionResult actionResult = parseActionResult(json); if (actionResult == null) { withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey)); } return actionResult; } @Override public void putActionResult(ActionKey actionKey, ActionResult actionResult) throws IOException { String json = JsonFormat.printer().print(actionResult); withVoidBackplaneException((jedis) -> jedis.setex(acKey(actionKey), config.getActionCacheExpire(), json)); } private void removeActionResult(Jedis jedis, ActionKey actionKey) { jedis.del(acKey(actionKey)); } @Override public void removeActionResult(ActionKey actionKey) throws IOException { withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey)); } @Override public void removeActionResults(Iterable<ActionKey> actionKeys) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (ActionKey actionKey : actionKeys) { p.del(acKey(actionKey)); } p.sync(); }); } @Override public ActionCacheScanResult scanActionCache(String scanToken, int count) throws IOException { final String jedisScanToken = scanToken == null ? SCAN_POINTER_START : scanToken; ImmutableList.Builder<Map.Entry<ActionKey, String>> results = new ImmutableList.Builder<>(); ScanParams scanParams = new ScanParams() .match(config.getActionCachePrefix() + ":*") .count(count); String token = withBackplaneException((jedis) -> { ScanResult<String> scanResult = jedis.scan(jedisScanToken, scanParams); List<String> keyResults = scanResult.getResult(); List<Response<String>> actionResults = new ArrayList<>(keyResults.size()); Pipeline p = jedis.pipelined(); for (int i = 0; i < keyResults.size(); i++) { actionResults.add(p.get(keyResults.get(i))); } p.sync(); for (int i = 0; i < keyResults.size(); i++) { String json = actionResults.get(i).get(); if (json == null) { continue; } String key = keyResults.get(i); results.add(new AbstractMap.SimpleEntry<>( DigestUtil.asActionKey(DigestUtil.parseDigest(key.split(":")[1])), json)); } return scanResult.getStringCursor().equals(SCAN_POINTER_START) ? null : scanResult.getStringCursor(); }); return new ActionCacheScanResult( token, Iterables.transform( results.build(), (entry) -> new AbstractMap.SimpleEntry<>( entry.getKey(), parseActionResult(entry.getValue())))); } @Override public void adjustBlobLocations(Digest blobDigest, Set<String> addWorkers, Set<String> removeWorkers) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); for (String workerName : addWorkers) { t.sadd(key, workerName); } for (String workerName : removeWorkers) { t.srem(key, workerName); } t.expire(key, config.getCasExpire()); t.exec(); }); } @Override public void addBlobLocation(Digest blobDigest, String workerName) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); t.sadd(key, workerName); t.expire(key, config.getCasExpire()); t.exec(); }); } @Override public void addBlobsLocation(Iterable<Digest> blobDigests, String workerName) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (Digest blobDigest : blobDigests) { String key = casKey(blobDigest); p.sadd(key, workerName); p.expire(key, config.getCasExpire()); } p.sync(); }); } @Override public void removeBlobLocation(Digest blobDigest, String workerName) throws IOException { String key = casKey(blobDigest); withVoidBackplaneException((jedis) -> jedis.srem(key, workerName)); } @Override public void removeBlobsLocation(Iterable<Digest> blobDigests, String workerName) throws IOException { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (Digest blobDigest : blobDigests) { p.srem(casKey(blobDigest), workerName); } p.sync(); }); } @Override public String getBlobLocation(Digest blobDigest) throws IOException { return withBackplaneException((jedis) -> jedis.srandmember(casKey(blobDigest))); } @Override public Set<String> getBlobLocationSet(Digest blobDigest) throws IOException { return withBackplaneException((jedis) -> jedis.smembers(casKey(blobDigest))); } @Override public Map<Digest, Set<String>> getBlobDigestsWorkers(Iterable<Digest> blobDigests) throws IOException { // FIXME pipeline ImmutableMap.Builder<Digest, Set<String>> blobDigestsWorkers = new ImmutableMap.Builder<>(); withVoidBackplaneException((jedis) -> { for (Digest blobDigest : blobDigests) { Set<String> workers = jedis.smembers(casKey(blobDigest)); if (workers.isEmpty()) { continue; } blobDigestsWorkers.put(blobDigest, workers); } }); return blobDigestsWorkers.build(); } public static Operation parseOperationJson(String operationJson) { if (operationJson == null) { return null; } try { Operation.Builder operationBuilder = Operation.newBuilder(); getOperationParser().merge(operationJson, operationBuilder); return operationBuilder.build(); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return null; } } private static JsonFormat.Parser getOperationParser() { return JsonFormat.parser().usingTypeRegistry( JsonFormat.TypeRegistry.newBuilder() .add(CompletedOperationMetadata.getDescriptor()) .add(ExecuteOperationMetadata.getDescriptor()) .add(QueuedOperationMetadata.getDescriptor()) .build()); } private String getOperation(Jedis jedis, String operationName) { String json = jedis.get(operationKey(operationName)); if (json == null) { return null; } return json; } @Override public Operation getOperation(String operationName) throws IOException { String json = withBackplaneException((jedis) -> getOperation(jedis, operationName)); return parseOperationJson(json); } @Override public boolean putOperation(Operation operation, Stage stage) throws IOException { boolean prequeue = stage == Stage.UNKNOWN && !operation.getDone(); boolean queue = stage == Stage.QUEUED; boolean complete = !queue && operation.getDone(); boolean publish = !queue && stage != Stage.UNKNOWN; if (complete) { // for filtering anything that shouldn't be stored operation = onComplete.apply(operation); } String json; try { json = operationPrinter.print(operation); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } String publishOperation; if (publish) { publishOperation = operationPrinter.print(onPublish.apply(operation)); } else { publishOperation = null; } String name = operation.getName(); withVoidBackplaneException((jedis) -> { if (complete) { completeOperation(jedis, name); } jedis.setex(operationKey(name), config.getOperationExpire(), json); if (queue) { queueOperation(jedis, name); } if (prequeue) { prequeueOperation(jedis, name); } if (publish) { jedis.publish(operationChannel(name), publishOperation); } }); return true; } private void prequeueOperation(Jedis jedis, String operationName) { jedis.lpush(config.getPreQueuedOperationsListName(), operationName); } private void queueOperation(Jedis jedis, String operationName) { if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) == 1) { System.err.println("RedisShardBackplane::queueOperation: WARNING Removed dispatched operation"); } jedis.lpush(config.getQueuedOperationsListName(), operationName); } public Map<String, Operation> getOperationsMap() throws IOException { ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>(); withVoidBackplaneException((jedis) -> { for (Map.Entry<String, String> entry : jedis.hgetAll(config.getDispatchedOperationsHashName()).entrySet()) { builder.put(entry.getKey(), entry.getValue()); } }); return Maps.transformValues(builder.build(), RedisShardBackplane::parseOperationJson); } @Override public Iterable<String> getOperations() throws IOException { throw new UnsupportedOperationException(); /* return withVoidBackplaneException((jedis) -> { Iterable<String> dispatchedOperations = jedis.hkeys(config.getDispatchedOperationsHashName()); Iterable<String> queuedOperations = jedis.lrange(config.getQueuedOperationsListName(), 0, -1); return Iterables.concat(queuedOperations, dispatchedOperations, getCompletedOperations(jedis)); }); */ } @Override public ImmutableList<ShardDispatchedOperation> getDispatchedOperations() throws IOException { ImmutableList.Builder<ShardDispatchedOperation> builder = new ImmutableList.Builder<>(); Map<String, String> dispatchedOperations = withBackplaneException((jedis) -> jedis.hgetAll(config.getDispatchedOperationsHashName())); ImmutableList.Builder<String> invalidOperationNames = new ImmutableList.Builder<>(); boolean hasInvalid = false; // executor work queue? for (Map.Entry<String, String> entry : dispatchedOperations.entrySet()) { try { ShardDispatchedOperation.Builder dispatchedOperationBuilder = ShardDispatchedOperation.newBuilder(); JsonFormat.parser().merge(entry.getValue(), dispatchedOperationBuilder); builder.add(dispatchedOperationBuilder.build()); } catch (InvalidProtocolBufferException e) { System.err.println("RedisShardBackplane::getDispatchedOperations: removing invalid operation " + entry.getKey()); e.printStackTrace(); /* guess we don't want to spin on this */ invalidOperationNames.add(entry.getKey()); hasInvalid = true; } } if (hasInvalid) { withVoidBackplaneException((jedis) -> { Pipeline p = jedis.pipelined(); for (String invalidOperationName : invalidOperationNames.build()) { p.hdel(config.getDispatchedOperationsHashName(), invalidOperationName); } p.sync(); }); } return builder.build(); } @Override public String deprequeueOperation() throws IOException, InterruptedException { String operationName = withBackplaneException((jedis) -> { List<String> result; do { result = jedis.brpop(1, config.getPreQueuedOperationsListName()); if (Thread.currentThread().isInterrupted()) { return null; } } while (result == null || result.isEmpty()); if (result.size() == 2 && result.get(0).equals(config.getPreQueuedOperationsListName())) { return result.get(1); } return null; }); if (Thread.interrupted()) { throw new InterruptedException(); } return operationName; } @Override public String dispatchOperation() throws IOException, InterruptedException { String operationName = withBackplaneException((jedis) -> { List<String> result; do { /* maybe we should really have a dispatch queue per registered worker */ result = jedis.brpop(1, config.getQueuedOperationsListName()); if (Thread.currentThread().isInterrupted()) { return null; } } while (result == null || result.isEmpty()); if (result.size() == 2 && result.get(0).equals(config.getQueuedOperationsListName())) { return result.get(1); } return null; }); if (operationName == null) { if (Thread.interrupted()) { throw new InterruptedException(); } return null; } // right here is an operation loss risk long requeueAt = System.currentTimeMillis() + 30 * 1000; if (!withBackplaneException((jedis) -> dispatchOperation(jedis, operationName, requeueAt))) { return null; } return operationName; } private boolean dispatchOperation(Jedis jedis, String operationName, long requeueAt) { ShardDispatchedOperation o = ShardDispatchedOperation.newBuilder() .setName(operationName) .setRequeueAt(requeueAt) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } /* if the operation is already in the dispatch list, fail the dispatch */ return jedis.hsetnx(config.getDispatchedOperationsHashName(), operationName, json) == 1; } @Override public boolean pollOperation(String operationName, Stage stage, long requeueAt) throws IOException { ShardDispatchedOperation o = ShardDispatchedOperation.newBuilder() .setName(operationName) .setRequeueAt(requeueAt) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return false; } return withBackplaneException((jedis) -> { if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) { if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) { return true; } /* someone else beat us to the punch, delete our incorrectly added key */ jedis.hdel(config.getDispatchedOperationsHashName(), operationName); } return false; }); } @Override public void prequeueOperation(String operationName) throws IOException { withVoidBackplaneException((jedis) -> prequeueOperation(jedis, operationName)); } @Override public void requeueDispatchedOperation(Operation operation) throws IOException { withVoidBackplaneException((jedis) -> queueOperation(jedis, operation.getName())); } private void completeOperation(Jedis jedis, String operationName) { if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) != 1) { System.err.println("RedisShardBackplane::completeOperation: WARNING " + operationName + " was not in dispatched list"); } } @Override public void completeOperation(String operationName) throws IOException { withVoidBackplaneException((jedis) -> completeOperation(jedis, operationName)); } @Override public void deleteOperation(String operationName) throws IOException { Operation o = Operation.newBuilder() .setName(operationName) .setDone(true) .setError(com.google.rpc.Status.newBuilder() .setCode(Code.UNAVAILABLE.value()) .build()) .build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { json = null; e.printStackTrace(); } final String publishOperation = json; withVoidBackplaneException((jedis) -> { Transaction t = jedis.multi(); t.hdel(config.getDispatchedOperationsHashName(), operationName); t.lrem(config.getQueuedOperationsListName(), 0, operationName); t.del(operationKey(operationName)); t.exec(); jedis.publish(operationChannel(operationName), publishOperation); }); } private Jedis getJedis() { if (!poolStarted) { throw Status.FAILED_PRECONDITION.withDescription("pool is not started").asRuntimeException(); } return pool.getResource(); } private String casKey(Digest blobDigest) { return config.getCasPrefix() + ":" + DigestUtil.toString(blobDigest); } private String treeKey(Digest blobDigest) { return config.getTreePrefix() + ":" + DigestUtil.toString(blobDigest); } private String acKey(ActionKey actionKey) { return config.getActionCachePrefix() + ":" + DigestUtil.toString(actionKey.getDigest()); } private String operationKey(String operationName) { return config.getOperationPrefix() + ":" + operationName; } private String operationChannel(String operationName) { return config.getOperationChannelPrefix() + ":" + operationName; } public static String parseOperationChannel(String channel) { return channel.split(":")[1]; } @Override public void putTree(Digest inputRoot, Iterable<Directory> directories) throws IOException { String treeValue = JsonFormat.printer().print(GetTreeResponse.newBuilder() .addAllDirectories(directories) .build()); withVoidBackplaneException((jedis) -> jedis.setex(treeKey(inputRoot), config.getTreeExpire(), treeValue)); } @Override public Iterable<Directory> getTree(Digest inputRoot) throws IOException { String json = withBackplaneException((jedis) -> jedis.get(treeKey(inputRoot))); if (json == null) { return null; } try { GetTreeResponse.Builder builder = GetTreeResponse.newBuilder(); JsonFormat.parser().merge(json, builder); return builder.build().getDirectoriesList(); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); return null; } } @Override public void removeTree(Digest inputRoot) throws IOException { withVoidBackplaneException((jedis) -> jedis.del(treeKey(inputRoot))); } @Override public boolean canQueue() throws IOException { int maxQueueDepth = config.getMaxQueueDepth(); return maxQueueDepth < 0 || withBackplaneException((jedis) -> jedis.llen(config.getQueuedOperationsListName()) < maxQueueDepth); } @Override public boolean canPrequeue() throws IOException { int maxPreQueueDepth = config.getMaxPreQueueDepth(); return maxPreQueueDepth < 0 || withBackplaneException((jedis) -> jedis.llen(config.getPreQueuedOperationsListName()) < maxPreQueueDepth); } }
Switch worker sets fetches to use milliseconds
src/main/java/build/buildfarm/instance/shard/RedisShardBackplane.java
Switch worker sets fetches to use milliseconds
Java
apache-2.0
ab5b884a6b18a870b8fd0b3b51384bf47c1e59c6
0
MTA-SZTAKI/longneck-core
package hu.sztaki.ilab.longneck.process.task; import hu.sztaki.ilab.longneck.Record; import hu.sztaki.ilab.longneck.bootstrap.PropertyUtils; import hu.sztaki.ilab.longneck.process.FailException; import hu.sztaki.ilab.longneck.process.FilterException; import hu.sztaki.ilab.longneck.process.FrameAddressResolver; import hu.sztaki.ilab.longneck.process.Kernel; import hu.sztaki.ilab.longneck.process.block.Sequence; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; /** * * @author Molnár Péter <molnarp@sztaki.mta.hu> */ public class ProcessWorker extends AbstractTask implements Runnable { /** Log to write messages to. */ private final Logger LOG = Logger.getLogger(ProcessWorker.class); /** The source queue, where records are read from. */ private final BlockingQueue<QueueItem> sourceQueue; /** The target queue, where records are written to. */ private final BlockingQueue<QueueItem> targetQueue; /** The error queue, where errors are written to. */ private final BlockingQueue<QueueItem> errorQueue; /** Local queue for cloned records. */ private final List<Record> localCloneQueue = new ArrayList<Record>(); /** Enable running of thread. */ private volatile boolean running = true; /** The bulk size. */ private int bulkSize = 100; private Kernel kernel; public ProcessWorker(BlockingQueue<QueueItem> sourceQueue, BlockingQueue<QueueItem> targetQueue, BlockingQueue<QueueItem> errorQueue, FrameAddressResolver frameAddressResolver, Sequence topLevelSequence, Properties runtimeProperties) { this.sourceQueue = sourceQueue; this.targetQueue = targetQueue; this.errorQueue = errorQueue; kernel = new Kernel(topLevelSequence, frameAddressResolver, localCloneQueue); // Read settings from runtime properties measureTimeEnabled = PropertyUtils.getBooleanProperty( runtimeProperties, "measureTimeEnabled", false); } @Override public void run() { // Run parent method super.run(); LOG.info("Starting up."); // Create queue item list List<Record> queueItemList = new ArrayList<Record>(bulkSize); boolean shutdownReceived = false; List<Record> targetRecords = new ArrayList<Record>(bulkSize); List<Record> errorRecords = new ArrayList<Record>(bulkSize); QueueItem item; try { while (running && (! shutdownReceived || ! localCloneQueue.isEmpty())) { item = null; // Query cloned records if (localCloneQueue.size() >= bulkSize || shutdownReceived) { // Determine count of removable elements int subListSize = Math.min(bulkSize, localCloneQueue.size()); // Clear queue item list and add elements from cloned record queue queueItemList.clear(); queueItemList.addAll(localCloneQueue.subList(0, subListSize)); // Remove items from cloned record queue localCloneQueue.subList(0, subListSize).clear(); // Create new queue item item = new QueueItem(queueItemList); // Increase counter stats.cloned += subListSize; } if (item == null && ! shutdownReceived) { // Get record from source queue; cloned records are taken first item = sourceQueue.poll(100, TimeUnit.MILLISECONDS); } // Check record, if null if (item == null) { continue; } stats.in += item.getRecords().size(); if (item.isNoMoreRecords()) { shutdownReceived = true; } List<Record> inRecords = item.getRecords(); for (Record record : inRecords) { try { // Process with kernel kernel.process(record); // Add record to output targetRecords.add(record); errorRecords.add(record); } catch (FailException ex) { LOG.debug(ex.getMessage(), ex); stats.failed += 1; errorRecords.add(record); } catch (FilterException ex) { // LOG.info(ex.getMessage(), ex); LOG.trace(ex.getMessage()) ; stats.filtered += 1; errorRecords.add(record); } } // Write to output if (! targetRecords.isEmpty()) { QueueItem outItem = new QueueItem(targetRecords); targetQueue.put(outItem); stats.out += outItem.getRecords().size(); } if (! errorRecords.isEmpty()) { errorQueue.put(new QueueItem(errorRecords)); } // Clean up targetRecords.clear(); errorRecords.clear(); } } catch (InterruptedException ex) { LOG.info("Interrupted.", ex); } catch (Exception ex) { LOG.fatal("Fatal error during processing.", ex); } // Log timings if (measureTimeEnabled) { stats.totalTimeMillis = this.getTotalTime(); stats.blockedTimeMillis = mxBean.getThreadInfo(Thread.currentThread().getId()).getBlockedTime(); } stats.setMeasureTimeEnabled(measureTimeEnabled); LOG.info(stats.toString()); LOG.info("Shutting down."); } public BlockingQueue<QueueItem> getSourceQueue() { return sourceQueue; } public BlockingQueue<QueueItem> getTargetQueue() { return targetQueue; } public BlockingQueue<QueueItem> getErrorQueue() { return errorQueue; } public Logger getLog() { return LOG; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } }
src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java
package hu.sztaki.ilab.longneck.process.task; import hu.sztaki.ilab.longneck.Record; import hu.sztaki.ilab.longneck.bootstrap.PropertyUtils; import hu.sztaki.ilab.longneck.process.FailException; import hu.sztaki.ilab.longneck.process.FilterException; import hu.sztaki.ilab.longneck.process.FrameAddressResolver; import hu.sztaki.ilab.longneck.process.Kernel; import hu.sztaki.ilab.longneck.process.block.Sequence; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; /** * * @author Molnár Péter <molnarp@sztaki.mta.hu> */ public class ProcessWorker extends AbstractTask implements Runnable { /** Log to write messages to. */ private final Logger LOG = Logger.getLogger(ProcessWorker.class); /** The source queue, where records are read from. */ private final BlockingQueue<QueueItem> sourceQueue; /** The target queue, where records are written to. */ private final BlockingQueue<QueueItem> targetQueue; /** The error queue, where errors are written to. */ private final BlockingQueue<QueueItem> errorQueue; /** Local queue for cloned records. */ private final List<Record> localCloneQueue = new ArrayList<Record>(); /** Enable running of thread. */ private volatile boolean running = true; /** The bulk size. */ private int bulkSize = 100; private Kernel kernel; public ProcessWorker(BlockingQueue<QueueItem> sourceQueue, BlockingQueue<QueueItem> targetQueue, BlockingQueue<QueueItem> errorQueue, FrameAddressResolver frameAddressResolver, Sequence topLevelSequence, Properties runtimeProperties) { this.sourceQueue = sourceQueue; this.targetQueue = targetQueue; this.errorQueue = errorQueue; kernel = new Kernel(topLevelSequence, frameAddressResolver, localCloneQueue); // Read settings from runtime properties measureTimeEnabled = PropertyUtils.getBooleanProperty( runtimeProperties, "measureTimeEnabled", false); } @Override public void run() { // Run parent method super.run(); LOG.info("Starting up."); // Create queue item list List<Record> queueItemList = new ArrayList<Record>(bulkSize); boolean shutdownReceived = false; List<Record> targetRecords = new ArrayList<Record>(bulkSize); List<Record> errorRecords = new ArrayList<Record>(bulkSize); QueueItem item; try { while (running && (! shutdownReceived || ! localCloneQueue.isEmpty())) { item = null; // Query cloned records if (localCloneQueue.size() >= bulkSize || shutdownReceived) { // Determine count of removable elements int subListSize = Math.min(bulkSize, localCloneQueue.size()); // Clear queue item list and add elements from cloned record queue queueItemList.clear(); queueItemList.addAll(localCloneQueue.subList(0, subListSize)); // Remove items from cloned record queue localCloneQueue.subList(0, subListSize).clear(); // Create new queue item item = new QueueItem(queueItemList); // Increase counter stats.cloned += subListSize; } if (item == null && ! shutdownReceived) { // Get record from source queue; cloned records are taken first item = sourceQueue.poll(100, TimeUnit.MILLISECONDS); } // Check record, if null if (item == null) { continue; } stats.in += item.getRecords().size(); if (item.isNoMoreRecords()) { shutdownReceived = true; } List<Record> inRecords = item.getRecords(); for (Record record : inRecords) { try { // Process with kernel kernel.process(record); // Add record to output targetRecords.add(record); errorRecords.add(record); } catch (FailException ex) { LOG.debug(ex.getMessage(), ex); stats.failed += 1; } catch (FilterException ex) { // LOG.info(ex.getMessage(), ex); LOG.trace(ex.getMessage()) ; stats.filtered += 1; errorRecords.add(record); } } // Write to output if (! targetRecords.isEmpty()) { QueueItem outItem = new QueueItem(targetRecords); targetQueue.put(outItem); stats.out += outItem.getRecords().size(); } if (! errorRecords.isEmpty()) { errorQueue.put(new QueueItem(errorRecords)); } // Clean up targetRecords.clear(); errorRecords.clear(); } } catch (InterruptedException ex) { LOG.info("Interrupted.", ex); } catch (Exception ex) { LOG.fatal("Fatal error during processing.", ex); } // Log timings if (measureTimeEnabled) { stats.totalTimeMillis = this.getTotalTime(); stats.blockedTimeMillis = mxBean.getThreadInfo(Thread.currentThread().getId()).getBlockedTime(); } stats.setMeasureTimeEnabled(measureTimeEnabled); LOG.info(stats.toString()); LOG.info("Shutting down."); } public BlockingQueue<QueueItem> getSourceQueue() { return sourceQueue; } public BlockingQueue<QueueItem> getTargetQueue() { return targetQueue; } public BlockingQueue<QueueItem> getErrorQueue() { return errorQueue; } public Logger getLog() { return LOG; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } }
FailException fix?
src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java
FailException fix?
Java
apache-2.0
6eefa6a8eacf0728725f9233d828390b36f7d93e
0
pyamsoft/power-manager,pyamsoft/power-manager
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.app.receiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import android.widget.Toast; import com.pyamsoft.powermanager.Injector; import com.pyamsoft.powermanager.app.logger.Logger; import com.pyamsoft.powermanager.app.manager.ExclusiveManager; import com.pyamsoft.powermanager.app.manager.Manager; import javax.inject.Inject; import javax.inject.Named; import timber.log.Timber; public class ScreenOnOffReceiver extends ChargingStateAwareReceiver { @NonNull private final static IntentFilter SCREEN_FILTER; static { SCREEN_FILTER = new IntentFilter(Intent.ACTION_SCREEN_OFF); SCREEN_FILTER.addAction(Intent.ACTION_SCREEN_ON); } @NonNull private final Context appContext; @Inject @Named("wifi_manager") Manager managerWifi; @Inject @Named("data_manager") Manager managerData; @Inject @Named("bluetooth_manager") Manager managerBluetooth; @Inject @Named("sync_manager") Manager managerSync; @Inject @Named("doze_manager") ExclusiveManager managerDoze; @Inject @Named("airplane_manager") Manager managerAirplane; @Inject @Named("logger_manager") Logger logger; private boolean isRegistered; public ScreenOnOffReceiver(@NonNull Context context) { this.appContext = context.getApplicationContext(); isRegistered = false; Injector.get().provideComponent().plusManagerComponent().inject(this); } @Override public final void onReceive(final Context context, final Intent intent) { if (null != intent) { final String action = intent.getAction(); final boolean charging = getCurrentChargingState(context); switch (action) { case Intent.ACTION_SCREEN_OFF: Timber.d("Screen off event"); disableManagers(charging); break; case Intent.ACTION_SCREEN_ON: Timber.d("Screen on event"); enableManagers(); break; default: Timber.e("Invalid event: %s", action); } } } private void enableManagers() { Timber.d("Enable all managed managers"); logger.log("Screen is ON, enable Managers"); managerAirplane.queueSet(); managerDoze.queueExclusiveSet(() -> { managerWifi.queueSet(); managerData.queueSet(); managerBluetooth.queueSet(); managerSync.queueSet(); }); } private void disableManagers(boolean charging) { Timber.d("Disable all managed managers"); logger.log("Screen is OFF, disable Managers"); managerAirplane.queueUnset(charging); managerDoze.queueExclusiveUnset(charging, () -> { managerWifi.queueUnset(charging); managerData.queueUnset(charging); managerBluetooth.queueUnset(charging); managerSync.queueUnset(charging); }); } public final void register() { if (!isRegistered) { cleanup(); appContext.registerReceiver(this, SCREEN_FILTER); isRegistered = true; Toast.makeText(appContext, "Power Manager started", Toast.LENGTH_SHORT).show(); } else { Timber.w("Already registered"); } } private void cleanup() { managerWifi.cleanup(); managerData.cleanup(); managerBluetooth.cleanup(); managerSync.cleanup(); managerDoze.cleanup(); managerAirplane.cleanup(); } public final void unregister() { if (isRegistered) { appContext.unregisterReceiver(this); cleanup(); isRegistered = false; Toast.makeText(appContext, "Power Manager suspended", Toast.LENGTH_SHORT).show(); } else { Timber.w("Already unregistered"); } } }
src/main/java/com/pyamsoft/powermanager/app/receiver/ScreenOnOffReceiver.java
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.app.receiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import android.widget.Toast; import com.pyamsoft.powermanager.Injector; import com.pyamsoft.powermanager.app.logger.Logger; import com.pyamsoft.powermanager.app.manager.ExclusiveManager; import com.pyamsoft.powermanager.app.manager.Manager; import javax.inject.Inject; import javax.inject.Named; import timber.log.Timber; public class ScreenOnOffReceiver extends ChargingStateAwareReceiver { @NonNull private final static IntentFilter SCREEN_FILTER; static { SCREEN_FILTER = new IntentFilter(Intent.ACTION_SCREEN_OFF); SCREEN_FILTER.addAction(Intent.ACTION_SCREEN_ON); } @NonNull private final Context appContext; @Inject @Named("wifi_manager") Manager managerWifi; @Inject @Named("data_manager") Manager managerData; @Inject @Named("bluetooth_manager") Manager managerBluetooth; @Inject @Named("sync_manager") Manager managerSync; @Inject @Named("doze_manager") ExclusiveManager managerDoze; @Inject @Named("airplane_manager") Manager managerAirplane; @Inject @Named("logger_manager") Logger logger; private boolean isRegistered; public ScreenOnOffReceiver(@NonNull Context context) { this.appContext = context.getApplicationContext(); isRegistered = false; Injector.get().provideComponent().plusManagerComponent().inject(this); } @Override public final void onReceive(final Context context, final Intent intent) { if (null != intent) { final String action = intent.getAction(); final boolean charging = getCurrentChargingState(context); switch (action) { case Intent.ACTION_SCREEN_OFF: Timber.d("Screen off event"); disableManagers(charging); break; case Intent.ACTION_SCREEN_ON: Timber.d("Screen on event"); enableManagers(); break; default: Timber.e("Invalid event: %s", action); } } } private void enableManagers() { Timber.d("Enable all managed managers"); logger.log("Screen is OFF, enable Managers"); managerAirplane.queueSet(); managerDoze.queueExclusiveSet(() -> { managerWifi.queueSet(); managerData.queueSet(); managerBluetooth.queueSet(); managerSync.queueSet(); }); } private void disableManagers(boolean charging) { Timber.d("Disable all managed managers"); logger.log("Screen is ON, disable Managers"); managerAirplane.queueUnset(charging); managerDoze.queueExclusiveUnset(charging, () -> { managerWifi.queueUnset(charging); managerData.queueUnset(charging); managerBluetooth.queueUnset(charging); managerSync.queueUnset(charging); }); } public final void register() { if (!isRegistered) { cleanup(); appContext.registerReceiver(this, SCREEN_FILTER); isRegistered = true; Toast.makeText(appContext, "Power Manager started", Toast.LENGTH_SHORT).show(); } else { Timber.w("Already registered"); } } private void cleanup() { managerWifi.cleanup(); managerData.cleanup(); managerBluetooth.cleanup(); managerSync.cleanup(); managerDoze.cleanup(); managerAirplane.cleanup(); } public final void unregister() { if (isRegistered) { appContext.unregisterReceiver(this); cleanup(); isRegistered = false; Toast.makeText(appContext, "Power Manager suspended", Toast.LENGTH_SHORT).show(); } else { Timber.w("Already unregistered"); } } }
Fix logging
src/main/java/com/pyamsoft/powermanager/app/receiver/ScreenOnOffReceiver.java
Fix logging
Java
apache-2.0
6480ffae80a6ef7d35e076c7abe70118b34f7970
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 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.vcs.log.ui.table; import com.intellij.ide.IdeTooltip; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.CommitId; import com.intellij.vcs.log.VcsShortCommitDetails; import com.intellij.vcs.log.data.LoadingDetails; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.EdgePrintElement; import com.intellij.vcs.log.graph.NodePrintElement; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.actions.GraphAction; import com.intellij.vcs.log.graph.actions.GraphAnswer; import com.intellij.vcs.log.impl.CommonUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PositionUtil; import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector; import com.intellij.vcs.log.ui.VcsLogColorManager; import com.intellij.vcs.log.ui.frame.CommitPresentationUtil; import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer; import com.intellij.vcs.log.ui.render.SimpleColoredComponentLinkMouseListener; import com.intellij.vcs.log.util.VcsLogUiUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.Collections; import static com.intellij.vcs.log.ui.table.GraphTableModel.*; /** * Processes mouse clicks and moves on the table */ public class GraphTableController { @NotNull private final VcsLogGraphTable myTable; @NotNull private final VcsLogData myLogData; @NotNull private final VcsLogUiProperties myProperties; @NotNull private final VcsLogColorManager myColorManager; @NotNull private final GraphCellPainter myGraphCellPainter; @NotNull private final GraphCommitCellRenderer myCommitRenderer; public GraphTableController(@NotNull VcsLogData logData, @NotNull VcsLogColorManager colorManager, @NotNull VcsLogUiProperties properties, @NotNull VcsLogGraphTable table, @NotNull GraphCellPainter graphCellPainter, @NotNull GraphCommitCellRenderer commitRenderer) { myTable = table; myLogData = logData; myProperties = properties; myColorManager = colorManager; myGraphCellPainter = graphCellPainter; myCommitRenderer = commitRenderer; MouseAdapter mouseAdapter = new MyMouseAdapter(); table.addMouseMotionListener(mouseAdapter); table.addMouseListener(mouseAdapter); } @Nullable PrintElement findPrintElement(@NotNull MouseEvent e) { int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { return findPrintElement(row, e); } return null; } @Nullable private PrintElement findPrintElement(int row, @NotNull MouseEvent e) { Point point = calcPoint4Graph(e.getPoint()); Collection<? extends PrintElement> printElements = myTable.getVisibleGraph().getRowInfo(row).getPrintElements(); return myGraphCellPainter.getElementUnderCursor(printElements, point.x, point.y); } private void performGraphAction(@Nullable PrintElement printElement, @NotNull MouseEvent e, @NotNull GraphAction.Type actionType) { boolean isClickOnGraphElement = actionType == GraphAction.Type.MOUSE_CLICK && printElement != null; if (isClickOnGraphElement) { triggerElementClick(printElement); } Selection previousSelection = myTable.getSelection(); GraphAnswer<Integer> answer = myTable.getVisibleGraph().getActionController().performAction(new GraphAction.GraphActionImpl(printElement, actionType)); handleGraphAnswer(answer, isClickOnGraphElement, previousSelection, e); } public void handleGraphAnswer(@Nullable GraphAnswer<Integer> answer, boolean dataCouldChange, @Nullable Selection previousSelection, @Nullable MouseEvent e) { if (dataCouldChange) { myTable.getModel().fireTableDataChanged(); // since fireTableDataChanged clears selection we restore it here if (previousSelection != null) { previousSelection .restore(myTable.getVisibleGraph(), answer == null || (answer.getCommitToJump() != null && answer.doJump()), false); } } myTable.repaint(); if (answer == null) { return; } Cursor cursorToSet = answer.getCursorToSet(); if (cursorToSet != null) { myTable.setCursor(UIUtil.cursorIfNotDefault(cursorToSet)); } if (answer.getCommitToJump() != null) { Integer row = myTable.getModel().getVisiblePack().getVisibleGraph().getVisibleRowIndex(answer.getCommitToJump()); if (row != null && row >= 0 && answer.doJump()) { myTable.jumpToRow(row); // TODO wait for the full log and then jump return; } if (e != null) showToolTip(getArrowTooltipText(answer.getCommitToJump(), row), e); } } @NotNull private Point calcPoint4Graph(@NotNull Point clickPoint) { int width = 0; for (int i = 0; i < myTable.getColumnModel().getColumnCount(); i++) { TableColumn column = myTable.getColumnModel().getColumn(i); if (column.getModelIndex() == COMMIT_COLUMN) break; width += column.getWidth(); } return new Point(clickPoint.x - width, PositionUtil.getYInsideRow(clickPoint, myTable.getRowHeight())); } @NotNull private String getArrowTooltipText(int commit, @Nullable Integer row) { VcsShortCommitDetails details; if (row != null && row >= 0) { details = myTable.getModel().getCommitMetadata(row); // preload rows around the commit } else { details = myLogData.getMiniDetailsGetter().getCommitData(commit, Collections.singleton(commit)); // preload just the commit } String balloonText = ""; if (details instanceof LoadingDetails) { CommitId commitId = myLogData.getCommitId(commit); if (commitId != null) { balloonText = "Jump to commit" + " " + commitId.getHash().toShortString(); if (myColorManager.hasMultiplePaths()) { balloonText += " in " + commitId.getRoot().getName(); } } } else { balloonText = "Jump to " + CommitPresentationUtil.getShortSummary(details); } return balloonText; } private void showToolTip(@NotNull String text, @NotNull MouseEvent e) { // standard tooltip does not allow to customize its location, and locating tooltip above can obscure some important info VcsLogUiUtil.showTooltip(myTable, new Point(e.getX() + 5, e.getY()), Balloon.Position.atRight, text); } private void showOrHideCommitTooltip(int row, int column, @NotNull MouseEvent e) { if (!showTooltip(row, column, e.getPoint(), false)) { if (IdeTooltipManager.getInstance().hasCurrent()) { IdeTooltipManager.getInstance().hideCurrent(e); } } } private boolean showTooltip(int row, int column, @NotNull Point point, boolean now) { JComponent tipComponent = myCommitRenderer.getTooltip(myTable.getValueAt(row, myTable.convertColumnIndexToView(column)), calcPoint4Graph(point), row); if (tipComponent != null) { myTable.getExpandableItemsHandler().setEnabled(false); IdeTooltip tooltip = new IdeTooltip(myTable, point, new Wrapper(tipComponent)).setPreferredPosition(Balloon.Position.below); IdeTooltipManager.getInstance().show(tooltip, now); return true; } return false; } public void showTooltip(int row) { Point point = new Point(getColumnLeftXCoordinate(myTable.convertColumnIndexToView(COMMIT_COLUMN)) + myCommitRenderer.getTooltipXCoordinate(row), row * myTable.getRowHeight() + myTable.getRowHeight() / 2); showTooltip(row, COMMIT_COLUMN, point, true); } private void performRootColumnAction() { if (myColorManager.hasMultiplePaths() && myProperties.exists(CommonUiProperties.SHOW_ROOT_NAMES)) { triggerClick("root.column"); myProperties.set(CommonUiProperties.SHOW_ROOT_NAMES, !myProperties.get(CommonUiProperties.SHOW_ROOT_NAMES)); } } private static void triggerElementClick(@NotNull PrintElement printElement) { if (printElement instanceof NodePrintElement) { triggerClick("node"); } else if (printElement instanceof EdgePrintElement) { if (((EdgePrintElement)printElement).hasArrow()) { triggerClick("arrow"); } } } private static void triggerClick(@NotNull String target) { VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.TABLE_CLICKED, data -> data.addData("target", target)); } protected int getColumnLeftXCoordinate(int viewColumnIndex) { int x = 0; for (int i = 0; i < viewColumnIndex; i++) { x += myTable.getColumnModel().getColumn(i).getWidth(); } return x; } private class MyMouseAdapter extends MouseAdapter { private static final int BORDER_THICKNESS = 3; @NotNull private final TableLinkMouseListener myLinkListener = new MyLinkMouseListener(); @Nullable private Cursor myLastCursor = null; @Override public void mouseClicked(MouseEvent e) { if (myLinkListener.onClick(e, e.getClickCount())) { return; } int c = myTable.columnAtPoint(e.getPoint()); int column = myTable.convertColumnIndexToModel(c); if (e.getClickCount() == 2) { // when we reset column width, commit column eats all the remaining space // (or gives the required space) // so it is logical that we reset column width by right border if it is on the left of the commit column // and by the left border otherwise int commitColumnIndex = myTable.convertColumnIndexToView(COMMIT_COLUMN); boolean useLeftBorder = c > commitColumnIndex; if ((useLeftBorder ? isOnLeftBorder(e, c) : isOnRightBorder(e, c)) && ArrayUtil.indexOf(DYNAMIC_COLUMNS, column) != -1) { myTable.resetColumnWidth(column); } else { // user may have clicked just outside of the border // in that case, c is not the column we are looking for int c2 = myTable.columnAtPoint(new Point(e.getPoint().x + (useLeftBorder ? 1 : -1) * JBUIScale.scale(BORDER_THICKNESS), e.getPoint().y)); int column2 = myTable.convertColumnIndexToModel(c2); if ((useLeftBorder ? isOnLeftBorder(e, c2) : isOnRightBorder(e, c2)) && ArrayUtil.indexOf(DYNAMIC_COLUMNS, column) != -1) { myTable.resetColumnWidth(column2); } } } int row = myTable.rowAtPoint(e.getPoint()); if ((row >= 0 && row < myTable.getRowCount()) && e.getClickCount() == 1) { if (column == ROOT_COLUMN) { performRootColumnAction(); } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement != null) { performGraphAction(printElement, e, GraphAction.Type.MOUSE_CLICK); } } } } public boolean isOnLeftBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS); } public boolean isOnRightBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) + myTable.getColumnModel().getColumn(column).getWidth() - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS); } @Override public void mouseMoved(MouseEvent e) { if (myTable.getRowCount() == 0) return; if (myTable.isResizingColumns()) return; myTable.getExpandableItemsHandler().setEnabled(true); if (myLinkListener.getTagAt(e) != null) { swapCursor(Cursor.HAND_CURSOR); return; } int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { int column = myTable.convertColumnIndexToModel(myTable.columnAtPoint(e.getPoint())); if (column == ROOT_COLUMN) { swapCursor(Cursor.HAND_CURSOR); return; } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement == null) restoreCursor(Cursor.HAND_CURSOR); performGraphAction(printElement, e, GraphAction.Type.MOUSE_OVER); // if printElement is null, still need to unselect whatever was selected in a graph if (printElement == null) { showOrHideCommitTooltip(row, column, e); } return; } } restoreCursor(Cursor.HAND_CURSOR); } private void swapCursor(int newCursorType) { if (myTable.getCursor().getType() != newCursorType && myLastCursor == null) { Cursor newCursor = Cursor.getPredefinedCursor(newCursorType); myLastCursor = myTable.getCursor(); myTable.setCursor(newCursor); } } private void restoreCursor(int newCursorType) { if (myTable.getCursor().getType() == newCursorType) { myTable.setCursor(UIUtil.cursorIfNotDefault(myLastCursor)); myLastCursor = null; } } @Override public void mouseEntered(MouseEvent e) { // Do nothing } @Override public void mouseExited(MouseEvent e) { myTable.getExpandableItemsHandler().setEnabled(true); } private class MyLinkMouseListener extends SimpleColoredComponentLinkMouseListener { @Nullable @Override public Object getTagAt(@NotNull MouseEvent e) { return ObjectUtils.tryCast(super.getTagAt(e), SimpleColoredComponent.BrowserLauncherTag.class); } } } }
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/GraphTableController.java
// Copyright 2000-2019 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.vcs.log.ui.table; import com.intellij.ide.IdeTooltip; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.CommitId; import com.intellij.vcs.log.VcsShortCommitDetails; import com.intellij.vcs.log.data.LoadingDetails; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.EdgePrintElement; import com.intellij.vcs.log.graph.NodePrintElement; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.actions.GraphAction; import com.intellij.vcs.log.graph.actions.GraphAnswer; import com.intellij.vcs.log.impl.CommonUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PositionUtil; import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector; import com.intellij.vcs.log.ui.VcsLogColorManager; import com.intellij.vcs.log.ui.frame.CommitPresentationUtil; import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer; import com.intellij.vcs.log.ui.render.SimpleColoredComponentLinkMouseListener; import com.intellij.vcs.log.util.VcsLogUiUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.Collections; import static com.intellij.vcs.log.ui.table.GraphTableModel.*; /** * Processes mouse clicks and moves on the table */ public class GraphTableController { @NotNull private final VcsLogGraphTable myTable; @NotNull private final VcsLogData myLogData; @NotNull private final VcsLogUiProperties myProperties; @NotNull private final VcsLogColorManager myColorManager; @NotNull private final GraphCellPainter myGraphCellPainter; @NotNull private final GraphCommitCellRenderer myCommitRenderer; public GraphTableController(@NotNull VcsLogData logData, @NotNull VcsLogColorManager colorManager, @NotNull VcsLogUiProperties properties, @NotNull VcsLogGraphTable table, @NotNull GraphCellPainter graphCellPainter, @NotNull GraphCommitCellRenderer commitRenderer) { myTable = table; myLogData = logData; myProperties = properties; myColorManager = colorManager; myGraphCellPainter = graphCellPainter; myCommitRenderer = commitRenderer; MouseAdapter mouseAdapter = new MyMouseAdapter(); table.addMouseMotionListener(mouseAdapter); table.addMouseListener(mouseAdapter); } @Nullable PrintElement findPrintElement(@NotNull MouseEvent e) { int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { return findPrintElement(row, e); } return null; } @Nullable private PrintElement findPrintElement(int row, @NotNull MouseEvent e) { Point point = calcPoint4Graph(e.getPoint()); Collection<? extends PrintElement> printElements = myTable.getVisibleGraph().getRowInfo(row).getPrintElements(); return myGraphCellPainter.getElementUnderCursor(printElements, point.x, point.y); } private void performGraphAction(@Nullable PrintElement printElement, @NotNull MouseEvent e, @NotNull GraphAction.Type actionType) { boolean isClickOnGraphElement = actionType == GraphAction.Type.MOUSE_CLICK && printElement != null; if (isClickOnGraphElement) { triggerElementClick(printElement); } Selection previousSelection = myTable.getSelection(); GraphAnswer<Integer> answer = myTable.getVisibleGraph().getActionController().performAction(new GraphAction.GraphActionImpl(printElement, actionType)); handleGraphAnswer(answer, isClickOnGraphElement, previousSelection, e); } public void handleGraphAnswer(@Nullable GraphAnswer<Integer> answer, boolean dataCouldChange, @Nullable Selection previousSelection, @Nullable MouseEvent e) { if (dataCouldChange) { myTable.getModel().fireTableDataChanged(); // since fireTableDataChanged clears selection we restore it here if (previousSelection != null) { previousSelection .restore(myTable.getVisibleGraph(), answer == null || (answer.getCommitToJump() != null && answer.doJump()), false); } } myTable.repaint(); if (answer == null) { return; } Cursor cursorToSet = answer.getCursorToSet(); if (cursorToSet != null) { myTable.setCursor(UIUtil.cursorIfNotDefault(cursorToSet)); } if (answer.getCommitToJump() != null) { Integer row = myTable.getModel().getVisiblePack().getVisibleGraph().getVisibleRowIndex(answer.getCommitToJump()); if (row != null && row >= 0 && answer.doJump()) { myTable.jumpToRow(row); // TODO wait for the full log and then jump return; } if (e != null) showToolTip(getArrowTooltipText(answer.getCommitToJump(), row), e); } } @NotNull private Point calcPoint4Graph(@NotNull Point clickPoint) { int width = 0; for (int i = 0; i < myTable.getColumnModel().getColumnCount(); i++) { TableColumn column = myTable.getColumnModel().getColumn(i); if (column.getModelIndex() == COMMIT_COLUMN) break; width += column.getWidth(); } return new Point(clickPoint.x - width, PositionUtil.getYInsideRow(clickPoint, myTable.getRowHeight())); } @NotNull private String getArrowTooltipText(int commit, @Nullable Integer row) { VcsShortCommitDetails details; if (row != null && row >= 0) { details = myTable.getModel().getCommitMetadata(row); // preload rows around the commit } else { details = myLogData.getMiniDetailsGetter().getCommitData(commit, Collections.singleton(commit)); // preload just the commit } String balloonText = ""; if (details instanceof LoadingDetails) { CommitId commitId = myLogData.getCommitId(commit); if (commitId != null) { balloonText = "Jump to commit" + " " + commitId.getHash().toShortString(); if (myColorManager.hasMultiplePaths()) { balloonText += " in " + commitId.getRoot().getName(); } } } else { balloonText = "Jump to " + CommitPresentationUtil.getShortSummary(details); } return balloonText; } private void showToolTip(@NotNull String text, @NotNull MouseEvent e) { // standard tooltip does not allow to customize its location, and locating tooltip above can obscure some important info VcsLogUiUtil.showTooltip(myTable, new Point(e.getX() + 5, e.getY()), Balloon.Position.atRight, text); } private void showOrHideCommitTooltip(int row, int column, @NotNull MouseEvent e) { if (!showTooltip(row, column, e.getPoint(), false)) { if (IdeTooltipManager.getInstance().hasCurrent()) { IdeTooltipManager.getInstance().hideCurrent(e); } } } private boolean showTooltip(int row, int column, @NotNull Point point, boolean now) { JComponent tipComponent = myCommitRenderer.getTooltip(myTable.getValueAt(row, myTable.convertColumnIndexToView(column)), calcPoint4Graph(point), row); if (tipComponent != null) { myTable.getExpandableItemsHandler().setEnabled(false); IdeTooltip tooltip = new IdeTooltip(myTable, point, new Wrapper(tipComponent)).setPreferredPosition(Balloon.Position.below); IdeTooltipManager.getInstance().show(tooltip, now); return true; } return false; } public void showTooltip(int row) { Point point = new Point(getColumnLeftXCoordinate(myTable.convertColumnIndexToView(COMMIT_COLUMN)) + myCommitRenderer.getTooltipXCoordinate(row), row * myTable.getRowHeight() + myTable.getRowHeight() / 2); showTooltip(row, COMMIT_COLUMN, point, true); } private void performRootColumnAction() { if (myColorManager.hasMultiplePaths() && myProperties.exists(CommonUiProperties.SHOW_ROOT_NAMES)) { triggerClick("root.column"); myProperties.set(CommonUiProperties.SHOW_ROOT_NAMES, !myProperties.get(CommonUiProperties.SHOW_ROOT_NAMES)); } } private static void triggerElementClick(@NotNull PrintElement printElement) { if (printElement instanceof NodePrintElement) { triggerClick("node"); } else if (printElement instanceof EdgePrintElement) { if (((EdgePrintElement)printElement).hasArrow()) { triggerClick("arrow"); } } } private static void triggerClick(@NotNull String target) { VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.TABLE_CLICKED, data -> data.addData("target", target)); } protected int getColumnLeftXCoordinate(int viewColumnIndex) { int x = 0; for (int i = 0; i < viewColumnIndex; i++) { x += myTable.getColumnModel().getColumn(i).getWidth(); } return x; } private class MyMouseAdapter extends MouseAdapter { private static final int BORDER_THICKNESS = 3; @NotNull private final TableLinkMouseListener myLinkListener = new MyLinkMouseListener(); @Nullable private Cursor myLastCursor = null; @Override public void mouseClicked(MouseEvent e) { if (myLinkListener.onClick(e, e.getClickCount())) { return; } int c = myTable.columnAtPoint(e.getPoint()); int column = myTable.convertColumnIndexToModel(c); if (e.getClickCount() == 2) { // when we reset column width, commit column eats all the remaining space // (or gives the required space) // so it is logical that we reset column width by right border if it is on the left of the commit column // and by the left border otherwise int commitColumnIndex = myTable.convertColumnIndexToView(COMMIT_COLUMN); boolean useLeftBorder = c > commitColumnIndex; if ((useLeftBorder ? isOnLeftBorder(e, c) : isOnRightBorder(e, c)) && ArrayUtil.indexOf(DYNAMIC_COLUMNS, column) != -1) { myTable.resetColumnWidth(column); } else { // user may have clicked just outside of the border // in that case, c is not the column we are looking for int c2 = myTable.columnAtPoint(new Point(e.getPoint().x + (useLeftBorder ? 1 : -1) * JBUIScale.scale(BORDER_THICKNESS), e.getPoint().y)); int column2 = myTable.convertColumnIndexToModel(c2); if ((useLeftBorder ? isOnLeftBorder(e, c2) : isOnRightBorder(e, c2)) && ArrayUtil.indexOf(DYNAMIC_COLUMNS, column) != -1) { myTable.resetColumnWidth(column2); } } } int row = myTable.rowAtPoint(e.getPoint()); if ((row >= 0 && row < myTable.getRowCount()) && e.getClickCount() == 1) { if (column == ROOT_COLUMN) { performRootColumnAction(); } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement != null) { performGraphAction(printElement, e, GraphAction.Type.MOUSE_CLICK); } } } } public boolean isOnLeftBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS); } public boolean isOnRightBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) + myTable.getColumnModel().getColumn(column).getWidth() - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS); } @Override public void mouseMoved(MouseEvent e) { if (myTable.isResizingColumns()) return; myTable.getExpandableItemsHandler().setEnabled(true); if (myLinkListener.getTagAt(e) != null) { swapCursor(Cursor.HAND_CURSOR); return; } int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { int column = myTable.convertColumnIndexToModel(myTable.columnAtPoint(e.getPoint())); if (column == ROOT_COLUMN) { swapCursor(Cursor.HAND_CURSOR); return; } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement == null) restoreCursor(Cursor.HAND_CURSOR); performGraphAction(printElement, e, GraphAction.Type.MOUSE_OVER); // if printElement is null, still need to unselect whatever was selected in a graph if (printElement == null) { showOrHideCommitTooltip(row, column, e); } return; } } restoreCursor(Cursor.HAND_CURSOR); } private void swapCursor(int newCursorType) { if (myTable.getCursor().getType() != newCursorType && myLastCursor == null) { Cursor newCursor = Cursor.getPredefinedCursor(newCursorType); myLastCursor = myTable.getCursor(); myTable.setCursor(newCursor); } } private void restoreCursor(int newCursorType) { if (myTable.getCursor().getType() == newCursorType) { myTable.setCursor(UIUtil.cursorIfNotDefault(myLastCursor)); myLastCursor = null; } } @Override public void mouseEntered(MouseEvent e) { // Do nothing } @Override public void mouseExited(MouseEvent e) { myTable.getExpandableItemsHandler().setEnabled(true); } private class MyLinkMouseListener extends SimpleColoredComponentLinkMouseListener { @Nullable @Override public Object getTagAt(@NotNull MouseEvent e) { return ObjectUtils.tryCast(super.getTagAt(e), SimpleColoredComponent.BrowserLauncherTag.class); } } } }
[vcs-log] do not override cursor for empty table When table is empty, status text controls the cursor. GitOrigin-RevId: 0ba37e8d0ea2cd95143305e2c3fdf140c370214c
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/GraphTableController.java
[vcs-log] do not override cursor for empty table
Java
apache-2.0
ae72db355967e6f1c500c13e7d4b56d1df365b9d
0
jawer/mvlasov
package ru.job4j.twodimensionaliterator; import java.util.Iterator; import java.util.NoSuchElementException; /**. * Class MatrixIterator implements Iterator for two-dimensional array including jugged array. * @author Mikhail Vlasov * @since 11.28.2017 * @version 1 */ public class MatrixIterator implements Iterator { /**. * Our array. */ private final int[][] values; /**. * Coordinates in array. */ private int x = 0, y = 0; /**. * Constructor. * @param values array. */ public MatrixIterator(int[][] values) { this.values = values; } /**. * Overriden hasNext checks if the next element exists. * @return boolean true if the next element exists. */ @Override public boolean hasNext() { if (x == values.length || y == values[x].length) { throw new NoSuchElementException("Out of array bound."); } return values.length > x || values[x].length > y; } /**. * Overriden next returns next element if available. Otherwise throws NoSuchElementException. * @return Object next element. */ @Override public Object next() { if (!hasNext()) { throw new NoSuchElementException("Out of array bound."); } else if (x + 1 == values.length && y + 1 == values[x].length) { return values[x++][y++]; } else if (y + 1 == values[x].length) { int temp = y; y = 0; return values[x++][temp]; } else { return values[x][y++]; } } }
chapter_005/src/main/java/ru/job4j/twodimensionaliterator/MatrixIterator.java
package ru.job4j.twodimensionaliterator; import java.util.Iterator; import java.util.NoSuchElementException; /**. * Class MatrixIterator implements Iterator for two-dimensional array including jugged array. * @author Mikhail Vlasov * @since 11.28.2017 * @version 1 */ public class MatrixIterator implements Iterator { /**. * Our array. */ private final int[][] values; /**. * Coordinates in array. */ private int x = 0, y = 0; /**. * Constructor. * @param values array. */ public MatrixIterator(int[][] values) { this.values = values; } /**. * Overriden hasNext checks if the next element exists. * @return boolean true if the next element exists. */ @Override public boolean hasNext() { if (x == values.length || y == values[x].length) { throw new NoSuchElementException("Out of array bound."); } return values.length > x || values[x].length > y; } /**. * Overriden next returns next element if available. Otherwise throws NoSuchElementException. * @return Object next element. */ @Override public Object next() { if (hasNext() == false) { throw new NoSuchElementException("Out of array bound."); } else if (x + 1 == values.length && y + 1 == values[x].length) { return values[x++][y++]; } else if (y + 1 == values[x].length) { int temp = y; y = 0; return values[x++][temp]; } else { return values[x][y++]; } } }
Task 9539
chapter_005/src/main/java/ru/job4j/twodimensionaliterator/MatrixIterator.java
Task 9539
Java
apache-2.0
251171c3b01b35b382deab69443ccafef31a8870
0
madhurihn/YCSB_ToyDB,madhurihn/YCSB_ToyDB,brianfrankcooper/YCSB,jaemyoun/YCSB,manolama/YCSB,ChristianNavolskyi/YCSB,brianfrankcooper/YCSB,ChristianNavolskyi/YCSB,zyguan/ycsb,brianfrankcooper/YCSB,leschekhomann/YCSB,manolama/YCSB,zyguan/ycsb,madhurihn/YCSB_ToyDB,manolama/YCSB,zyguan/ycsb,jaemyoun/YCSB,brianfrankcooper/YCSB,jaemyoun/YCSB,cricket007/YCSB,leschekhomann/YCSB,leschekhomann/YCSB,madhurihn/YCSB_ToyDB,cricket007/YCSB,manolama/YCSB,zyguan/ycsb,ChristianNavolskyi/YCSB,leschekhomann/YCSB,cricket007/YCSB,cricket007/YCSB,ChristianNavolskyi/YCSB,jaemyoun/YCSB
/** * Copyright (c) 2012 YCSB contributors. 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. See accompanying * LICENSE file. */ package com.yahoo.ycsb.db; import static org.elasticsearch.common.settings.Settings.Builder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DB; import com.yahoo.ycsb.DBException; import com.yahoo.ycsb.Status; import com.yahoo.ycsb.StringByteIterator; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.node.Node; import org.elasticsearch.search.SearchHit; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Vector; /** * Elasticsearch client for YCSB framework. * * <p> * Default properties to set: * </p> * <ul> * <li>es.cluster.name = es.ycsb.cluster * <li>es.client = true * <li>es.index.key = es.ycsb * </ul> * * @author Sharmarke Aden * */ public class ElasticsearchClient extends DB { public static final String DEFAULT_CLUSTER_NAME = "es.ycsb.cluster"; public static final String DEFAULT_INDEX_KEY = "es.ycsb"; public static final String DEFAULT_REMOTE_HOST = "localhost:9300"; private Node node; private Client client; private String indexKey; private Boolean remoteMode; /** * Initialize any state for this DB. Called once per DB instance; there is one * DB instance per client thread. */ @Override public void init() throws DBException { Properties props = getProperties(); this.indexKey = props.getProperty("es.index.key", DEFAULT_INDEX_KEY); String clusterName = props.getProperty("cluster.name", DEFAULT_CLUSTER_NAME); // Check if transport client needs to be used (To connect to multiple // elasticsearch nodes) remoteMode = Boolean .parseBoolean(props.getProperty("elasticsearch.remote", "false")); Boolean newdb = Boolean.parseBoolean(props.getProperty("elasticsearch.newdb", "false")); Builder settings = Settings.settingsBuilder() .put("node.local", "true") .put("path.data", System.getProperty("java.io.tmpdir") + "/esdata") .put("index.mapping._id.indexed", "true") .put("index.gateway.type", "none") .put("index.number_of_shards", "1") .put("index.number_of_replicas", "0") .put("path.home", System.getProperty("java.io.tmpdir")); // if properties file contains elasticsearch user defined properties // add it to the settings file (will overwrite the defaults). settings.put(props); System.out.println( "Elasticsearch starting node = " + settings.get("cluster.name")); System.out .println("Elasticsearch node data path = " + settings.get("path.data")); System.out.println("Elasticsearch Remote Mode = " + remoteMode); // Remote mode support for connecting to remote elasticsearch cluster if (remoteMode) { settings.put("client.transport.sniff", true) .put("client.transport.ignore_cluster_name", false) .put("client.transport.ping_timeout", "30s") .put("client.transport.nodes_sampler_interval", "30s"); // Default it to localhost:9300 String[] nodeList = props.getProperty("elasticsearch.hosts.list", DEFAULT_REMOTE_HOST) .split(","); System.out.println("Elasticsearch Remote Hosts = " + props.getProperty("elasticsearch.hosts.list", DEFAULT_REMOTE_HOST)); TransportClient tClient = TransportClient.builder() .settings(settings).build(); for (String h : nodeList) { String[] nodes = h.split(":"); try { tClient.addTransportAddress(new InetSocketTransportAddress( InetAddress.getByName(nodes[0]), Integer.parseInt(nodes[1]) )); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse port number.", e); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unable to Identify host.", e); } } client = tClient; } else { // Start node only if transport client mode is disabled node = nodeBuilder().clusterName(clusterName).settings(settings).node(); node.start(); client = node.client(); } //wait for shards to be ready client.admin().cluster() .health(new ClusterHealthRequest("lists").waitForActiveShards(1)) .actionGet(); if (newdb) { client.admin().indices().prepareDelete(indexKey).execute().actionGet(); client.admin().indices().prepareCreate(indexKey).execute().actionGet(); } else { boolean exists = client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (!exists) { client.admin().indices().prepareCreate(indexKey).execute().actionGet(); } } } @Override public void cleanup() throws DBException { if (!remoteMode) { if (!node.isClosed()) { client.close(); node.close(); } } else { client.close(); } } /** * Insert a record in the database. Any field/value pairs in the specified * values HashMap will be written into the record with the specified record * key. * * @param table * The name of the table * @param key * The record key of the record to insert. * @param values * A HashMap of field/value pairs to insert in the record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status insert(String table, String key, HashMap<String, ByteIterator> values) { try { final XContentBuilder doc = jsonBuilder().startObject(); for (Entry<String, String> entry : StringByteIterator.getStringMap(values) .entrySet()) { doc.field(entry.getKey(), entry.getValue()); } doc.endObject(); client.prepareIndex(indexKey, table, key).setSource(doc).execute() .actionGet(); return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Delete a record from the database. * * @param table * The name of the table * @param key * The record key of the record to delete. * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status delete(String table, String key) { try { client.prepareDelete(indexKey, table, key).execute().actionGet(); return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Read a record from the database. Each field/value pair from the result will * be stored in a HashMap. * * @param table * The name of the table * @param key * The record key of the record to read. * @param fields * The list of fields to read, or null for all of them * @param result * A HashMap of field/value pairs for the result * @return Zero on success, a non-zero error code on error or "not found". */ @Override public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) { try { final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); if (response.isExists()) { if (fields != null) { for (String field : fields) { result.put(field, new StringByteIterator( (String) response.getSource().get(field))); } } else { for (String field : response.getSource().keySet()) { result.put(field, new StringByteIterator( (String) response.getSource().get(field))); } } return Status.OK; } } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Update a record in the database. Any field/value pairs in the specified * values HashMap will be written into the record with the specified record * key, overwriting any existing values with the same field name. * * @param table * The name of the table * @param key * The record key of the record to write. * @param values * A HashMap of field/value pairs to update in the record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status update(String table, String key, HashMap<String, ByteIterator> values) { try { final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); if (response.isExists()) { for (Entry<String, String> entry : StringByteIterator .getStringMap(values).entrySet()) { response.getSource().put(entry.getKey(), entry.getValue()); } client.prepareIndex(indexKey, table, key) .setSource(response.getSource()).execute().actionGet(); return Status.OK; } } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Perform a range scan for a set of records in the database. Each field/value * pair from the result will be stored in a HashMap. * * @param table * The name of the table * @param startkey * The record key of the first record to read. * @param recordcount * The number of records to read * @param fields * The list of fields to read, or null for all of them * @param result * A Vector of HashMaps, where each HashMap is a set field/value * pairs for one record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { final RangeQueryBuilder rangeQuery = rangeQuery("_id").gte(startkey); final SearchResponse response = client.prepareSearch(indexKey) .setTypes(table) .setQuery(rangeQuery) .setSize(recordcount) .execute() .actionGet(); HashMap<String, ByteIterator> entry; for (SearchHit hit : response.getHits()) { entry = new HashMap<String, ByteIterator>(fields.size()); for (String field : fields) { entry.put(field, new StringByteIterator((String) hit.getSource().get(field))); } result.add(entry); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } }
elasticsearch/src/main/java/com/yahoo/ycsb/db/ElasticsearchClient.java
/** * Copyright (c) 2012 YCSB contributors. 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. See accompanying * LICENSE file. */ package com.yahoo.ycsb.db; import static org.elasticsearch.common.settings.Settings.Builder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DB; import com.yahoo.ycsb.DBException; import com.yahoo.ycsb.Status; import com.yahoo.ycsb.StringByteIterator; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.node.Node; import org.elasticsearch.search.SearchHit; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Vector; /** * Elasticsearch client for YCSB framework. * * <p> * Default properties to set: * </p> * <ul> * <li>es.cluster.name = es.ycsb.cluster * <li>es.client = true * <li>es.index.key = es.ycsb * </ul> * * @author Sharmarke Aden * */ public class ElasticsearchClient extends DB { public static final String DEFAULT_CLUSTER_NAME = "es.ycsb.cluster"; public static final String DEFAULT_INDEX_KEY = "es.ycsb"; public static final String DEFAULT_REMOTE_HOST = "localhost:9300"; private Node node; private Client client; private String indexKey; private Boolean remoteMode; /** * Initialize any state for this DB. Called once per DB instance; there is one * DB instance per client thread. */ @Override public void init() throws DBException { Properties props = getProperties(); this.indexKey = props.getProperty("es.index.key", DEFAULT_INDEX_KEY); String clusterName = props.getProperty("cluster.name", DEFAULT_CLUSTER_NAME); // Check if transport client needs to be used (To connect to multiple // elasticsearch nodes) remoteMode = Boolean .parseBoolean(props.getProperty("elasticsearch.remote", "false")); Boolean newdb = Boolean.parseBoolean(props.getProperty("elasticsearch.newdb", "false")); Builder settings = Settings.settingsBuilder() .put("node.local", "true") .put("path.data", System.getProperty("java.io.tmpdir") + "/esdata") .put("discovery.zen.ping.multicast.enabled", "false") .put("index.mapping._id.indexed", "true") .put("index.gateway.type", "none") .put("index.number_of_shards", "1") .put("index.number_of_replicas", "0") .put("path.home", System.getProperty("java.io.tmpdir")); // if properties file contains elasticsearch user defined properties // add it to the settings file (will overwrite the defaults). settings.put(props); System.out.println( "Elasticsearch starting node = " + settings.get("cluster.name")); System.out .println("Elasticsearch node data path = " + settings.get("path.data")); System.out.println("Elasticsearch Remote Mode = " + remoteMode); // Remote mode support for connecting to remote elasticsearch cluster if (remoteMode) { settings.put("client.transport.sniff", true) .put("client.transport.ignore_cluster_name", false) .put("client.transport.ping_timeout", "30s") .put("client.transport.nodes_sampler_interval", "30s"); // Default it to localhost:9300 String[] nodeList = props.getProperty("elasticsearch.hosts.list", DEFAULT_REMOTE_HOST) .split(","); System.out.println("Elasticsearch Remote Hosts = " + props.getProperty("elasticsearch.hosts.list", DEFAULT_REMOTE_HOST)); TransportClient tClient = TransportClient.builder() .settings(settings).build(); for (String h : nodeList) { String[] nodes = h.split(":"); try { tClient.addTransportAddress(new InetSocketTransportAddress( InetAddress.getByName(nodes[0]), Integer.parseInt(nodes[1]) )); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse port number.", e); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unable to Identify host.", e); } } client = tClient; } else { // Start node only if transport client mode is disabled node = nodeBuilder().clusterName(clusterName).settings(settings).node(); node.start(); client = node.client(); } //wait for shards to be ready client.admin().cluster() .health(new ClusterHealthRequest("lists").waitForActiveShards(1)) .actionGet(); if (newdb) { client.admin().indices().prepareDelete(indexKey).execute().actionGet(); client.admin().indices().prepareCreate(indexKey).execute().actionGet(); } else { boolean exists = client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (!exists) { client.admin().indices().prepareCreate(indexKey).execute().actionGet(); } } } @Override public void cleanup() throws DBException { if (!remoteMode) { if (!node.isClosed()) { client.close(); node.close(); } } else { client.close(); } } /** * Insert a record in the database. Any field/value pairs in the specified * values HashMap will be written into the record with the specified record * key. * * @param table * The name of the table * @param key * The record key of the record to insert. * @param values * A HashMap of field/value pairs to insert in the record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status insert(String table, String key, HashMap<String, ByteIterator> values) { try { final XContentBuilder doc = jsonBuilder().startObject(); for (Entry<String, String> entry : StringByteIterator.getStringMap(values) .entrySet()) { doc.field(entry.getKey(), entry.getValue()); } doc.endObject(); client.prepareIndex(indexKey, table, key).setSource(doc).execute() .actionGet(); return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Delete a record from the database. * * @param table * The name of the table * @param key * The record key of the record to delete. * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status delete(String table, String key) { try { client.prepareDelete(indexKey, table, key).execute().actionGet(); return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Read a record from the database. Each field/value pair from the result will * be stored in a HashMap. * * @param table * The name of the table * @param key * The record key of the record to read. * @param fields * The list of fields to read, or null for all of them * @param result * A HashMap of field/value pairs for the result * @return Zero on success, a non-zero error code on error or "not found". */ @Override public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) { try { final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); if (response.isExists()) { if (fields != null) { for (String field : fields) { result.put(field, new StringByteIterator( (String) response.getSource().get(field))); } } else { for (String field : response.getSource().keySet()) { result.put(field, new StringByteIterator( (String) response.getSource().get(field))); } } return Status.OK; } } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Update a record in the database. Any field/value pairs in the specified * values HashMap will be written into the record with the specified record * key, overwriting any existing values with the same field name. * * @param table * The name of the table * @param key * The record key of the record to write. * @param values * A HashMap of field/value pairs to update in the record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status update(String table, String key, HashMap<String, ByteIterator> values) { try { final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); if (response.isExists()) { for (Entry<String, String> entry : StringByteIterator .getStringMap(values).entrySet()) { response.getSource().put(entry.getKey(), entry.getValue()); } client.prepareIndex(indexKey, table, key) .setSource(response.getSource()).execute().actionGet(); return Status.OK; } } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } /** * Perform a range scan for a set of records in the database. Each field/value * pair from the result will be stored in a HashMap. * * @param table * The name of the table * @param startkey * The record key of the first record to read. * @param recordcount * The number of records to read * @param fields * The list of fields to read, or null for all of them * @param result * A Vector of HashMaps, where each HashMap is a set field/value * pairs for one record * @return Zero on success, a non-zero error code on error. See this class's * description for a discussion of error codes. */ @Override public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { final RangeQueryBuilder rangeQuery = rangeQuery("_id").gte(startkey); final SearchResponse response = client.prepareSearch(indexKey) .setTypes(table) .setQuery(rangeQuery) .setSize(recordcount) .execute() .actionGet(); HashMap<String, ByteIterator> entry; for (SearchHit hit : response.getHits()) { entry = new HashMap<String, ByteIterator>(fields.size()); for (String field : fields) { entry.put(field, new StringByteIterator((String) hit.getSource().get(field))); } result.add(entry); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; } }
[elasticsearch] Remove unneeded multicast setting
elasticsearch/src/main/java/com/yahoo/ycsb/db/ElasticsearchClient.java
[elasticsearch] Remove unneeded multicast setting
Java
apache-2.0
1eb22149d0bd0bb6384a1b2c17f987ec0798934f
0
joelind/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone
/* * Copyright 2007 ZXing 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 com.google.zxing.client.j2me; import javax.microedition.amms.control.camera.ExposureControl; import javax.microedition.amms.control.camera.FocusControl; import javax.microedition.amms.control.camera.ZoomControl; import javax.microedition.media.Control; import javax.microedition.media.Controllable; import javax.microedition.media.MediaException; /** * <p>See {@link DefaultMultimediaManager} documentation for details.</p> * * <p>This class should never be directly imported or reference in the code.</p> * * @author Sean Owen (srowen@google.com) */ final class AdvancedMultimediaManager implements MultimediaManager { private static final int NO_ZOOM = 100; private static final int MAX_ZOOM = 200; private static final long FOCUS_TIME_MS = 750L; private static final String DESIRED_METERING = "center-weighted"; AdvancedMultimediaManager() { // Another try at fixing Issue 70. Seems like FocusControl et al. are sometimes not // loaded until first use in the setFocus() method. This is too late for our // mechanism to handle, since it is trying to detect this API is not available // at the time this class is instantiated. We can't move the player.getControl() calls // into here since we don't have a Controllable to call on, since we can't pass an // arg into the constructor, since we can't do that in J2ME when instantiating via // newInstance(). So we just try writing some dead code here to induce the VM to // definitely load the classes now: Control dummy = null; ExposureControl dummy1 = (ExposureControl) dummy; FocusControl dummy2 = (FocusControl) dummy; ZoomControl dummy3 = (ZoomControl) dummy; } public void setFocus(Controllable player) { FocusControl focusControl = (FocusControl) player.getControl("javax.microedition.amms.control.camera.FocusControl"); if (focusControl == null) { focusControl = (FocusControl) player.getControl("FocusControl"); } if (focusControl != null) { try { if (focusControl.isMacroSupported() && !focusControl.getMacro()) { focusControl.setMacro(true); } if (focusControl.isAutoFocusSupported()) { focusControl.setFocus(FocusControl.AUTO); try { Thread.sleep(FOCUS_TIME_MS); // let it focus... } catch (InterruptedException ie) { // continue } focusControl.setFocus(FocusControl.AUTO_LOCK); } } catch (MediaException me) { // continue } } } public void setZoom(Controllable player) { ZoomControl zoomControl = (ZoomControl) player.getControl("javax.microedition.amms.control.camera.ZoomControl"); if (zoomControl == null) { zoomControl = (ZoomControl) player.getControl("ZoomControl"); } if (zoomControl != null) { // We zoom in if possible to encourage the viewer to take a snapshot from a greater distance. // This is a crude way of dealing with the fact that many phone cameras will not focus at a // very close range. int maxZoom = zoomControl.getMaxOpticalZoom(); if (maxZoom > NO_ZOOM) { zoomControl.setOpticalZoom(maxZoom > MAX_ZOOM ? MAX_ZOOM : maxZoom); } else { int maxDigitalZoom = zoomControl.getMaxDigitalZoom(); if (maxDigitalZoom > NO_ZOOM) { zoomControl.setDigitalZoom(maxDigitalZoom > MAX_ZOOM ? MAX_ZOOM : maxDigitalZoom); } } } } public void setExposure(Controllable player) { ExposureControl exposureControl = (ExposureControl) player.getControl("javax.microedition.amms.control.camera.ExposureControl"); if (exposureControl == null) { exposureControl = (ExposureControl) player.getControl("ExposureControl"); } if (exposureControl != null) { int[] supportedISOs = exposureControl.getSupportedISOs(); if (supportedISOs != null && supportedISOs.length > 0) { int maxISO = Integer.MIN_VALUE; for (int i = 0; i < supportedISOs.length; i++) { if (supportedISOs[i] > maxISO) { maxISO = supportedISOs[i]; } } try { exposureControl.setISO(maxISO); } catch (MediaException me) { // continue } } String[] supportedMeterings = exposureControl.getSupportedLightMeterings(); if (supportedMeterings != null) { for (int i = 0; i < supportedMeterings.length; i++) { if (DESIRED_METERING.equals(supportedMeterings[i])) { exposureControl.setLightMetering(DESIRED_METERING); break; } } } } } }
javame/src/com/google/zxing/client/j2me/AdvancedMultimediaManager.java
/* * Copyright 2007 ZXing 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 com.google.zxing.client.j2me; import javax.microedition.amms.control.camera.ExposureControl; import javax.microedition.amms.control.camera.FocusControl; import javax.microedition.amms.control.camera.ZoomControl; import javax.microedition.media.Controllable; import javax.microedition.media.MediaException; /** * <p>See {@link DefaultMultimediaManager} documentation for details.</p> * * <p>This class should never be directly imported or reference in the code.</p> * * @author Sean Owen (srowen@google.com) */ final class AdvancedMultimediaManager implements MultimediaManager { private static final int NO_ZOOM = 100; private static final int MAX_ZOOM = 200; private static final long FOCUS_TIME_MS = 750L; private static final String DESIRED_METERING = "center-weighted"; public void setFocus(Controllable player) { FocusControl focusControl = (FocusControl) player.getControl("javax.microedition.amms.control.camera.FocusControl"); if (focusControl == null) { focusControl = (FocusControl) player.getControl("FocusControl"); } if (focusControl != null) { try { if (focusControl.isMacroSupported() && !focusControl.getMacro()) { focusControl.setMacro(true); } if (focusControl.isAutoFocusSupported()) { focusControl.setFocus(FocusControl.AUTO); try { Thread.sleep(FOCUS_TIME_MS); // let it focus... } catch (InterruptedException ie) { // continue } focusControl.setFocus(FocusControl.AUTO_LOCK); } } catch (MediaException me) { // continue } } } public void setZoom(Controllable player) { ZoomControl zoomControl = (ZoomControl) player.getControl("javax.microedition.amms.control.camera.ZoomControl"); if (zoomControl == null) { zoomControl = (ZoomControl) player.getControl("ZoomControl"); } if (zoomControl != null) { // We zoom in if possible to encourage the viewer to take a snapshot from a greater distance. // This is a crude way of dealing with the fact that many phone cameras will not focus at a // very close range. int maxZoom = zoomControl.getMaxOpticalZoom(); if (maxZoom > NO_ZOOM) { zoomControl.setOpticalZoom(maxZoom > MAX_ZOOM ? MAX_ZOOM : maxZoom); } else { int maxDigitalZoom = zoomControl.getMaxDigitalZoom(); if (maxDigitalZoom > NO_ZOOM) { zoomControl.setDigitalZoom(maxDigitalZoom > MAX_ZOOM ? MAX_ZOOM : maxDigitalZoom); } } } } public void setExposure(Controllable player) { ExposureControl exposureControl = (ExposureControl) player.getControl("javax.microedition.amms.control.camera.ExposureControl"); if (exposureControl == null) { exposureControl = (ExposureControl) player.getControl("ExposureControl"); } if (exposureControl != null) { int[] supportedISOs = exposureControl.getSupportedISOs(); if (supportedISOs != null && supportedISOs.length > 0) { int maxISO = Integer.MIN_VALUE; for (int i = 0; i < supportedISOs.length; i++) { if (supportedISOs[i] > maxISO) { maxISO = supportedISOs[i]; } } try { exposureControl.setISO(maxISO); } catch (MediaException me) { // continue } } String[] supportedMeterings = exposureControl.getSupportedLightMeterings(); if (supportedMeterings != null) { for (int i = 0; i < supportedMeterings.length; i++) { if (DESIRED_METERING.equals(supportedMeterings[i])) { exposureControl.setLightMetering(DESIRED_METERING); break; } } } } } }
Another light hack attempt to work around Issue 70
javame/src/com/google/zxing/client/j2me/AdvancedMultimediaManager.java
Another light hack attempt to work around Issue 70
Java
apache-2.0
51fb66888afee9a2b90094d814cafb4973bb7adc
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespavisit; import com.yahoo.document.BucketId; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.json.JsonWriter; import com.yahoo.document.serialization.XmlStream; import com.yahoo.documentapi.AckToken; import com.yahoo.documentapi.DumpVisitorDataHandler; import com.yahoo.documentapi.VisitorDataHandler; import com.yahoo.documentapi.messagebus.protocol.DocumentListEntry; import com.yahoo.documentapi.messagebus.protocol.DocumentListMessage; import com.yahoo.documentapi.messagebus.protocol.EmptyBucketsMessage; import com.yahoo.documentapi.messagebus.protocol.MapVisitorMessage; import com.yahoo.log.LogLevel; import com.yahoo.messagebus.Message; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * A visitor data and progress handler that writes to STDOUT. * * Due to java not being able to inherit two classes, and neither being an * interface this had to be implemented by creating a wrapper class. * * @author Thomas Gundersen */ public class StdOutVisitorHandler extends VdsVisitHandler { private static final Logger log = Logger.getLogger( StdOutVisitorHandler.class.getName()); private boolean printIds; private boolean indentXml; private int processTimeMilliSecs; private PrintStream out; private final boolean jsonOutput; private VisitorDataHandler dataHandler; public StdOutVisitorHandler(boolean printIds, boolean indentXml, boolean showProgress, boolean showStatistics, boolean doStatistics, boolean abortOnClusterDown, int processtime, boolean jsonOutput) { this(printIds, indentXml, showProgress, showStatistics, doStatistics, abortOnClusterDown, processtime, jsonOutput, createStdOutPrintStream()); } StdOutVisitorHandler(boolean printIds, boolean indentXml, boolean showProgress, boolean showStatistics, boolean doStatistics, boolean abortOnClusterDown, int processtime, boolean jsonOutput, PrintStream out) { super(showProgress, showStatistics, abortOnClusterDown); this.printIds = printIds; this.indentXml = indentXml; this.processTimeMilliSecs = processtime; this.jsonOutput = jsonOutput; this.out = out; this.dataHandler = new DataHandler(doStatistics); } private static PrintStream createStdOutPrintStream() { try { return new PrintStream(System.out, true, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // Will not happen - UTF-8 is always supported } } @Override public void onDone() { } public VisitorDataHandler getDataHandler() { return dataHandler; } class StatisticsMap extends LinkedHashMap<String, Integer> { int maxSize; StatisticsMap(int maxSize) { super(100, (float)0.75, true); this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) { if (size() > maxSize) { dump(eldest); return true; } return false; } private void dump(Map.Entry<String, Integer> e) { out.println(e.getKey() + ":" + e.getValue()); } public void dumpAll() { for (Map.Entry<String, Integer> e : entrySet()) { dump(e); } clear(); } } class DataHandler extends DumpVisitorDataHandler { boolean doStatistics; StatisticsMap statisticsMap = new StatisticsMap(10000); private volatile boolean first = true; public DataHandler(boolean doStatistics) { this.doStatistics = doStatistics; } @Override public void onMessage(Message m, AckToken token) { if (processTimeMilliSecs > 0) { try { Thread.sleep(processTimeMilliSecs); } catch (InterruptedException e) {} } synchronized (printLock) { if (m instanceof MapVisitorMessage) { onMapVisitorData(((MapVisitorMessage)m).getData()); ack(token); } else if (m instanceof DocumentListMessage) { DocumentListMessage dlm = (DocumentListMessage)m; onDocumentList(dlm.getBucketId(), dlm.getDocuments()); ack(token); } else if (m instanceof EmptyBucketsMessage) { onEmptyBuckets(((EmptyBucketsMessage)m).getBucketIds()); ack(token); } else { super.onMessage(m, token); } } } @Override public void onDocument(Document doc, long timestamp) { try { if (lastLineIsProgress) { System.err.print('\r'); } if (printIds) { out.print(doc.getId()); out.print(" (Last modified at "); out.println(timestamp + ")"); } else { if (jsonOutput) { writeJsonDocument(doc); } else { out.print(doc.toXML( indentXml ? " " : "")); } } } catch (Exception e) { System.err.println("Failed to output document: " + e.getMessage()); getControlHandler().abort(); } } private void writeJsonDocument(Document doc) throws IOException { writeFeedStartOrRecordSeparator(); out.write(JsonWriter.toByteArray(doc)); } @Override public void onRemove(DocumentId docId) { try { if (lastLineIsProgress) { System.err.print('\r'); } if (printIds) { out.println(docId + " (Removed)"); } else { if (jsonOutput) { writeJsonDocumentRemove(docId); } else { XmlStream stream = new XmlStream(); stream.beginTag("remove"); stream.addAttribute("documentid", docId); stream.endTag(); assert(stream.isFinalized()); out.print(stream); } } } catch (Exception e) { System.err.println("Failed to output document: " + e.getMessage()); getControlHandler().abort(); } } private void writeJsonDocumentRemove(DocumentId docId) throws IOException { writeFeedStartOrRecordSeparator(); out.write(JsonWriter.documentRemove(docId)); } private void writeFeedStartOrRecordSeparator() { if (first) { out.println("["); first = false; } else { out.println(","); } } private void writeFeedEnd() { out.println("]"); } public void onMapVisitorData(Map<String, String> data) { for (String key : data.keySet()) { if (doStatistics) { Integer i = statisticsMap.get(key); if (i != null) { statisticsMap.put(key, Integer.parseInt(data.get(key)) + i); } else { statisticsMap.put(key, Integer.parseInt(data.get(key))); } } else { out.println(key + ":" + data.get(key)); } } } public void onDocumentList(BucketId bucketId, List<DocumentListEntry> documents) { out.println("Got document list of bucket " + bucketId.toString()); for (DocumentListEntry entry : documents) { entry.getDocument().setLastModified(entry.getTimestamp()); onDocument(entry.getDocument(), entry.getTimestamp()); } } public void onEmptyBuckets(List<BucketId> bucketIds) { StringBuilder buckets = new StringBuilder(); for(BucketId bid : bucketIds) { buckets.append(" "); buckets.append(bid.toString()); } log.log(LogLevel.INFO, "Got EmptyBuckets: " + buckets); } @Override public synchronized void onDone() { if (jsonOutput) { writeFeedEnd(); } statisticsMap.dumpAll(); super.onDone(); } } }
vespaclient-java/src/main/java/com/yahoo/vespavisit/StdOutVisitorHandler.java
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespavisit; import com.yahoo.document.BucketId; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.json.JsonWriter; import com.yahoo.document.serialization.XmlStream; import com.yahoo.documentapi.AckToken; import com.yahoo.documentapi.DumpVisitorDataHandler; import com.yahoo.documentapi.VisitorDataHandler; import com.yahoo.documentapi.messagebus.protocol.DocumentListEntry; import com.yahoo.documentapi.messagebus.protocol.DocumentListMessage; import com.yahoo.documentapi.messagebus.protocol.EmptyBucketsMessage; import com.yahoo.documentapi.messagebus.protocol.MapVisitorMessage; import com.yahoo.log.LogLevel; import com.yahoo.messagebus.Message; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * A visitor data and progress handler that writes to STDOUT. * * Due to java not being able to inherit two classes, and neither being an * interface this had to be implemented by creating a wrapper class. * * @author Thomas Gundersen */ public class StdOutVisitorHandler extends VdsVisitHandler { private static final Logger log = Logger.getLogger( StdOutVisitorHandler.class.getName()); private boolean printIds; private boolean indentXml; private int processTimeMilliSecs; private PrintStream out; private final boolean jsonOutput; private VisitorDataHandler dataHandler; public StdOutVisitorHandler(boolean printIds, boolean indentXml, boolean showProgress, boolean showStatistics, boolean doStatistics, boolean abortOnClusterDown, int processtime, boolean jsonOutput) { super(showProgress, showStatistics, abortOnClusterDown); this.printIds = printIds; this.indentXml = indentXml; this.processTimeMilliSecs = processtime; this.jsonOutput = jsonOutput; this.out = createStdOutPrintStream(); dataHandler = new DataHandler(doStatistics); } private static PrintStream createStdOutPrintStream() { try { return new PrintStream(System.out, true, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // Will not happen - UTF-8 is always supported } } @Override public void onDone() { } public VisitorDataHandler getDataHandler() { return dataHandler; } class StatisticsMap extends LinkedHashMap<String, Integer> { int maxSize; StatisticsMap(int maxSize) { super(100, (float)0.75, true); this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) { if (size() > maxSize) { dump(eldest); return true; } return false; } private void dump(Map.Entry<String, Integer> e) { out.println(e.getKey() + ":" + e.getValue()); } public void dumpAll() { for (Map.Entry<String, Integer> e : entrySet()) { dump(e); } clear(); } } class DataHandler extends DumpVisitorDataHandler { boolean doStatistics; StatisticsMap statisticsMap = new StatisticsMap(10000); private volatile boolean first = true; public DataHandler(boolean doStatistics) { this.doStatistics = doStatistics; } @Override public void onMessage(Message m, AckToken token) { if (processTimeMilliSecs > 0) { try { Thread.sleep(processTimeMilliSecs); } catch (InterruptedException e) {} } synchronized (printLock) { if (m instanceof MapVisitorMessage) { onMapVisitorData(((MapVisitorMessage)m).getData()); ack(token); } else if (m instanceof DocumentListMessage) { DocumentListMessage dlm = (DocumentListMessage)m; onDocumentList(dlm.getBucketId(), dlm.getDocuments()); ack(token); } else if (m instanceof EmptyBucketsMessage) { onEmptyBuckets(((EmptyBucketsMessage)m).getBucketIds()); ack(token); } else { super.onMessage(m, token); } } } @Override public void onDocument(Document doc, long timestamp) { try { if (lastLineIsProgress) { System.err.print('\r'); } if (printIds) { out.print(doc.getId()); out.print(" (Last modified at "); out.println(timestamp + ")"); } else { if (jsonOutput) { writeJsonDocument(doc); } else { out.print(doc.toXML( indentXml ? " " : "")); } } } catch (Exception e) { System.err.println("Failed to output document: " + e.getMessage()); getControlHandler().abort(); } } private void writeJsonDocument(Document doc) throws IOException { writeFeedStartOrRecordSeparator(); out.write(JsonWriter.toByteArray(doc)); } @Override public void onRemove(DocumentId docId) { try { if (lastLineIsProgress) { System.err.print('\r'); } if (printIds) { out.println(docId + " (Removed)"); } else { if (jsonOutput) { writeJsonDocumentRemove(docId); } else { XmlStream stream = new XmlStream(); stream.beginTag("remove"); stream.addAttribute("documentid", docId); stream.endTag(); assert(stream.isFinalized()); out.print(stream); } } } catch (Exception e) { System.err.println("Failed to output document: " + e.getMessage()); getControlHandler().abort(); } } private void writeJsonDocumentRemove(DocumentId docId) throws IOException { writeFeedStartOrRecordSeparator(); out.write(JsonWriter.documentRemove(docId)); } private void writeFeedStartOrRecordSeparator() { if (first) { out.println("["); first = false; } else { out.println(","); } } private void writeFeedEnd() { out.println("]"); } public void onMapVisitorData(Map<String, String> data) { for (String key : data.keySet()) { if (doStatistics) { Integer i = statisticsMap.get(key); if (i != null) { statisticsMap.put(key, Integer.parseInt(data.get(key)) + i); } else { statisticsMap.put(key, Integer.parseInt(data.get(key))); } } else { out.println(key + ":" + data.get(key)); } } } public void onDocumentList(BucketId bucketId, List<DocumentListEntry> documents) { out.println("Got document list of bucket " + bucketId.toString()); for (DocumentListEntry entry : documents) { entry.getDocument().setLastModified(entry.getTimestamp()); onDocument(entry.getDocument(), entry.getTimestamp()); } } public void onEmptyBuckets(List<BucketId> bucketIds) { StringBuilder buckets = new StringBuilder(); for(BucketId bid : bucketIds) { buckets.append(" "); buckets.append(bid.toString()); } log.log(LogLevel.INFO, "Got EmptyBuckets: " + buckets); } @Override public synchronized void onDone() { if (jsonOutput) { writeFeedEnd(); } statisticsMap.dumpAll(); super.onDone(); } } }
Add contructor intended for unit testing
vespaclient-java/src/main/java/com/yahoo/vespavisit/StdOutVisitorHandler.java
Add contructor intended for unit testing
Java
apache-2.0
f1efbcbba97b710f48ee12a6be8d82f807e3154a
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package gcm2sbml.parser; import gcm2sbml.util.GlobalConstants; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import lhpn2sbml.parser.LHPNFile; import buttons.Buttons; /** * This class describes a GCM file * * @author Nam Nguyen * @organization University of Utah * @email namphuon@cs.utah.edu */ public class GCMFile { public GCMFile() { species = new HashMap<String, Properties>(); influences = new HashMap<String, Properties>(); promoters = new HashMap<String, Properties>(); components = new HashMap<String, Properties>(); globalParameters = new HashMap<String, String>(); parameters = new HashMap<String, String>(); loadDefaultParameters(); } public String getSBMLFile() { return sbmlFile; } public void setSBMLFile(String file) { sbmlFile = file; } public boolean getDimAbs() { return dimAbs; } public void setDimAbs(boolean dimAbs) { this.dimAbs = dimAbs; } public boolean getBioAbs() { return bioAbs; } public void setBioAbs(boolean bioAbs) { this.bioAbs = bioAbs; } public void createLogicalModel(final String filename) { final JFrame naryFrame = new JFrame("Thresholds"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryFrame.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; naryFrame.addWindowListener(w); JTabbedPane naryTabs = new JTabbedPane(); ArrayList<JPanel> specProps = new ArrayList<JPanel>(); final ArrayList<JTextField> texts = new ArrayList<JTextField>(); final ArrayList<JList> consLevel = new ArrayList<JList>(); final ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); final ArrayList<String> specs = new ArrayList<String>(); for (String spec : species.keySet()) { specs.add(spec); JPanel newPanel1 = new JPanel(new GridLayout(1, 2)); JPanel newPanel2 = new JPanel(new GridLayout(1, 2)); JPanel otherLabel = new JPanel(); otherLabel.add(new JLabel(spec + " Amount:")); newPanel2.add(otherLabel); consLevel.add(new JList()); conLevel.add(new Object[0]); consLevel.get(consLevel.size() - 1).setListData(new Object[0]); conLevel.set(conLevel.size() - 1, new Object[0]); JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100)); scroll.setViewportView(consLevel.get(consLevel.size() - 1)); JPanel area = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel addAndRemove = new JPanel(); JTextField adding = new JTextField(15); texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new JButton("Remove"); Add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int number = Integer.parseInt(e.getActionCommand().substring(3, e.getActionCommand().length())); try { int get = Integer.parseInt(texts.get(number).getText().trim()); if (get <= 0) { JOptionPane.showMessageDialog(naryFrame, "Amounts Must Be Positive Integers.", "Error", JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[] adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0); Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number), add, false, null, null, null, null, null, null, naryFrame); int in; for (int out = 1; out < sort.length; out++) { int temp = Integer.parseInt((String) sort[out]); in = out; while (in > 0 && Integer.parseInt((String) sort[in - 1]) >= temp) { sort[in] = sort[in - 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Amounts Must Be Positive Integers.", "Error", JOptionPane.ERROR_MESSAGE); } } }); Add.setActionCommand("Add" + (consLevel.size() - 1)); Remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int number = Integer.parseInt(e.getActionCommand().substring(6, e.getActionCommand().length())); conLevel.set(number, Buttons .remove(consLevel.get(number), conLevel.get(number))); } }); Remove.setActionCommand("Remove" + (consLevel.size() - 1)); addAndRemove.add(adding); addAndRemove.add(Add); addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new BorderLayout()); newnewPanel.add(newPanel1, "North"); newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove, "South"); specProps.add(newnewPanel); naryTabs.addTab(spec + " Properties", specProps.get(specProps.size() - 1)); } JButton naryRun = new JButton("Create"); JButton naryClose = new JButton("Cancel"); naryRun.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { convertToLHPN(specs, conLevel).save(filename); naryFrame.dispose(); } }); naryClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { naryFrame.dispose(); } }); JPanel naryRunPanel = new JPanel(); naryRunPanel.add(naryRun); naryRunPanel.add(naryClose); JPanel naryPanel = new JPanel(new BorderLayout()); naryPanel.add(naryTabs, "Center"); naryPanel.add(naryRunPanel, "South"); naryFrame.setContentPane(naryPanel); naryFrame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = naryFrame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; naryFrame.setLocation(x, y); naryFrame.setResizable(false); naryFrame.setVisible(true); } private LHPNFile convertToLHPN(ArrayList<String> specs, ArrayList<Object[]> conLevel) { HashMap<String, ArrayList<String>> infl = new HashMap<String, ArrayList<String>>(); for (String influence : influences.keySet()) { if (influences.get(influence).get(GlobalConstants.TYPE).equals( GlobalConstants.ACTIVATION)) { String input = getInput(influence); String output = getOutput(influence); if (influences.get(influence).contains(GlobalConstants.BIO) && influences.get(influence).get(GlobalConstants.BIO).equals("yes")) { if (infl.containsKey(output)) { infl.get(output).add("bioAct:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("bioAct:" + input + ":" + influence); infl.put(output, out); } } else { if (infl.containsKey(output)) { infl.get(output).add("act:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("act:" + input + ":" + influence); infl.put(output, out); } } } else if (influences.get(influence).get(GlobalConstants.TYPE).equals( GlobalConstants.REPRESSION)) { String input = getInput(influence); String output = getOutput(influence); if (influences.get(influence).contains(GlobalConstants.BIO) && influences.get(influence).get(GlobalConstants.BIO).equals("yes")) { if (infl.containsKey(output)) { infl.get(output).add("bioRep:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("bioRep:" + input + ":" + influence); infl.put(output, out); } } else { if (infl.containsKey(output)) { infl.get(output).add("rep:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("rep:" + input + ":" + influence); infl.put(output, out); } } } } LHPNFile LHPN = new LHPNFile(); Properties initCond = new Properties(); initCond.put("rate", "0"); initCond.put("value", "0"); LHPN.addVar("r", initCond); for (int i = 0; i < specs.size(); i++) { int placeNum = 0; int transNum = 0; String previousPlaceName = specs.get(i) + placeNum; placeNum++; LHPN.addPlace(previousPlaceName, true); LHPN.addInteger(specs.get(i), "0"); String number = "0"; for (Object threshold : conLevel.get(i)) { LHPN.addPlace(specs.get(i) + placeNum, false); LHPN.addTransition(specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(previousPlaceName, specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + "_trans" + transNum, specs.get(i) + placeNum); LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), (String) threshold); ArrayList<String> activators = new ArrayList<String>(); ArrayList<String> repressors = new ArrayList<String>(); ArrayList<String> bioActivators = new ArrayList<String>(); ArrayList<String> bioRepressors = new ArrayList<String>(); Double np = Double .parseDouble(parameters.get(GlobalConstants.STOICHIOMETRY_STRING)); Double ng = Double.parseDouble(parameters .get(GlobalConstants.PROMOTER_COUNT_STRING)); Double kb = Double.parseDouble(parameters.get(GlobalConstants.KBASAL_STRING)); Double Kb = Double.parseDouble(parameters.get(GlobalConstants.KBIO_STRING)); Double Ko = Double.parseDouble(parameters.get(GlobalConstants.RNAP_BINDING_STRING)); Double ka = Double.parseDouble(parameters.get(GlobalConstants.ACTIVED_STRING)); Double Ka = Double.parseDouble(parameters.get(GlobalConstants.KACT_STRING)); Double ko = Double.parseDouble(parameters.get(GlobalConstants.OCR_STRING)); Double Kr = Double.parseDouble(parameters.get(GlobalConstants.KREP_STRING)); Double kd = Double.parseDouble(parameters.get(GlobalConstants.KDECAY_STRING)); Double nc = Double .parseDouble(parameters.get(GlobalConstants.COOPERATIVITY_STRING)); Double RNAP = Double.parseDouble(parameters.get(GlobalConstants.RNAP_STRING)); if (infl.containsKey(specs.get(i))) { for (String in : infl.get(specs.get(i))) { String[] parse = in.split(":"); String species = parse[1]; String influence = parse[2]; String promoter = influence.split(" ")[influence.split(" ").length - 1]; if (parse[0].equals("act")) { activators.add(species); } else if (parse[0].equals("rep")) { repressors.add(species); } else if (parse[0].equals("bioAct")) { bioActivators.add(species); } else if (parse[0].equals("bioRep")) { bioRepressors.add(species); } Properties p = this.species.get(species); if (p.contains(GlobalConstants.KDECAY_STRING)) { kd = Double.parseDouble((String) p.get(GlobalConstants.KDECAY_STRING)); } p = influences.get(influence); if (p.contains(GlobalConstants.COOPERATIVITY_STRING)) { nc = Double.parseDouble((String) p .get(GlobalConstants.COOPERATIVITY_STRING)); } if (p.contains(GlobalConstants.KREP_STRING)) { Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING)); } if (p.contains(GlobalConstants.KACT_STRING)) { Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING)); } if (p.contains(GlobalConstants.KBIO_STRING)) { Kb = Double.parseDouble((String) p.get(GlobalConstants.KBIO_STRING)); } p = promoters.get(promoter); if (p.contains(GlobalConstants.PROMOTER_COUNT_STRING)) { ng = Double.parseDouble((String) p .get(GlobalConstants.PROMOTER_COUNT_STRING)); } if (p.contains(GlobalConstants.RNAP_BINDING_STRING)) { Ko = Double.parseDouble((String) p .get(GlobalConstants.RNAP_BINDING_STRING)); } if (p.contains(GlobalConstants.OCR_STRING)) { ko = Double.parseDouble((String) p.get(GlobalConstants.OCR_STRING)); } if (p.contains(GlobalConstants.STOICHIOMETRY_STRING)) { np = Double.parseDouble((String) p .get(GlobalConstants.STOICHIOMETRY_STRING)); } if (p.contains(GlobalConstants.KBASAL_STRING)) { kb = Double.parseDouble((String) p.get(GlobalConstants.KBASAL_STRING)); } if (p.contains(GlobalConstants.ACTIVED_STRING)) { ka = Double.parseDouble((String) p.get(GlobalConstants.ACTIVED_STRING)); } } } String addBio = "" + Kb; for (String bioAct : bioActivators) { addBio += "*" + bioAct; } if (!addBio.equals("" + Kb)) { activators.add(addBio); } addBio = "" + Kb; for (String bioRep : bioRepressors) { addBio += "*" + bioRep; } if (!addBio.equals("" + Kb)) { repressors.add(addBio); } String rate = ""; if (activators.size() != 0) { if (repressors.size() != 0) { rate += (np * ng) + "*(" + (kb * Ko * RNAP); for (String act : activators) { rate += "+" + (ka * Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")/(" + (1 + (Ko * RNAP)); for (String act : activators) { rate += "+" + (Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")"; } else { rate += (np * ng) + "*(" + (kb * Ko * RNAP); for (String act : activators) { rate += "+" + (ka * Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")/(" + (1 + (Ko * RNAP)); for (String act : activators) { rate += "+" + (Ka * RNAP) + "*(" + act + "^" + nc + ")"; } for (String rep : repressors) { rate += "+" + Kr + "*(" + rep + "^" + nc + ")"; } rate += ")"; } } else { if (repressors.size() != 0) { rate += (np * ko * ng) + "*(" + (Ko * RNAP) + ")/(" + (1 + (Ko * RNAP)); for (String rep : repressors) { rate += "+" + Kr + "*(" + rep + "^" + nc + ")"; } rate += ")"; } } if (rate.equals("")) { rate = "0.0"; } LHPN.addRateAssign(specs.get(i) + "_trans" + transNum, "r", "(" + rate + ")/" + "(" + threshold + "-" + number + ")"); transNum++; LHPN.addTransition(specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + placeNum, specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + "_trans" + transNum, previousPlaceName); LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), number); LHPN.addRateAssign(specs.get(i) + "_trans" + transNum, "r", "(" + specs.get(i) + "*" + kd + ")/" + "(" + threshold + "-" + number + ")"); transNum++; previousPlaceName = specs.get(i) + placeNum; placeNum++; number = (String) threshold; } } return LHPN; } public void save(String filename) { try { PrintStream p = new PrintStream(new FileOutputStream(filename)); StringBuffer buffer = new StringBuffer("digraph G {\n"); for (String s : species.keySet()) { buffer.append(s + " ["); Properties prop = species.get(s); for (Object propName : prop.keySet()) { if ((propName.toString().equals(GlobalConstants.NAME)) || (propName.toString().equals("label"))) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\"" + prop.getProperty(propName.toString()).toString() + "\"" + ","); } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (!prop.containsKey("shape")) { buffer.append("shape=ellipse,"); } if (!prop.containsKey("label")) { buffer.append("label=\"" + s + "\""); } else { buffer.deleteCharAt(buffer.lastIndexOf(",")); } // buffer.deleteCharAt(buffer.length() - 1); buffer.append("]\n"); } for (String s : components.keySet()) { buffer.append(s + " ["); Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals("gcm")) { buffer.append(checkCompabilitySave(propName.toString()) + "=\"" + prop.getProperty(propName.toString()).toString()+ "\""); } } buffer.append("]\n"); } for (String s : influences.keySet()) { buffer.append(getInput(s) + " -> "// + getArrow(s) + " " + getOutput(s) + " ["); Properties prop = influences.get(s); String promo = "default"; if (prop.containsKey(GlobalConstants.PROMOTER)) { promo = prop.getProperty(GlobalConstants.PROMOTER); } prop.setProperty(GlobalConstants.NAME, "\""+ getInput(s) + " " + getArrow(s) + " " + getOutput(s)+ ", Promoter " + promo + "\""); for (Object propName : prop.keySet()) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } String type = ""; if (!prop.containsKey("arrowhead")) { if (prop.getProperty(GlobalConstants.TYPE).equals( GlobalConstants.ACTIVATION)) { type = "vee"; } else { type = "tee"; } buffer.append("arrowhead=" + type + ""); } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } for (String s : components.keySet()) { Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (!propName.toString().equals("gcm") && !propName.toString().equals(GlobalConstants.ID)) { buffer.append(s + " -> " + prop.getProperty(propName.toString()).toString() + " [port=" + propName.toString()); buffer.append(", arrowhead=none]\n"); } } } buffer.append("}\nGlobal {\n"); for (String s : defaultParameters.keySet()) { if (globalParameters.containsKey(s)) { String value = globalParameters.get(s); buffer.append(s + "=" + value + "\n"); } } buffer.append("}\nPromoters {\n"); for (String s : promoters.keySet()) { buffer.append(s + " ["); Properties prop = promoters.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals(GlobalConstants.NAME)) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\"" + prop.getProperty(propName.toString()).toString() + "\"" + ","); } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } /* buffer.append("}\nComponents {\n"); for (String s : components.keySet()) { buffer.append(s + " ["); Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals(GlobalConstants.ID)) { } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } */ buffer.append("}\n"); buffer.append(GlobalConstants.SBMLFILE + "=\"" + sbmlFile + "\"\n"); if (bioAbs) { buffer.append(GlobalConstants.BIOABS + "=true\n"); } if (dimAbs) { buffer.append(GlobalConstants.DIMABS + "=true\n"); } p.print(buffer); p.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void load(String filename) { species = new HashMap<String, Properties>(); influences = new HashMap<String, Properties>(); promoters = new HashMap<String, Properties>(); components = new HashMap<String, Properties>(); globalParameters = new HashMap<String, String>(); parameters = new HashMap<String, String>(); StringBuffer data = new StringBuffer(); loadDefaultParameters(); try { BufferedReader in = new BufferedReader(new FileReader(filename)); String str; while ((str = in.readLine()) != null) { data.append(str + "\n"); } in.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Error opening file"); } try { parseStates(data); parseInfluences(data); parseGlobal(data); parsePromoters(data); //parseComponents(data); parseSBMLFile(data); parseBioAbs(data); parseDimAbs(data); } catch (Exception e) { throw new IllegalArgumentException("Unable to parse GCM"); // JOptionPane.showMessageDialog(null, // "Unable to parse model, creating a blank model.", "Error", // JOptionPane.ERROR_MESSAGE); // species = new HashMap<String, Properties>(); // influences = new HashMap<String, Properties>(); // promoters = new HashMap<String, Properties>(); // globalParameters = new HashMap<String, String>(); } } public void changePromoterName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); String newInfluenceName = ""; if (influences.get(s).containsKey(GlobalConstants.PROMOTER) && influences.get(s).get(GlobalConstants.PROMOTER).equals(oldName)) { newInfluenceName = input + " " + arrow + " " + output + ", Promoter " + newName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); influences.get(newInfluenceName).setProperty(GlobalConstants.PROMOTER, newName); } } promoters.put(newName, promoters.get(oldName)); promoters.remove(oldName); } public void changeSpeciesName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); boolean replaceInput = input.equals(oldName); boolean replaceOutput = output.equals(oldName); String newInfluenceName = ""; if (replaceInput || replaceOutput) { if (replaceInput) { newInfluenceName = newInfluenceName + newName; } else { newInfluenceName = newInfluenceName + input; } if (replaceOutput) { newInfluenceName = newInfluenceName + " " + arrow + " " + newName; } else { newInfluenceName = newInfluenceName + " " + arrow + " " + output; } String promoterName = "default"; if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) { promoterName = influences.get(s).get( GlobalConstants.PROMOTER).toString(); } newInfluenceName = newInfluenceName + ", Promoter " + promoterName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); } } species.put(newName, species.get(oldName)); species.remove(oldName); } public void changeComponentName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); boolean replaceInput = input.equals(oldName); boolean replaceOutput = output.equals(oldName); String newInfluenceName = ""; if (replaceInput || replaceOutput) { if (replaceInput) { newInfluenceName = newInfluenceName + newName; } else { newInfluenceName = newInfluenceName + input; } if (replaceOutput) { newInfluenceName = newInfluenceName + " " + arrow + " " + newName; } else { newInfluenceName = newInfluenceName + " " + arrow + " " + output; } String promoterName = "default"; if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) { promoterName = influences.get(s).get( GlobalConstants.PROMOTER).toString(); } newInfluenceName = newInfluenceName + ", Promoter " + promoterName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); } } components.put(newName, components.get(oldName)); components.remove(oldName); } public void addSpecies(String name, Properties property) { species.put(name, property); } public void addPromoter(String name, Properties properties) { promoters.put(name.replace("\"", ""), properties); } public void addComponent(String name, Properties properties) { components.put(name, properties); } public void addInfluences(String name, Properties property) { influences.put(name, property); // Now check to see if a promoter exists in the property if (property.containsKey("promoter")) { promoters.put( property.getProperty("promoter").replaceAll("\"", ""), new Properties()); } } public void removeSpecies(String name) { if (name != null && species.containsKey(name)) { species.remove(name); } } public HashMap<String, Properties> getSpecies() { return species; } public HashMap<String, Properties> getComponents() { return components; } public String getComponentPortMap(String s) { String portmap = "("; Properties c = components.get(s); ArrayList<String> ports = new ArrayList<String>(); for (Object key : c.keySet()) { if (!key.equals("gcm")) { ports.add((String) key); } } int i, j; String index; for (i = 1; i < ports.size(); i++) { index = ports.get(i); j = i; while ((j > 0) && ports.get(j - 1).compareToIgnoreCase(index) > 0) { ports.set(j, ports.get(j - 1)); j = j - 1; } ports.set(j, index); } if (ports.size() > 0) { portmap += ports.get(0) + "->" + c.getProperty(ports.get(0)); } for (int k = 1; k < ports.size(); k++) { portmap += ", " + ports.get(k) + "->" + c.getProperty(ports.get(k)); } portmap += ")"; return portmap; } public HashMap<String, Properties> getInfluences() { return influences; } /** * Checks to see if removing influence is okay * * @param name * influence to remove * @return true, it is always okay to remove influence */ public boolean removeInfluenceCheck(String name) { return true; } /** * Checks to see if removing specie is okay * * @param name * specie to remove * @return true if specie is in no influences */ public boolean removeSpeciesCheck(String name) { for (String s : influences.keySet()) { if (s.contains(name)) { return false; } } return true; } public boolean removeComponentCheck(String name) { for (String s : influences.keySet()) { if ((" " + s + " ").contains(" " + name + " ")) { return false; } } return true; } /** * Checks to see if removing promoter is okay * * @param name * promoter to remove * @return true if promoter is in no influences */ public boolean removePromoterCheck(String name) { for (Properties p : influences.values()) { if (p.containsKey(GlobalConstants.PROMOTER) && p.getProperty(GlobalConstants.PROMOTER).equals(name)) { return false; } } return true; } public void removePromoter(String name) { if (name != null && promoters.containsKey(name)) { promoters.remove(name); } } public void removeComponent(String name) { if (name != null && components.containsKey(name)) { components.remove(name); } } public void removeInfluence(String name) { if (name != null && influences.containsKey(name)) { influences.remove(name); } } public String getInput(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(2); } public String getArrow(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(3) + matcher.group(4); } public String getOutput(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(5); } public String getPromoter(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(6); } public String[] getSpeciesAsArray() { String[] s = new String[species.size()]; s = species.keySet().toArray(s); Arrays.sort(s); return s; } public String[] getPromotersAsArray() { String[] s = new String[promoters.size()]; s = promoters.keySet().toArray(s); Arrays.sort(s); return s; } public HashMap<String, Properties> getPromoters() { return promoters; } public HashMap<String, String> getGlobalParameters() { return globalParameters; } public HashMap<String, String> getDefaultParameters() { return defaultParameters; } public HashMap<String, String> getParameters() { return parameters; } public String getParameter(String parameter) { if (globalParameters.containsKey(parameter)) { return globalParameters.get(parameter); } else { return defaultParameters.get(parameter); } } public void setParameter(String parameter, String value) { globalParameters.put(parameter, value); parameters.put(parameter, value); } public void removeParameter(String parameter) { globalParameters.remove(parameter); } private void parseStates(StringBuffer data) { Pattern network = Pattern.compile(NETWORK); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); matcher.find(); matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } //for backwards compatibility if (properties.containsKey("const")) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.CONSTANT); } else if (!properties.containsKey(GlobalConstants.TYPE)) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.NORMAL); } if (properties.getProperty(GlobalConstants.TYPE).equals("constant")) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.CONSTANT); } //for backwards compatibility if (properties.containsKey("label")) { properties.put(GlobalConstants.ID, properties.getProperty("label").replace("\"", "")); } if (properties.containsKey("gcm")) { if (properties.containsKey(GlobalConstants.TYPE)) { properties.remove(GlobalConstants.TYPE); } properties.put("gcm", properties.getProperty("gcm").replace("\"", "")); components.put(name, properties); } else { species.put(name, properties); } } } private void parseSBMLFile(StringBuffer data) { Pattern pattern = Pattern.compile(SBMLFILE); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { sbmlFile = matcher.group(1); } } private void parseDimAbs(StringBuffer data) { Pattern pattern = Pattern.compile(DIMABS); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { if (matcher.group(1).equals("true")) { dimAbs = true; } } } private void parseBioAbs(StringBuffer data) { Pattern pattern = Pattern.compile(BIOABS); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { if (matcher.group(1).equals("true")) { bioAbs = true; } } } private void parseGlobal(StringBuffer data) { Pattern pattern = Pattern.compile(GLOBAL); Pattern propPattern = Pattern.compile(PROPERTY); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { String s = matcher.group(1); matcher = propPattern.matcher(s); while (matcher.find()) { if (matcher.group(3)!=null) { globalParameters.put(matcher.group(1), matcher.group(3)); parameters.put(matcher.group(1), matcher.group(3)); } else { globalParameters.put(matcher.group(1), matcher.group(4)); parameters.put(matcher.group(1), matcher.group(4)); } } } } private void parsePromoters(StringBuffer data) { Pattern network = Pattern.compile(PROMOTERS_LIST); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); if (!matcher.find()) { return; } matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } promoters.put(name, properties); } } /* private void parseComponents(StringBuffer data) { Pattern network = Pattern.compile(COMPONENTS_LIST); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); if (!matcher.find()) { return; } matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } components.put(name, properties); } } */ private void parseInfluences(StringBuffer data) { Pattern pattern = Pattern.compile(REACTION); Pattern propPattern = Pattern.compile(PROPERTY); Matcher matcher = pattern.matcher(data.toString()); while (matcher.find()) { Matcher propMatcher = propPattern.matcher(matcher.group(6)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(3)); if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER) && !promoters.containsKey(propMatcher.group(3))) { promoters.put(propMatcher.group(3).replaceAll("\"", ""), new Properties()); properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(3).replace("\"", "")); //for backwards compatibility } } else { properties.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(4)); if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER) && !promoters.containsKey(propMatcher.group(4))) { promoters.put(propMatcher.group(4).replaceAll("\"", ""), new Properties()); properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(4).replace("\"", "")); //for backwards compatibility } } } if (properties.containsKey("port")) { components.get(matcher.group(2)).put(properties.get("port"), matcher.group(5)); } else { String name = ""; if (properties.containsKey("arrowhead")) { if (properties.getProperty("arrowhead").indexOf("vee") != -1) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.ACTIVATION); if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { name = matcher.group(2) + " +> " + matcher.group(5); } else { name = matcher.group(2) + " -> " + matcher.group(5); } } else { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.REPRESSION); if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { name = matcher.group(2) + " +| " + matcher.group(5); } else { name = matcher.group(2) + " -| " + matcher.group(5); } } } if (properties.getProperty(GlobalConstants.PROMOTER) != null) { name = name + ", Promoter " + properties.getProperty(GlobalConstants.PROMOTER); } else { name = name + ", Promoter " + "default"; } if (!properties.containsKey("label")) { String label = properties.getProperty(GlobalConstants.PROMOTER); if (label == null) { label = ""; } if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { label = label + "+"; } properties.put("label", "\""+label+"\""); } properties.put(GlobalConstants.NAME, name); influences.put(name, properties); } } } public void loadDefaultParameters() { Preferences biosimrc = Preferences.userRoot(); defaultParameters = new HashMap<String, String>(); defaultParameters.put(GlobalConstants.KDECAY_STRING, biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); defaultParameters.put(GlobalConstants.KASSOCIATION_STRING, biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "")); defaultParameters.put(GlobalConstants.KBIO_STRING, biosimrc.get("biosim.gcm.KBIO_VALUE", "")); defaultParameters.put(GlobalConstants.COOPERATIVITY_STRING, biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "")); defaultParameters.put(GlobalConstants.KREP_STRING, biosimrc.get("biosim.gcm.KREP_VALUE", "")); defaultParameters.put(GlobalConstants.KACT_STRING, biosimrc.get("biosim.gcm.KACT_VALUE", "")); defaultParameters.put(GlobalConstants.RNAP_BINDING_STRING, biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "")); defaultParameters.put(GlobalConstants.RNAP_STRING, biosimrc.get("biosim.gcm.RNAP_VALUE", "")); defaultParameters.put(GlobalConstants.OCR_STRING, biosimrc.get("biosim.gcm.OCR_VALUE", "")); defaultParameters.put(GlobalConstants.KBASAL_STRING, biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); defaultParameters.put(GlobalConstants.PROMOTER_COUNT_STRING, biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "")); defaultParameters.put(GlobalConstants.STOICHIOMETRY_STRING, biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "")); defaultParameters.put(GlobalConstants.ACTIVED_STRING, biosimrc.get("biosim.gcm.ACTIVED_VALUE", "")); defaultParameters.put(GlobalConstants.MAX_DIMER_STRING, biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "")); defaultParameters.put(GlobalConstants.INITIAL_STRING, biosimrc.get("biosim.gcm.INITIAL_VALUE", "")); for (String s : defaultParameters.keySet()) { parameters.put(s, defaultParameters.get(s)); } } public void setParameters(HashMap<String, String> parameters) { for (String s : parameters.keySet()) { defaultParameters.put(s, parameters.get(s)); this.parameters.put(s, parameters.get(s)); } } private String checkCompabilitySave(String key) { if (key.equals(GlobalConstants.MAX_DIMER_STRING)) { return "maxDimer"; } return key; } private String checkCompabilityLoad(String key) { if (key.equals("maxDimer")) { return GlobalConstants.MAX_DIMER_STRING; } return key; } private static final String NETWORK = "digraph\\sG\\s\\{([^}]*)\\s\\}"; private static final String STATE = "(^|\\n) *([^- \\n]*) *\\[(.*)\\]"; private static final String REACTION = "(^|\\n) *([^ \\n]*) (\\-|\\+)(\\>|\\|) *([^ \n]*) *\\[([^\\]]*)]"; // private static final String PARSE = "(^|\\n) *([^ \\n,]*) *\\-\\> *([^ // \n,]*)"; private static final String PARSE = "(^|\\n) *([^ \\n,]*) (\\-|\\+)(\\>|\\|) *([^ \n,]*), Promoter ([a-zA-Z\\d_]+)"; private static final String PROPERTY = "([a-zA-Z\\ \\-]+)=(\"([^\"]*)\"|([^\\s,]+))"; private static final String GLOBAL = "Global\\s\\{([^}]*)\\s\\}"; private static final String SBMLFILE = GlobalConstants.SBMLFILE + "=\"([^\"]*)\""; private static final String DIMABS = GlobalConstants.DIMABS + "=(true|false)"; private static final String BIOABS = GlobalConstants.BIOABS + "=(true|false)"; private static final String PROMOTERS_LIST = "Promoters\\s\\{([^}]*)\\s\\}"; //private static final String COMPONENTS_LIST = "Components\\s\\{([^}]*)\\s\\}"; private String sbmlFile = ""; private boolean dimAbs = false; private boolean bioAbs = false; private HashMap<String, Properties> species; private HashMap<String, Properties> influences; private HashMap<String, Properties> promoters; private HashMap<String, Properties> components; private HashMap<String, String> parameters; private HashMap<String, String> defaultParameters; private HashMap<String, String> globalParameters; }
gui/src/gcm2sbml/parser/GCMFile.java
package gcm2sbml.parser; import gcm2sbml.util.GlobalConstants; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import lhpn2sbml.parser.LHPNFile; import buttons.Buttons; /** * This class describes a GCM file * * @author Nam Nguyen * @organization University of Utah * @email namphuon@cs.utah.edu */ public class GCMFile { public GCMFile() { species = new HashMap<String, Properties>(); influences = new HashMap<String, Properties>(); promoters = new HashMap<String, Properties>(); components = new HashMap<String, Properties>(); globalParameters = new HashMap<String, String>(); parameters = new HashMap<String, String>(); loadDefaultParameters(); } public String getSBMLFile() { return sbmlFile; } public void setSBMLFile(String file) { sbmlFile = file; } public boolean getDimAbs() { return dimAbs; } public void setDimAbs(boolean dimAbs) { this.dimAbs = dimAbs; } public boolean getBioAbs() { return bioAbs; } public void setBioAbs(boolean bioAbs) { this.bioAbs = bioAbs; } public void createLogicalModel(final String filename) { final JFrame naryFrame = new JFrame("Thresholds"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { naryFrame.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; naryFrame.addWindowListener(w); JTabbedPane naryTabs = new JTabbedPane(); ArrayList<JPanel> specProps = new ArrayList<JPanel>(); final ArrayList<JTextField> texts = new ArrayList<JTextField>(); final ArrayList<JList> consLevel = new ArrayList<JList>(); final ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); final ArrayList<String> specs = new ArrayList<String>(); for (String spec : species.keySet()) { specs.add(spec); JPanel newPanel1 = new JPanel(new GridLayout(1, 2)); JPanel newPanel2 = new JPanel(new GridLayout(1, 2)); JPanel otherLabel = new JPanel(); otherLabel.add(new JLabel(spec + " Amount:")); newPanel2.add(otherLabel); consLevel.add(new JList()); conLevel.add(new Object[0]); consLevel.get(consLevel.size() - 1).setListData(new Object[0]); conLevel.set(conLevel.size() - 1, new Object[0]); JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100)); scroll.setViewportView(consLevel.get(consLevel.size() - 1)); JPanel area = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel addAndRemove = new JPanel(); JTextField adding = new JTextField(15); texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new JButton("Remove"); Add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int number = Integer.parseInt(e.getActionCommand().substring(3, e.getActionCommand().length())); try { int get = Integer.parseInt(texts.get(number).getText().trim()); if (get <= 0) { JOptionPane.showMessageDialog(naryFrame, "Amounts Must Be Positive Integers.", "Error", JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[] adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0); Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number), add, false, null, null, null, null, null, null, naryFrame); int in; for (int out = 1; out < sort.length; out++) { double temp = Double.parseDouble((String) sort[out]); in = out; while (in > 0 && Double.parseDouble((String) sort[in - 1]) >= temp) { sort[in] = sort[in - 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch (Exception e1) { JOptionPane.showMessageDialog(naryFrame, "Amounts Must Be Positive Integers.", "Error", JOptionPane.ERROR_MESSAGE); } } }); Add.setActionCommand("Add" + (consLevel.size() - 1)); Remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int number = Integer.parseInt(e.getActionCommand().substring(6, e.getActionCommand().length())); conLevel.set(number, Buttons .remove(consLevel.get(number), conLevel.get(number))); } }); Remove.setActionCommand("Remove" + (consLevel.size() - 1)); addAndRemove.add(adding); addAndRemove.add(Add); addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new BorderLayout()); newnewPanel.add(newPanel1, "North"); newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove, "South"); specProps.add(newnewPanel); naryTabs.addTab(spec + " Properties", specProps.get(specProps.size() - 1)); } JButton naryRun = new JButton("Create"); JButton naryClose = new JButton("Cancel"); naryRun.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { convertToLHPN(specs, conLevel).save(filename); naryFrame.dispose(); } }); naryClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { naryFrame.dispose(); } }); JPanel naryRunPanel = new JPanel(); naryRunPanel.add(naryRun); naryRunPanel.add(naryClose); JPanel naryPanel = new JPanel(new BorderLayout()); naryPanel.add(naryTabs, "Center"); naryPanel.add(naryRunPanel, "South"); naryFrame.setContentPane(naryPanel); naryFrame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = naryFrame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; naryFrame.setLocation(x, y); naryFrame.setResizable(false); naryFrame.setVisible(true); } private LHPNFile convertToLHPN(ArrayList<String> specs, ArrayList<Object[]> conLevel) { HashMap<String, ArrayList<String>> infl = new HashMap<String, ArrayList<String>>(); for (String influence : influences.keySet()) { if (influences.get(influence).get(GlobalConstants.TYPE).equals( GlobalConstants.ACTIVATION)) { String input = getInput(influence); String output = getOutput(influence); if (influences.get(influence).get(GlobalConstants.BIO).equals("yes")) { if (infl.containsKey(output)) { infl.get(output).add("bioAct:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("bioAct:" + input + ":" + influence); infl.put(output, out); } } else { if (infl.containsKey(output)) { infl.get(output).add("act:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("act:" + input + ":" + influence); infl.put(output, out); } } } else if (influences.get(influence).get(GlobalConstants.TYPE).equals( GlobalConstants.REPRESSION)) { String input = getInput(influence); String output = getOutput(influence); if (influences.get(influence).get(GlobalConstants.BIO).equals("yes")) { if (infl.containsKey(output)) { infl.get(output).add("bioRep:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("bioRep:" + input + ":" + influence); infl.put(output, out); } } else { if (infl.containsKey(output)) { infl.get(output).add("rep:" + input + ":" + influence); } else { ArrayList<String> out = new ArrayList<String>(); out.add("rep:" + input + ":" + influence); infl.put(output, out); } } } } LHPNFile LHPN = new LHPNFile(); Properties initCond = new Properties(); initCond.put("rate", "0"); LHPN.addVar("r", initCond); for (int i = 0; i < specs.size(); i++) { int placeNum = 0; int transNum = 0; String previousPlaceName = specs.get(i) + placeNum; placeNum++; LHPN.addPlace(previousPlaceName, true); LHPN.addInteger(specs.get(i), "0"); String number = "0"; for (Object threshold : conLevel.get(i)) { LHPN.addPlace(specs.get(i) + placeNum, false); LHPN.addTransition(specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(previousPlaceName, specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + "_trans" + transNum, specs.get(i) + placeNum); LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), (String) threshold); ArrayList<String> activators = new ArrayList<String>(); ArrayList<String> repressors = new ArrayList<String>(); ArrayList<String> bioActivators = new ArrayList<String>(); ArrayList<String> bioRepressors = new ArrayList<String>(); Double np = Double .parseDouble(parameters.get(GlobalConstants.STOICHIOMETRY_STRING)); Double ng = Double.parseDouble(parameters .get(GlobalConstants.PROMOTER_COUNT_STRING)); Double kb = Double.parseDouble(parameters.get(GlobalConstants.KBASAL_STRING)); Double Kb = Double.parseDouble(parameters.get(GlobalConstants.KBIO_STRING)); Double Ko = Double.parseDouble(parameters.get(GlobalConstants.RNAP_BINDING_STRING)); Double ka = Double.parseDouble(parameters.get(GlobalConstants.ACTIVED_STRING)); Double Ka = Double.parseDouble(parameters.get(GlobalConstants.KACT_STRING)); Double ko = Double.parseDouble(parameters.get(GlobalConstants.OCR_STRING)); Double Kr = Double.parseDouble(parameters.get(GlobalConstants.KREP_STRING)); Double kd = Double.parseDouble(parameters.get(GlobalConstants.KDECAY_STRING)); Double nc = Double .parseDouble(parameters.get(GlobalConstants.COOPERATIVITY_STRING)); Double RNAP = Double.parseDouble(parameters.get(GlobalConstants.RNAP_STRING)); if (infl.containsKey(specs.get(i))) { for (String in : infl.get(specs.get(i))) { String[] parse = in.split(":"); String species = parse[1]; String influence = parse[2]; String promoter = influence.split(" ")[influence.split(" ").length - 1]; if (parse[0].equals("act")) { activators.add(species); } else if (parse[0].equals("rep")) { repressors.add(species); } else if (parse[0].equals("bioAct")) { bioActivators.add(species); } else if (parse[0].equals("bioRep")) { bioRepressors.add(species); } Properties p = this.species.get(species); if (p.contains(GlobalConstants.KDECAY_STRING)) { kd = Double.parseDouble((String) p.get(GlobalConstants.KDECAY_STRING)); } p = influences.get(influence); if (p.contains(GlobalConstants.COOPERATIVITY_STRING)) { nc = Double.parseDouble((String) p .get(GlobalConstants.COOPERATIVITY_STRING)); } if (p.contains(GlobalConstants.KREP_STRING)) { Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING)); } if (p.contains(GlobalConstants.KACT_STRING)) { Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING)); } if (p.contains(GlobalConstants.KBIO_STRING)) { Kb = Double.parseDouble((String) p.get(GlobalConstants.KBIO_STRING)); } p = promoters.get(promoter); if (p.contains(GlobalConstants.PROMOTER_COUNT_STRING)) { ng = Double.parseDouble((String) p .get(GlobalConstants.PROMOTER_COUNT_STRING)); } if (p.contains(GlobalConstants.RNAP_BINDING_STRING)) { Ko = Double.parseDouble((String) p .get(GlobalConstants.RNAP_BINDING_STRING)); } if (p.contains(GlobalConstants.OCR_STRING)) { ko = Double.parseDouble((String) p.get(GlobalConstants.OCR_STRING)); } if (p.contains(GlobalConstants.STOICHIOMETRY_STRING)) { np = Double.parseDouble((String) p .get(GlobalConstants.STOICHIOMETRY_STRING)); } if (p.contains(GlobalConstants.KBASAL_STRING)) { kb = Double.parseDouble((String) p.get(GlobalConstants.KBASAL_STRING)); } if (p.contains(GlobalConstants.ACTIVED_STRING)) { ka = Double.parseDouble((String) p.get(GlobalConstants.ACTIVED_STRING)); } } } String addBio = "" + Kb; for (String bioAct : bioActivators) { addBio += "*" + bioAct; } activators.add(addBio); addBio = "" + Kb; for (String bioRep : bioRepressors) { addBio += "*" + bioRep; } repressors.add(addBio); String rate = ""; if (activators.size() != 0) { if (repressors.size() != 0) { rate += (np * ng) + "*(" + (kb * Ko * RNAP); for (String act : activators) { rate += "+" + (ka * Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")/(" + (1 + (Ko * RNAP)); for (String act : activators) { rate += "+" + (Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")"; } else { rate += (np * ng) + "*(" + (kb * Ko * RNAP); for (String act : activators) { rate += "+" + (ka * Ka * RNAP) + "*(" + act + "^" + nc + ")"; } rate += ")/(" + (1 + (Ko * RNAP)); for (String act : activators) { rate += "+" + (Ka * RNAP) + "*(" + act + "^" + nc + ")"; } for (String rep : repressors) { rate += "+" + Kr + "*(" + rep + "^" + nc + ")"; } rate += ")"; } } else { if (repressors.size() != 0) { rate += (np * ko * ng) + "*(" + (Ko * RNAP) + ")/(" + (1 + (Ko * RNAP)); for (String rep : repressors) { rate += "+" + Kr + "*(" + rep + "^" + nc + ")"; } rate += ")"; } } if (rate.equals("")) { rate = "0.0"; } LHPN.addRateAssign(specs.get(i) + "_trans" + transNum, "r", "(" + rate + ")/" + "(" + threshold + "-" + number + ")"); transNum++; LHPN.addTransition(specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + placeNum, specs.get(i) + "_trans" + transNum); LHPN.addControlFlow(specs.get(i) + "_trans" + transNum, previousPlaceName); LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), number); LHPN.addRateAssign(specs.get(i) + "_trans" + transNum, "r", "(" + specs.get(i) + "*" + kd + ")/" + "(" + threshold + "-" + number + ")"); transNum++; previousPlaceName = specs.get(i) + placeNum; placeNum++; number = (String) threshold; } } return LHPN; } public void save(String filename) { try { PrintStream p = new PrintStream(new FileOutputStream(filename)); StringBuffer buffer = new StringBuffer("digraph G {\n"); for (String s : species.keySet()) { buffer.append(s + " ["); Properties prop = species.get(s); for (Object propName : prop.keySet()) { if ((propName.toString().equals(GlobalConstants.NAME)) || (propName.toString().equals("label"))) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\"" + prop.getProperty(propName.toString()).toString() + "\"" + ","); } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (!prop.containsKey("shape")) { buffer.append("shape=ellipse,"); } if (!prop.containsKey("label")) { buffer.append("label=\"" + s + "\""); } else { buffer.deleteCharAt(buffer.lastIndexOf(",")); } // buffer.deleteCharAt(buffer.length() - 1); buffer.append("]\n"); } for (String s : components.keySet()) { buffer.append(s + " ["); Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals("gcm")) { buffer.append(checkCompabilitySave(propName.toString()) + "=\"" + prop.getProperty(propName.toString()).toString()+ "\""); } } buffer.append("]\n"); } for (String s : influences.keySet()) { buffer.append(getInput(s) + " -> "// + getArrow(s) + " " + getOutput(s) + " ["); Properties prop = influences.get(s); String promo = "default"; if (prop.containsKey(GlobalConstants.PROMOTER)) { promo = prop.getProperty(GlobalConstants.PROMOTER); } prop.setProperty(GlobalConstants.NAME, "\""+ getInput(s) + " " + getArrow(s) + " " + getOutput(s)+ ", Promoter " + promo + "\""); for (Object propName : prop.keySet()) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } String type = ""; if (!prop.containsKey("arrowhead")) { if (prop.getProperty(GlobalConstants.TYPE).equals( GlobalConstants.ACTIVATION)) { type = "vee"; } else { type = "tee"; } buffer.append("arrowhead=" + type + ""); } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } for (String s : components.keySet()) { Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (!propName.toString().equals("gcm") && !propName.toString().equals(GlobalConstants.ID)) { buffer.append(s + " -> " + prop.getProperty(propName.toString()).toString() + " [port=" + propName.toString()); buffer.append(", arrowhead=none]\n"); } } } buffer.append("}\nGlobal {\n"); for (String s : defaultParameters.keySet()) { if (globalParameters.containsKey(s)) { String value = globalParameters.get(s); buffer.append(s + "=" + value + "\n"); } } buffer.append("}\nPromoters {\n"); for (String s : promoters.keySet()) { buffer.append(s + " ["); Properties prop = promoters.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals(GlobalConstants.NAME)) { buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\"" + prop.getProperty(propName.toString()).toString() + "\"" + ","); } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } /* buffer.append("}\nComponents {\n"); for (String s : components.keySet()) { buffer.append(s + " ["); Properties prop = components.get(s); for (Object propName : prop.keySet()) { if (propName.toString().equals(GlobalConstants.ID)) { } else { buffer.append(checkCompabilitySave(propName.toString()) + "=" + prop.getProperty(propName.toString()).toString() + ","); } } if (buffer.charAt(buffer.length() - 1) == ',') { buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n"); } */ buffer.append("}\n"); buffer.append(GlobalConstants.SBMLFILE + "=\"" + sbmlFile + "\"\n"); if (bioAbs) { buffer.append(GlobalConstants.BIOABS + "=true\n"); } if (dimAbs) { buffer.append(GlobalConstants.DIMABS + "=true\n"); } p.print(buffer); p.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void load(String filename) { species = new HashMap<String, Properties>(); influences = new HashMap<String, Properties>(); promoters = new HashMap<String, Properties>(); components = new HashMap<String, Properties>(); globalParameters = new HashMap<String, String>(); parameters = new HashMap<String, String>(); StringBuffer data = new StringBuffer(); loadDefaultParameters(); try { BufferedReader in = new BufferedReader(new FileReader(filename)); String str; while ((str = in.readLine()) != null) { data.append(str + "\n"); } in.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Error opening file"); } try { parseStates(data); parseInfluences(data); parseGlobal(data); parsePromoters(data); //parseComponents(data); parseSBMLFile(data); parseBioAbs(data); parseDimAbs(data); } catch (Exception e) { throw new IllegalArgumentException("Unable to parse GCM"); // JOptionPane.showMessageDialog(null, // "Unable to parse model, creating a blank model.", "Error", // JOptionPane.ERROR_MESSAGE); // species = new HashMap<String, Properties>(); // influences = new HashMap<String, Properties>(); // promoters = new HashMap<String, Properties>(); // globalParameters = new HashMap<String, String>(); } } public void changePromoterName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); String newInfluenceName = ""; if (influences.get(s).containsKey(GlobalConstants.PROMOTER) && influences.get(s).get(GlobalConstants.PROMOTER).equals(oldName)) { newInfluenceName = input + " " + arrow + " " + output + ", Promoter " + newName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); influences.get(newInfluenceName).setProperty(GlobalConstants.PROMOTER, newName); } } promoters.put(newName, promoters.get(oldName)); promoters.remove(oldName); } public void changeSpeciesName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); boolean replaceInput = input.equals(oldName); boolean replaceOutput = output.equals(oldName); String newInfluenceName = ""; if (replaceInput || replaceOutput) { if (replaceInput) { newInfluenceName = newInfluenceName + newName; } else { newInfluenceName = newInfluenceName + input; } if (replaceOutput) { newInfluenceName = newInfluenceName + " " + arrow + " " + newName; } else { newInfluenceName = newInfluenceName + " " + arrow + " " + output; } String promoterName = "default"; if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) { promoterName = influences.get(s).get( GlobalConstants.PROMOTER).toString(); } newInfluenceName = newInfluenceName + ", Promoter " + promoterName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); } } species.put(newName, species.get(oldName)); species.remove(oldName); } public void changeComponentName(String oldName, String newName) { String[] sArray = new String[influences.keySet().size()]; sArray = influences.keySet().toArray(sArray); for (int i = 0; i < sArray.length; i++) { String s = sArray[i]; String input = getInput(s); String arrow = getArrow(s); String output = getOutput(s); boolean replaceInput = input.equals(oldName); boolean replaceOutput = output.equals(oldName); String newInfluenceName = ""; if (replaceInput || replaceOutput) { if (replaceInput) { newInfluenceName = newInfluenceName + newName; } else { newInfluenceName = newInfluenceName + input; } if (replaceOutput) { newInfluenceName = newInfluenceName + " " + arrow + " " + newName; } else { newInfluenceName = newInfluenceName + " " + arrow + " " + output; } String promoterName = "default"; if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) { promoterName = influences.get(s).get( GlobalConstants.PROMOTER).toString(); } newInfluenceName = newInfluenceName + ", Promoter " + promoterName; influences.put(newInfluenceName, influences.get(s)); influences.remove(s); } } components.put(newName, components.get(oldName)); components.remove(oldName); } public void addSpecies(String name, Properties property) { species.put(name, property); } public void addPromoter(String name, Properties properties) { promoters.put(name.replace("\"", ""), properties); } public void addComponent(String name, Properties properties) { components.put(name, properties); } public void addInfluences(String name, Properties property) { influences.put(name, property); // Now check to see if a promoter exists in the property if (property.containsKey("promoter")) { promoters.put( property.getProperty("promoter").replaceAll("\"", ""), new Properties()); } } public void removeSpecies(String name) { if (name != null && species.containsKey(name)) { species.remove(name); } } public HashMap<String, Properties> getSpecies() { return species; } public HashMap<String, Properties> getComponents() { return components; } public String getComponentPortMap(String s) { String portmap = "("; Properties c = components.get(s); ArrayList<String> ports = new ArrayList<String>(); for (Object key : c.keySet()) { if (!key.equals("gcm")) { ports.add((String) key); } } int i, j; String index; for (i = 1; i < ports.size(); i++) { index = ports.get(i); j = i; while ((j > 0) && ports.get(j - 1).compareToIgnoreCase(index) > 0) { ports.set(j, ports.get(j - 1)); j = j - 1; } ports.set(j, index); } if (ports.size() > 0) { portmap += ports.get(0) + "->" + c.getProperty(ports.get(0)); } for (int k = 1; k < ports.size(); k++) { portmap += ", " + ports.get(k) + "->" + c.getProperty(ports.get(k)); } portmap += ")"; return portmap; } public HashMap<String, Properties> getInfluences() { return influences; } /** * Checks to see if removing influence is okay * * @param name * influence to remove * @return true, it is always okay to remove influence */ public boolean removeInfluenceCheck(String name) { return true; } /** * Checks to see if removing specie is okay * * @param name * specie to remove * @return true if specie is in no influences */ public boolean removeSpeciesCheck(String name) { for (String s : influences.keySet()) { if (s.contains(name)) { return false; } } return true; } public boolean removeComponentCheck(String name) { for (String s : influences.keySet()) { if ((" " + s + " ").contains(" " + name + " ")) { return false; } } return true; } /** * Checks to see if removing promoter is okay * * @param name * promoter to remove * @return true if promoter is in no influences */ public boolean removePromoterCheck(String name) { for (Properties p : influences.values()) { if (p.containsKey(GlobalConstants.PROMOTER) && p.getProperty(GlobalConstants.PROMOTER).equals(name)) { return false; } } return true; } public void removePromoter(String name) { if (name != null && promoters.containsKey(name)) { promoters.remove(name); } } public void removeComponent(String name) { if (name != null && components.containsKey(name)) { components.remove(name); } } public void removeInfluence(String name) { if (name != null && influences.containsKey(name)) { influences.remove(name); } } public String getInput(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(2); } public String getArrow(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(3) + matcher.group(4); } public String getOutput(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(5); } public String getPromoter(String name) { Pattern pattern = Pattern.compile(PARSE); Matcher matcher = pattern.matcher(name); matcher.find(); return matcher.group(6); } public String[] getSpeciesAsArray() { String[] s = new String[species.size()]; s = species.keySet().toArray(s); Arrays.sort(s); return s; } public String[] getPromotersAsArray() { String[] s = new String[promoters.size()]; s = promoters.keySet().toArray(s); Arrays.sort(s); return s; } public HashMap<String, Properties> getPromoters() { return promoters; } public HashMap<String, String> getGlobalParameters() { return globalParameters; } public HashMap<String, String> getDefaultParameters() { return defaultParameters; } public HashMap<String, String> getParameters() { return parameters; } public String getParameter(String parameter) { if (globalParameters.containsKey(parameter)) { return globalParameters.get(parameter); } else { return defaultParameters.get(parameter); } } public void setParameter(String parameter, String value) { globalParameters.put(parameter, value); parameters.put(parameter, value); } public void removeParameter(String parameter) { globalParameters.remove(parameter); } private void parseStates(StringBuffer data) { Pattern network = Pattern.compile(NETWORK); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); matcher.find(); matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } //for backwards compatibility if (properties.containsKey("const")) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.CONSTANT); } else if (!properties.containsKey(GlobalConstants.TYPE)) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.NORMAL); } if (properties.getProperty(GlobalConstants.TYPE).equals("constant")) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.CONSTANT); } //for backwards compatibility if (properties.containsKey("label")) { properties.put(GlobalConstants.ID, properties.getProperty("label").replace("\"", "")); } if (properties.containsKey("gcm")) { if (properties.containsKey(GlobalConstants.TYPE)) { properties.remove(GlobalConstants.TYPE); } properties.put("gcm", properties.getProperty("gcm").replace("\"", "")); components.put(name, properties); } else { species.put(name, properties); } } } private void parseSBMLFile(StringBuffer data) { Pattern pattern = Pattern.compile(SBMLFILE); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { sbmlFile = matcher.group(1); } } private void parseDimAbs(StringBuffer data) { Pattern pattern = Pattern.compile(DIMABS); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { if (matcher.group(1).equals("true")) { dimAbs = true; } } } private void parseBioAbs(StringBuffer data) { Pattern pattern = Pattern.compile(BIOABS); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { if (matcher.group(1).equals("true")) { bioAbs = true; } } } private void parseGlobal(StringBuffer data) { Pattern pattern = Pattern.compile(GLOBAL); Pattern propPattern = Pattern.compile(PROPERTY); Matcher matcher = pattern.matcher(data.toString()); if (matcher.find()) { String s = matcher.group(1); matcher = propPattern.matcher(s); while (matcher.find()) { if (matcher.group(3)!=null) { globalParameters.put(matcher.group(1), matcher.group(3)); parameters.put(matcher.group(1), matcher.group(3)); } else { globalParameters.put(matcher.group(1), matcher.group(4)); parameters.put(matcher.group(1), matcher.group(4)); } } } } private void parsePromoters(StringBuffer data) { Pattern network = Pattern.compile(PROMOTERS_LIST); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); if (!matcher.find()) { return; } matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } promoters.put(name, properties); } } /* private void parseComponents(StringBuffer data) { Pattern network = Pattern.compile(COMPONENTS_LIST); Matcher matcher = network.matcher(data.toString()); Pattern pattern = Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY); if (!matcher.find()) { return; } matcher = pattern.matcher(matcher.group(1)); while (matcher.find()) { String name = matcher.group(2); Matcher propMatcher = propPattern.matcher(matcher.group(3)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1), propMatcher.group(3)); } else { properties.put(propMatcher.group(1), propMatcher.group(4)); } } components.put(name, properties); } } */ private void parseInfluences(StringBuffer data) { Pattern pattern = Pattern.compile(REACTION); Pattern propPattern = Pattern.compile(PROPERTY); Matcher matcher = pattern.matcher(data.toString()); while (matcher.find()) { Matcher propMatcher = propPattern.matcher(matcher.group(6)); Properties properties = new Properties(); while (propMatcher.find()) { if (propMatcher.group(3)!=null) { properties.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(3)); if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER) && !promoters.containsKey(propMatcher.group(3))) { promoters.put(propMatcher.group(3).replaceAll("\"", ""), new Properties()); properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(3).replace("\"", "")); //for backwards compatibility } } else { properties.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(4)); if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER) && !promoters.containsKey(propMatcher.group(4))) { promoters.put(propMatcher.group(4).replaceAll("\"", ""), new Properties()); properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(4).replace("\"", "")); //for backwards compatibility } } } if (properties.containsKey("port")) { components.get(matcher.group(2)).put(properties.get("port"), matcher.group(5)); } else { String name = ""; if (properties.containsKey("arrowhead")) { if (properties.getProperty("arrowhead").indexOf("vee") != -1) { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.ACTIVATION); if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { name = matcher.group(2) + " +> " + matcher.group(5); } else { name = matcher.group(2) + " -> " + matcher.group(5); } } else { properties.setProperty(GlobalConstants.TYPE, GlobalConstants.REPRESSION); if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { name = matcher.group(2) + " +| " + matcher.group(5); } else { name = matcher.group(2) + " -| " + matcher.group(5); } } } if (properties.getProperty(GlobalConstants.PROMOTER) != null) { name = name + ", Promoter " + properties.getProperty(GlobalConstants.PROMOTER); } else { name = name + ", Promoter " + "default"; } if (!properties.containsKey("label")) { String label = properties.getProperty(GlobalConstants.PROMOTER); if (label == null) { label = ""; } if (properties.containsKey(GlobalConstants.BIO) && properties.get(GlobalConstants.BIO).equals("yes")) { label = label + "+"; } properties.put("label", "\""+label+"\""); } properties.put(GlobalConstants.NAME, name); influences.put(name, properties); } } } public void loadDefaultParameters() { Preferences biosimrc = Preferences.userRoot(); defaultParameters = new HashMap<String, String>(); defaultParameters.put(GlobalConstants.KDECAY_STRING, biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); defaultParameters.put(GlobalConstants.KASSOCIATION_STRING, biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "")); defaultParameters.put(GlobalConstants.KBIO_STRING, biosimrc.get("biosim.gcm.KBIO_VALUE", "")); defaultParameters.put(GlobalConstants.COOPERATIVITY_STRING, biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "")); defaultParameters.put(GlobalConstants.KREP_STRING, biosimrc.get("biosim.gcm.KREP_VALUE", "")); defaultParameters.put(GlobalConstants.KACT_STRING, biosimrc.get("biosim.gcm.KACT_VALUE", "")); defaultParameters.put(GlobalConstants.RNAP_BINDING_STRING, biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "")); defaultParameters.put(GlobalConstants.RNAP_STRING, biosimrc.get("biosim.gcm.RNAP_VALUE", "")); defaultParameters.put(GlobalConstants.OCR_STRING, biosimrc.get("biosim.gcm.OCR_VALUE", "")); defaultParameters.put(GlobalConstants.KBASAL_STRING, biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); defaultParameters.put(GlobalConstants.PROMOTER_COUNT_STRING, biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "")); defaultParameters.put(GlobalConstants.STOICHIOMETRY_STRING, biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "")); defaultParameters.put(GlobalConstants.ACTIVED_STRING, biosimrc.get("biosim.gcm.ACTIVED_VALUE", "")); defaultParameters.put(GlobalConstants.MAX_DIMER_STRING, biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "")); defaultParameters.put(GlobalConstants.INITIAL_STRING, biosimrc.get("biosim.gcm.INITIAL_VALUE", "")); for (String s : defaultParameters.keySet()) { parameters.put(s, defaultParameters.get(s)); } } public void setParameters(HashMap<String, String> parameters) { for (String s : parameters.keySet()) { defaultParameters.put(s, parameters.get(s)); this.parameters.put(s, parameters.get(s)); } } private String checkCompabilitySave(String key) { if (key.equals(GlobalConstants.MAX_DIMER_STRING)) { return "maxDimer"; } return key; } private String checkCompabilityLoad(String key) { if (key.equals("maxDimer")) { return GlobalConstants.MAX_DIMER_STRING; } return key; } private static final String NETWORK = "digraph\\sG\\s\\{([^}]*)\\s\\}"; private static final String STATE = "(^|\\n) *([^- \\n]*) *\\[(.*)\\]"; private static final String REACTION = "(^|\\n) *([^ \\n]*) (\\-|\\+)(\\>|\\|) *([^ \n]*) *\\[([^\\]]*)]"; // private static final String PARSE = "(^|\\n) *([^ \\n,]*) *\\-\\> *([^ // \n,]*)"; private static final String PARSE = "(^|\\n) *([^ \\n,]*) (\\-|\\+)(\\>|\\|) *([^ \n,]*), Promoter ([a-zA-Z\\d_]+)"; private static final String PROPERTY = "([a-zA-Z\\ \\-]+)=(\"([^\"]*)\"|([^\\s,]+))"; private static final String GLOBAL = "Global\\s\\{([^}]*)\\s\\}"; private static final String SBMLFILE = GlobalConstants.SBMLFILE + "=\"([^\"]*)\""; private static final String DIMABS = GlobalConstants.DIMABS + "=(true|false)"; private static final String BIOABS = GlobalConstants.BIOABS + "=(true|false)"; private static final String PROMOTERS_LIST = "Promoters\\s\\{([^}]*)\\s\\}"; //private static final String COMPONENTS_LIST = "Components\\s\\{([^}]*)\\s\\}"; private String sbmlFile = ""; private boolean dimAbs = false; private boolean bioAbs = false; private HashMap<String, Properties> species; private HashMap<String, Properties> influences; private HashMap<String, Properties> promoters; private HashMap<String, Properties> components; private HashMap<String, String> parameters; private HashMap<String, String> defaultParameters; private HashMap<String, String> globalParameters; }
Changed LHPN Conversion To Use Local Parameters Instead Of Global Parameters
gui/src/gcm2sbml/parser/GCMFile.java
Changed LHPN Conversion To Use Local Parameters Instead Of Global Parameters
Java
apache-2.0
fe1752845323db83fda276bd4162b6d77b529b8a
0
PRIDE-Utilities/jmzTab,PRIDE-Utilities/jmzTab,nilshoffmann/jmztab,PRIDE-Utilities/jmzTab,nilshoffmann/jmztab
package uk.ac.ebi.pride.jmztab.utils; import uk.ac.ebi.pride.jmztab.utils.errors.MZTabErrorType; import java.io.File; /** * @author qingwei * @since 21/02/13 */ public class MZTabFileParserRun { public void check(File tabFile) throws Exception { System.out.println("checking " + tabFile.getName() + " with Error level"); MZTabFileParser mzTabFileParser = new MZTabFileParser(tabFile, System.out, MZTabErrorType.Level.Error); mzTabFileParser.getMZTabFile(); System.out.println("Finish!"); System.out.println(); } public static void main(String[] args) throws Exception { MZTabFileParserRun run = new MZTabFileParserRun(); File inDir = new File("temp"); for (File tabFile : inDir.listFiles()) { if(tabFile.isFile() && !tabFile.isHidden()){ System.out.println(tabFile.getAbsolutePath()); run.check(tabFile); } } } }
jmztab-util/src/test/java/uk/ac/ebi/pride/jmztab/utils/MZTabFileParserRun.java
package uk.ac.ebi.pride.jmztab.utils; import uk.ac.ebi.pride.jmztab.utils.errors.MZTabErrorType; import java.io.File; /** * @author qingwei * @since 21/02/13 */ public class MZTabFileParserRun { public void check(File tabFile) throws Exception { System.out.println("checking " + tabFile.getName() + " with Error level"); MZTabFileParser mzTabFileParser = new MZTabFileParser(tabFile, System.out, MZTabErrorType.Level.Error); mzTabFileParser.getMZTabFile(); System.out.println("Finish!"); System.out.println(); } public static void main(String[] args) throws Exception { MZTabFileParserRun run = new MZTabFileParserRun(); File inDir = new File("temp"); for (File tabFile : inDir.listFiles()) { if(tabFile.isFile() && !tabFile.isHidden()) run.check(tabFile); } } }
system output logg
jmztab-util/src/test/java/uk/ac/ebi/pride/jmztab/utils/MZTabFileParserRun.java
system output logg
Java
apache-2.0
b0ebf4b8c1c30c5c31d4b7580a0d82c3a4db7164
0
naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder
/* * 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.ngrinder.agent.service; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.grinder.SingleConsole; import net.grinder.common.GrinderProperties; import net.grinder.common.processidentity.AgentIdentity; import net.grinder.console.communication.AgentProcessControlImplementation; import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatusUpdateListener; import net.grinder.engine.controller.AgentControllerIdentityImplementation; import net.grinder.message.console.AgentControllerState; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.mutable.MutableInt; import org.ngrinder.agent.model.AgentRequest; import org.ngrinder.agent.repository.AgentManagerRepository; import org.ngrinder.agent.store.AgentInfoStore; import org.ngrinder.common.exception.NGrinderRuntimeException; import org.ngrinder.infra.config.Config; import org.ngrinder.infra.hazelcast.HazelcastService; import org.ngrinder.infra.hazelcast.task.AgentStateTask; import org.ngrinder.infra.hazelcast.topic.listener.TopicListener; import org.ngrinder.infra.hazelcast.topic.message.TopicEvent; import org.ngrinder.infra.hazelcast.topic.subscriber.TopicSubscriber; import org.ngrinder.infra.schedule.ScheduledTaskService; import org.ngrinder.model.AgentInfo; import org.ngrinder.model.User; import org.ngrinder.monitor.controller.model.SystemDataModel; import org.ngrinder.perftest.service.AgentManager; import org.ngrinder.region.service.RegionService; import org.ngrinder.service.AbstractAgentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import static java.util.Collections.emptySet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; import static org.apache.commons.lang.StringUtils.contains; import static org.apache.commons.lang.StringUtils.endsWith; import static org.ngrinder.agent.model.AgentRequest.RequestType.STOP_AGENT; import static org.ngrinder.agent.model.AgentRequest.RequestType.UPDATE_AGENT; import static org.ngrinder.common.constant.CacheConstants.*; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL; import static org.ngrinder.common.util.CollectionUtils.newHashMap; import static org.ngrinder.common.util.ExceptionUtils.processException; import static org.ngrinder.common.util.TypeConvertUtils.cast; /** * Agent manager service. * * @since 3.0 */ @Service @RequiredArgsConstructor public class AgentService extends AbstractAgentService implements TopicListener<AgentRequest>, AgentStatusUpdateListener { protected static final Logger LOGGER = LoggerFactory.getLogger(AgentService.class); protected final AgentManager agentManager; protected final AgentManagerRepository agentManagerRepository; @Getter private final Config config; private final RegionService regionService; private final HazelcastService hazelcastService; private final TopicSubscriber topicSubscriber; protected final AgentInfoStore agentInfoStore; protected final ScheduledTaskService scheduledTaskService; @Value("${ngrinder.version}") private String nGrinderVersion; @PostConstruct public void init() { agentManager.addAgentStatusUpdateListener(this); topicSubscriber.addListener(AGENT_TOPIC_LISTENER_NAME, this); } private void fillUpAgentInfo(AgentInfo agentInfo, AgentProcessControlImplementation.AgentStatus status) { if (agentInfo == null || status == null) { return; } AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) status.getAgentIdentity(); AgentControllerState state = status.getAgentControllerState(); agentInfo.setState(state); agentInfo.setIp(requireNonNull(agentIdentity).getIp()); agentInfo.setRegion(resolveRegion(agentIdentity.getRegion())); agentInfo.setAgentIdentity(agentIdentity); agentInfo.setName(agentIdentity.getName()); agentInfo.setVersion(agentManager.getAgentVersion(agentIdentity)); agentInfo.setPort(agentManager.getAttachedAgentConnectingPort(agentIdentity)); } private String resolveRegion(String attachedAgentRegion) { String controllerRegion = config.getRegion(); if (attachedAgentRegion != null && attachedAgentRegion.contains("_owned_")) { String[] regionTokens = attachedAgentRegion.split("_owned_", 2); if (StringUtils.equals(controllerRegion, regionTokens[0])) { return attachedAgentRegion; } else { return controllerRegion + "_owned_" + regionTokens[1]; } } return controllerRegion; } private List<AgentInfo> getAllReady() { return agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isReady()) .collect(toList()); } public List<AgentInfo> getAllActive() { return agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isActive()) .collect(toList()); } /** * Get the available agent count map in all regions of the user, including * the free agents and user specified agents. * * @param userId current user id * @return user available agent count map */ @Override public Map<String, MutableInt> getAvailableAgentCountMap(String userId) { Set<String> regions = getRegions(); Map<String, MutableInt> availShareAgents = newHashMap(regions); Map<String, MutableInt> availUserOwnAgent = newHashMap(regions); for (String region : regions) { availShareAgents.put(region, new MutableInt(0)); availUserOwnAgent.put(region, new MutableInt(0)); } String myAgentSuffix = "owned_" + userId; for (AgentInfo agentInfo : getAllActive()) { // Skip all agents which are disapproved, inactive or // have no region prefix. if (!agentInfo.isApproved()) { continue; } String fullRegion = agentInfo.getRegion(); String region = agentManager.extractRegionKey(fullRegion); if (StringUtils.isBlank(region) || !regions.contains(region)) { continue; } // It's my own agent if (fullRegion.endsWith(myAgentSuffix)) { incrementAgentCount(availUserOwnAgent, region, userId); } else if (!fullRegion.contains("owned_")) { incrementAgentCount(availShareAgents, region, userId); } } int maxAgentSizePerConsole = agentManager.getMaxAgentSizePerConsole(); for (String region : regions) { MutableInt mutableInt = availShareAgents.get(region); int shareAgentCount = mutableInt.intValue(); mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole)); mutableInt.add(availUserOwnAgent.get(region)); } return availShareAgents; } private void incrementAgentCount(Map<String, MutableInt> agentMap, String region, String userId) { if (!agentMap.containsKey(region)) { LOGGER.warn("Region: {} not exist in cluster nor owned by user: {}.", region, userId); } else { agentMap.get(region).increment(); } } protected Set<String> getRegions() { return regionService.getAll().keySet(); } @Override public AgentControllerIdentityImplementation getAgentIdentityByIpAndName(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo != null) { return cast(agentInfo.getAgentIdentity()); } return null; } public AgentInfo getAgent(String ip, String name) { return agentInfoStore.getAgentInfo(createAgentKey(ip, name)); } /** * Approve/disapprove the agent on given id. * * @param ip ip * @param name host name * @param approve true/false */ @Transactional public void approve(String ip, String name, boolean approve) { AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name); if (agentInfoInDB != null) { agentInfoInDB.setApproved(approve); } else { agentInfoInDB = new AgentInfo(); agentInfoInDB.setIp(ip); agentInfoInDB.setName(name); agentInfoInDB.setApproved(approve); agentManagerRepository.save(agentInfoInDB); } agentManagerRepository.flush(); updateApproveInStore(ip, name, approve); } private void updateApproveInStore(String ip, String name, boolean approve) { AgentInfo agentInfo = getAgent(ip, name); agentInfo.setApproved(approve); agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo); } /** * Get all free approved agents * * @return AgentInfo set */ private Set<AgentInfo> getAllFreeApprovedAgents() { return getAllReady() .stream() .filter(AgentInfo::isApproved) .collect(toSet()); } /** * Get all free approved agents attached to current node. * * @return AgentInfo set * */ public Set<AgentInfo> getAllAttachedFreeApprovedAgents() { return getAllFreeApprovedAgents() .stream() .filter(this::isCurrentRegion) .collect(toSet()); } /** * Get all approved agents for given user which are not used now. * * @param userId user id * @return AgentInfo set */ public Set<AgentInfo> getAllAttachedFreeApprovedAgentsForUser(String userId) { return getAllFreeApprovedAgents() .stream() .filter(this::isCurrentRegion) .filter(agentInfo -> isOwnedAgent(agentInfo, userId) || isCommonAgent(agentInfo)) .collect(toSet()); } private boolean isCurrentRegion(AgentInfo agentInfo) { String region = config.getRegion(); return StringUtils.equals(region, agentManager.extractRegionKey(agentInfo.getRegion())); } private boolean isOwnedAgent(AgentInfo agentInfo, String userId) { return endsWith(agentInfo.getRegion(), "owned_" + userId); } private boolean isCommonAgent(AgentInfo agentInfo) { return !contains(agentInfo.getRegion(), "owned_"); } /** * Assign the agents on the given console. * * @param user user * @param singleConsole {@link SingleConsole} to which agents will be assigned * @param grinderProperties {@link GrinderProperties} to be distributed. * @param agentCount the count of agents. */ public synchronized void runAgent(User user, final SingleConsole singleConsole, final GrinderProperties grinderProperties, final Integer agentCount) { final Set<AgentInfo> allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId()); final Set<AgentInfo> necessaryAgents = selectAgent(user, allFreeAgents, agentCount); if (hasOldVersionAgent(necessaryAgents)) { for (AgentInfo agentInfo : necessaryAgents) { if (!agentInfo.getVersion().equals(nGrinderVersion)) { update(agentInfo.getIp(), agentInfo.getName()); } } throw new NGrinderRuntimeException("Old version agent is detected so, update message has been sent automatically." + "\n Please restart perftest after few minutes."); } hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); LOGGER.info("{} agents are starting for user {}", agentCount, user.getUserId()); for (AgentInfo agentInfo : necessaryAgents) { LOGGER.info("- Agent {}", agentInfo.getName()); } agentManager.runAgent(singleConsole, grinderProperties, necessaryAgents); } private boolean hasOldVersionAgent(Set<AgentInfo> agentInfos) { return agentInfos.stream().anyMatch(agentInfo -> !agentInfo.getVersion().equals(nGrinderVersion)); } /** * Select agent. This method return agent set which is belong to the given user first and then share agent set. * * Priority of agent selection. * 1. owned agent of recently used. * 2. owned agent. * 3. public agent of recently used. * 4. public agent. * * @param user user * @param allFreeAgents available agents * @param agentCount number of agents * @return selected agents. */ Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Comparator<AgentInfo> recentlyUsedPriorityComparator = (agent1, agent2) -> { if (recentlyUsedAgents.contains(agent1)) { return -1; } if (recentlyUsedAgents.contains(agent2)) { return 1; } return 0; }; Stream<AgentInfo> ownedFreeAgentStream = allFreeAgents .stream() .filter(agentInfo -> isOwnedAgent(agentInfo, user.getUserId())) .sorted(recentlyUsedPriorityComparator); Stream<AgentInfo> freeAgentStream = allFreeAgents .stream() .filter(this::isCommonAgent) .sorted(recentlyUsedPriorityComparator); return concat(ownedFreeAgentStream, freeAgentStream) .limit(agentCount) .collect(toSet()); } /** * Stop agent. If it's in cluster mode, it queue to agentRequestCache. * otherwise, it send stop message to the agent. * * @param ip ip of agent to stop. * @param name host name of agent to stop. */ @Override public void stop(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo == null) { return; } publishTopic(agentInfo, STOP_AGENT); } public void stop(AgentControllerIdentityImplementation agentIdentity) { agentManager.stopAgent(agentIdentity); } @Override public void update(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo == null) { return; } publishTopic(agentInfo, UPDATE_AGENT); } @Override public SystemDataModel getSystemDataModel(String ip, String name, String region) { return hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new AgentStateTask(ip, name), agentManager.extractRegionKey(region)); } /** * Update the agent * * @param agentIdentity agent identity to be updated. */ public void updateAgent(AgentIdentity agentIdentity) { agentManager.updateAgent(agentIdentity, agentManager.getAgentForceUpdate() ? "99.99" : config.getVersion()); } private String createAgentKey(String ip, String name) { return ip + "_" + name; } /** * Ready agent state count return * * @param userId The login user id * @param targetRegion targetRegion The name of target region * @return ready Agent count */ @Override public int getReadyAgentCount(String userId, String targetRegion) { int readyAgentCnt = 0; String myOwnAgent = targetRegion + "_owned_" + userId; for (AgentInfo agentInfo : getAllReady()) { if (!agentInfo.isApproved()) { continue; } String fullRegion = agentInfo.getRegion(); if (StringUtils.equals(fullRegion, targetRegion) || StringUtils.equals(fullRegion, myOwnAgent)) { readyAgentCnt++; } } return readyAgentCnt; } @Override public List<AgentInfo> getAllAttached() { return agentInfoStore.getAllAgentInfo(); } @Override public String createKey(AgentControllerIdentityImplementation agentIdentity) { return createAgentKey(agentIdentity.getIp(), agentIdentity.getName()); } private void publishTopic(AgentInfo agentInfo, AgentRequest.RequestType requestType) { hazelcastService.publish(AGENT_TOPIC_NAME, new TopicEvent<>(AGENT_TOPIC_LISTENER_NAME, agentManager.extractRegionKey(agentInfo.getRegion()), new AgentRequest(agentInfo.getIp(), agentInfo.getName(), requestType))); } @Override public void execute(TopicEvent<AgentRequest> event) { if (event.getKey().equals(config.getRegion())) { AgentRequest agentRequest = event.getData(); AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName()); if (agentIdentity != null) { agentRequest.getRequestType().process(AgentService.this, agentIdentity); } } } @Override public void update(Map<AgentIdentity, AgentProcessControlImplementation.AgentStatus> agentMap) { boolean approved = config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL); Set<AgentInfo> agentInfoSet = agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> StringUtils.equals(agentManager.extractRegionKey(agentInfo.getRegion()), config.getRegion())) .collect(toSet()); for (AgentProcessControlImplementation.AgentStatus status : agentMap.values()) { AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) status.getAgentIdentity(); AgentInfo agentInfo = agentInfoStore.getAgentInfo(createKey(agentIdentity)); // check new agent if (agentInfo == null) { agentInfo = new AgentInfo(); } fillUpAgentInfo(agentInfo, status); AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(agentInfo.getIp(), agentInfo.getName()); if (agentInfoInDB != null) { agentInfo.setApproved(agentInfoInDB.getApproved()); } else { agentInfo.setApproved(approved); } agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo); agentInfoSet.remove(agentInfo); } // delete disconnected agent. for (AgentInfo agentInfo : agentInfoSet) { agentInfoStore.deleteAgentInfo(agentInfo.getAgentKey()); } } }
ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java
/* * 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.ngrinder.agent.service; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.grinder.SingleConsole; import net.grinder.common.GrinderProperties; import net.grinder.common.processidentity.AgentIdentity; import net.grinder.console.communication.AgentProcessControlImplementation; import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatusUpdateListener; import net.grinder.engine.controller.AgentControllerIdentityImplementation; import net.grinder.message.console.AgentControllerState; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.mutable.MutableInt; import org.ngrinder.agent.model.AgentRequest; import org.ngrinder.agent.repository.AgentManagerRepository; import org.ngrinder.agent.store.AgentInfoStore; import org.ngrinder.infra.config.Config; import org.ngrinder.infra.hazelcast.HazelcastService; import org.ngrinder.infra.hazelcast.task.AgentStateTask; import org.ngrinder.infra.hazelcast.topic.listener.TopicListener; import org.ngrinder.infra.hazelcast.topic.message.TopicEvent; import org.ngrinder.infra.hazelcast.topic.subscriber.TopicSubscriber; import org.ngrinder.infra.schedule.ScheduledTaskService; import org.ngrinder.model.AgentInfo; import org.ngrinder.model.User; import org.ngrinder.monitor.controller.model.SystemDataModel; import org.ngrinder.perftest.service.AgentManager; import org.ngrinder.region.service.RegionService; import org.ngrinder.service.AbstractAgentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import static java.util.Collections.emptySet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; import static org.apache.commons.lang.StringUtils.contains; import static org.apache.commons.lang.StringUtils.endsWith; import static org.ngrinder.agent.model.AgentRequest.RequestType.STOP_AGENT; import static org.ngrinder.agent.model.AgentRequest.RequestType.UPDATE_AGENT; import static org.ngrinder.common.constant.CacheConstants.*; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL; import static org.ngrinder.common.util.CollectionUtils.newHashMap; import static org.ngrinder.common.util.TypeConvertUtils.cast; /** * Agent manager service. * * @since 3.0 */ @Service @RequiredArgsConstructor public class AgentService extends AbstractAgentService implements TopicListener<AgentRequest>, AgentStatusUpdateListener { protected static final Logger LOGGER = LoggerFactory.getLogger(AgentService.class); protected final AgentManager agentManager; protected final AgentManagerRepository agentManagerRepository; @Getter private final Config config; private final RegionService regionService; private final HazelcastService hazelcastService; private final TopicSubscriber topicSubscriber; protected final AgentInfoStore agentInfoStore; protected final ScheduledTaskService scheduledTaskService; @PostConstruct public void init() { agentManager.addAgentStatusUpdateListener(this); topicSubscriber.addListener(AGENT_TOPIC_LISTENER_NAME, this); } private void fillUpAgentInfo(AgentInfo agentInfo, AgentProcessControlImplementation.AgentStatus status) { if (agentInfo == null || status == null) { return; } AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) status.getAgentIdentity(); AgentControllerState state = status.getAgentControllerState(); agentInfo.setState(state); agentInfo.setIp(requireNonNull(agentIdentity).getIp()); agentInfo.setRegion(resolveRegion(agentIdentity.getRegion())); agentInfo.setAgentIdentity(agentIdentity); agentInfo.setName(agentIdentity.getName()); agentInfo.setVersion(agentManager.getAgentVersion(agentIdentity)); agentInfo.setPort(agentManager.getAttachedAgentConnectingPort(agentIdentity)); } private String resolveRegion(String attachedAgentRegion) { String controllerRegion = config.getRegion(); if (attachedAgentRegion != null && attachedAgentRegion.contains("_owned_")) { String[] regionTokens = attachedAgentRegion.split("_owned_", 2); if (StringUtils.equals(controllerRegion, regionTokens[0])) { return attachedAgentRegion; } else { return controllerRegion + "_owned_" + regionTokens[1]; } } return controllerRegion; } private List<AgentInfo> getAllReady() { return agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isReady()) .collect(toList()); } public List<AgentInfo> getAllActive() { return agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isActive()) .collect(toList()); } /** * Get the available agent count map in all regions of the user, including * the free agents and user specified agents. * * @param userId current user id * @return user available agent count map */ @Override public Map<String, MutableInt> getAvailableAgentCountMap(String userId) { Set<String> regions = getRegions(); Map<String, MutableInt> availShareAgents = newHashMap(regions); Map<String, MutableInt> availUserOwnAgent = newHashMap(regions); for (String region : regions) { availShareAgents.put(region, new MutableInt(0)); availUserOwnAgent.put(region, new MutableInt(0)); } String myAgentSuffix = "owned_" + userId; for (AgentInfo agentInfo : getAllActive()) { // Skip all agents which are disapproved, inactive or // have no region prefix. if (!agentInfo.isApproved()) { continue; } String fullRegion = agentInfo.getRegion(); String region = agentManager.extractRegionKey(fullRegion); if (StringUtils.isBlank(region) || !regions.contains(region)) { continue; } // It's my own agent if (fullRegion.endsWith(myAgentSuffix)) { incrementAgentCount(availUserOwnAgent, region, userId); } else if (!fullRegion.contains("owned_")) { incrementAgentCount(availShareAgents, region, userId); } } int maxAgentSizePerConsole = agentManager.getMaxAgentSizePerConsole(); for (String region : regions) { MutableInt mutableInt = availShareAgents.get(region); int shareAgentCount = mutableInt.intValue(); mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole)); mutableInt.add(availUserOwnAgent.get(region)); } return availShareAgents; } private void incrementAgentCount(Map<String, MutableInt> agentMap, String region, String userId) { if (!agentMap.containsKey(region)) { LOGGER.warn("Region: {} not exist in cluster nor owned by user: {}.", region, userId); } else { agentMap.get(region).increment(); } } protected Set<String> getRegions() { return regionService.getAll().keySet(); } @Override public AgentControllerIdentityImplementation getAgentIdentityByIpAndName(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo != null) { return cast(agentInfo.getAgentIdentity()); } return null; } public AgentInfo getAgent(String ip, String name) { return agentInfoStore.getAgentInfo(createAgentKey(ip, name)); } /** * Approve/disapprove the agent on given id. * * @param ip ip * @param name host name * @param approve true/false */ @Transactional public void approve(String ip, String name, boolean approve) { AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name); if (agentInfoInDB != null) { agentInfoInDB.setApproved(approve); } else { agentInfoInDB = new AgentInfo(); agentInfoInDB.setIp(ip); agentInfoInDB.setName(name); agentInfoInDB.setApproved(approve); agentManagerRepository.save(agentInfoInDB); } agentManagerRepository.flush(); updateApproveInStore(ip, name, approve); } private void updateApproveInStore(String ip, String name, boolean approve) { AgentInfo agentInfo = getAgent(ip, name); agentInfo.setApproved(approve); agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo); } /** * Get all free approved agents * * @return AgentInfo set */ private Set<AgentInfo> getAllFreeApprovedAgents() { return getAllReady() .stream() .filter(AgentInfo::isApproved) .collect(toSet()); } /** * Get all free approved agents attached to current node. * * @return AgentInfo set * */ public Set<AgentInfo> getAllAttachedFreeApprovedAgents() { return getAllFreeApprovedAgents() .stream() .filter(this::isCurrentRegion) .collect(toSet()); } /** * Get all approved agents for given user which are not used now. * * @param userId user id * @return AgentInfo set */ public Set<AgentInfo> getAllAttachedFreeApprovedAgentsForUser(String userId) { return getAllFreeApprovedAgents() .stream() .filter(this::isCurrentRegion) .filter(agentInfo -> isOwnedAgent(agentInfo, userId) || isCommonAgent(agentInfo)) .collect(toSet()); } private boolean isCurrentRegion(AgentInfo agentInfo) { String region = config.getRegion(); return StringUtils.equals(region, agentManager.extractRegionKey(agentInfo.getRegion())); } private boolean isOwnedAgent(AgentInfo agentInfo, String userId) { return endsWith(agentInfo.getRegion(), "owned_" + userId); } private boolean isCommonAgent(AgentInfo agentInfo) { return !contains(agentInfo.getRegion(), "owned_"); } /** * Assign the agents on the given console. * * @param user user * @param singleConsole {@link SingleConsole} to which agents will be assigned * @param grinderProperties {@link GrinderProperties} to be distributed. * @param agentCount the count of agents. */ public synchronized void runAgent(User user, final SingleConsole singleConsole, final GrinderProperties grinderProperties, final Integer agentCount) { final Set<AgentInfo> allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId()); final Set<AgentInfo> necessaryAgents = selectAgent(user, allFreeAgents, agentCount); hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); LOGGER.info("{} agents are starting for user {}", agentCount, user.getUserId()); for (AgentInfo agentInfo : necessaryAgents) { LOGGER.info("- Agent {}", agentInfo.getName()); } agentManager.runAgent(singleConsole, grinderProperties, necessaryAgents); } /** * Select agent. This method return agent set which is belong to the given user first and then share agent set. * * Priority of agent selection. * 1. owned agent of recently used. * 2. owned agent. * 3. public agent of recently used. * 4. public agent. * * @param user user * @param allFreeAgents available agents * @param agentCount number of agents * @return selected agents. */ Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) { Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Comparator<AgentInfo> agentInfoComparator = (agent1, agent2) -> { if (recentlyUsedAgents.contains(agent1)) { return -1; } if (recentlyUsedAgents.contains(agent2)) { return 1; } return 0; }; Stream<AgentInfo> ownedFreeAgentStream = allFreeAgents .stream() .filter(agentInfo -> isOwnedAgent(agentInfo, user.getUserId())) .sorted(agentInfoComparator); Stream<AgentInfo> freeAgentStream = allFreeAgents .stream() .filter(this::isCommonAgent) .sorted(agentInfoComparator); return concat(ownedFreeAgentStream, freeAgentStream) .limit(agentCount) .collect(toSet()); } /** * Stop agent. If it's in cluster mode, it queue to agentRequestCache. * otherwise, it send stop message to the agent. * * @param ip ip of agent to stop. * @param name host name of agent to stop. */ @Override public void stop(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo == null) { return; } publishTopic(agentInfo, STOP_AGENT); } public void stop(AgentControllerIdentityImplementation agentIdentity) { agentManager.stopAgent(agentIdentity); } @Override public void update(String ip, String name) { AgentInfo agentInfo = getAgent(ip, name); if (agentInfo == null) { return; } publishTopic(agentInfo, UPDATE_AGENT); } @Override public SystemDataModel getSystemDataModel(String ip, String name, String region) { return hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new AgentStateTask(ip, name), agentManager.extractRegionKey(region)); } /** * Update the agent * * @param agentIdentity agent identity to be updated. */ public void updateAgent(AgentIdentity agentIdentity) { agentManager.updateAgent(agentIdentity, agentManager.getAgentForceUpdate() ? "99.99" : config.getVersion()); } private String createAgentKey(String ip, String name) { return ip + "_" + name; } /** * Ready agent state count return * * @param userId The login user id * @param targetRegion targetRegion The name of target region * @return ready Agent count */ @Override public int getReadyAgentCount(String userId, String targetRegion) { int readyAgentCnt = 0; String myOwnAgent = targetRegion + "_owned_" + userId; for (AgentInfo agentInfo : getAllReady()) { if (!agentInfo.isApproved()) { continue; } String fullRegion = agentInfo.getRegion(); if (StringUtils.equals(fullRegion, targetRegion) || StringUtils.equals(fullRegion, myOwnAgent)) { readyAgentCnt++; } } return readyAgentCnt; } @Override public List<AgentInfo> getAllAttached() { return agentInfoStore.getAllAgentInfo(); } @Override public String createKey(AgentControllerIdentityImplementation agentIdentity) { return createAgentKey(agentIdentity.getIp(), agentIdentity.getName()); } private void publishTopic(AgentInfo agentInfo, AgentRequest.RequestType requestType) { hazelcastService.publish(AGENT_TOPIC_NAME, new TopicEvent<>(AGENT_TOPIC_LISTENER_NAME, agentManager.extractRegionKey(agentInfo.getRegion()), new AgentRequest(agentInfo.getIp(), agentInfo.getName(), requestType))); } @Override public void execute(TopicEvent<AgentRequest> event) { if (event.getKey().equals(config.getRegion())) { AgentRequest agentRequest = event.getData(); AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName()); if (agentIdentity != null) { agentRequest.getRequestType().process(AgentService.this, agentIdentity); } } } @Override public void update(Map<AgentIdentity, AgentProcessControlImplementation.AgentStatus> agentMap) { boolean approved = config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL); Set<AgentInfo> agentInfoSet = agentInfoStore.getAllAgentInfo() .stream() .filter(agentInfo -> StringUtils.equals(agentManager.extractRegionKey(agentInfo.getRegion()), config.getRegion())) .collect(toSet()); for (AgentProcessControlImplementation.AgentStatus status : agentMap.values()) { AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) status.getAgentIdentity(); AgentInfo agentInfo = agentInfoStore.getAgentInfo(createKey(agentIdentity)); // check new agent if (agentInfo == null) { agentInfo = new AgentInfo(); } fillUpAgentInfo(agentInfo, status); AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(agentInfo.getIp(), agentInfo.getName()); if (agentInfoInDB != null) { agentInfo.setApproved(agentInfoInDB.getApproved()); } else { agentInfo.setApproved(approved); } agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo); agentInfoSet.remove(agentInfo); } // delete disconnected agent. for (AgentInfo agentInfo : agentInfoSet) { agentInfoStore.deleteAgentInfo(agentInfo.getAgentKey()); } } }
check and update old version agents
ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java
check and update old version agents
Java
apache-2.0
2902a9a3c07e881dd7aeae0a55189facfab1966c
0
twogee/ant-ivy,jaikiran/ant-ivy,twogee/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,apache/ant-ivy,twogee/ant-ivy,apache/ant-ivy,twogee/ant-ivy,jaikiran/ant-ivy
/* * 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.ivy.plugins.parser.xml; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParser; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParserTest; import org.apache.ivy.util.FileUtil; public class XmlModuleDescriptorWriterTest extends TestCase { private static String LICENSE; static { try { LICENSE = FileUtil.readEntirely(new BufferedReader(new InputStreamReader( XmlModuleDescriptorWriterTest.class.getResourceAsStream("license.xml")))); } catch (IOException e) { e.printStackTrace(); } } private File dest = new File("build/test/test-write.xml"); public void testSimple() throws Exception { DefaultModuleDescriptor md = (DefaultModuleDescriptor) XmlModuleDescriptorParser .getInstance().parseDescriptor(new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-simple.xml"), true); md.setResolvedPublicationDate(new GregorianCalendar(2005, 4, 1, 11, 0, 0).getTime()); md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), "NONE")); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-simple.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testInfo() throws Exception { DefaultModuleDescriptor md = (DefaultModuleDescriptor) XmlModuleDescriptorParser .getInstance().parseDescriptor(new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-info.xml"), true); md.setResolvedPublicationDate(new GregorianCalendar(2005, 4, 1, 11, 0, 0).getTime()); md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), "NONE")); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-info.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testDependencies() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-dependencies.xml"), true); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-dependencies.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testFull() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-full.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfos() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extrainfo.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-extrainfo.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfosWithNestedElement() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extrainfo-nested.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-extrainfo-nested.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfosFromMaven() throws Exception { ModuleDescriptor md = PomModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), PomModuleDescriptorParserTest.class .getResource("test-versionPropertyDependencyMgt.pom"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); wrote = wrote.replaceFirst("publication=\"([0-9])*\"", "publication=\"20140429153143\""); System.out.println(wrote); String expected = readEntirely("test-write-extrainfo-from-maven.xml").replaceAll("\r\n", "\n").replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtends() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extends-all.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))).replaceAll( "\r\n?", "\n"); String expected = readEntirely("test-write-extends.xml").replaceAll("\r\n?", "\n"); assertEquals(expected, wrote); } /** * Test that the transitive attribute is written for non-transitive configurations. * * <code><conf ... transitive="false" ... /></code> * * @see <a href="https://issues.apache.org/jira/browse/IVY-1207">IVY-1207</a> * @throws Exception */ public void testTransitiveAttributeForNonTransitiveConfs() throws Exception { // Given a ModuleDescriptor with a non-transitive configuration DefaultModuleDescriptor md = new DefaultModuleDescriptor(new ModuleRevisionId(new ModuleId( "myorg", "myname"), "1.0"), "integration", new Date()); Configuration conf = new Configuration("conf", Visibility.PUBLIC, "desc", null, false, null); md.addConfiguration(conf); // When the ModuleDescriptor is written XmlModuleDescriptorWriter.write(md, LICENSE, dest); // Then the transitive attribute must be set to false String output = FileUtil.readEntirely(dest); String writtenConf = output.substring(output.indexOf("<configurations>") + 16, output.indexOf("</configurations>")).trim(); assertTrue("Transitive attribute not set to false: " + writtenConf, writtenConf.indexOf("transitive=\"false\"") >= 0); } /** * Test that the transitive attribute is not written when the configuration IS transitive. * * This is the default and writing it will only add noise and cause a deviation from the known * behavior (before fixing IVY-1207). * * @see <a href="https://issues.apache.org/jira/browse/IVY-1207">IVY-1207</a> * @throws Exception */ public void testTransitiveAttributeNotWrittenForTransitiveConfs() throws Exception { // Given a ModuleDescriptor with a transitive configuration DefaultModuleDescriptor md = new DefaultModuleDescriptor(new ModuleRevisionId(new ModuleId( "myorg", "myname"), "1.0"), "integration", new Date()); Configuration conf = new Configuration("conf", Visibility.PUBLIC, "desc", null, true, null); md.addConfiguration(conf); // When the ModuleDescriptor is written XmlModuleDescriptorWriter.write(md, LICENSE, dest); // Then the transitive attribute must NOT be written String output = FileUtil.readEntirely(dest); String writtenConf = output.substring(output.indexOf("<configurations>") + 16, output.indexOf("</configurations>")).trim(); assertFalse("Transitive attribute set: " + writtenConf, writtenConf.indexOf("transitive=") >= 0); } private String readEntirely(String resource) throws IOException { return FileUtil.readEntirely(new BufferedReader(new InputStreamReader( XmlModuleDescriptorWriterTest.class.getResource(resource).openStream()))); } public void setUp() { if (dest.exists()) { dest.delete(); } if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } } protected void tearDown() throws Exception { if (dest.exists()) { dest.delete(); } } }
test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.plugins.parser.xml; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.Configuration.Visibility; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleId; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParser; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParserTest; import org.apache.ivy.util.FileUtil; public class XmlModuleDescriptorWriterTest extends TestCase { private static String LICENSE; static { try { LICENSE = FileUtil.readEntirely(new BufferedReader(new InputStreamReader( XmlModuleDescriptorWriterTest.class.getResourceAsStream("license.xml")))); } catch (IOException e) { e.printStackTrace(); } } private File dest = new File("build/test/test-write.xml"); public void testSimple() throws Exception { DefaultModuleDescriptor md = (DefaultModuleDescriptor) XmlModuleDescriptorParser .getInstance().parseDescriptor(new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-simple.xml"), true); md.setResolvedPublicationDate(new GregorianCalendar(2005, 4, 1, 11, 0, 0).getTime()); md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), "NONE")); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-simple.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testInfo() throws Exception { DefaultModuleDescriptor md = (DefaultModuleDescriptor) XmlModuleDescriptorParser .getInstance().parseDescriptor(new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-info.xml"), true); md.setResolvedPublicationDate(new GregorianCalendar(2005, 4, 1, 11, 0, 0).getTime()); md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), "NONE")); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-info.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testDependencies() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-dependencies.xml"), true); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-dependencies.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testFull() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-full.xml").replaceAll("\r\n", "\n").replace( '\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfos() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extrainfo.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-extrainfo.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfosWithNestedElement() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extrainfo-nested.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-extrainfo-nested.xml").replaceAll("\r\n", "\n") .replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtraInfosFromMaven() throws Exception { ModuleDescriptor md = PomModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), PomModuleDescriptorParserTest.class .getResource("test-versionPropertyDependencyMgt.pom"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))) .replaceAll("\r\n", "\n").replace('\r', '\n'); String expected = readEntirely("test-write-extrainfo-from-maven.xml").replaceAll("\r\n", "\n").replace('\r', '\n'); assertEquals(expected, wrote); } public void testExtends() throws Exception { ModuleDescriptor md = XmlModuleDescriptorParser.getInstance().parseDescriptor( new IvySettings(), XmlModuleDescriptorWriterTest.class.getResource("test-extends-all.xml"), false); XmlModuleDescriptorWriter.write(md, LICENSE, dest); assertTrue(dest.exists()); String wrote = FileUtil.readEntirely(new BufferedReader(new FileReader(dest))).replaceAll( "\r\n?", "\n"); String expected = readEntirely("test-write-extends.xml").replaceAll("\r\n?", "\n"); assertEquals(expected, wrote); } /** * Test that the transitive attribute is written for non-transitive configurations. * * <code><conf ... transitive="false" ... /></code> * * @see <a href="https://issues.apache.org/jira/browse/IVY-1207">IVY-1207</a> * @throws Exception */ public void testTransitiveAttributeForNonTransitiveConfs() throws Exception { // Given a ModuleDescriptor with a non-transitive configuration DefaultModuleDescriptor md = new DefaultModuleDescriptor(new ModuleRevisionId(new ModuleId( "myorg", "myname"), "1.0"), "integration", new Date()); Configuration conf = new Configuration("conf", Visibility.PUBLIC, "desc", null, false, null); md.addConfiguration(conf); // When the ModuleDescriptor is written XmlModuleDescriptorWriter.write(md, LICENSE, dest); // Then the transitive attribute must be set to false String output = FileUtil.readEntirely(dest); String writtenConf = output.substring(output.indexOf("<configurations>") + 16, output.indexOf("</configurations>")).trim(); assertTrue("Transitive attribute not set to false: " + writtenConf, writtenConf.indexOf("transitive=\"false\"") >= 0); } /** * Test that the transitive attribute is not written when the configuration IS transitive. * * This is the default and writing it will only add noise and cause a deviation from the known * behavior (before fixing IVY-1207). * * @see <a href="https://issues.apache.org/jira/browse/IVY-1207">IVY-1207</a> * @throws Exception */ public void testTransitiveAttributeNotWrittenForTransitiveConfs() throws Exception { // Given a ModuleDescriptor with a transitive configuration DefaultModuleDescriptor md = new DefaultModuleDescriptor(new ModuleRevisionId(new ModuleId( "myorg", "myname"), "1.0"), "integration", new Date()); Configuration conf = new Configuration("conf", Visibility.PUBLIC, "desc", null, true, null); md.addConfiguration(conf); // When the ModuleDescriptor is written XmlModuleDescriptorWriter.write(md, LICENSE, dest); // Then the transitive attribute must NOT be written String output = FileUtil.readEntirely(dest); String writtenConf = output.substring(output.indexOf("<configurations>") + 16, output.indexOf("</configurations>")).trim(); assertFalse("Transitive attribute set: " + writtenConf, writtenConf.indexOf("transitive=") >= 0); } private String readEntirely(String resource) throws IOException { return FileUtil.readEntirely(new BufferedReader(new InputStreamReader( XmlModuleDescriptorWriterTest.class.getResource(resource).openStream()))); } public void setUp() { if (dest.exists()) { dest.delete(); } if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } } protected void tearDown() throws Exception { if (dest.exists()) { dest.delete(); } } }
Fix broken unit test, force publication date on testExtraInfosWithNestedElement as PomParsing can generate a publication date based on file modification date git-svn-id: bddd0b838a5b7898c5897d85c562f956f46262e5@1592662 13f79535-47bb-0310-9956-ffa450edef68
test/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriterTest.java
Fix broken unit test, force publication date on testExtraInfosWithNestedElement as PomParsing can generate a publication date based on file modification date
Java
apache-2.0
95f56277a18d71282150d9ff035a5ed65f190c3d
0
apache/jena,kidaa/jena,kidaa/jena,apache/jena,tr3vr/jena,kamir/jena,samaitra/jena,samaitra/jena,apache/jena,kamir/jena,kidaa/jena,samaitra/jena,apache/jena,apache/jena,apache/jena,CesarPantoja/jena,CesarPantoja/jena,kamir/jena,kidaa/jena,CesarPantoja/jena,samaitra/jena,tr3vr/jena,samaitra/jena,tr3vr/jena,CesarPantoja/jena,tr3vr/jena,kamir/jena,apache/jena,tr3vr/jena,apache/jena,kamir/jena,CesarPantoja/jena,kamir/jena,tr3vr/jena,CesarPantoja/jena,kidaa/jena,CesarPantoja/jena,samaitra/jena,kidaa/jena,tr3vr/jena,samaitra/jena,kidaa/jena,kamir/jena
/* * 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.jena.tdb.transaction ; import org.apache.jena.atlas.lib.Sync ; import org.apache.jena.query.ReadWrite ; import org.apache.jena.sparql.JenaTransactionException ; import org.apache.jena.sparql.core.DatasetGraphTrackActive ; import org.apache.jena.sparql.util.Context ; import org.apache.jena.tdb.StoreConnection ; import org.apache.jena.tdb.TDB ; import org.apache.jena.tdb.base.file.Location ; import org.apache.jena.tdb.store.DatasetGraphTDB ; /** * Transactional DatasetGraph that allows one active transaction. For multiple * read transactions, create multiple DatasetGraphTransaction objects. This is * analogous to a "connection" in JDBC. */ public class DatasetGraphTransaction extends DatasetGraphTrackActive implements Sync { /* * Initially, the app can use this DatasetGraph non-transactionally. But as * soon as it starts a transaction, the dataset can only be used inside * transactions. * * There are two per-thread state variables: txn: ThreadLocalTxn -- the * transactional , one time use dataset isInTransactionB: ThreadLocalBoolean * -- flags true between begin and commit/abort, and end for read * transactions. */ static class ThreadLocalTxn extends ThreadLocal<DatasetGraphTxn> { // This is the default - but nice to give it a name and to set it // clearly. @Override protected DatasetGraphTxn initialValue() { return null ; } } static class ThreadLocalBoolean extends ThreadLocal<Boolean> { @Override protected Boolean initialValue() { return false ; } } // Transaction per thread per DatasetGraphTransaction object. private ThreadLocalTxn txn = new ThreadLocalTxn() ; private ThreadLocalBoolean inTransaction = new ThreadLocalBoolean() ; private final StoreConnection sConn ; private boolean isClosed = false ; public DatasetGraphTransaction(Location location) { sConn = StoreConnection.make(location) ; } public Location getLocation() { return sConn.getLocation() ; } public DatasetGraphTDB getDatasetGraphToQuery() { checkNotClosed() ; return get() ; } /** Access the base storage - use with care */ public DatasetGraphTDB getBaseDatasetGraph() { checkNotClosed() ; return sConn.getBaseDataset() ; } /** Get the current DatasetGraphTDB */ @Override public DatasetGraphTDB get() { if ( isInTransaction() ) { DatasetGraphTxn dsgTxn = txn.get() ; if ( dsgTxn == null ) throw new TDBTransactionException("In a transaction but no transactional DatasetGraph") ; return dsgTxn.getView() ; } if ( sConn.haveUsedInTransaction() ) throw new TDBTransactionException("Not in a transaction") ; // Never used in a transaction - return underlying database for old // style (non-transactional) usage. return sConn.getBaseDataset() ; } @Override protected void checkActive() { checkNotClosed() ; if ( !isInTransaction() ) throw new JenaTransactionException("Not in a transaction (" + getLocation() + ")") ; } @Override protected void checkNotActive() { checkNotClosed() ; if ( sConn.haveUsedInTransaction() && isInTransaction() ) throw new JenaTransactionException("Currently in a transaction (" + getLocation() + ")") ; } protected void checkNotClosed() { if ( isClosed ) throw new JenaTransactionException("Already closed") ; } @Override public boolean isInTransaction() { checkNotClosed() ; return inTransaction.get() ; } public boolean isClosed() { return isClosed ; } public void syncIfNotTransactional() { if ( !sConn.haveUsedInTransaction() ) sConn.getBaseDataset().sync() ; } @Override protected void _begin(ReadWrite readWrite) { checkNotClosed() ; DatasetGraphTxn dsgTxn = sConn.begin(readWrite) ; txn.set(dsgTxn) ; inTransaction.set(true) ; } @Override protected void _commit() { checkNotClosed() ; txn.get().commit() ; inTransaction.set(false) ; } @Override protected void _abort() { checkNotClosed() ; txn.get().abort() ; inTransaction.set(false) ; } @Override protected void _end() { checkNotClosed() ; DatasetGraphTxn dsg = txn.get() ; // It's null if end() already called. if ( dsg == null ) { TDB.logInfo.warn("Transaction already ended") ; return ; } txn.get().end() ; // May already be false due to .commit/.abort. inTransaction.set(false) ; txn.set(null) ; } @Override public String toString() { try { if ( isInTransaction() ) // Risky ... return get().toString() ; // Hence ... return getBaseDatasetGraph().toString() ; } catch (Throwable th) { return "DatasetGraphTransaction" ; } } @Override protected void _close() { if ( isClosed ) return ; if ( !sConn.haveUsedInTransaction() && get() != null ) { // Non-transactional behaviour. DatasetGraphTDB dsg = get() ; dsg.sync() ; dsg.close() ; StoreConnection.release(dsg.getLocation()) ; isClosed = true ; return ; } if ( isInTransaction() ) { TDB.logInfo.warn("Attempt to close a DatasetGraphTransaction while a transaction is active - ignored close (" + getLocation() + ")") ; return ; } isClosed = true ; txn.remove() ; inTransaction.remove() ; } @Override public Context getContext() { // Not the transactional dataset. return getBaseDatasetGraph().getContext() ; } /** * Return some information about the store connection and transaction * manager for this dataset. */ public SysTxnState getTransMgrState() { return sConn.getTransMgrState() ; } @Override public void sync() { if ( !sConn.haveUsedInTransaction() && get() != null ) get().sync() ; } }
jena-tdb/src/main/java/org/apache/jena/tdb/transaction/DatasetGraphTransaction.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.tdb.transaction ; import org.apache.jena.atlas.lib.Sync ; import org.apache.jena.query.ReadWrite ; import org.apache.jena.sparql.JenaTransactionException ; import org.apache.jena.sparql.core.DatasetGraphTrackActive ; import org.apache.jena.sparql.util.Context ; import org.apache.jena.tdb.StoreConnection ; import org.apache.jena.tdb.TDB ; import org.apache.jena.tdb.base.file.Location ; import org.apache.jena.tdb.store.DatasetGraphTDB ; /** * Transactional DatasetGraph that allows one active transaction. For multiple * read transactions, create multiple DatasetGraphTransaction objects. This is * analogous to a "connection" in JDBC. */ public class DatasetGraphTransaction extends DatasetGraphTrackActive implements Sync { /* * Initially, the app can use this DatasetGraph non-transactionally. But as * soon as it starts a transaction, the dataset can only be used inside * transactions. * * There are two per-thread state variables: txn: ThreadLocalTxn -- the * transactional , one time use dataset isInTransactionB: ThreadLocalBoolean * -- flags true between begin and commit/abort, and end for read * transactions. */ static class ThreadLocalTxn extends ThreadLocal<DatasetGraphTxn> { // This is the default - but nice to give it a name and to set it // clearly. @Override protected DatasetGraphTxn initialValue() { return null ; } } static class ThreadLocalBoolean extends ThreadLocal<Boolean> { @Override protected Boolean initialValue() { return false ; } } // Transaction per thread per DatasetGraphTransaction object. private ThreadLocalTxn txn = new ThreadLocalTxn() ; private ThreadLocalBoolean inTransaction = new ThreadLocalBoolean() ; private final StoreConnection sConn ; private boolean isClosed = false ; public DatasetGraphTransaction(Location location) { sConn = StoreConnection.make(location) ; } public Location getLocation() { return sConn.getLocation() ; } public DatasetGraphTDB getDatasetGraphToQuery() { checkNotClosed() ; return get() ; } /** Access the base storage - use with care */ public DatasetGraphTDB getBaseDatasetGraph() { checkNotClosed() ; return sConn.getBaseDataset() ; } /** Get the current DatasetGraphTDB */ @Override public DatasetGraphTDB get() { if ( isInTransaction() ) { DatasetGraphTxn dsgTxn = txn.get() ; if ( dsgTxn == null ) throw new TDBTransactionException("In a transaction but no transactional DatasetGraph") ; return dsgTxn.getView() ; } if ( sConn.haveUsedInTransaction() ) throw new TDBTransactionException("Not in a transaction") ; // Never used in a transaction - return underlying database for old // style (non-transactional) usage. return sConn.getBaseDataset() ; } @Override protected void checkActive() { checkNotClosed() ; if ( sConn.haveUsedInTransaction() && !isInTransaction() ) throw new JenaTransactionException("Not in a transaction (" + getLocation() + ")") ; } @Override protected void checkNotActive() { checkNotClosed() ; if ( sConn.haveUsedInTransaction() && isInTransaction() ) throw new JenaTransactionException("Currently in a transaction (" + getLocation() + ")") ; } protected void checkNotClosed() { if ( isClosed ) throw new JenaTransactionException("Already closed") ; } @Override public boolean isInTransaction() { checkNotClosed() ; return inTransaction.get() ; } public boolean isClosed() { return isClosed ; } public void syncIfNotTransactional() { if ( !sConn.haveUsedInTransaction() ) sConn.getBaseDataset().sync() ; } @Override protected void _begin(ReadWrite readWrite) { checkNotClosed() ; DatasetGraphTxn dsgTxn = sConn.begin(readWrite) ; txn.set(dsgTxn) ; inTransaction.set(true) ; } @Override protected void _commit() { checkNotClosed() ; txn.get().commit() ; inTransaction.set(false) ; } @Override protected void _abort() { checkNotClosed() ; txn.get().abort() ; inTransaction.set(false) ; } @Override protected void _end() { checkNotClosed() ; DatasetGraphTxn dsg = txn.get() ; // It's null if end() already called. if ( dsg == null ) { TDB.logInfo.warn("Transaction already ended") ; return ; } txn.get().end() ; // May already be false due to .commit/.abort. inTransaction.set(false) ; txn.set(null) ; } @Override public String toString() { try { if ( isInTransaction() ) // Risky ... return get().toString() ; // Hence ... return getBaseDatasetGraph().toString() ; } catch (Throwable th) { return "DatasetGraphTransaction" ; } } @Override protected void _close() { if ( isClosed ) return ; if ( !sConn.haveUsedInTransaction() && get() != null ) { // Non-transactional behaviour. DatasetGraphTDB dsg = get() ; dsg.sync() ; dsg.close() ; StoreConnection.release(dsg.getLocation()) ; isClosed = true ; return ; } if ( isInTransaction() ) { TDB.logInfo.warn("Attempt to close a DatasetGraphTransaction while a transaction is active - ignored close (" + getLocation() + ")") ; return ; } isClosed = true ; txn.remove() ; inTransaction.remove() ; } @Override public Context getContext() { // Not the transactional dataset. return getBaseDatasetGraph().getContext() ; } /** * Return some information about the store connection and transaction * manager for this dataset. */ public SysTxnState getTransMgrState() { return sConn.getTransMgrState() ; } @Override public void sync() { if ( !sConn.haveUsedInTransaction() && get() != null ) get().sync() ; } }
Fix checkActive
jena-tdb/src/main/java/org/apache/jena/tdb/transaction/DatasetGraphTransaction.java
Fix checkActive
Java
bsd-3-clause
1bea931ed002bc5c9550571579e0abebd80862da
0
icedman21/k-9,denim2x/k-9,dpereira411/k-9,sonork/k-9,indus1/k-9,deepworks/k-9,imaeses/k-9,roscrazy/k-9,cliniome/pki,imaeses/k-9,WenduanMou1/k-9,huhu/k-9,dpereira411/k-9,dgger/k-9,sanderbaas/k-9,msdgwzhy6/k-9,huhu/k-9,crr0004/k-9,nilsbraden/k-9,tonytamsf/k-9,rtreffer/openpgp-k-9,XiveZ/k-9,github201407/k-9,Valodim/k-9,github201407/k-9,suzp1984/k-9,cketti/k-9,CodingRmy/k-9,sebkur/k-9,sanderbaas/k-9,farmboy0/k-9,farmboy0/k-9,mawiegand/k-9,dhootha/k-9,herpiko/k-9,gilbertw1/k-9,philipwhiuk/k-9,msdgwzhy6/k-9,vt0r/k-9,vasyl-khomko/k-9,tonytamsf/k-9,gnebsy/k-9,jca02266/k-9,rishabhbitsg/k-9,leixinstar/k-9,Eagles2F/k-9,jberkel/k-9,dpereira411/k-9,cliniome/pki,tsunli/k-9,tsunli/k-9,bashrc/k-9,torte71/k-9,gaionim/k-9,rollbrettler/k-9,philipwhiuk/q-mail,moparisthebest/k-9,rishabhbitsg/k-9,gaionim/k-9,439teamwork/k-9,deepworks/k-9,roscrazy/k-9,gnebsy/k-9,cooperpellaton/k-9,sebkur/k-9,WenduanMou1/k-9,torte71/k-9,moparisthebest/k-9,dgger/k-9,mawiegand/k-9,torte71/k-9,gaionim/k-9,leixinstar/k-9,vasyl-khomko/k-9,ndew623/k-9,crr0004/k-9,msdgwzhy6/k-9,vasyl-khomko/k-9,k9mail/k-9,GuillaumeSmaha/k-9,icedman21/k-9,konfer/k-9,Eagles2F/k-9,dgger/k-9,icedman21/k-9,vt0r/k-9,crr0004/k-9,KitAway/k-9,cooperpellaton/k-9,dhootha/k-9,mawiegand/k-9,deepworks/k-9,denim2x/k-9,herpiko/k-9,XiveZ/k-9,439teamwork/k-9,k9mail/k-9,denim2x/k-9,philipwhiuk/q-mail,k9mail/k-9,sedrubal/k-9,G00fY2/k-9_material_design,herpiko/k-9,gilbertw1/k-9,tonytamsf/k-9,cketti/k-9,cketti/k-9,nilsbraden/k-9,github201407/k-9,nilsbraden/k-9,KitAway/k-9,suzp1984/k-9,vatsalsura/k-9,rtreffer/openpgp-k-9,thuanpq/k-9,sanderbaas/k-9,GuillaumeSmaha/k-9,jca02266/k-9,suzp1984/k-9,gnebsy/k-9,ndew623/k-9,bashrc/k-9,sonork/k-9,konfer/k-9,indus1/k-9,sedrubal/k-9,cliniome/pki,konfer/k-9,cooperpellaton/k-9,439teamwork/k-9,KitAway/k-9,dhootha/k-9,rollbrettler/k-9,gilbertw1/k-9,ndew623/k-9,rollbrettler/k-9,Eagles2F/k-9,G00fY2/k-9_material_design,GuillaumeSmaha/k-9,thuanpq/k-9,sebkur/k-9,leixinstar/k-9,XiveZ/k-9,philipwhiuk/k-9,cketti/k-9,sonork/k-9,tsunli/k-9,WenduanMou1/k-9,huhu/k-9,jca02266/k-9,imaeses/k-9,farmboy0/k-9,philipwhiuk/q-mail,bashrc/k-9,vatsalsura/k-9,moparisthebest/k-9,CodingRmy/k-9,thuanpq/k-9,jberkel/k-9
package com.fsck.k9.controller; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.PowerManager; import android.os.Process; import android.text.TextUtils; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.FolderList; import com.fsck.k9.activity.MessageList; import com.fsck.k9.helper.Utility; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.LocalStore.PendingCommand; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { /** * The maximum message size that we'll consider to be "small". A small message is downloaded * in full immediately instead of in pieces. Anything over this size will be downloaded in * pieces with attachments being left off completely and downloaded on demand. * * * 25k for a "small" message was picked by educated trial and error. * http://answers.google.com/answers/threadview?id=312463 claims that the * average size of an email is 59k, which I feel is too large for our * blind download. The following tests were performed on a download of * 25 random messages. * <pre> * 5k - 61 seconds, * 25k - 51 seconds, * 55k - 53 seconds, * </pre> * So 25k gives good performance and a reasonable data footprint. Sounds good to me. */ private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk"; private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash"; private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk"; private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag"; private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append"; private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead"; private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge"; private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>(); private Thread mThread; private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>(); private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>(); private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>(); ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>(); private final ExecutorService threadPool = Executors.newFixedThreadPool(5); public enum SORT_TYPE { SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true), SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true), SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true), SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true), SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true); private int ascendingToast; private int descendingToast; private boolean defaultAscending; SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) { ascendingToast = ascending; descendingToast = descending; defaultAscending = ndefaultAscending; } public int getToast(boolean ascending) { if (ascending) { return ascendingToast; } else { return descendingToast; } } public boolean isDefaultAscending() { return defaultAscending; } }; private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private MessagingListener checkMailListener = null; private MemorizingListener memorizingListener = new MemorizingListener(); private boolean mBusy; private Application mApplication; // Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>(); private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid()); } private String createMessageKey(Account account, String folder, String uid) { return account.getUuid() + ":" + folder + ":" + uid; } private void suppressMessage(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return; } String messKey = createMessageKey(account, folder, message); deletedUids.put(messKey, "true"); } private void unsuppressMessage(Account account, String folder, String uid) { if (account == null || folder == null || uid == null) { return; } String messKey = createMessageKey(account, folder, uid); deletedUids.remove(messKey); } private boolean isMessageSuppressed(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return false; } String messKey = createMessageKey(account, folder, message); if (deletedUids.containsKey(messKey)) { return true; } return false; } private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.start(); if (memorizingListener != null) { addListener(memorizingListener); } } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application * @return */ public synchronized static MessagingController getInstance(Application application) { if (inst == null) { inst = new MessagingController(application); } return inst; } public boolean isBusy() { return mBusy; } public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { String commandDescription = null; try { Command command = mCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; command.runnable.run(); if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(mCommands.size() > 0); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; while (retries-- > 0) { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; command.isForeground = isForeground; queue.put(command); return; } catch (InterruptedException ie) { try { Thread.sleep(200); } catch (InterruptedException ne) { } e = ie; } } throw new Error(e); } public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } public void refreshListener(MessagingListener listener) { if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } public void removeListener(MessagingListener listener) { mListeners.remove(listener); } public Set<MessagingListener> getListeners() { return mListeners; } public Set<MessagingListener> getListeners(MessagingListener listener) { if (listener == null) { return mListeners; } Set<MessagingListener> listeners = new CopyOnWriteArraySet<MessagingListener>(mListeners); listeners.add(listener); return listeners; } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * TODO this needs to cache the remote folder list * * @param account * @param includeRemote * @param listener * @throws MessagingException */ public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } List<? extends Folder> localFolders = null; try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(new Folder[0]); if (refreshRemote || localFolders == null || localFolders.size() == 0) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } }); } private void doRefreshRemote(final Account account, MessagingListener listener) { put("doRefreshRemote", listener, new Runnable() { public void run() { List<? extends Folder> localFolders = null; try { Store store = account.getRemoteStore(); List<? extends Folder> remoteFolders = store.getPersonalNamespaces(false); LocalStore localStore = account.getLocalStore(); HashSet<String> remoteFolderNames = new HashSet<String>(); for (int i = 0, count = remoteFolders.size(); i < count; i++) { LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName()); if (!localFolder.exists()) { localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount()); } remoteFolderNames.add(remoteFolders.get(i).getName()); } localFolders = localStore.getPersonalNamespaces(false); /* * Clear out any folders that are no longer on the remote store. */ for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); if (localFolderName.equalsIgnoreCase(K9.INBOX) || localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName())) { continue; } if (!remoteFolderNames.contains(localFolder.getName())) { localFolder.delete(false); } } localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(new Folder[0]); for (MessagingListener l : getListeners()) { l.listFolders(account, folderArray); } for (MessagingListener l : getListeners()) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } } }); } /** * List the messages in the local message store for the given folder asynchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { listLocalMessagesSynchronous(account, folder, listener); } }); } /** * List the messages in the local message store for the given folder synchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesStarted(account, folder); } Folder localFolder = null; MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { List<Message> pendingMessages = new ArrayList<Message>(); int totalDone = 0; public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { if (isMessageSuppressed(account, folder, message) == false) { pendingMessages.add(message); totalDone++; if (pendingMessages.size() > 10) { addPendingMessages(); } } else { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesRemoveMessage(account, folder, message); } } } public void messagesFinished(int number) { addPendingMessages(); } private void addPendingMessages() { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesAddMessages(account, folder, pendingMessages); } pendingMessages.clear(); } }; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); localFolder.getMessages( retrievalListener, false // Skip deleted messages ); if (K9.DEBUG) Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished"); for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFinished(account, folder); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFailed(account, folder, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener) { searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages, searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener); } /** * Find all messages in any local account which match the query 'query' * @param folderNames TODO * @param query * @param listener * @param searchAccounts TODO * @param account TODO * @param account * @throws MessagingException */ public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { if (K9.DEBUG) { Log.i(K9.LOG_TAG, "searchLocalMessages (" + "accountUuids=" + Utility.combine(accountUuids, ',') + ", folderNames = " + Utility.combine(folderNames, ',') + ", messages.size() = " + (messages != null ? messages.length : null) + ", query = " + query + ", integrate = " + integrate + ", requiredFlags = " + Utility.combine(requiredFlags, ',') + ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',') + ")"); } threadPool.execute(new Runnable() { public void run() { final AccountStats stats = new AccountStats(); final Set<String> accountUuidsSet = new HashSet<String>(); if (accountUuids != null) { for (String accountUuid : accountUuids) { accountUuidsSet.add(accountUuid); } } final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); Account[] accounts = prefs.getAccounts(); List<LocalFolder> foldersToSearch = null; boolean displayableOnly = false; boolean noSpecialFolders = true; for (final Account account : accounts) { if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false) { continue; } if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true) { displayableOnly = true; noSpecialFolders = true; } else if (integrate == false && folderNames == null) { Account.Searchable searchableFolders = account.getSearchableFolders(); switch (searchableFolders) { case NONE: continue; case DISPLAYABLE: displayableOnly = true; break; } } List<Message> messagesToSearch = null; if (messages != null) { messagesToSearch = new LinkedList<Message>(); for (Message message : messages) { if (message.getFolder().getAccount().getUuid().equals(account.getUuid())) { messagesToSearch.add(message); } } if (messagesToSearch.isEmpty()) { continue; } } if (listener != null) { listener.listLocalMessagesStarted(account, null); } if (integrate || displayableOnly || folderNames != null || noSpecialFolders) { List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>(); try { LocalStore store = account.getLocalStore(); List<? extends Folder> folders = store.getPersonalNamespaces(false); Set<String> folderNameSet = null; if (folderNames != null) { folderNameSet = new HashSet<String>(); for (String folderName : folderNames) { folderNameSet.add(folderName); } } for (Folder folder : folders) { LocalFolder localFolder = (LocalFolder)folder; boolean include = true; folder.refresh(prefs); String localFolderName = localFolder.getName(); if (integrate) { include = localFolder.isIntegrate(); } else { if (folderNameSet != null) { if (folderNameSet.contains(localFolderName) == false) { include = false; } } // Never exclude the INBOX (see issue 1817) else if (noSpecialFolders && !localFolderName.equals(K9.INBOX) && ( localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName()))) { include = false; } else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass())) { include = false; } } if (include) { tmpFoldersToSearch.add(localFolder); } } if (tmpFoldersToSearch.size() < 1) { continue; } foldersToSearch = tmpFoldersToSearch; } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me); addErrorMessage(account, null, me); } } MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { if (isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message) == false) { List<Message> messages = new ArrayList<Message>(); messages.add(message); stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } } public void messagesFinished(int number) { } }; try { String[] queryFields = {"html_content","subject","sender_list"}; LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, queryFields , query, foldersToSearch, messagesToSearch == null ? null : messagesToSearch.toArray(new Message[0]), requiredFlags, forbiddenFlags); } catch (Exception e) { if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } if (listener != null) { listener.searchStats(stats); } } }); } public void loadMoreMessages(Account account, String folder, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); synchronizeMailbox(account, folder, listener, null); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } public void resetVisibleLimits(Account[] accounts) { for (Account account : accounts) { try { LocalStore localStore = account.getLocalStore(); localStore.resetVisibleLimits(account.getDisplayCount()); } catch (MessagingException e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); } } } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener * @param providedRemoteFolder TODO */ public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) { putBackground("synchronizeMailbox", listener, new Runnable() { public void run() { synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder); } }); } /** * Start foreground synchronization of the specified folder. This is generally only called * by synchronizeMailbox. * @param account * @param folder * * TODO Break this method up into smaller chunks. * @param providedRemoteFolder TODO */ private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); } /* * We don't ever sync the Outbox or errors folder */ if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } return; } Exception commandException = null; try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); commandException = e; } /* * Get the message list from the local store and create an index of * the uids within the list. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); final LocalFolder localFolder = tLocalFolder; localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); HashMap<String, Message> localUidMap = new HashMap<String, Message>(); for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } if (providedRemoteFolder != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { return; } /* * Synchronization process: Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); } } /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); if (visibleLimit < 1) { visibleLimit = K9.DEFAULT_VISIBLE_LIMIT; } Message[] remoteMessageArray = new Message[0]; final ArrayList<Message> remoteMessages = new ArrayList<Message>(); // final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); final Date earliestDate = account.getEarliestPollDate(); if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folder); } remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null); int messageCount = remoteMessageArray.length; for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount); } Message localMessage = localUidMap.get(thisMess.getUid()); if (localMessage == null || localMessage.olderThan(earliestDate) == false) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); } } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ if (account.syncRemoteDeletions()) { for (Message localMessage : localMessages) { if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED)) { localMessage.setFlag(Flag.X_DESTROYED, true); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } } } localMessages = null; /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages); setLocalFlaggedCountToRemote(localFolder, remoteFolder); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } /* * Notify listeners that we're finally done. */ localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed( account, folder, rootMessage); } addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); } finally { if (providedRemoteFolder == null && remoteFolder != null) { remoteFolder.close(); } if (tLocalFolder != null) { tLocalFolder.close(); } } } /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException { if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || folder.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); return false; } } } return true; } private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException { int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); if (remoteUnreadMessageCount != -1) { localFolder.setUnreadMessageCount(remoteUnreadMessageCount); } else { int unreadCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false) { unreadCount++; } } localFolder.setUnreadMessageCount(unreadCount); } return localFolder.getUnreadMessageCount(); } private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException { int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount(); if (remoteFlaggedMessageCount != -1) { localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount); } else { int flaggedCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false) { flaggedCount++; } } localFolder.setFlaggedMessageCount(flaggedCount); } } private int downloadMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); if (earliestDate != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); } } final String folder = remoteFolder.getName(); ArrayList<Message> syncFlagMessages = new ArrayList<Message>(); List<Message> unsyncedMessages = new ArrayList<Message>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Message> messages = new ArrayList<Message>(inputMessages); for (Message message : messages) { if (message.isSet(Flag.DELETED)) { syncFlagMessages.add(message); } else if (isMessageSuppressed(account, folder, message) == false) { Message localMessage = localFolder.getMessage(message.getUid()); if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); unsyncedMessages.add(message); } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } } else if (localMessage.isSet(Flag.DELETED) == false) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); } } } } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); messages.clear(); final ArrayList<Message> largeMessages = new ArrayList<Message>(); final ArrayList<Message> smallMessages = new ArrayList<Message>(); if (unsyncedMessages.size() > 0) { /* * Reverse the order of the messages. Depending on the server this may get us * fetch results for newest to oldest. If not, no harm done. */ Collections.reverse(unsyncedMessages); int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if (listSize > visibleLimit) { unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize); } FetchProfile fp = new FetchProfile(); if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages,largeMessages, progress, todo, fp); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and " + smallMessages.size() + " small messages out of " + unsyncedMessages.size() + " unsynced messages"); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, newMessages, todo, fp); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, newMessages, todo, fp); largeMessages.clear(); /* * Refresh the flags for any messages in the local store that we didn't just * download. */ refreshLocalMessageFlags(account,remoteFolder,localFolder,syncFlagMessages,progress,todo); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); localFolder.purgeToVisibleLimit(new MessageRemovalListener() { public void messageRemoved(Message message) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } }); return newMessages.get(); } private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> unsyncedMessages, final ArrayList<Message> smallMessages, final ArrayList<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (K9.DEBUG) { if (message.isSet(Flag.DELETED)) { Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was marked deleted on server, skipping"); } else { Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than " + earliestDate + ", skipping"); } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } // And include it in the view if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ if (isMessageSuppressed(account, folder, message) == false) { // Store the new message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); } private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) { if (isMessageSuppressed(account, folder, message)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+ "but just downloaded. "+ "The race condition means we wasted some bandwidth. Oh well."); } return false; } if (message.olderThan(earliestDate)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " + earliestDate + ", hence not saving"); } return false; } return true; } private void downloadSmallMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> smallMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); return; } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); progress.incrementAndGet(); // Set a flag indicating this message has now be fully downloaded localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (notifyAccount(mApplication, account, message) == true) { newMessages.incrementAndGet(); } } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); } private void downloadLargeMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> largeMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); continue; } if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. */ if (message.getSize() < account.getMaximumAutoDownloadMessageSize()) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { remoteFolder.fetchPart(message, part, null); } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found progress.incrementAndGet(); Message localMessage = localFolder.getMessage(message.getUid()); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } // Send a notification of this message if (notifyAccount(mApplication, account, message) == true) { newMessages.incrementAndGet(); } }//for large messsages if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); } private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> syncFlagMessages, final AtomicInteger progress, final int todo ) throws MessagingException { final String folder = remoteFolder.getName(); if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); List<Message> undeletedMessages = new LinkedList<Message>(); for (Message message : syncFlagMessages) { if (message.isSet(Flag.DELETED) == false) { undeletedMessages.add(message); } } remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null); for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); if (messageChanged) { if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } else { for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } } private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().getAccount().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED }) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; } private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; do { nextCause = rootCause.getCause(); if (nextCause != null) { rootCause = nextCause; } } while (nextCause != null); return rootCause.getMessage(); } private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } private void processPendingCommands(final Account account) { putBackground("processPendingCommands", null, new Runnable() { public void run() { try { processPendingCommandsSynchronous(account); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList<PendingCommand> commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); if (todo == 0) { return; } for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; try { for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* * We specifically do not catch any exceptions here. If a command fails it is * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ try { if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopy(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); } else { throw me; } } finally { progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; } finally { for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. Once the local message is successfully processed it is deleted so * that the server message will be synchronized down without an additional copy being * created. * TODO update the local message UID instead of deleteing it * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; try { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid); if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } /* * If the message does not exist remotely we just upload it and then * update our local copy with the new uid. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage } , fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } } else { /* * If the remote message exists we need to determine which copy to keep. */ /* * See if the remote message is newer than ours. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.setFlag(Flag.X_DESTROYED, true); } else { /* * Otherwise we'll upload our message and then delete the remote message. */ fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage }, fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); } /** * Process a pending trash message command. * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; try { String srcFolder = command.arguments[0]; if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; String isCopyS = command.arguments[2]; Store remoteStore = account.getRemoteStore(); remoteSrcFolder = remoteStore.getFolder(srcFolder); List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName); } else { remoteDestFolder = remoteStore.getFolder(destFolder); if (isCopy) { remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder); } else { remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder); } } if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } } finally { if (remoteSrcFolder != null) { remoteSrcFolder.close(); } if (remoteDestFolder != null) { remoteDestFolder.close(); } } } private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = folderName; command.arguments[1] = newState; command.arguments[2] = flag; for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); processPendingCommands(account); } }); } /** * Processes a pending mark read or unread command. * * @param command arguments = (String folder, String uid, boolean read) * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } boolean newState = Boolean.parseBoolean(command.arguments[1]); Flag flag = Flag.valueOf(command.arguments[2]); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } if (messages.size() == 0) { return; } remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid); boolean newState = Boolean.parseBoolean(command.arguments[2]); Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } private void queueExpunge(final Account account, final String folderName) { putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; command.arguments = new String[1]; command.arguments[0] = folderName; queuePendingCommand(account, command); processPendingCommands(account); } }); } private void processPendingExpunge(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (account.getErrorFolderName().equals(srcFolder)) { return; } Store remoteStore = account.getRemoteStore(); Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); remoteMessage.delete(account.getTrashFolderName()); remoteSrcFolder.close(); return; } remoteDestFolder.open(OpenMode.READ_WRITE); if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false) { message.setFlag(Flag.SEEN, true); for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } localFolder.setUnreadMessageCount(0); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); } finally { if (localFolder != null) { localFolder.close(); } if (remoteFolder != null) { remoteFolder.close(); } } } static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); public void addErrorMessage(Account account, String subject, Throwable t) { if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (t == null) { return; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); if (subject == null) { subject = getRootCauseMessage(t); } addErrorMessage(account, subject, baos.toString()); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void addErrorMessage(Account account, String subject, String body) { if (K9.ENABLE_ERROR_FOLDER == false) { return; } if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (body == null || body.length() < 1) { return; } Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(body)); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setSubject(subject); long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); List<String> args = new ArrayList<String>(); args.add(folder); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MARK_ALL_AS_READ; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } public void setFlag( final Message[] messages, final Flag flag, final boolean newState) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { String[] uids = new String[messages.size()]; for (int i = 0; i < messages.size(); i++) { uids[i] = messages.get(i).getUid(); } setFlag(account, folder.getName(), uids, flag, newState); } }); } public void setFlag( final Account account, final String folderName, final String[] uids, final Flag flag, final boolean newState) { // TODO: put this into the background, but right now that causes odd behavior // because the FolderMessageList doesn't have its own cache of the flag states Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); ArrayList<Message> messages = new ArrayList<Message>(); for (int i = 0; i < uids.length; i++) { String uid = uids[i]; // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && newState == false && uid != null && account.getOutboxFolderName().equals(folderName)) { sendCount.remove(uid); } Message msg = localFolder.getMessage(uid); if (msg != null) { messages.add(msg); } } localFolder.setFlags(messages.toArray(new Message[0]), new Flag[] {flag}, newState); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } if (account.getErrorFolderName().equals(folderName)) { return; } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { if (localFolder != null) { localFolder.close(); } } }//setMesssageFlag public void clearAllPending(final Account account) { try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } private void loadMessageForViewRemote(final Account account, final String folder, final String uid, final MessagingListener listener) { put("loadMessageForViewRemote", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); } else { /* * At this point the message is not available, so we need to download it * fully if possible. */ Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); remoteFolder.open(OpenMode.READ_WRITE); // Get the remote message and fully download it Message remoteMessage = remoteFolder.getMessage(uid); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // Store the message locally and load the stored message into memory localFolder.appendMessages(new Message[] { remoteMessage }); message = localFolder.getMessage(uid); localFolder.fetch(new Message[] { message }, fp, null); // Mark that this message is now fully synched message.setFlag(Flag.X_DOWNLOADED_FULL, true); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } finally { if (remoteFolder!=null) { remoteFolder.close(); } if (localFolder!=null) { localFolder.close(); } }//finally }//run }); } public void loadMessageForView(final Account account, final String folder, final String uid, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewStarted(account, folder, uid); } threadPool.execute(new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = (LocalMessage)localFolder.getMessage(uid); if (message==null || message.getId()==0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlag(new Message[] { message }, Flag.SEEN, true); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { loadMessageForViewRemote(account, folder, uid, listener); if (!message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { localFolder.close(); return; } } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } } }); } /** * Attempts to load the attachment specified by part from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment( final Account account, final Message message, final Part part, final Object tag, final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ try { if (part.getBody() != null) { for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, false); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } return; } } catch (MessagingException me) { /* * If the header isn't there the attachment isn't downloaded yet, so just continue * on. */ } for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, true); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } put("loadAttachment", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); /* * We clear out any attachments already cached in the entire store and then * we update the passed in message to reflect that there are no cached * attachments. This is in support of limiting the account to having one * attachment downloaded at a time. */ localStore.pruneCachedAttachments(); ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); localFolder = localStore.getFolder(message.getFolder().getName()); remoteFolder = remoteStore.getFolder(message.getFolder().getName()); remoteFolder.open(OpenMode.READ_WRITE); //FIXME: This is an ugly hack that won't be needed once the Message objects have been united. Message remoteMessage = remoteFolder.getMessage(message.getUid()); remoteMessage.setBody(message.getBody()); remoteFolder.fetchPart(remoteMessage, part, null); localFolder.updateMessage((LocalMessage)message); for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); for (MessagingListener l : getListeners()) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } if (listener != null) { listener.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } addErrorMessage(account, null, me); } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } }); } /** * Stores the given message in the Outbox and starts a sendPendingMessages command to * attempt to send the message. * @param account * @param message * @param listener */ public void sendMessage(final Account account, final Message message, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, null); } catch (Exception e) { /* for (MessagingListener l : getListeners()) { // TODO general failed } */ addErrorMessage(account, null, e); } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final Account account, MessagingListener listener) { putBackground("sendPendingMessages", listener, new Runnable() { public void run() { sendPendingMessagesSynchronous(account); } }); } public boolean messagesPendingSend(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); int localMessages = localFolder.getMessageCount(); if (localMessages > 0) { return true; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); } finally { if (localFolder != null) { localFolder.close(); } } return false; } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); boolean anyFlagged = false; int progress = 0; int todo = localMessages.length; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* * The profile we will use to pull all of the content * for a given local message into memory for sending. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); for (Message message : localMessages) { if (message.isSet(Flag.DELETED)) { message.setFlag(Flag.X_DESTROYED, true); continue; } if (message.isSet(Flag.FLAGGED)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid()); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging"); message.setFlag(Flag.FLAGGED, true); anyFlagged = true; continue; } localFolder.fetch(new Message[] { message }, fp, null); try { message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } if (K9.FOLDER_NONE.equals(account.getSentFolderName())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = (LocalFolder) localStore.getFolder( account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); localFolder.moveMessages( new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localSentFolder.getName(), message.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } } catch (Exception e) { if (e instanceof MessagingException) { MessagingException me = (MessagingException)e; if (me.isPermanentFailure() == false) { // Decrement the counter if the message could not possibly have been sent int newVal = count.decrementAndGet(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal + "; no possible send"); } } message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); /* * We ignore this exception because a future refresh will retry this * message. */ } } if (localFolder.getMessageCount() == 0) { localFolder.delete(false); } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (anyFlagged) { addErrorMessage(account, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME)); NotificationManager notifMgr = (NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis()); Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName()); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0); notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi); notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; notifMgr.notify(-1000 - account.getAccountNumber(), notif); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while closing folder", e); } } } } public void getAccountStats(final Context context, final Account account, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { try { AccountStats stats = account.getStats(context); l.accountStatusChanged(account, stats); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } } }; put("getAccountStats:" + account.getDescription(), l, unreadRunnable); } public void getFolderUnreadMessageCount(final Account account, final String folderName, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { int unreadMessageCount = 0; try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); } }; put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable); } public boolean isMoveCapable(Message message) { if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { return true; } else { return false; } } public boolean isCopyCapable(Message message) { return isMoveCapable(message); } public boolean isMoveCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } public boolean isCopyCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { for (Message message : messages) { suppressMessage(account, srcFolder, message); } putBackground("moveMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { putBackground("copyMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages, final String destFolder, final boolean isCopy, MessagingListener listener) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false)) { return; } if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false)) { return; } Folder localSrcFolder = localStore.getFolder(srcFolder); Folder localDestFolder = localStore.getFolder(destFolder); List<String> uids = new LinkedList<String>(); for (Message message : inMessages) { String uid = message.getUid(); if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } } Message[] messages = localSrcFolder.getMessages(uids.toArray(new String[0]), null); if (messages.length > 0) { Map<String, Message> origUidMap = new HashMap<String, Message>(); for (Message message : messages) { origUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); localSrcFolder.copyMessages(messages, localDestFolder); } else { localSrcFolder.moveMessages(messages, localDestFolder); for (String origUid : origUidMap.keySet()) { for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid()); } unsuppressMessage(account, srcFolder, origUid); } } queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(new String[0])); } processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } public void expunge(final Account account, final String folder, final MessagingListener listener) { putBackground("expunge", null, new Runnable() { public void run() { queueExpunge(account, folder); } }); } public void deleteDraft(final Account account, String uid) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message != null) { deleteMessages(new Message[] { message }, null); } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { if (localFolder != null) { localFolder.close(); } } } public void deleteMessages(final Message[] messages, final MessagingListener listener) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { for (Message message : messages) { suppressMessage(account, folder.getName(), message); } putBackground("deleteMessages", null, new Runnable() { public void run() { deleteMessagesSynchronous(account, folder.getName(), messages.toArray(new Message[0]), listener); } }); } }); } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved for (Message message : messages) { if (listener != null) { listener.messageDeleted(account, folder, message); } for (MessagingListener l : getListeners()) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (localTrashFolder.exists() == false) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists() == true) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); localFolder.moveMessages(messages, localTrashFolder); } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); } else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } for (String uid : uids) { unsuppressMessage(account, folder, uid); } } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); } finally { if (localFolder != null) { localFolder.close(); } if (localTrashFolder != null) { localTrashFolder.close(); } } } private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); try { if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } finally { if (remoteFolder != null) { remoteFolder.close(); } } } public void emptyTrash(final Account account, MessagingListener listener) { putBackground("emptyTrash", listener, new Runnable() { public void run() { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.setFlags(new Flag[] { Flag.DELETED }, true); for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } List<String> args = new ArrayList<String>(); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EMPTY_TRASH; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } }); } public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); try { Intent msg=new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject()); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } }); } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. * * @param context * @param account * @param listener */ public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) { TracingWakeLock twakeLock = null; if (useManualWakeLock) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail"); twakeLock.setReferenceCounted(false); twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT); } final TracingWakeLock wakeLock = twakeLock; for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } putBackground("checkMail", listener, new Runnable() { public void run() { final NotificationManager notifMgr = (NotificationManager)context .getSystemService(Context.NOTIFICATION_SERVICE); try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Account[] accounts; if (account != null) { accounts = new Account[] { account }; } else { accounts = prefs.getAccounts(); } for (final Account account : accounts) { final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (ignoreLastCheckedTime == false && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); account.setRingNotified(false); putBackground("sendPending " + account.getDescription(), null, new Runnable() { public void run() { if (messagesPendingSend(account)) { if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title), account.getDescription() , pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } try { sendPendingMessagesSynchronous(account); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } } } } ); try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode); continue; } if (K9.DEBUG) Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + new Date(folder.getLastChecked())); if (ignoreLastCheckedTime == false && folder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); continue; } putBackground("sync" + folder.getName(), null, new Runnable() { public void run() { LocalFolder tLocalFolder = null; try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder.getName()); tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription() + context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } try { synchronizeMailboxSynchronous(account, folder.getName(), listener, null); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); } finally { if (tLocalFolder != null) { tLocalFolder.close(); } } } } ); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); try { AccountStats stats = account.getStats(context); int unreadMessageCount = stats.unreadMessageCount; if (unreadMessageCount == 0) { notifyAccountCancel(context, account); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } } } ); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); if (wakeLock != null) { wakeLock.release(); } for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } } } ); } }); } public void compact(final Account account, final MessagingListener ml) { putBackground("compact:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } public void clear(final Account account, final MessagingListener ml) { putBackground("clear:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); } } }); } public void recreate(final Account account, final MessagingListener ml) { putBackground("recreate:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.recreate(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); } } }); } /** Creates a notification of new email messages * ringtone, lights, and vibration to be played */ private boolean notifyAccount(Context context, Account account, Message message) { int unreadMessageCount = 0; try { AccountStats stats = account.getStats(context); unreadMessageCount = stats.unreadMessageCount; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } // Do not notify if the user does not have notifications // enabled or if the message has been read if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) { return false; } Folder folder = message.getFolder(); if (folder != null) { // No notification for new messages in Trash, Drafts, or Sent folder. // But do notify if it's the INBOX (see issue 1817). String folderName = folder.getName(); if (!K9.INBOX.equals(folderName) && (account.getTrashFolderName().equals(folderName) || account.getDraftsFolderName().equals(folderName) || account.getSentFolderName().equals(folderName))) { return false; } } // If we have a message, set the notification to "<From>: <Subject>" StringBuffer messageNotice = new StringBuffer(); try { if (message != null && message.getFrom() != null) { Address[] fromAddrs = message.getFrom(); String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null; String subject = message.getSubject(); if (subject == null) { subject = context.getString(R.string.general_no_subject); } if (from != null) { // Show From: address by default if (account.isAnIdentity(fromAddrs) == false) { messageNotice.append(from + ": " + subject); } // show To: if the message was sent from me else { // Do not notify of mail from self if !isNotifySelfNewMail if (!account.isNotifySelfNewMail()) { return false; } Address[] rcpts = message.getRecipients(Message.RecipientType.TO); String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null; if (to != null) { messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject); } else { messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject); } } } } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e); } // If we could not set a per-message notification, revert to a default message if (messageNotice.length() == 0) { messageNotice.append(context.getString(R.string.notification_new_title)); } NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis()); notif.number = unreadMessageCount; Intent i = FolderList.actionHandleNotification(context, account, account.getAutoExpandFolderName()); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, account.getDescription()); notif.setLatestEventInfo(context, accountNotice, messageNotice, pi); // Only ring or vibrate if we have not done so already on this // account and fetch if (!account.isRingNotified()) { account.setRingNotified(true); if (account.shouldRing()) { String ringtone = account.getRingtone(); notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone); } if (account.isVibrate()) { int times = account.getVibrateTimes(); long[] pattern1 = new long[] {100,200}; long[] pattern2 = new long[] {100,500}; long[] pattern3 = new long[] {200,200}; long[] pattern4 = new long[] {200,500}; long[] pattern5 = new long[] {500,500}; long[] src = null; switch (account.getVibratePattern()) { case 1: src = pattern1; break; case 2: src = pattern2; break; case 3: src = pattern3; break; case 4: src = pattern4; break; case 5: src = pattern5; break; default: notif.defaults |= Notification.DEFAULT_VIBRATE; break; } if (src != null) { long[] dest = new long[src.length * times]; for (int n = 0; n < times; n++) { System.arraycopy(src, 0, dest, n * src.length, src.length); } notif.vibrate = dest; } } } notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; notif.audioStreamType = AudioManager.STREAM_NOTIFICATION; notifMgr.notify(account.getAccountNumber(), notif); return true; } /** Cancel a notification of new email messages */ public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); notifMgr.cancel(-1000 - account.getAccountNumber()); } public Message saveDraft(final Account account, final Message message) { Message localMessage = null; try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { return true; } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); class Command implements Comparable<Command> { public Runnable runnable; public MessagingListener listener; public String description; boolean isForeground; int sequence = sequencing.getAndIncrement(); @Override public int compareTo(Command other) { if (other.isForeground == true && isForeground == false) { return 1; } else if (other.isForeground == false && isForeground == true) { return -1; } else { return (sequence - other.sequence); } } } public MessagingListener getCheckMailListener() { return checkMailListener; } public void setCheckMailListener(MessagingListener checkMailListener) { if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; if (this.checkMailListener != null) { addListener(this.checkMailListener); } } public SORT_TYPE getSortType() { return sortType; } public void setSortType(SORT_TYPE sortType) { this.sortType = sortType; } public boolean isSortAscending(SORT_TYPE sortType) { Boolean sortAsc = sortAscending.get(sortType); if (sortAsc == null) { return sortType.isDefaultAscending(); } else return sortAsc; } public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending) { sortAscending.put(sortType, nsortAscending); } public Collection<Pusher> getPushers() { return pushers.values(); } public boolean setupPushing(final Account account) { try { Pusher previousPusher = pushers.remove(account); if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); List<String> names = new ArrayList<String>(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { if (folder.getName().equals(account.getErrorFolderName()) || folder.getName().equals(account.getOutboxFolderName())) { if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which should never be pushed"); continue; } folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in push mode " + fPushClass + " while account is in push mode " + aPushMode); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); names.add(folder.getName()); } if (names.size() > 0) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); names = names.subList(0, maxPushFolders); } try { Store store = account.getRemoteStore(); if (store.isPushCapable() == false) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); if (pusher != null) { Pusher oldPusher = pushers.putIfAbsent(account, pusher); if (oldPusher == null) { pusher.start(names); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator<Pusher> iter = pushers.values().iterator(); while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() + ", folder " + remoteFolder.getName(), null, new Runnable() { public void run() { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder= localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); account.setRingNotified(false); int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size()); setLocalFlaggedCountToRemote(localFolder, remoteFolder); localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; try { localFolder.setStatus(errorMessage); } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to close localFolder", e); } } latch.countDown(); } } }); try { latch.await(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } enum MemorizingState { STARTED, FINISHED, FAILED }; class Memory { Account account; String folderName; MemorizingState syncingState = null; MemorizingState sendingState = null; MemorizingState pushingState = null; MemorizingState processingState = null; String failureMessage = null; int syncingTotalMessagesInMailbox; int syncingNumNewMessages; int folderCompleted = 0; int folderTotal = 0; String processingCommandTitle = null; Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } String getKey() { return getMemoryKey(account, folderName); } } static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } class MemorizingListener extends MessagingListener { HashMap<String, Memory> memories = new HashMap<String, Memory>(31); Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } return memory; } @Override public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; memory.syncingNumNewMessages = numNewMessages; } @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } synchronized void refreshOther(MessagingListener other) { if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; for (Memory memory : memories.values()) { if (memory.syncingState != null) { switch (memory.syncingState) { case STARTED: syncStarted = memory; break; case FINISHED: other.synchronizeMailboxFinished(memory.account, memory.folderName, memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); break; case FAILED: other.synchronizeMailboxFailed(memory.account, memory.folderName, memory.failureMessage); break; } } if (memory.sendingState != null) { switch (memory.sendingState) { case STARTED: sendStarted = memory; break; case FINISHED: other.sendPendingMessagesCompleted(memory.account); break; case FAILED: other.sendPendingMessagesFailed(memory.account); break; } } if (memory.pushingState != null) { switch (memory.pushingState) { case STARTED: other.setPushActive(memory.account, memory.folderName, true); break; case FINISHED: other.setPushActive(memory.account, memory.folderName, false); break; } } if (memory.processingState != null) { switch (memory.processingState) { case STARTED: processingStarted = memory; break; case FINISHED: case FAILED: other.pendingCommandsFinished(memory.account); break; } } } Memory somethingStarted = null; if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; } @Override public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } private void actOnMessages(Message[] messages, MessageActor actor) { Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>(); for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map<Folder, List<Message>> folderMap = accountMap.get(account); if (folderMap == null) { folderMap = new HashMap<Folder, List<Message>>(); accountMap.put(account, folderMap); } List<Message> messageList = folderMap.get(folder); if (messageList == null) { messageList = new LinkedList<Message>(); folderMap.put(folder, messageList); } messageList.add(message); } for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map<Folder, List<Message>> folderMap = entry.getValue(); for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List<Message> messageList = folderEntry.getValue(); actor.act(account, folder, messageList); } } } interface MessageActor { public void act(final Account account, final Folder folder, final List<Message> messages); } }
src/com/fsck/k9/controller/MessagingController.java
package com.fsck.k9.controller; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.PowerManager; import android.os.Process; import android.text.TextUtils; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.AccountStats; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.FolderList; import com.fsck.k9.activity.MessageList; import com.fsck.k9.helper.Utility; import com.fsck.k9.helper.power.TracingPowerManager; import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Transport; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.LocalStore.PendingCommand; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { /** * The maximum message size that we'll consider to be "small". A small message is downloaded * in full immediately instead of in pieces. Anything over this size will be downloaded in * pieces with attachments being left off completely and downloaded on demand. * * * 25k for a "small" message was picked by educated trial and error. * http://answers.google.com/answers/threadview?id=312463 claims that the * average size of an email is 59k, which I feel is too large for our * blind download. The following tests were performed on a download of * 25 random messages. * <pre> * 5k - 61 seconds, * 25k - 51 seconds, * 55k - 53 seconds, * </pre> * So 25k gives good performance and a reasonable data footprint. Sounds good to me. */ private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy"; private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk"; private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash"; private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk"; private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag"; private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append"; private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead"; private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge"; private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>(); private Thread mThread; private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>(); private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>(); private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>(); ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>(); private final ExecutorService threadPool = Executors.newFixedThreadPool(5); public enum SORT_TYPE { SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false), SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true), SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true), SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true), SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true), SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true); private int ascendingToast; private int descendingToast; private boolean defaultAscending; SORT_TYPE(int ascending, int descending, boolean ndefaultAscending) { ascendingToast = ascending; descendingToast = descending; defaultAscending = ndefaultAscending; } public int getToast(boolean ascending) { if (ascending) { return ascendingToast; } else { return descendingToast; } } public boolean isDefaultAscending() { return defaultAscending; } }; private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private MessagingListener checkMailListener = null; private MemorizingListener memorizingListener = new MemorizingListener(); private boolean mBusy; private Application mApplication; // Key is accountUuid:folderName:messageUid , value is unimportant private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>(); private String createMessageKey(Account account, String folder, Message message) { return createMessageKey(account, folder, message.getUid()); } private String createMessageKey(Account account, String folder, String uid) { return account.getUuid() + ":" + folder + ":" + uid; } private void suppressMessage(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return; } String messKey = createMessageKey(account, folder, message); deletedUids.put(messKey, "true"); } private void unsuppressMessage(Account account, String folder, String uid) { if (account == null || folder == null || uid == null) { return; } String messKey = createMessageKey(account, folder, uid); deletedUids.remove(messKey); } private boolean isMessageSuppressed(Account account, String folder, Message message) { if (account == null || folder == null || message == null) { return false; } String messKey = createMessageKey(account, folder, message); if (deletedUids.containsKey(messKey)) { return true; } return false; } private MessagingController(Application application) { mApplication = application; mThread = new Thread(this); mThread.start(); if (memorizingListener != null) { addListener(memorizingListener); } } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application * @return */ public synchronized static MessagingController getInstance(Application application) { if (inst == null) { inst = new MessagingController(application); } return inst; } public boolean isBusy() { return mBusy; } public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { String commandDescription = null; try { Command command = mCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); mBusy = true; command.runnable.run(); if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(mCommands.size() > 0); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, true); } private void putBackground(String description, MessagingListener listener, Runnable runnable) { putCommand(mCommands, description, listener, runnable, false); } private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground) { int retries = 10; Exception e = null; while (retries-- > 0) { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; command.isForeground = isForeground; queue.put(command); return; } catch (InterruptedException ie) { try { Thread.sleep(200); } catch (InterruptedException ne) { } e = ie; } } throw new Error(e); } public void addListener(MessagingListener listener) { mListeners.add(listener); refreshListener(listener); } public void refreshListener(MessagingListener listener) { if (memorizingListener != null && listener != null) { memorizingListener.refreshOther(listener); } } public void removeListener(MessagingListener listener) { mListeners.remove(listener); } public Set<MessagingListener> getListeners() { return mListeners; } public Set<MessagingListener> getListeners(MessagingListener listener) { if (listener == null) { return mListeners; } Set<MessagingListener> listeners = new CopyOnWriteArraySet<MessagingListener>(mListeners); listeners.add(listener); return listeners; } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * TODO this needs to cache the remote folder list * * @param account * @param includeRemote * @param listener * @throws MessagingException */ public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { for (MessagingListener l : getListeners(listener)) { l.listFoldersStarted(account); } List<? extends Folder> localFolders = null; try { Store localStore = account.getLocalStore(); localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(new Folder[0]); if (refreshRemote || localFolders == null || localFolders.size() == 0) { doRefreshRemote(account, listener); return; } for (MessagingListener l : getListeners(listener)) { l.listFolders(account, folderArray); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listFoldersFailed(account, e.getMessage()); } addErrorMessage(account, null, e); return; } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } for (MessagingListener l : getListeners(listener)) { l.listFoldersFinished(account); } } }); } private void doRefreshRemote(final Account account, MessagingListener listener) { put("doRefreshRemote", listener, new Runnable() { public void run() { List<? extends Folder> localFolders = null; try { Store store = account.getRemoteStore(); List<? extends Folder> remoteFolders = store.getPersonalNamespaces(false); LocalStore localStore = account.getLocalStore(); HashSet<String> remoteFolderNames = new HashSet<String>(); for (int i = 0, count = remoteFolders.size(); i < count; i++) { LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName()); if (!localFolder.exists()) { localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount()); } remoteFolderNames.add(remoteFolders.get(i).getName()); } localFolders = localStore.getPersonalNamespaces(false); /* * Clear out any folders that are no longer on the remote store. */ for (Folder localFolder : localFolders) { String localFolderName = localFolder.getName(); if (localFolderName.equalsIgnoreCase(K9.INBOX) || localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName())) { continue; } if (!remoteFolderNames.contains(localFolder.getName())) { localFolder.delete(false); } } localFolders = localStore.getPersonalNamespaces(false); Folder[] folderArray = localFolders.toArray(new Folder[0]); for (MessagingListener l : getListeners()) { l.listFolders(account, folderArray); } for (MessagingListener l : getListeners()) { l.listFoldersFinished(account); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.listFoldersFailed(account, ""); } addErrorMessage(account, null, e); } finally { if (localFolders != null) { for (Folder localFolder : localFolders) { if (localFolder != null) { localFolder.close(); } } } } } }); } /** * List the messages in the local message store for the given folder asynchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessages(final Account account, final String folder, final MessagingListener listener) { threadPool.execute(new Runnable() { public void run() { listLocalMessagesSynchronous(account, folder, listener); } }); } /** * List the messages in the local message store for the given folder synchronously. * * @param account * @param folder * @param listener * @throws MessagingException */ public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesStarted(account, folder); } Folder localFolder = null; MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { List<Message> pendingMessages = new ArrayList<Message>(); int totalDone = 0; public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { if (isMessageSuppressed(account, folder, message) == false) { pendingMessages.add(message); totalDone++; if (pendingMessages.size() > 10) { addPendingMessages(); } } else { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesRemoveMessage(account, folder, message); } } } public void messagesFinished(int number) { addPendingMessages(); } private void addPendingMessages() { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesAddMessages(account, folder, pendingMessages); } pendingMessages.clear(); } }; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); localFolder.getMessages( retrievalListener, false // Skip deleted messages ); if (K9.DEBUG) Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished"); for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFinished(account, folder); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.listLocalMessagesFailed(account, folder, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener) { searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages, searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener); } /** * Find all messages in any local account which match the query 'query' * @param folderNames TODO * @param query * @param listener * @param searchAccounts TODO * @param account TODO * @param account * @throws MessagingException */ public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate, final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener) { if (K9.DEBUG) { Log.i(K9.LOG_TAG, "searchLocalMessages (" + "accountUuids=" + Utility.combine(accountUuids, ',') + ", folderNames = " + Utility.combine(folderNames, ',') + ", messages.size() = " + (messages != null ? messages.length : null) + ", query = " + query + ", integrate = " + integrate + ", requiredFlags = " + Utility.combine(requiredFlags, ',') + ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',') + ")"); } threadPool.execute(new Runnable() { public void run() { final AccountStats stats = new AccountStats(); final Set<String> accountUuidsSet = new HashSet<String>(); if (accountUuids != null) { for (String accountUuid : accountUuids) { accountUuidsSet.add(accountUuid); } } final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext()); Account[] accounts = prefs.getAccounts(); List<LocalFolder> foldersToSearch = null; boolean displayableOnly = false; boolean noSpecialFolders = true; for (final Account account : accounts) { if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false) { continue; } if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true) { displayableOnly = true; noSpecialFolders = true; } else if (integrate == false && folderNames == null) { Account.Searchable searchableFolders = account.getSearchableFolders(); switch (searchableFolders) { case NONE: continue; case DISPLAYABLE: displayableOnly = true; break; } } List<Message> messagesToSearch = null; if (messages != null) { messagesToSearch = new LinkedList<Message>(); for (Message message : messages) { if (message.getFolder().getAccount().getUuid().equals(account.getUuid())) { messagesToSearch.add(message); } } if (messagesToSearch.isEmpty()) { continue; } } if (listener != null) { listener.listLocalMessagesStarted(account, null); } if (integrate || displayableOnly || folderNames != null || noSpecialFolders) { List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>(); try { LocalStore store = account.getLocalStore(); List<? extends Folder> folders = store.getPersonalNamespaces(false); Set<String> folderNameSet = null; if (folderNames != null) { folderNameSet = new HashSet<String>(); for (String folderName : folderNames) { folderNameSet.add(folderName); } } for (Folder folder : folders) { LocalFolder localFolder = (LocalFolder)folder; boolean include = true; folder.refresh(prefs); String localFolderName = localFolder.getName(); if (integrate) { include = localFolder.isIntegrate(); } else { if (folderNameSet != null) { if (folderNameSet.contains(localFolderName) == false) { include = false; } } // Never exclude the INBOX (see issue 1817) else if (noSpecialFolders && !localFolderName.equals(K9.INBOX) && ( localFolderName.equals(account.getTrashFolderName()) || localFolderName.equals(account.getOutboxFolderName()) || localFolderName.equals(account.getDraftsFolderName()) || localFolderName.equals(account.getSentFolderName()) || localFolderName.equals(account.getErrorFolderName()))) { include = false; } else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass())) { include = false; } } if (include) { tmpFoldersToSearch.add(localFolder); } } if (tmpFoldersToSearch.size() < 1) { continue; } foldersToSearch = tmpFoldersToSearch; } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me); addErrorMessage(account, null, me); } } MessageRetrievalListener retrievalListener = new MessageRetrievalListener() { public void messageStarted(String message, int number, int ofTotal) {} public void messageFinished(Message message, int number, int ofTotal) { if (isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message) == false) { List<Message> messages = new ArrayList<Message>(); messages.add(message); stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0; stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0; if (listener != null) { listener.listLocalMessagesAddMessages(account, null, messages); } } } public void messagesFinished(int number) { } }; try { String[] queryFields = {"html_content","subject","sender_list"}; LocalStore localStore = account.getLocalStore(); localStore.searchForMessages(retrievalListener, queryFields , query, foldersToSearch, messagesToSearch == null ? null : messagesToSearch.toArray(new Message[0]), requiredFlags, forbiddenFlags); } catch (Exception e) { if (listener != null) { listener.listLocalMessagesFailed(account, null, e.getMessage()); } addErrorMessage(account, null, e); } finally { if (listener != null) { listener.listLocalMessagesFinished(account, null); } } } if (listener != null) { listener.searchStats(stats); } } }); } public void loadMoreMessages(Account account, String folder, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount()); synchronizeMailbox(account, folder, listener, null); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Unable to set visible limit on folder", me); } } public void resetVisibleLimits(Account[] accounts) { for (Account account : accounts) { try { LocalStore localStore = account.getLocalStore(); localStore.resetVisibleLimits(account.getDisplayCount()); } catch (MessagingException e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Unable to reset visible limits", e); } } } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener * @param providedRemoteFolder TODO */ public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder) { putBackground("synchronizeMailbox", listener, new Runnable() { public void run() { synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder); } }); } /** * Start foreground synchronization of the specified folder. This is generally only called * by synchronizeMailbox. * @param account * @param folder * * TODO Break this method up into smaller chunks. * @param providedRemoteFolder TODO */ private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder) { Folder remoteFolder = null; LocalFolder tLocalFolder = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxStarted(account, folder); } /* * We don't ever sync the Outbox or errors folder */ if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName())) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } return; } Exception commandException = null; try { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " + account.getDescription()); try { processPendingCommandsSynchronous(account); } catch (Exception e) { addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e); commandException = e; } /* * Get the message list from the local store and create an index of * the uids within the list. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder); final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder); final LocalFolder localFolder = tLocalFolder; localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); HashMap<String, Message> localUidMap = new HashMap<String, Message>(); for (Message message : localMessages) { localUidMap.put(message.getUid(), message); } if (providedRemoteFolder != null) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder); remoteFolder = providedRemoteFolder; } else { Store remoteStore = account.getRemoteStore(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder); remoteFolder = remoteStore.getFolder(folder); if (! verifyOrCreateRemoteSpecialFolder(account, folder, remoteFolder, listener)) { return; } /* * Synchronization process: Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder); remoteFolder.open(OpenMode.READ_WRITE); if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder); remoteFolder.expunge(); } } /* * Get the remote message count. */ int remoteMessageCount = remoteFolder.getMessageCount(); int visibleLimit = localFolder.getVisibleLimit(); if (visibleLimit < 1) { visibleLimit = K9.DEFAULT_VISIBLE_LIMIT; } Message[] remoteMessageArray = new Message[0]; final ArrayList<Message> remoteMessages = new ArrayList<Message>(); // final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount); final Date earliestDate = account.getEarliestPollDate(); if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder); final AtomicInteger headerProgress = new AtomicInteger(0); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersStarted(account, folder); } remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null); int messageCount = remoteMessageArray.length; for (Message thisMess : remoteMessageArray) { headerProgress.incrementAndGet(); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersProgress(account, folder, headerProgress.get(), messageCount); } Message localMessage = localUidMap.get(thisMess.getUid()); if (localMessage == null || localMessage.olderThan(earliestDate) == false) { remoteMessages.add(thisMess); remoteUidMap.put(thisMess.getUid(), thisMess); } } if (K9.DEBUG) Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder); remoteMessageArray = null; for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxHeadersFinished(account, folder, headerProgress.get(), remoteUidMap.size()); } } else if (remoteMessageCount < 0) { throw new Exception("Message count " + remoteMessageCount + " for folder " + folder); } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ if (account.syncRemoteDeletions()) { for (Message localMessage : localMessages) { if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED)) { localMessage.setFlag(Flag.X_DESTROYED, true); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } } } localMessages = null; /* * Now we download the actual content of messages. */ int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages); setLocalFlaggedCountToRemote(localFolder, remoteFolder); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, unreadMessageCount); } /* * Notify listeners that we're finally done. */ localFolder.setLastChecked(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date() + " with " + newMessages + " new messages"); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages); } if (commandException != null) { String rootMessage = getRootCauseMessage(commandException); Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" + tLocalFolder.getName() + " was '" + rootMessage + "'"); localFolder.setStatus(rootMessage); for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed(account, folder, rootMessage); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder); } catch (Exception e) { Log.e(K9.LOG_TAG, "synchronizeMailbox", e); // If we don't set the last checked, it can try too often during // failure conditions String rootMessage = getRootCauseMessage(e); if (tLocalFolder != null) { try { tLocalFolder.setStatus(rootMessage); tLocalFolder.setLastChecked(System.currentTimeMillis()); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" + tLocalFolder.getName(), e); } } for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFailed( account, folder, rootMessage); } addErrorMessage(account, null, e); Log.e(K9.LOG_TAG, "Failed synchronizing folder " + account.getDescription() + ":" + folder + " @ " + new Date()); } finally { if (providedRemoteFolder == null && remoteFolder != null) { remoteFolder.close(); } if (tLocalFolder != null) { tLocalFolder.close(); } } } /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ private boolean verifyOrCreateRemoteSpecialFolder(final Account account, final String folder, final Folder remoteFolder, final MessagingListener listener) throws MessagingException { if (folder.equals(account.getTrashFolderName()) || folder.equals(account.getSentFolderName()) || folder.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : getListeners(listener)) { l.synchronizeMailboxFinished(account, folder, 0, 0); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder); return false; } } } return true; } private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException { int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); if (remoteUnreadMessageCount != -1) { localFolder.setUnreadMessageCount(remoteUnreadMessageCount); } else { int unreadCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false) { unreadCount++; } } localFolder.setUnreadMessageCount(unreadCount); } return localFolder.getUnreadMessageCount(); } private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException { int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount(); if (remoteFlaggedMessageCount != -1) { localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount); } else { int flaggedCount = 0; Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false) { flaggedCount++; } } localFolder.setFlaggedMessageCount(flaggedCount); } } private int downloadMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); if (earliestDate != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate); } } final String folder = remoteFolder.getName(); ArrayList<Message> syncFlagMessages = new ArrayList<Message>(); List<Message> unsyncedMessages = new ArrayList<Message>(); final AtomicInteger newMessages = new AtomicInteger(0); List<Message> messages = new ArrayList<Message>(inputMessages); for (Message message : messages) { if (message.isSet(Flag.DELETED)) { syncFlagMessages.add(message); } else if (isMessageSuppressed(account, folder, message) == false) { Message localMessage = localFolder.getMessage(message.getUid()); if (localMessage == null) { if (!flagSyncOnly) { if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded"); unsyncedMessages.add(message); } else { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded"); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL)); localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL)); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } } } } else if (localMessage.isSet(Flag.DELETED) == false) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store"); if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded, even partially; trying again"); unsyncedMessages.add(message); } else { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } syncFlagMessages.add(message); } } } } final AtomicInteger progress = new AtomicInteger(0); final int todo = unsyncedMessages.size() + syncFlagMessages.size(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages"); messages.clear(); final ArrayList<Message> largeMessages = new ArrayList<Message>(); final ArrayList<Message> smallMessages = new ArrayList<Message>(); if (unsyncedMessages.size() > 0) { /* * Reverse the order of the messages. Depending on the server this may get us * fetch results for newest to oldest. If not, no harm done. */ Collections.reverse(unsyncedMessages); int visibleLimit = localFolder.getVisibleLimit(); int listSize = unsyncedMessages.size(); if (listSize > visibleLimit) { unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize); } FetchProfile fp = new FetchProfile(); if (remoteFolder.supportsFetchingFlags()) { fp.add(FetchProfile.Item.FLAGS); } fp.add(FetchProfile.Item.ENVELOPE); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder); fetchUnsyncedMessages(account, remoteFolder, localFolder, unsyncedMessages, smallMessages,largeMessages, progress, todo, fp); // If a message didn't exist, messageFinished won't be called, but we shouldn't try again // If we got here, nothing failed for (Message message : unsyncedMessages) { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and " + smallMessages.size() + " small messages out of " + unsyncedMessages.size() + " unsynced messages"); unsyncedMessages.clear(); /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); // fp.add(FetchProfile.Item.FLAGS); // fp.add(FetchProfile.Item.ENVELOPE); downloadSmallMessages(account, remoteFolder, localFolder, smallMessages, progress, newMessages, todo, fp); smallMessages.clear(); /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); downloadLargeMessages(account, remoteFolder, localFolder, largeMessages, progress, newMessages, todo, fp); largeMessages.clear(); /* * Refresh the flags for any messages in the local store that we didn't just * download. */ refreshLocalMessageFlags(account,remoteFolder,localFolder,syncFlagMessages,progress,todo); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages"); localFolder.purgeToVisibleLimit(new MessageRemovalListener() { public void messageRemoved(Message message) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, message); } } }); return newMessages.get(); } private void fetchUnsyncedMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, List<Message> unsyncedMessages, final ArrayList<Message> smallMessages, final ArrayList<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message); if (newPushState != null) { localFolder.setPushState(newPushState); } if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (K9.DEBUG) { if (message.isSet(Flag.DELETED)) { Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid() + " was marked deleted on server, skipping"); } else { Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than " + earliestDate + ", skipping"); } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } // And include it in the view if (message.getSubject() != null && message.getFrom() != null) { /* * We check to make sure that we got something worth * showing (subject and from) because some protocols * (POP) may not be able to give us headers for * ENVELOPE, only size. */ if (isMessageSuppressed(account, folder, message) == false) { // Store the new message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); syncFlags(localMessage, message); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message " + account + ":" + folder + ":" + message.getUid()); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e); addErrorMessage(account, null, e); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); } private boolean shouldImportMessage(final Account account, final String folder, final Message message, final AtomicInteger progress, final Date earliestDate) { if (isMessageSuppressed(account, folder, message)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+ "but just downloaded. "+ "The race condition means we wasted some bandwidth. Oh well."); } return false; } if (message.olderThan(earliestDate)) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than " + earliestDate + ", hence not saving"); } return false; } return true; } private void downloadSmallMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> smallMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); return; } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); progress.incrementAndGet(); // Set a flag indicating this message has now be fully downloaded localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } if (!localMessage.isSet(Flag.SEEN)) { // Send a notification of this message if (notifyAccount(mApplication, account, message) == true) { newMessages.incrementAndGet(); } } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me); } } public void messageStarted(String uid, int number, int ofTotal) { } public void messagesFinished(int total) {} }); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder); } private void downloadLargeMessages(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> largeMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (!shouldImportMessage(account, folder, message, progress, earliestDate)) { progress.incrementAndGet(); continue; } if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Certain (POP3) servers give you the whole message even when you ask for only the first x Kb if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * Mark the message as fully downloaded if the message size is smaller than * the account's autodownload size limit, otherwise mark as only a partial * download. This will prevent the system from downloading the same message * twice. */ if (message.getSize() < account.getMaximumAutoDownloadMessageSize()) { localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } else { // Set a flag indicating that the message has been partially downloaded and // is ready for view. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } } } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { remoteFolder.fetchPart(message, part, null); } // Store the updated message locally localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } if (K9.DEBUG) Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message " + account + ":" + folder + ":" + message.getUid()); // Update the listener with what we've found progress.incrementAndGet(); Message localMessage = localFolder.getMessage(message.getUid()); for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); l.synchronizeMailboxProgress(account, folder, progress.get(), todo); if (!localMessage.isSet(Flag.SEEN)) { l.synchronizeMailboxNewMessage(account, folder, localMessage); } } if (!localMessage.isSet(Flag.SEEN)) { // Send a notification of this message if (notifyAccount(mApplication, account, message) == true) { newMessages.incrementAndGet(); } } }//for large messsages if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder); } private void refreshLocalMessageFlags(final Account account, final Folder remoteFolder, final LocalFolder localFolder, ArrayList<Message> syncFlagMessages, final AtomicInteger progress, final int todo ) throws MessagingException { final String folder = remoteFolder.getName(); if (remoteFolder.supportsFetchingFlags()) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "SYNC: About to sync flags for " + syncFlagMessages.size() + " remote messages for folder " + folder); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); List<Message> undeletedMessages = new LinkedList<Message>(); for (Message message : syncFlagMessages) { if (message.isSet(Flag.DELETED) == false) { undeletedMessages.add(message); } } remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null); for (Message remoteMessage : syncFlagMessages) { Message localMessage = localFolder.getMessage(remoteMessage.getUid()); boolean messageChanged = syncFlags(localMessage, remoteMessage); if (messageChanged) { if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage)) { for (MessagingListener l : getListeners()) { l.synchronizeMailboxRemovedMessage(account, folder, localMessage); } } else { for (MessagingListener l : getListeners()) { l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage); } } } progress.incrementAndGet(); for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } } } } private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().getAccount().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED }) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; } private String getRootCauseMessage(Throwable t) { Throwable rootCause = t; Throwable nextCause = rootCause; do { nextCause = rootCause.getCause(); if (nextCause != null) { rootCause = nextCause; } } while (nextCause != null); return rootCause.getMessage(); } private void queuePendingCommand(Account account, PendingCommand command) { try { LocalStore localStore = account.getLocalStore(); localStore.addPendingCommand(command); } catch (Exception e) { addErrorMessage(account, null, e); throw new RuntimeException("Unable to enqueue pending command", e); } } private void processPendingCommands(final Account account) { putBackground("processPendingCommands", null, new Runnable() { public void run() { try { processPendingCommandsSynchronous(account); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "processPendingCommands", me); addErrorMessage(account, null, me); /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } private void processPendingCommandsSynchronous(Account account) throws MessagingException { LocalStore localStore = account.getLocalStore(); ArrayList<PendingCommand> commands = localStore.getPendingCommands(); int progress = 0; int todo = commands.size(); if (todo == 0) { return; } for (MessagingListener l : getListeners()) { l.pendingCommandsProcessing(account); l.synchronizeMailboxProgress(account, null, progress, todo); } PendingCommand processingCommand = null; try { for (PendingCommand command : commands) { processingCommand = command; if (K9.DEBUG) Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'"); String[] components = command.command.split("\\."); String commandTitle = components[components.length - 1]; for (MessagingListener l : getListeners()) { l.pendingCommandStarted(account, commandTitle); } /* * We specifically do not catch any exceptions here. If a command fails it is * most likely due to a server or IO error and it must be retried before any * other command processes. This maintains the order of the commands. */ try { if (PENDING_COMMAND_APPEND.equals(command.command)) { processPendingAppend(command, account); } else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command)) { processPendingSetFlag(command, account); } else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) { processPendingSetFlagOld(command, account); } else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) { processPendingMarkAllAsRead(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command)) { processPendingMoveOrCopy(command, account); } else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) { processPendingMoveOrCopyOld(command, account); } else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) { processPendingEmptyTrash(command, account); } else if (PENDING_COMMAND_EXPUNGE.equals(command.command)) { processPendingExpunge(command, account); } localStore.removePendingCommand(command); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'"); } catch (MessagingException me) { if (me.isPermanentFailure()) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue"); localStore.removePendingCommand(processingCommand); } else { throw me; } } finally { progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, null, progress, todo); l.pendingCommandCompleted(account, commandTitle); } } } } catch (MessagingException me) { addErrorMessage(account, null, me); Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me); throw me; } finally { for (MessagingListener l : getListeners()) { l.pendingCommandsFinished(account); } } } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. Once the local message is successfully processed it is deleted so * that the server message will be synchronized down without an additional copy being * created. * TODO update the local message UID instead of deleteing it * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingAppend(PendingCommand command, Account account) throws MessagingException { Folder remoteFolder = null; LocalFolder localFolder = null; try { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid); if (localMessage == null) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return; } } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(localMessage.getUid()); } if (remoteMessage == null) { if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) { Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() + " has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " + " same message id"); String rUid = remoteFolder.getUidFromMessageId(localMessage); if (rUid != null) { Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " + " uid " + rUid + ", assuming message was already copied and aborting this copy"); String oldUid = localMessage.getUid(); localMessage.setUid(rUid); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } return; } else { Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append"); } } /* * If the message does not exist remotely we just upload it and then * update our local copy with the new uid. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage } , fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } } else { /* * If the remote message exists we need to determine which copy to keep. */ /* * See if the remote message is newer than ours. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = localMessage.getInternalDate(); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate != null && remoteDate.compareTo(localDate) > 0) { /* * If the remote message is newer than ours we'll just * delete ours and move on. A sync will get the server message * if we need to be able to see it. */ localMessage.setFlag(Flag.X_DESTROYED, true); } else { /* * Otherwise we'll upload our message and then delete the remote message. */ fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { localMessage }, fp, null); String oldUid = localMessage.getUid(); localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true); remoteFolder.appendMessages(new Message[] { localMessage }); localFolder.changeUid(localMessage); for (MessagingListener l : getListeners()) { l.messageUidChanged(account, folder, oldUid, localMessage.getUid()); } if (remoteDate != null) { remoteMessage.setFlag(Flag.DELETED, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } } } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[]) { if (account.getErrorFolderName().equals(srcFolder)) { return; } PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = srcFolder; command.arguments[1] = destFolder; command.arguments[2] = Boolean.toString(isCopy); for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); } /** * Process a pending trash message command. * * @param command arguments = (String folder, String uid) * @param account * @throws MessagingException */ private void processPendingMoveOrCopy(PendingCommand command, Account account) throws MessagingException { Folder remoteSrcFolder = null; Folder remoteDestFolder = null; try { String srcFolder = command.arguments[0]; if (account.getErrorFolderName().equals(srcFolder)) { return; } String destFolder = command.arguments[1]; String isCopyS = command.arguments[2]; Store remoteStore = account.getRemoteStore(); remoteSrcFolder = remoteStore.getFolder(srcFolder); List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteSrcFolder.getMessage(uid)); } } boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (!remoteSrcFolder.exists()) { throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder + ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message"); String destFolderName = destFolder; if (K9.FOLDER_NONE.equals(destFolderName)) { destFolderName = null; } remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName); } else { remoteDestFolder = remoteStore.getFolder(destFolder); if (isCopy) { remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder); } else { remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder); } } if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder); remoteSrcFolder.expunge(); } } finally { if (remoteSrcFolder != null) { remoteSrcFolder.close(); } if (remoteDestFolder != null) { remoteDestFolder.close(); } } } private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids) { putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_SET_FLAG_BULK; int length = 3 + uids.length; command.arguments = new String[length]; command.arguments[0] = folderName; command.arguments[1] = newState; command.arguments[2] = flag; for (int i = 0; i < uids.length; i++) { command.arguments[3 + i] = uids[i]; } queuePendingCommand(account, command); processPendingCommands(account); } }); } /** * Processes a pending mark read or unread command. * * @param command arguments = (String folder, String uid, boolean read) * @param account */ private void processPendingSetFlag(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } boolean newState = Boolean.parseBoolean(command.arguments[1]); Flag flag = Flag.valueOf(command.arguments[2]); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } List<Message> messages = new ArrayList<Message>(); for (int i = 3; i < command.arguments.length; i++) { String uid = command.arguments[i]; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { messages.add(remoteFolder.getMessage(uid)); } } if (messages.size() == 0) { return; } remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingSetFlagOld(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; String uid = command.arguments[1]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid); boolean newState = Boolean.parseBoolean(command.arguments[2]); Flag flag = Flag.valueOf(command.arguments[3]); Folder remoteFolder = null; try { Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteFolder.getMessage(uid); } if (remoteMessage == null) { return; } remoteMessage.setFlag(flag, newState); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } private void queueExpunge(final Account account, final String folderName) { putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable() { public void run() { PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EXPUNGE; command.arguments = new String[1]; command.arguments[0] = folderName; queuePendingCommand(account, command); processPendingCommands(account); } }); } private void processPendingExpunge(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; if (account.getErrorFolderName().equals(folder)) { return; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder); Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(folder); try { if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.expunge(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder); } finally { if (remoteFolder != null) { remoteFolder.close(); } } } // TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1 // Eventually, it should be removed private void processPendingMoveOrCopyOld(PendingCommand command, Account account) throws MessagingException { String srcFolder = command.arguments[0]; String uid = command.arguments[1]; String destFolder = command.arguments[2]; String isCopyS = command.arguments[3]; boolean isCopy = false; if (isCopyS != null) { isCopy = Boolean.parseBoolean(isCopyS); } if (account.getErrorFolderName().equals(srcFolder)) { return; } Store remoteStore = account.getRemoteStore(); Folder remoteSrcFolder = remoteStore.getFolder(srcFolder); Folder remoteDestFolder = remoteStore.getFolder(destFolder); if (!remoteSrcFolder.exists()) { throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true); } remoteSrcFolder.open(OpenMode.READ_WRITE); if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true); } Message remoteMessage = null; if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { remoteMessage = remoteSrcFolder.getMessage(uid); } if (remoteMessage == null) { throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true); } if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder + ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy == false && destFolder.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message"); remoteMessage.delete(account.getTrashFolderName()); remoteSrcFolder.close(); return; } remoteDestFolder.open(OpenMode.READ_WRITE); if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) { throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true); } if (isCopy) { remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder); } else { remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder); } remoteSrcFolder.close(); remoteDestFolder.close(); } private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException { String folder = command.arguments[0]; Folder remoteFolder = null; LocalFolder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = (LocalFolder) localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message[] messages = localFolder.getMessages(null, false); for (Message message : messages) { if (message.isSet(Flag.SEEN) == false) { message.setFlag(Flag.SEEN, true); for (MessagingListener l : getListeners()) { l.listLocalMessagesUpdateMessage(account, folder, message); } } } localFolder.setUnreadMessageCount(0); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, 0); } if (account.getErrorFolderName().equals(folder)) { return; } Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true); remoteFolder.close(); } catch (UnsupportedOperationException uoe) { Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe); } finally { if (localFolder != null) { localFolder.close(); } if (remoteFolder != null) { remoteFolder.close(); } } } static long uidfill = 0; static AtomicBoolean loopCatch = new AtomicBoolean(); public void addErrorMessage(Account account, String subject, Throwable t) { if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (t == null) { return; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); if (subject == null) { subject = getRootCauseMessage(t); } addErrorMessage(account, subject, baos.toString()); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void addErrorMessage(Account account, String subject, String body) { if (K9.ENABLE_ERROR_FOLDER == false) { return; } if (loopCatch.compareAndSet(false, true) == false) { return; } try { if (body == null || body.length() < 1) { return; } Store localStore = account.getLocalStore(); LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName()); Message[] messages = new Message[1]; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(body)); message.setFlag(Flag.X_DOWNLOADED_FULL, true); message.setSubject(subject); long nowTime = System.currentTimeMillis(); Date nowDate = new Date(nowTime); message.setInternalDate(nowDate); message.addSentDate(nowDate); message.setFrom(new Address(account.getEmail(), "K9mail internal")); messages[0] = message; localFolder.appendMessages(messages); localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000)); } catch (Throwable it) { Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it); } finally { loopCatch.set(false); } } public void markAllMessagesRead(final Account account, final String folder) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read"); List<String> args = new ArrayList<String>(); args.add(folder); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_MARK_ALL_AS_READ; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } public void setFlag( final Message[] messages, final Flag flag, final boolean newState) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { String[] uids = new String[messages.size()]; for (int i = 0; i < messages.size(); i++) { uids[i] = messages.get(i).getUid(); } setFlag(account, folder.getName(), uids, flag, newState); } }); } public void setFlag( final Account account, final String folderName, final String[] uids, final Flag flag, final boolean newState) { // TODO: put this into the background, but right now that causes odd behavior // because the FolderMessageList doesn't have its own cache of the flag states Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folderName); localFolder.open(OpenMode.READ_WRITE); ArrayList<Message> messages = new ArrayList<Message>(); for (int i = 0; i < uids.length; i++) { String uid = uids[i]; // Allows for re-allowing sending of messages that could not be sent if (flag == Flag.FLAGGED && newState == false && uid != null && account.getOutboxFolderName().equals(folderName)) { sendCount.remove(uid); } Message msg = localFolder.getMessage(uid); if (msg != null) { messages.add(msg); } } localFolder.setFlags(messages.toArray(new Message[0]), new Flag[] {flag}, newState); for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount()); } if (account.getErrorFolderName().equals(folderName)) { return; } queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids); processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException(me); } finally { if (localFolder != null) { localFolder.close(); } } }//setMesssageFlag public void clearAllPending(final Account account) { try { Log.w(K9.LOG_TAG, "Clearing pending commands!"); LocalStore localStore = account.getLocalStore(); localStore.removePendingCommands(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to clear pending command", me); addErrorMessage(account, null, me); } } private void loadMessageForViewRemote(final Account account, final String folder, final String uid, final MessagingListener listener) { put("loadMessageForViewRemote", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message.isSet(Flag.X_DOWNLOADED_FULL)) { /* * If the message has been synchronized since we were called we'll * just hand it back cause it's ready to go. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); } else { /* * At this point the message is not available, so we need to download it * fully if possible. */ Store remoteStore = account.getRemoteStore(); remoteFolder = remoteStore.getFolder(folder); remoteFolder.open(OpenMode.READ_WRITE); // Get the remote message and fully download it Message remoteMessage = remoteFolder.getMessage(uid); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // Store the message locally and load the stored message into memory localFolder.appendMessages(new Message[] { remoteMessage }); message = localFolder.getMessage(uid); localFolder.fetch(new Message[] { message }, fp, null); // Mark that this message is now fully synched message.setFlag(Flag.X_DOWNLOADED_FULL, true); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } finally { if (remoteFolder!=null) { remoteFolder.close(); } if (localFolder!=null) { localFolder.close(); } }//finally }//run }); } public void loadMessageForView(final Account account, final String folder, final String uid, final MessagingListener listener) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewStarted(account, folder, uid); } threadPool.execute(new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(folder); localFolder.open(OpenMode.READ_WRITE); LocalMessage message = (LocalMessage)localFolder.getMessage(uid); if (message==null || message.getId()==0) { throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid); } if (!message.isSet(Flag.SEEN)) { message.setFlag(Flag.SEEN, true); setFlag(new Message[] { message }, Flag.SEEN, true); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewHeadersAvailable(account, folder, uid, message); } if (!message.isSet(Flag.X_DOWNLOADED_FULL)) { loadMessageForViewRemote(account, folder, uid, listener); if (!message.isSet(Flag.X_DOWNLOADED_PARTIAL)) { localFolder.close(); return; } } FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localFolder.fetch(new Message[] { message }, fp, null); localFolder.close(); for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewBodyAvailable(account, folder, uid, message); } for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFinished(account, folder, uid, message); } } catch (Exception e) { for (MessagingListener l : getListeners(listener)) { l.loadMessageForViewFailed(account, folder, uid, e); } addErrorMessage(account, null, e); } } }); } /** * Attempts to load the attachment specified by part from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment( final Account account, final Message message, final Part part, final Object tag, final MessagingListener listener) { /* * Check if the attachment has already been downloaded. If it has there's no reason to * download it, so we just tell the listener that it's ready to go. */ try { if (part.getBody() != null) { for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, false); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } return; } } catch (MessagingException me) { /* * If the header isn't there the attachment isn't downloaded yet, so just continue * on. */ } for (MessagingListener l : getListeners()) { l.loadAttachmentStarted(account, message, part, tag, true); } if (listener != null) { listener.loadAttachmentStarted(account, message, part, tag, false); } put("loadAttachment", listener, new Runnable() { public void run() { Folder remoteFolder = null; LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); /* * We clear out any attachments already cached in the entire store and then * we update the passed in message to reflect that there are no cached * attachments. This is in support of limiting the account to having one * attachment downloaded at a time. */ localStore.pruneCachedAttachments(); ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); for (Part attachment : attachments) { attachment.setBody(null); } Store remoteStore = account.getRemoteStore(); localFolder = localStore.getFolder(message.getFolder().getName()); remoteFolder = remoteStore.getFolder(message.getFolder().getName()); remoteFolder.open(OpenMode.READ_WRITE); //FIXME: This is an ugly hack that won't be needed once the Message objects have been united. Message remoteMessage = remoteFolder.getMessage(message.getUid()); remoteMessage.setBody(message.getBody()); remoteFolder.fetchPart(remoteMessage, part, null); localFolder.updateMessage((LocalMessage)message); for (MessagingListener l : getListeners()) { l.loadAttachmentFinished(account, message, part, tag); } if (listener != null) { listener.loadAttachmentFinished(account, message, part, tag); } } catch (MessagingException me) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Exception loading attachment", me); for (MessagingListener l : getListeners()) { l.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } if (listener != null) { listener.loadAttachmentFailed(account, message, part, tag, me.getMessage()); } addErrorMessage(account, null, me); } finally { if (remoteFolder != null) { remoteFolder.close(); } if (localFolder != null) { localFolder.close(); } } } }); } /** * Stores the given message in the Outbox and starts a sendPendingMessages command to * attempt to send the message. * @param account * @param message * @param listener */ public void sendMessage(final Account account, final Message message, MessagingListener listener) { try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); Message localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); localFolder.close(); sendPendingMessages(account, null); } catch (Exception e) { /* for (MessagingListener l : getListeners()) { // TODO general failed } */ addErrorMessage(account, null, e); } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final Account account, MessagingListener listener) { putBackground("sendPendingMessages", listener, new Runnable() { public void run() { sendPendingMessagesSynchronous(account); } }); } public boolean messagesPendingSend(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return false; } localFolder.open(OpenMode.READ_WRITE); int localMessages = localFolder.getMessageCount(); if (localMessages > 0) { return true; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e); } finally { if (localFolder != null) { localFolder.close(); } } return false; } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessagesSynchronous(final Account account) { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder( account.getOutboxFolderName()); if (!localFolder.exists()) { return; } for (MessagingListener l : getListeners()) { l.sendPendingMessagesStarted(account); } localFolder.open(OpenMode.READ_WRITE); Message[] localMessages = localFolder.getMessages(null); boolean anyFlagged = false; int progress = 0; int todo = localMessages.length; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } /* * The profile we will use to pull all of the content * for a given local message into memory for sending. */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send"); Transport transport = Transport.getInstance(account); for (Message message : localMessages) { if (message.isSet(Flag.DELETED)) { message.setFlag(Flag.X_DESTROYED, true); continue; } if (message.isSet(Flag.FLAGGED)) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid()); continue; } try { AtomicInteger count = new AtomicInteger(0); AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count); if (oldCount != null) { count = oldCount; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get()); if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS) { Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging"); message.setFlag(Flag.FLAGGED, true); anyFlagged = true; continue; } localFolder.fetch(new Message[] { message }, fp, null); try { message.setFlag(Flag.X_SEND_IN_PROGRESS, true); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid()); transport.sendMessage(message); message.setFlag(Flag.X_SEND_IN_PROGRESS, false); message.setFlag(Flag.SEEN, true); progress++; for (MessagingListener l : getListeners()) { l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo); } if (K9.FOLDER_NONE.equals(account.getSentFolderName())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message"); message.setFlag(Flag.DELETED, true); } else { LocalFolder localSentFolder = (LocalFolder) localStore.getFolder( account.getSentFolderName()); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); localFolder.moveMessages( new Message[] { message }, localSentFolder); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") "); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localSentFolder.getName(), message.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } } catch (Exception e) { if (e instanceof MessagingException) { MessagingException me = (MessagingException)e; if (me.isPermanentFailure() == false) { // Decrement the counter if the message could not possibly have been sent int newVal = count.decrementAndGet(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal + "; no possible send"); } } message.setFlag(Flag.X_SEND_FAILED, true); Log.e(K9.LOG_TAG, "Failed to send message", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e); for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed( account, localFolder.getName(), getRootCauseMessage(e)); } addErrorMessage(account, null, e); /* * We ignore this exception because a future refresh will retry this * message. */ } } if (localFolder.getMessageCount() == 0) { localFolder.delete(false); } for (MessagingListener l : getListeners()) { l.sendPendingMessagesCompleted(account); } if (anyFlagged) { addErrorMessage(account, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME)); NotificationManager notifMgr = (NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis()); Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName()); PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0); notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject), mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi); notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR; notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; notifMgr.notify(-1000 - account.getAccountNumber(), notif); } } catch (Exception e) { for (MessagingListener l : getListeners()) { l.sendPendingMessagesFailed(account); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while closing folder", e); } } } } public void getAccountStats(final Context context, final Account account, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { try { AccountStats stats = account.getStats(context); l.accountStatusChanged(account, stats); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } } }; put("getAccountStats:" + account.getDescription(), l, unreadRunnable); } public void getFolderUnreadMessageCount(final Account account, final String folderName, final MessagingListener l) { Runnable unreadRunnable = new Runnable() { public void run() { int unreadMessageCount = 0; try { Folder localFolder = account.getLocalStore().getFolder(folderName); unreadMessageCount = localFolder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me); } l.folderStatusChanged(account, folderName, unreadMessageCount); } }; put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable); } public boolean isMoveCapable(Message message) { if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX)) { return true; } else { return false; } } public boolean isCopyCapable(Message message) { return isMoveCapable(message); } public boolean isMoveCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isMoveCapable() && remoteStore.isMoveCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me); return false; } } public boolean isCopyCapable(final Account account) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); return localStore.isCopyCapable() && remoteStore.isCopyCapable(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me); return false; } } public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { for (Message message : messages) { suppressMessage(account, srcFolder, message); } putBackground("moveMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener); } }); } public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder, final MessagingListener listener) { putBackground("copyMessages", null, new Runnable() { public void run() { moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener); } }); } public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder, final MessagingListener listener) { copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener); } private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages, final String destFolder, final boolean isCopy, MessagingListener listener) { try { Store localStore = account.getLocalStore(); Store remoteStore = account.getRemoteStore(); if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false)) { return; } if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false)) { return; } Folder localSrcFolder = localStore.getFolder(srcFolder); Folder localDestFolder = localStore.getFolder(destFolder); List<String> uids = new LinkedList<String>(); for (Message message : inMessages) { String uid = message.getUid(); if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) { uids.add(uid); } } Message[] messages = localSrcFolder.getMessages(uids.toArray(new String[0]), null); if (messages.length > 0) { Map<String, Message> origUidMap = new HashMap<String, Message>(); for (Message message : messages) { origUidMap.put(message.getUid(), message); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder + ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy); if (isCopy) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.BODY); localSrcFolder.fetch(messages, fp, null); localSrcFolder.copyMessages(messages, localDestFolder); } else { localSrcFolder.moveMessages(messages, localDestFolder); for (String origUid : origUidMap.keySet()) { for (MessagingListener l : getListeners()) { l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid()); } unsuppressMessage(account, srcFolder, origUid); } } queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(new String[0])); } processPendingCommands(account); } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error moving message", me); } } public void expunge(final Account account, final String folder, final MessagingListener listener) { putBackground("expunge", null, new Runnable() { public void run() { queueExpunge(account, folder); } }); } public void deleteDraft(final Account account, String uid) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); Message message = localFolder.getMessage(uid); if (message != null) { deleteMessages(new Message[] { message }, null); } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { if (localFolder != null) { localFolder.close(); } } } public void deleteMessages(final Message[] messages, final MessagingListener listener) { actOnMessages(messages, new MessageActor() { @Override public void act(final Account account, final Folder folder, final List<Message> messages) { for (Message message : messages) { suppressMessage(account, folder.getName(), message); } putBackground("deleteMessages", null, new Runnable() { public void run() { deleteMessagesSynchronous(account, folder.getName(), messages.toArray(new Message[0]), listener); } }); } }); } private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages, MessagingListener listener) { Folder localFolder = null; Folder localTrashFolder = null; String[] uids = getUidsFromMessages(messages); try { //We need to make these callbacks before moving the messages to the trash //as messages get a new UID after being moved for (Message message : messages) { if (listener != null) { listener.messageDeleted(account, folder, message); } for (MessagingListener l : getListeners()) { l.messageDeleted(account, folder, message); } } Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(folder); if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName())) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying"); localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true); } else { localTrashFolder = localStore.getFolder(account.getTrashFolderName()); if (localTrashFolder.exists() == false) { localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES); } if (localTrashFolder.exists() == true) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving"); localFolder.moveMessages(messages, localTrashFolder); } } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount()); if (localTrashFolder != null) { l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount()); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy()); if (folder.equals(account.getOutboxFolderName())) { for (Message message : messages) { // If the message was in the Outbox, then it has been copied to local Trash, and has // to be copied to remote trash PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { account.getTrashFolderName(), message.getUid() }; queuePendingCommand(account, command); } processPendingCommands(account); } else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) { queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids); processPendingCommands(account); } else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ) { queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids); processPendingCommands(account); } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server"); } for (String uid : uids) { unsuppressMessage(account, folder, uid); } } catch (MessagingException me) { addErrorMessage(account, null, me); throw new RuntimeException("Error deleting message from local store.", me); } finally { if (localFolder != null) { localFolder.close(); } if (localTrashFolder != null) { localTrashFolder.close(); } } } private String[] getUidsFromMessages(Message[] messages) { String[] uids = new String[messages.length]; for (int i = 0; i < messages.length; i++) { uids[i] = messages[i].getUid(); } return uids; } private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException { Store remoteStore = account.getRemoteStore(); Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName()); try { if (remoteFolder.exists()) { remoteFolder.open(OpenMode.READ_WRITE); remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true); if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy())) { remoteFolder.expunge(); } } } finally { if (remoteFolder != null) { remoteFolder.close(); } } } public void emptyTrash(final Account account, MessagingListener listener) { putBackground("emptyTrash", listener, new Runnable() { public void run() { Folder localFolder = null; try { Store localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getTrashFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.setFlags(new Flag[] { Flag.DELETED }, true); for (MessagingListener l : getListeners()) { l.emptyTrashCompleted(account); } List<String> args = new ArrayList<String>(); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_EMPTY_TRASH; command.arguments = args.toArray(new String[0]); queuePendingCommand(account, command); processPendingCommands(account); } catch (Exception e) { Log.e(K9.LOG_TAG, "emptyTrash failed", e); addErrorMessage(account, null, e); } finally { if (localFolder != null) { localFolder.close(); } } } }); } public void sendAlternate(final Context context, Account account, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName() + ":" + message.getUid() + " for sendAlternate"); loadMessageForView(account, message.getFolder().getName(), message.getUid(), new MessagingListener() { @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, Message message) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder + ":" + message.getUid() + " for sendAlternate"); try { Intent msg=new Intent(Intent.ACTION_SEND); String quotedText = null; Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part == null) { part = MimeUtility.findFirstPartByMimeType(message, "text/html"); } if (part != null) { quotedText = MimeUtility.getTextFromPart(part); } if (quotedText != null) { msg.putExtra(Intent.EXTRA_TEXT, quotedText); } msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject()); msg.setType("text/plain"); context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title))); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me); } } }); } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. * * @param context * @param account * @param listener */ public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) { TracingWakeLock twakeLock = null; if (useManualWakeLock) { TracingPowerManager pm = TracingPowerManager.getPowerManager(context); twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail"); twakeLock.setReferenceCounted(false); twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT); } final TracingWakeLock wakeLock = twakeLock; for (MessagingListener l : getListeners()) { l.checkMailStarted(context, account); } putBackground("checkMail", listener, new Runnable() { public void run() { final NotificationManager notifMgr = (NotificationManager)context .getSystemService(Context.NOTIFICATION_SERVICE); try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting mail check"); Preferences prefs = Preferences.getPreferences(context); Account[] accounts; if (account != null) { accounts = new Account[] { account }; } else { accounts = prefs.getAccounts(); } for (final Account account : accounts) { final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000; if (ignoreLastCheckedTime == false && accountInterval <= 0) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription()); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription()); account.setRingNotified(false); putBackground("sendPending " + account.getDescription(), null, new Runnable() { public void run() { if (messagesPendingSend(account)) { if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title), account.getDescription() , pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } try { sendPendingMessagesSynchronous(account); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } } } } ); try { Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aSyncMode = account.getFolderSyncMode(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fSyncClass = folder.getSyncClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never sync a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aSyncMode, fSyncClass)) { // Do not sync folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + " which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode); continue; } if (K9.DEBUG) Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " + new Date(folder.getLastChecked())); if (ignoreLastCheckedTime == false && folder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); continue; } putBackground("sync" + folder.getName(), null, new Runnable() { public void run() { LocalFolder tLocalFolder = null; try { // In case multiple Commands get enqueued, don't run more than // once final LocalStore localStore = account.getLocalStore(); tLocalFolder = localStore.getFolder(folder.getName()); tLocalFolder.open(Folder.OpenMode.READ_WRITE); if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() > (System.currentTimeMillis() - accountInterval)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName() + ", previously synced @ " + new Date(folder.getLastChecked()) + " which would be too recent for the account period"); return; } if (account.isShowOngoing()) { Notification notif = new Notification(R.drawable.ic_menu_refresh, context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()), System.currentTimeMillis()); Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription() + context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi); notif.flags = Notification.FLAG_ONGOING_EVENT; if (K9.NOTIFICATION_LED_WHILE_SYNCING) { notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME; } notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif); } try { synchronizeMailboxSynchronous(account, folder.getName(), listener, null); } finally { if (account.isShowOngoing()) { notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while processing folder " + account.getDescription() + ":" + folder.getName(), e); addErrorMessage(account, null, e); } finally { if (tLocalFolder != null) { tLocalFolder.close(); } } } } ); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e); addErrorMessage(account, null, e); } finally { putBackground("clear notification flag for " + account.getDescription(), null, new Runnable() { public void run() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription()); account.setRingNotified(false); try { AccountStats stats = account.getStats(context); int unreadMessageCount = stats.unreadMessageCount; if (unreadMessageCount == 0) { notifyAccountCancel(context, account); } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } } } ); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to synchronize mail", e); addErrorMessage(account, null, e); } putBackground("finalize sync", null, new Runnable() { public void run() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Finished mail sync"); if (wakeLock != null) { wakeLock.release(); } for (MessagingListener l : getListeners()) { l.checkMailFinished(context, account); } } } ); } }); } public void compact(final Account account, final MessagingListener ml) { putBackground("compact:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.compact(); long newSize = localStore.getSize(); if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e); } } }); } public void clear(final Account account, final MessagingListener ml) { putBackground("clear:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.clear(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e); } } }); } public void recreate(final Account account, final MessagingListener ml) { putBackground("recreate:" + account.getDescription(), ml, new Runnable() { public void run() { try { LocalStore localStore = account.getLocalStore(); long oldSize = localStore.getSize(); localStore.recreate(); localStore.resetVisibleLimits(account.getDisplayCount()); long newSize = localStore.getSize(); AccountStats stats = new AccountStats(); stats.size = newSize; stats.unreadMessageCount = 0; stats.flaggedMessageCount = 0; if (ml != null) { ml.accountSizeChanged(account, oldSize, newSize); ml.accountStatusChanged(account, stats); } for (MessagingListener l : getListeners()) { l.accountSizeChanged(account, oldSize, newSize); l.accountStatusChanged(account, stats); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e); } } }); } /** Creates a notification of new email messages * ringtone, lights, and vibration to be played */ private boolean notifyAccount(Context context, Account account, Message message) { int unreadMessageCount = 0; try { AccountStats stats = account.getStats(context); unreadMessageCount = stats.unreadMessageCount; } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e); } // Do not notify if the user does not have notifications // enabled or if the message has been read if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN)) { return false; } Folder folder = message.getFolder(); if (folder != null) { // No notification for new messages in Trash, Drafts, or Sent folder. // But do notify if it's the INBOX (see issue 1817). String folderName = folder.getName(); if (!K9.INBOX.equals(folderName) && (account.getTrashFolderName().equals(folderName) || account.getDraftsFolderName().equals(folderName) || account.getSentFolderName().equals(folderName))) { return false; } } // If we have a message, set the notification to "<From>: <Subject>" StringBuffer messageNotice = new StringBuffer(); try { if (message != null && message.getFrom() != null) { Address[] fromAddrs = message.getFrom(); String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null; String subject = message.getSubject(); if (subject == null) { subject = context.getString(R.string.general_no_subject); } if (from != null) { // Show From: address by default if (account.isAnIdentity(fromAddrs) == false) { messageNotice.append(from + ": " + subject); } // show To: if the message was sent from me else { // Do not notify of mail from self if !isNotifySelfNewMail if (!account.isNotifySelfNewMail()) { return false; } Address[] rcpts = message.getRecipients(Message.RecipientType.TO); String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null; if (to != null) { messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject); } else { messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject); } } } } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e); } // If we could not set a per-message notification, revert to a default message if (messageNotice.length() == 0) { messageNotice.append(context.getString(R.string.notification_new_title)); } NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis()); notif.number = unreadMessageCount; Intent i = FolderList.actionHandleNotification(context, account, account.getAutoExpandFolderName()); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, account.getDescription()); notif.setLatestEventInfo(context, accountNotice, messageNotice, pi); // Only ring or vibrate if we have not done so already on this // account and fetch if (!account.isRingNotified()) { account.setRingNotified(true); if (account.shouldRing()) { String ringtone = account.getRingtone(); notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone); } if (account.isVibrate()) { int times = account.getVibrateTimes(); long[] pattern1 = new long[] {100,200}; long[] pattern2 = new long[] {100,500}; long[] pattern3 = new long[] {200,200}; long[] pattern4 = new long[] {200,500}; long[] pattern5 = new long[] {500,500}; long[] src = null; switch (account.getVibratePattern()) { case 1: src = pattern1; break; case 2: src = pattern2; break; case 3: src = pattern3; break; case 4: src = pattern4; break; case 5: src = pattern5; break; default: notif.defaults |= Notification.DEFAULT_VIBRATE; break; } if (src != null) { long[] dest = new long[src.length * times]; for (int n = 0; n < times; n++) { System.arraycopy(src, 0, dest, n * src.length, src.length); } notif.vibrate = dest; } } } notif.flags |= Notification.FLAG_SHOW_LIGHTS; notif.ledARGB = account.getLedColor(); notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME; notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME; notif.audioStreamType = AudioManager.STREAM_NOTIFICATION; notifMgr.notify(account.getAccountNumber(), notif); return true; } /** Cancel a notification of new email messages */ public void notifyAccountCancel(Context context, Account account) { NotificationManager notifMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(account.getAccountNumber()); notifMgr.cancel(-1000 - account.getAccountNumber()); } public Message saveDraft(final Account account, final Message message) { Message localMessage = null; try { LocalStore localStore = account.getLocalStore(); LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(OpenMode.READ_WRITE); localFolder.appendMessages(new Message[] { message }); localMessage = localFolder.getMessage(message.getUid()); localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); PendingCommand command = new PendingCommand(); command.command = PENDING_COMMAND_APPEND; command.arguments = new String[] { localFolder.getName(), localMessage.getUid() }; queuePendingCommand(account, command); processPendingCommands(account); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to save message as draft.", e); addErrorMessage(account, null, e); } return localMessage; } public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode) { if (aMode == Account.FolderMode.NONE || (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { return true; } else { return false; } } static AtomicInteger sequencing = new AtomicInteger(0); class Command implements Comparable<Command> { public Runnable runnable; public MessagingListener listener; public String description; boolean isForeground; int sequence = sequencing.getAndIncrement(); @Override public int compareTo(Command other) { if (other.isForeground == true && isForeground == false) { return 1; } else if (other.isForeground == false && isForeground == true) { return -1; } else { return (sequence - other.sequence); } } } public MessagingListener getCheckMailListener() { return checkMailListener; } public void setCheckMailListener(MessagingListener checkMailListener) { if (this.checkMailListener != null) { removeListener(this.checkMailListener); } this.checkMailListener = checkMailListener; if (this.checkMailListener != null) { addListener(this.checkMailListener); } } public SORT_TYPE getSortType() { return sortType; } public void setSortType(SORT_TYPE sortType) { this.sortType = sortType; } public boolean isSortAscending(SORT_TYPE sortType) { Boolean sortAsc = sortAscending.get(sortType); if (sortAsc == null) { return sortType.isDefaultAscending(); } else return sortAsc; } public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending) { sortAscending.put(sortType, nsortAscending); } public Collection<Pusher> getPushers() { return pushers.values(); } public boolean setupPushing(final Account account) { try { Pusher previousPusher = pushers.remove(account); if (previousPusher != null) { previousPusher.stop(); } Preferences prefs = Preferences.getPreferences(mApplication); Account.FolderMode aDisplayMode = account.getFolderDisplayMode(); Account.FolderMode aPushMode = account.getFolderPushMode(); List<String> names = new ArrayList<String>(); Store localStore = account.getLocalStore(); for (final Folder folder : localStore.getPersonalNamespaces(false)) { if (folder.getName().equals(account.getErrorFolderName()) || folder.getName().equals(account.getOutboxFolderName())) { if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which should never be pushed"); continue; } folder.open(Folder.OpenMode.READ_WRITE); folder.refresh(prefs); Folder.FolderClass fDisplayClass = folder.getDisplayClass(); Folder.FolderClass fPushClass = folder.getPushClass(); if (modeMismatch(aDisplayMode, fDisplayClass)) { // Never push a folder that isn't displayed if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode); continue; } if (modeMismatch(aPushMode, fPushClass)) { // Do not push folders in the wrong class if (K9.DEBUG && false) Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() + " which is in push mode " + fPushClass + " while account is in push mode " + aPushMode); continue; } if (K9.DEBUG) Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName()); names.add(folder.getName()); } if (names.size() > 0) { PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this); int maxPushFolders = account.getMaxPushFolders(); if (names.size() > maxPushFolders) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size() + ", greater than limit of " + maxPushFolders + ", truncating"); names = names.subList(0, maxPushFolders); } try { Store store = account.getRemoteStore(); if (store.isPushCapable() == false) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping"); return false; } Pusher pusher = store.getPusher(receiver); if (pusher != null) { Pusher oldPusher = pushers.putIfAbsent(account, pusher); if (oldPusher == null) { pusher.start(names); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); return false; } return true; } else { if (K9.DEBUG) Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription()); return false; } } catch (Exception e) { Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e); } return false; } public void stopAllPushing() { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Stopping all pushers"); Iterator<Pusher> iter = pushers.values().iterator(); while (iter.hasNext()) { Pusher pusher = iter.next(); iter.remove(); pusher.stop(); } } public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription() + ", folder " + remoteFolder.getName()); final CountDownLatch latch = new CountDownLatch(1); putBackground("Push messageArrived of account " + account.getDescription() + ", folder " + remoteFolder.getName(), null, new Runnable() { public void run() { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder= localStore.getFolder(remoteFolder.getName()); localFolder.open(OpenMode.READ_WRITE); account.setRingNotified(false); int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly); int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size()); setLocalFlaggedCountToRemote(localFolder, remoteFolder); localFolder.setLastPush(System.currentTimeMillis()); localFolder.setStatus(null); if (K9.DEBUG) Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount); if (unreadMessageCount == 0) { notifyAccountCancel(mApplication, account); } for (MessagingListener l : getListeners()) { l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount); } } catch (Exception e) { String rootMessage = getRootCauseMessage(e); String errorMessage = "Push failed: " + rootMessage; try { localFolder.setStatus(errorMessage); } catch (Exception se) { Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se); } for (MessagingListener l : getListeners()) { l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage); } addErrorMessage(account, null, e); } finally { if (localFolder != null) { try { localFolder.close(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to close localFolder", e); } } latch.countDown(); } } }); try { latch.await(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e); } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released"); } enum MemorizingState { STARTED, FINISHED, FAILED }; class Memory { Account account; String folderName; MemorizingState syncingState = null; MemorizingState sendingState = null; MemorizingState pushingState = null; MemorizingState processingState = null; String failureMessage = null; int syncingTotalMessagesInMailbox; int syncingNumNewMessages; int folderCompleted = 0; int folderTotal = 0; String processingCommandTitle = null; Memory(Account nAccount, String nFolderName) { account = nAccount; folderName = nFolderName; } String getKey() { return getMemoryKey(account, folderName); } } static String getMemoryKey(Account taccount, String tfolderName) { return taccount.getDescription() + ":" + tfolderName; } class MemorizingListener extends MessagingListener { HashMap<String, Memory> memories = new HashMap<String, Memory>(31); Memory getMemory(Account account, String folderName) { Memory memory = memories.get(getMemoryKey(account, folderName)); if (memory == null) { memory = new Memory(account, folderName); memories.put(memory.getKey(), memory); } return memory; } @Override public synchronized void synchronizeMailboxStarted(Account account, String folder) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FINISHED; memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox; memory.syncingNumNewMessages = numNewMessages; } @Override public synchronized void synchronizeMailboxFailed(Account account, String folder, String message) { Memory memory = getMemory(account, folder); memory.syncingState = MemorizingState.FAILED; memory.failureMessage = message; } synchronized void refreshOther(MessagingListener other) { if (other != null) { Memory syncStarted = null; Memory sendStarted = null; Memory processingStarted = null; for (Memory memory : memories.values()) { if (memory.syncingState != null) { switch (memory.syncingState) { case STARTED: syncStarted = memory; break; case FINISHED: other.synchronizeMailboxFinished(memory.account, memory.folderName, memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages); break; case FAILED: other.synchronizeMailboxFailed(memory.account, memory.folderName, memory.failureMessage); break; } } if (memory.sendingState != null) { switch (memory.sendingState) { case STARTED: sendStarted = memory; break; case FINISHED: other.sendPendingMessagesCompleted(memory.account); break; case FAILED: other.sendPendingMessagesFailed(memory.account); break; } } if (memory.pushingState != null) { switch (memory.pushingState) { case STARTED: other.setPushActive(memory.account, memory.folderName, true); break; case FINISHED: other.setPushActive(memory.account, memory.folderName, false); break; } } if (memory.processingState != null) { switch (memory.processingState) { case STARTED: processingStarted = memory; break; case FINISHED: case FAILED: other.pendingCommandsFinished(memory.account); break; } } } Memory somethingStarted = null; if (syncStarted != null) { other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName); somethingStarted = syncStarted; } if (sendStarted != null) { other.sendPendingMessagesStarted(sendStarted.account); somethingStarted = sendStarted; } if (processingStarted != null) { other.pendingCommandsProcessing(processingStarted.account); if (processingStarted.processingCommandTitle != null) { other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle); } else { other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle); } somethingStarted = processingStarted; } if (somethingStarted != null && somethingStarted.folderTotal > 0) { other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal); } } } @Override public synchronized void setPushActive(Account account, String folderName, boolean active) { Memory memory = getMemory(account, folderName); memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED); } @Override public synchronized void sendPendingMessagesStarted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void sendPendingMessagesCompleted(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FINISHED; } @Override public synchronized void sendPendingMessagesFailed(Account account) { Memory memory = getMemory(account, null); memory.sendingState = MemorizingState.FAILED; } @Override public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total) { Memory memory = getMemory(account, folderName); memory.folderCompleted = completed; memory.folderTotal = total; } @Override public synchronized void pendingCommandsProcessing(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.STARTED; memory.folderCompleted = 0; memory.folderTotal = 0; } @Override public synchronized void pendingCommandsFinished(Account account) { Memory memory = getMemory(account, null); memory.processingState = MemorizingState.FINISHED; } @Override public synchronized void pendingCommandStarted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = commandTitle; } @Override public synchronized void pendingCommandCompleted(Account account, String commandTitle) { Memory memory = getMemory(account, null); memory.processingCommandTitle = null; } } private void actOnMessages(Message[] messages, MessageActor actor) { Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>(); for (Message message : messages) { Folder folder = message.getFolder(); Account account = folder.getAccount(); Map<Folder, List<Message>> folderMap = accountMap.get(account); if (folderMap == null) { folderMap = new HashMap<Folder, List<Message>>(); accountMap.put(account, folderMap); } List<Message> messageList = folderMap.get(folder); if (messageList == null) { messageList = new LinkedList<Message>(); folderMap.put(folder, messageList); } messageList.add(message); } for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet()) { Account account = entry.getKey(); //account.refresh(Preferences.getPreferences(K9.app)); Map<Folder, List<Message>> folderMap = entry.getValue(); for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet()) { Folder folder = folderEntry.getKey(); List<Message> messageList = folderEntry.getValue(); actor.act(account, folder, messageList); } } } interface MessageActor { public void act(final Account account, final Folder folder, final List<Message> messages); } }
since we're checking seen status within the notify method, (first thing, even), we don't need to do it in the caller code.
src/com/fsck/k9/controller/MessagingController.java
since we're checking seen status within the notify method, (first thing, even), we don't need to do it in the caller code.
Java
bsd-3-clause
2e7881de263ea0f3e601733f79fd3ab5cd6b77ff
0
ibnemahdi/owasp-esapi-java,ibnemahdi/owasp-esapi-java,Fierozen/owasp-esapi-java,ibnemahdi/owasp-esapi-java,Fierozen/owasp-esapi-java,Fierozen/owasp-esapi-java
/** * OWASP Enterprise Security API (ESAPI) * * This file is part of the Open Web Application Security Project (OWASP) * Enterprise Security API (ESAPI) project. For details, please see * http://www.owasp.org/esapi. * * Copyright (c) 2007 - The OWASP Foundation * * The ESAPI is published by OWASP under the LGPL. You should read and accept the * LICENSE before you use, modify, and/or redistribute this software. * * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @created 2007 */ package org.owasp.esapi.interfaces; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.owasp.esapi.User; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.EncryptionException; /** * The IAuthenticator interface defines a set of methods for generating and * handling account credentials and session identifiers. The goal of this * interface is to encourage developers to protect credentials from disclosure * to the maximum extent possible. * <P> * <img src="doc-files/Authenticator.jpg" height="600"> * <P> * Once possible implementation relies on the use of a thread local variable to * store the current user's identity. The application is responsible for calling * setCurrentUser() as soon as possible after each HTTP request is received. The * value of getCurrentUser() is used in several other places in this API. This * eliminates the need to pass a user object to methods throughout the library. * For example, all of the logging, access control, and exception calls need * access to the currently logged in user. * <P> * The goal is to minimize the responsibility of the developer for * authentication. In this example, the user simply calls authenticate with the * current request and the name of the parameters containing the username and * password. The implementation should verify the password if necessary, create * a session if necessary, and set the user as the current user. * * <pre> * public void doPost(ServletRequest request, ServletResponse response) { * try { * ESAPI.authenticator().authenticate(request, response, &quot;username&quot;,&quot;password&quot;); * // continue with authenticated user * } catch (AuthenticationException e) { * // handle failed authentication (it's already been logged) * } * </pre> * * @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a * href="http://www.aspectsecurity.com">Aspect Security</a> * @since June 1, 2007 */ public interface IAuthenticator { /** * Clear the current user, request, and response. This allows the thread to be reused safely. */ void clearCurrent(); /** * Authenticates the user's credentials from the HttpServletRequest if * necessary, creates a session if necessary, and sets the user as the * current user. * * @param request * the current HTTP request * @param response * the response * * @return the user * * @throws AuthenticationException * the authentication exception */ User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException; // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Logs out the current user. */ void logout(); /** * Creates the user. * * @param accountName * the account name * @param password1 * the password * @param password2 * copy of the password * * @return the new User object * * @throws AuthenticationException * the authentication exception */ User createUser(String accountName, String password1, String password2) throws AuthenticationException; // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Generate a strong password. * * @return the string */ String generateStrongPassword(); /** * Generate strong password that takes into account the user's information and old password. * * @param oldPassword * the old password * @param user * the user * * @return the string */ String generateStrongPassword(String oldPassword, IUser user); /** * Returns the User matching the provided accountName. * * @param accountName * the account name * * @return the matching User object, or null if no match exists */ User getUser(String accountName); // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Gets the user names. * * @return the user names */ Set getUserNames(); /** * Returns the currently logged in User. * * @return the matching User object, or the Anonymous user if no match * exists */ User getCurrentUser(); // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Sets the currently logged in User. * * @param user * the current user */ void setCurrentUser(IUser user); /** * Returns a string representation of the hashed password, using the * accountName as the salt. The salt helps to prevent against "rainbow" * table attacks where the attacker pre-calculates hashes for known strings. * * @param password * the password * @param accountName * the account name * * @return the string */ String hashPassword(String password, String accountName) throws EncryptionException; /** * Removes the account. * * @param accountName * the account name * * @throws AuthenticationException * the authentication exception */ void removeUser(String accountName) throws AuthenticationException; /** * Validate password strength. * * @param accountName * the account name * * @return true, if successful * * @throws AuthenticationException * the authentication exception */ void verifyAccountNameStrength(String context, String accountName) throws AuthenticationException; /** * Validate password strength. * * @param newPassword * the new password * @param oldPassword * the old password * @return true, if successful * * @throws AuthenticationException * the authentication exception */ void verifyPasswordStrength(String newPassword, String oldPassword) throws AuthenticationException; /** * Verifies the account exists. * * @param accountName * the account name * * @return true, if successful */ boolean exists(String accountName); }
src/org/owasp/esapi/interfaces/IAuthenticator.java
/** * OWASP Enterprise Security API (ESAPI) * * This file is part of the Open Web Application Security Project (OWASP) * Enterprise Security API (ESAPI) project. For details, please see * http://www.owasp.org/esapi. * * Copyright (c) 2007 - The OWASP Foundation * * The ESAPI is published by OWASP under the LGPL. You should read and accept the * LICENSE before you use, modify, and/or redistribute this software. * * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @created 2007 */ package org.owasp.esapi.interfaces; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.owasp.esapi.User; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.EncryptionException; /** * The IAuthenticator interface defines a set of methods for generating and * handling account credentials and session identifiers. The goal of this * interface is to encourage developers to protect credentials from disclosure * to the maximum extent possible. * <P> * <img src="doc-files/Authenticator.jpg" height="600"> * <P> * Once possible implementation relies on the use of a thread local variable to * store the current user's identity. The application is responsible for calling * setCurrentUser() as soon as possible after each HTTP request is received. The * value of getCurrentUser() is used in several other places in this API. This * eliminates the need to pass a user object to methods throughout the library. * For example, all of the logging, access control, and exception calls need * access to the currently logged in user. * <P> * The goal is to minimize the responsibility of the developer for * authentication. In this example, the user simply calls authenticate with the * current request and the name of the parameters containing the username and * password. The implementation should verify the password if necessary, create * a session if necessary, and set the user as the current user. * * <pre> * public void doPost(ServletRequest request, ServletResponse response) { * try { * ESAPI.authenticator().authenticate(request, response, &quot;username&quot;,&quot;password&quot;); * // continue with authenticated user * } catch (AuthenticationException e) { * // handle failed authentication (it's already been logged) * } * </pre> * * @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a * href="http://www.aspectsecurity.com">Aspect Security</a> * @since June 1, 2007 */ public interface IAuthenticator { /** * Clear the current user, request, and response. This allows the thread to be reused safely. */ void clearCurrent(); /** * Authenticates the user's credentials from the HttpServletRequest if * necessary, creates a session if necessary, and sets the user as the * current user. * * @param request * the current HTTP request * @param response * the response * * @return the user * * @throws AuthenticationException * the authentication exception */ User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException; // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Logs out the current user. */ void logout(); /** * Creates the user. * * @param accountName * the account name * @param password1 * the password * @param password2 * copy of the password * * @return the new User object * * @throws AuthenticationException * the authentication exception */ User createUser(String accountName, String password1, String password2) throws AuthenticationException; // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Generate a strong password. * * @return the string */ String generateStrongPassword(); /** * Generate strong password that takes into account the user's information and old password. * * @param oldPassword * the old password * @param user * the user * * @return the string */ String generateStrongPassword(String oldPassword, IUser user); /** * Returns the User matching the provided accountName. * * @param accountName * the account name * * @return the matching User object, or null if no match exists */ User getUser(String accountName); // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Gets the user names. * * @return the user names */ Set getUserNames(); /** * Returns the currently logged in User. * * @return the matching User object, or the Anonymous user if no match * exists */ User getCurrentUser(); // FIXME: Future - Should return IUser, works in Java 1.5+ but hacked here for Java 1.4 /** * Sets the currently logged in User. * * @param user * the current user */ void setCurrentUser(IUser user); /** * Returns a string representation of the hashed password, using the * accountName as the salt. The salt helps to prevent against "rainbow" * table attacks where the attacker pre-calculates hashes for known strings. * * @param password * the password * @param accountName * the account name * * @return the string */ String hashPassword(String password, String accountName) throws EncryptionException; /** * Removes the account. * * @param accountName * the account name * * @throws AuthenticationException * the authentication exception */ void removeUser(String accountName) throws AuthenticationException; /** * Validate password strength. * * @param accountName * the account name * * @return true, if successful * * @throws AuthenticationException * the authentication exception */ void verifyAccountNameStrength(String context, String accountName) throws AuthenticationException; /** * Validate password strength. * * @param oldPassword * the old password * @param newPassword * the new password * * @return true, if successful * * @throws AuthenticationException * the authentication exception */ void verifyPasswordStrength(String oldPassword, String newPassword) throws AuthenticationException; /** * Verifies the account exists. * * @param accountName * the account name * * @return true, if successful */ boolean exists(String accountName); }
fixed order of arguments in verifyPasswordStrength to match reference implementation
src/org/owasp/esapi/interfaces/IAuthenticator.java
fixed order of arguments in verifyPasswordStrength to match reference implementation
Java
bsd-3-clause
add7ecc6b79e811c9de08950da8ade4156e18952
0
aic-sri-international/aic-expresso,aic-sri-international/aic-expresso
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso 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 com.sri.ai.grinder.sgdpllt.core.solver; import static com.sri.ai.expresso.api.IntensionalSet.intensionalMultiSet; import static com.sri.ai.expresso.helper.Expressions.FALSE; import static com.sri.ai.expresso.helper.Expressions.ONE; import static com.sri.ai.expresso.helper.Expressions.TRUE; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.expresso.helper.Expressions.makeSymbol; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.MAX; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.PRODUCT; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.SUM; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.getCondition; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.getIndexExpressions; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.isCountingFormulaEquivalentExpression; import static com.sri.ai.grinder.sgdpllt.library.set.Sets.isIntensionalMultiSet; import static com.sri.ai.grinder.sgdpllt.theory.base.ExpressionConditionedOnLiteralSolutionStep.stepDependingOnLiteral; import static com.sri.ai.util.Util.list; import static com.sri.ai.util.Util.map; import static com.sri.ai.util.collect.StackedHashMap.stackedHashMap; import java.util.Collection; import java.util.Map; import com.google.common.annotations.Beta; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.api.QuantifiedExpression; import com.sri.ai.expresso.type.FunctionType; import com.sri.ai.grinder.sgdpllt.api.Context; import com.sri.ai.grinder.sgdpllt.api.ExpressionLiteralSplitterStepSolver; import com.sri.ai.grinder.sgdpllt.api.QuantifierEliminator; import com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup; import com.sri.ai.grinder.sgdpllt.group.Conjunction; import com.sri.ai.grinder.sgdpllt.group.Disjunction; import com.sri.ai.grinder.sgdpllt.group.Max; import com.sri.ai.grinder.sgdpllt.group.Product; import com.sri.ai.grinder.sgdpllt.group.Sum; import com.sri.ai.grinder.sgdpllt.group.SumProduct; import com.sri.ai.grinder.sgdpllt.interpreter.BruteForceCommonInterpreter; import com.sri.ai.grinder.sgdpllt.interpreter.SGDPLLT; import com.sri.ai.grinder.sgdpllt.library.boole.ForAll; import com.sri.ai.grinder.sgdpllt.library.boole.ThereExists; import com.sri.ai.grinder.sgdpllt.library.indexexpression.IndexExpressions; import com.sri.ai.grinder.sgdpllt.simplifier.api.Simplifier; import com.sri.ai.grinder.sgdpllt.simplifier.api.TopSimplifier; import com.sri.ai.grinder.sgdpllt.simplifier.core.Recursive; import com.sri.ai.grinder.sgdpllt.simplifier.core.TopExhaustive; import com.sri.ai.util.Util; import com.sri.ai.util.base.IdentityWrapper; /** * A step solver for symbolically evaluating an expression. * <p> * Currently supports only expressions that are composed of function applications or symbols. * * This step solver implements the following pseudo-code: * <pre> * An evaluator step solver for an expression E keeps: * - a map Evaluators from identity wrappers * of the sub-expression of E to their own evaluator step solver * (this allows us to remember sequel step solvers obtained from previous attempts at evaluating each sub-expression). * - the index SEIndex of the next sub-expression to be analyzed. * All sub-expressions with indices less than SEIndex are considered fully evaluated. Its step is: E <- exhaustively top-simplify E if not already so if E is a literal split on it with sequel step solvers true and false else if SEIndex != E.numberOfArguments // not yet evaluated all sub-expressions SE <- E.get(SEIndex) SEEvaluator <- Evaluators(SE), or make a new one // this may re-use sequel step solver for SE from previous attempt SEStep <- SEEvaluator.step if SEStep depends on L with sub step solvers S1 and S2 return ItDependsOn on literal L with two sequel step solvers (for evaluating E) for cases L true and L false. The sequel step solver for L true (false) contains a Evaluators(SE) map modified to map SE to its own sequel solver, provided by SEStep for when L is true (false). else SEvalue <- SEStep.getValue() // for abbreviation only if SEvalue == SE // no change to SE, so no change to E. Just move on to next sub-expression Evaluator' <- clone Evaluator'.Evaluators <- stacked map on Evaluators with new entry { SE -> SEEvaluator // so we remember the solution if a future simplification surfaces an already fully evaluated sub-expression, including SE, as E' Evaluator'.SEIndex++ // go to next sub-expression return Evaluator'.step() else E' <- exhaustively top-simplify(E[SE/SEvalue]) if E' == SE // E has been reduced to SE itself, which we just evaluated, so we just return the step for SE return SEStep else Evaluator' <- Evaluators(E') // E' may be a previously evaluated sub-expression or not; re-use evaluator or make a new one return Evaluator'.step else return Solution(E) // Remember: step solver assumes sub-expressions before SEIndex fully evaluated and E top-simplified already wrt them </pre> * @author braz * */ @Beta public class EvaluatorStepSolver implements ExpressionLiteralSplitterStepSolver { private static interface Rewriter { public Step rewrite(Expression expression, Context context); }; private Expression expression; private boolean alreadyExhaustivelyTopSimplified; private int subExpressionIndex; private Map<IdentityWrapper, ExpressionLiteralSplitterStepSolver> evaluators; public EvaluatorStepSolver(Expression expression) { super(); this.expression = expression; this.subExpressionIndex = 0; this.evaluators = map(); this.alreadyExhaustivelyTopSimplified = false; } @Override public EvaluatorStepSolver clone() { EvaluatorStepSolver result = null; try { result = (EvaluatorStepSolver) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return result; } private EvaluatorStepSolver cloneWithAnotherExpression(Expression newExpression, boolean alreadyExhaustivelyTopSimplified) { EvaluatorStepSolver result = clone(); result.expression = newExpression; result.subExpressionIndex = 0; result.alreadyExhaustivelyTopSimplified = alreadyExhaustivelyTopSimplified; return result; } public Expression getExpression() { return expression; } Collection<Rewriter> rewriters; @Override public Step step(Context context) { Step result = null; TopSimplifier topSimplifier = context.getTheory().getMapBasedTopSimplifier(); TopSimplifier exhaustiveTopSimplifier = new TopExhaustive(topSimplifier); Expression exhaustivelyTopSimplifiedExpression; if (alreadyExhaustivelyTopSimplified) { exhaustivelyTopSimplifiedExpression = expression; } else { exhaustivelyTopSimplifiedExpression = exhaustiveTopSimplifier.apply(expression, context); } rewriters = Util.<Rewriter>list( (Expression e, Context c) -> { if (c.isLiteral(e)) { Simplifier totalSimplifier = new Recursive(exhaustiveTopSimplifier); Expression completelySimplifiedLiteral = totalSimplifier.apply(e, c); return stepDependingOnLiteral(completelySimplifiedLiteral, TRUE, FALSE, c); } else { return null; } } , (Expression e, Context c) -> { if (fromFunctorToGroup.containsKey(e.getFunctor())&& isIntensionalMultiSet(e.get(0)) ) { if (isQuantifierOverFunctions((QuantifiedExpression)e.get(0), c)) { // TODO - more optimal approach return getQuantificationOverFunctionsSolutionUsingBruteForce(e, c); } else { QuantifierEliminator quantifierEliminator; if (e.hasFunctor(SUM)) { // take advantage of factorized bodies, if available quantifierEliminator = new SGVET(new SumProduct()); } else { AssociativeCommutativeGroup group = fromFunctorToGroup.get(e.getFunctor()); quantifierEliminator = new SGDPLLT(group); } Expression quantifierFreeExpression = quantifierEliminator.solve(e, c); return new Solution(quantifierFreeExpression); } } else { return null; } } , (Expression e, Context c) -> { if (isCountingFormulaEquivalentExpression(e)) { // | {{ (on I) Head : Condition }} | ---> sum ( {{ (on I) 1 : Condition }} ) // or: // | I : Condition | --> sum({{ (on I) 1 : Condition }}) Expression set = intensionalMultiSet(getIndexExpressions(e), ONE, getCondition(e)); Expression functionOnSet = apply(SUM, set); if (isQuantifierOverFunctions((QuantifiedExpression) set, c)) { // TODO - more optimal approach return getQuantificationOverFunctionsSolutionUsingBruteForce(functionOnSet, c); } else { QuantifierEliminator sgvet = new SGVET(new SumProduct()); Expression quantifierFreeExpression = sgvet.solve(functionOnSet, c); return new Solution(quantifierFreeExpression); } } else return null; } ); for (Rewriter rewriter : rewriters) { if (result == null) { result = rewriter.rewrite(exhaustivelyTopSimplifiedExpression, context); } } if (result == null) { // if (context.isLiteral(exhaustivelyTopSimplifiedExpression)) { // Simplifier totalSimplifier = new Recursive(exhaustiveTopSimplifier); // Expression completelySimplifiedLiteral = totalSimplifier.apply(exhaustivelyTopSimplifiedExpression, context); // result = stepDependingOnLiteral(completelySimplifiedLiteral, TRUE, FALSE, context); // } // TODO: the next few cases always produce solver steps, never a ItDependsOn solver step. // We should eventually use quantifier eliminator step solvers that may return ItDependsOn solver steps // else // if (fromFunctorToGroup.containsKey(expression.getFunctor())&& isIntensionalMultiSet(expression.get(0)) ) { // if (isQuantifierOverFunctions((QuantifiedExpression)expression.get(0), context)) { // // TODO - more optimal approach // result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); // } // else { // QuantifierEliminator quantifierEliminator; // if (expression.hasFunctor(SUM)) { // take advantage of factorized bodies, if available // quantifierEliminator = new SGVET(new SumProduct()); // } // else { // AssociativeCommutativeGroup group = fromFunctorToGroup.get(expression.getFunctor()); // quantifierEliminator = new SGDPLLT(group); // } // Expression quantifierFreeExpression = quantifierEliminator.solve(expression, context); // result = new Solution(quantifierFreeExpression); // } // } // else // if (isCountingFormulaEquivalentExpression(expression)) { // // | {{ (on I) Head : Condition }} | ---> sum ( {{ (on I) 1 : Condition }} ) // // or: // // | I : Condition | --> sum({{ (on I) 1 : Condition }}) // Expression set = intensionalMultiSet(getIndexExpressions(expression), ONE, getCondition(expression)); // Expression functionOnSet = apply(SUM, set); // if (isQuantifierOverFunctions((QuantifiedExpression) set, context)) { // // TODO - more optimal approach // result = getQuantificationOverFunctionsSolutionUsingBruteForce(functionOnSet, context); // } // else { // QuantifierEliminator sgvet = new SGVET(new SumProduct()); // Expression quantifierFreeExpression = sgvet.solve(functionOnSet, context); // result = new Solution(quantifierFreeExpression); // } // } // else if (expression.getSyntacticFormType().equals(ForAll.SYNTACTIC_FORM_TYPE)) { if (isQuantifierOverFunctions((QuantifiedExpression) expression, context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); } else { QuantifierEliminator sgdpllt = new SGDPLLT(new Conjunction()); Expression resultExpression = sgdpllt.solve(expression, context); result = new Solution(resultExpression); } } else if (expression.getSyntacticFormType().equals(ThereExists.SYNTACTIC_FORM_TYPE)) { if (isQuantifierOverFunctions((QuantifiedExpression) expression, context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); } else { QuantifierEliminator sgdpllt = new SGDPLLT(new Disjunction()); Expression resultExpression = sgdpllt.solve(expression, context); result = new Solution(resultExpression); } } } if (result == null) { if (subExpressionIndex != exhaustivelyTopSimplifiedExpression.numberOfArguments()) { Expression subExpression = exhaustivelyTopSimplifiedExpression.get(subExpressionIndex); ExpressionLiteralSplitterStepSolver subExpressionEvaluator = getEvaluatorFor(subExpression, false /* not known to be exhaustively top-simplified already */); Step subExpressionStep = subExpressionEvaluator.step(context); if (subExpressionStep == null) { return null; } if (subExpressionStep.itDepends()) { EvaluatorStepSolver ifTrue = clone(); ifTrue.setEvaluatorFor(subExpression, subExpressionStep.getStepSolverForWhenSplitterIsTrue()); EvaluatorStepSolver ifFalse = clone(); ifFalse.setEvaluatorFor(subExpression, subExpressionStep.getStepSolverForWhenSplitterIsFalse()); result = new ItDependsOn( subExpressionStep.getSplitterLiteral(), subExpressionStep.getContextSplittingWhenSplitterIsLiteral(), ifTrue, ifFalse); } else if (subExpressionStep.getValue() == subExpression) { // no change, just record the evaluator for this sub-expression and move on to the next one ExpressionLiteralSplitterStepSolver nextStepSolver; nextStepSolver = clone(); ((EvaluatorStepSolver) nextStepSolver).setEvaluatorFor(subExpression, subExpressionEvaluator); ((EvaluatorStepSolver) nextStepSolver).subExpressionIndex++; result = nextStepSolver.step(context); } else { Expression expressionWithSubExpressionReplacedByItsValue = exhaustivelyTopSimplifiedExpression.set(subExpressionIndex, subExpressionStep.getValue()); Expression exhaustivelyTopSimplifiedAfterSubExpressionEvaluation = exhaustiveTopSimplifier.apply(expressionWithSubExpressionReplacedByItsValue, context); if (exhaustivelyTopSimplifiedAfterSubExpressionEvaluation == subExpression) { // topSimplified turns out to be the sub-expression itself // we already know the result for that: the non-dependent subExpressionStep itself. return subExpressionStep; } else { // topSimplified is either a former sub-expression, or new. // try to reuse evaluator if available, or a make a new one, and use it ExpressionLiteralSplitterStepSolver nextStepSolver = getEvaluatorFor(exhaustivelyTopSimplifiedAfterSubExpressionEvaluation, true /* already top-simplified */); result = nextStepSolver.step(context); } } } else { result = new Solution(exhaustivelyTopSimplifiedExpression); } } return result; } private ExpressionLiteralSplitterStepSolver getEvaluatorFor(Expression anotherExpression, boolean alreadyExhaustivelyTopSimplified) { ExpressionLiteralSplitterStepSolver result = evaluators.get(anotherExpression); if (result == null) { result = cloneWithAnotherExpression(anotherExpression, alreadyExhaustivelyTopSimplified); setEvaluatorFor(anotherExpression, result); } return result; } private void setEvaluatorFor(Expression expression, ExpressionLiteralSplitterStepSolver stepSolver) { // make new map based on old one, without altering it evaluators = stackedHashMap(new IdentityWrapper(expression), stepSolver, evaluators); } @Override public String toString() { return "Evaluate " + expression + " from " + subExpressionIndex + "-th sub-expression on"; } private static boolean isQuantifierOverFunctions(QuantifiedExpression quantifiedExpression, Context context) { boolean result = false; for (Expression typeExpression : IndexExpressions.getIndexDomains(quantifiedExpression)) { if (context.getType(typeExpression) instanceof FunctionType) { result = true; break; } } return result; } private static Solution getQuantificationOverFunctionsSolutionUsingBruteForce(Expression expression, Context context) { BruteForceCommonInterpreter bruteForceCommonInterpreter = new BruteForceCommonInterpreter(); Expression quantifierFreeExpression = bruteForceCommonInterpreter.apply(expression, context); Solution result = new Solution(quantifierFreeExpression); return result; } private static Map<Expression, AssociativeCommutativeGroup> fromFunctorToGroup = map( makeSymbol(SUM), new Sum(), makeSymbol(MAX), new Max(), makeSymbol(PRODUCT), new Product() ); }
src/main/java/com/sri/ai/grinder/sgdpllt/core/solver/EvaluatorStepSolver.java
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso 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 com.sri.ai.grinder.sgdpllt.core.solver; import static com.sri.ai.expresso.api.IntensionalSet.intensionalMultiSet; import static com.sri.ai.expresso.helper.Expressions.FALSE; import static com.sri.ai.expresso.helper.Expressions.ONE; import static com.sri.ai.expresso.helper.Expressions.TRUE; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.expresso.helper.Expressions.makeSymbol; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.MAX; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.PRODUCT; import static com.sri.ai.grinder.sgdpllt.library.FunctorConstants.SUM; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.getCondition; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.getIndexExpressions; import static com.sri.ai.grinder.sgdpllt.library.set.CountingFormulaEquivalentExpressions.isCountingFormulaEquivalentExpression; import static com.sri.ai.grinder.sgdpllt.library.set.Sets.isIntensionalMultiSet; import static com.sri.ai.grinder.sgdpllt.theory.base.ExpressionConditionedOnLiteralSolutionStep.stepDependingOnLiteral; import static com.sri.ai.util.Util.map; import static com.sri.ai.util.collect.StackedHashMap.stackedHashMap; import java.util.Map; import com.google.common.annotations.Beta; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.api.QuantifiedExpression; import com.sri.ai.expresso.type.FunctionType; import com.sri.ai.grinder.sgdpllt.api.Context; import com.sri.ai.grinder.sgdpllt.api.ExpressionLiteralSplitterStepSolver; import com.sri.ai.grinder.sgdpllt.api.QuantifierEliminator; import com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup; import com.sri.ai.grinder.sgdpllt.group.Conjunction; import com.sri.ai.grinder.sgdpllt.group.Disjunction; import com.sri.ai.grinder.sgdpllt.group.Max; import com.sri.ai.grinder.sgdpllt.group.Product; import com.sri.ai.grinder.sgdpllt.group.Sum; import com.sri.ai.grinder.sgdpllt.group.SumProduct; import com.sri.ai.grinder.sgdpllt.interpreter.BruteForceCommonInterpreter; import com.sri.ai.grinder.sgdpllt.interpreter.SGDPLLT; import com.sri.ai.grinder.sgdpllt.library.boole.ForAll; import com.sri.ai.grinder.sgdpllt.library.boole.ThereExists; import com.sri.ai.grinder.sgdpllt.library.indexexpression.IndexExpressions; import com.sri.ai.grinder.sgdpllt.simplifier.api.Simplifier; import com.sri.ai.grinder.sgdpllt.simplifier.api.TopSimplifier; import com.sri.ai.grinder.sgdpllt.simplifier.core.Recursive; import com.sri.ai.grinder.sgdpllt.simplifier.core.TopExhaustive; import com.sri.ai.util.base.IdentityWrapper; /** * A step solver for symbolically evaluating an expression. * <p> * Currently supports only expressions that are composed of function applications or symbols. * * This step solver implements the following pseudo-code: * <pre> * An evaluator step solver for an expression E keeps: * - a map Evaluators from identity wrappers * of the sub-expression of E to their own evaluator step solver * (this allows us to remember sequel step solvers obtained from previous attempts at evaluating each sub-expression). * - the index SEIndex of the next sub-expression to be analyzed. * All sub-expressions with indices less than SEIndex are considered fully evaluated. Its step is: E <- exhaustively top-simplify E if not already so if E is a literal split on it with sequel step solvers true and false else if SEIndex != E.numberOfArguments // not yet evaluated all sub-expressions SE <- E.get(SEIndex) SEEvaluator <- Evaluators(SE), or make a new one // this may re-use sequel step solver for SE from previous attempt SEStep <- SEEvaluator.step if SEStep depends on L with sub step solvers S1 and S2 return ItDependsOn on literal L with two sequel step solvers (for evaluating E) for cases L true and L false. The sequel step solver for L true (false) contains a Evaluators(SE) map modified to map SE to its own sequel solver, provided by SEStep for when L is true (false). else SEvalue <- SEStep.getValue() // for abbreviation only if SEvalue == SE // no change to SE, so no change to E. Just move on to next sub-expression Evaluator' <- clone Evaluator'.Evaluators <- stacked map on Evaluators with new entry { SE -> SEEvaluator // so we remember the solution if a future simplification surfaces an already fully evaluated sub-expression, including SE, as E' Evaluator'.SEIndex++ // go to next sub-expression return Evaluator'.step() else E' <- exhaustively top-simplify(E[SE/SEvalue]) if E' == SE // E has been reduced to SE itself, which we just evaluated, so we just return the step for SE return SEStep else Evaluator' <- Evaluators(E') // E' may be a previously evaluated sub-expression or not; re-use evaluator or make a new one return Evaluator'.step else return Solution(E) // Remember: step solver assumes sub-expressions before SEIndex fully evaluated and E top-simplified already wrt them </pre> * @author braz * */ @Beta public class EvaluatorStepSolver implements ExpressionLiteralSplitterStepSolver { private Expression expression; private boolean alreadyExhaustivelyTopSimplified; private int subExpressionIndex; private Map<IdentityWrapper, ExpressionLiteralSplitterStepSolver> evaluators; public EvaluatorStepSolver(Expression expression) { super(); this.expression = expression; this.subExpressionIndex = 0; this.evaluators = map(); this.alreadyExhaustivelyTopSimplified = false; } @Override public EvaluatorStepSolver clone() { EvaluatorStepSolver result = null; try { result = (EvaluatorStepSolver) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return result; } private EvaluatorStepSolver cloneWithAnotherExpression(Expression newExpression, boolean alreadyExhaustivelyTopSimplified) { EvaluatorStepSolver result = clone(); result.expression = newExpression; result.subExpressionIndex = 0; result.alreadyExhaustivelyTopSimplified = alreadyExhaustivelyTopSimplified; return result; } public Expression getExpression() { return expression; } @Override public Step step(Context context) { Step result; TopSimplifier topSimplifier = context.getTheory().getMapBasedTopSimplifier(); TopSimplifier exhaustiveTopSimplifier = new TopExhaustive(topSimplifier); Simplifier totalSimplifier = new Recursive(exhaustiveTopSimplifier); Expression exhaustivelyTopSimplifiedExpression; if (alreadyExhaustivelyTopSimplified) { exhaustivelyTopSimplifiedExpression = expression; } else { exhaustivelyTopSimplifiedExpression = exhaustiveTopSimplifier.apply(expression, context); } if (context.isLiteral(exhaustivelyTopSimplifiedExpression)) { Expression completelySimplifiedLiteral = totalSimplifier.apply(exhaustivelyTopSimplifiedExpression, context); result = stepDependingOnLiteral(completelySimplifiedLiteral, TRUE, FALSE, context); } // TODO: the next few cases always produce solver steps, never a ItDependsOn solver step. // We should eventually use quantifier eliminator step solvers that may return ItDependsOn solver steps else if (fromFunctorToGroup.containsKey(expression.getFunctor())&& isIntensionalMultiSet(expression.get(0)) ) { if (isQuantifierOverFunctions((QuantifiedExpression)expression.get(0), context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); } else { QuantifierEliminator quantifierEliminator; if (expression.hasFunctor(SUM)) { // take advantage of factorized bodies, if available quantifierEliminator = new SGVET(new SumProduct()); } else { AssociativeCommutativeGroup group = fromFunctorToGroup.get(expression.getFunctor()); quantifierEliminator = new SGDPLLT(group); } Expression quantifierFreeExpression = quantifierEliminator.solve(expression, context); result = new Solution(quantifierFreeExpression); } } else if (isCountingFormulaEquivalentExpression(expression)) { // | {{ (on I) Head : Condition }} | ---> sum ( {{ (on I) 1 : Condition }} ) // or: // | I : Condition | --> sum({{ (on I) 1 : Condition }}) Expression set = intensionalMultiSet(getIndexExpressions(expression), ONE, getCondition(expression)); Expression functionOnSet = apply(SUM, set); if (isQuantifierOverFunctions((QuantifiedExpression) set, context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(functionOnSet, context); } else { QuantifierEliminator sgvet = new SGVET(new SumProduct()); Expression quantifierFreeExpression = sgvet.solve(functionOnSet, context); result = new Solution(quantifierFreeExpression); } } else if (expression.getSyntacticFormType().equals(ForAll.SYNTACTIC_FORM_TYPE)) { if (isQuantifierOverFunctions((QuantifiedExpression) expression, context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); } else { QuantifierEliminator sgdpllt = new SGDPLLT(new Conjunction()); Expression resultExpression = sgdpllt.solve(expression, context); result = new Solution(resultExpression); } } else if (expression.getSyntacticFormType().equals(ThereExists.SYNTACTIC_FORM_TYPE)) { if (isQuantifierOverFunctions((QuantifiedExpression) expression, context)) { // TODO - more optimal approach result = getQuantificationOverFunctionsSolutionUsingBruteForce(expression, context); } else { QuantifierEliminator sgdpllt = new SGDPLLT(new Disjunction()); Expression resultExpression = sgdpllt.solve(expression, context); result = new Solution(resultExpression); } } else if (subExpressionIndex != exhaustivelyTopSimplifiedExpression.numberOfArguments()) { Expression subExpression = exhaustivelyTopSimplifiedExpression.get(subExpressionIndex); ExpressionLiteralSplitterStepSolver subExpressionEvaluator = getEvaluatorFor(subExpression, false /* not known to be exhaustively top-simplified already */); Step subExpressionStep = subExpressionEvaluator.step(context); if (subExpressionStep == null) { return null; } if (subExpressionStep.itDepends()) { EvaluatorStepSolver ifTrue = clone(); ifTrue.setEvaluatorFor(subExpression, subExpressionStep.getStepSolverForWhenSplitterIsTrue()); EvaluatorStepSolver ifFalse = clone(); ifFalse.setEvaluatorFor(subExpression, subExpressionStep.getStepSolverForWhenSplitterIsFalse()); result = new ItDependsOn( subExpressionStep.getSplitterLiteral(), subExpressionStep.getContextSplittingWhenSplitterIsLiteral(), ifTrue, ifFalse); } else if (subExpressionStep.getValue() == subExpression) { // no change, just record the evaluator for this sub-expression and move on to the next one ExpressionLiteralSplitterStepSolver nextStepSolver; nextStepSolver = clone(); ((EvaluatorStepSolver) nextStepSolver).setEvaluatorFor(subExpression, subExpressionEvaluator); ((EvaluatorStepSolver) nextStepSolver).subExpressionIndex++; result = nextStepSolver.step(context); } else { Expression expressionWithSubExpressionReplacedByItsValue = exhaustivelyTopSimplifiedExpression.set(subExpressionIndex, subExpressionStep.getValue()); Expression exhaustivelyTopSimplifiedAfterSubExpressionEvaluation = exhaustiveTopSimplifier.apply(expressionWithSubExpressionReplacedByItsValue, context); if (exhaustivelyTopSimplifiedAfterSubExpressionEvaluation == subExpression) { // topSimplified turns out to be the sub-expression itself // we already know the result for that: the non-dependent subExpressionStep itself. return subExpressionStep; } else { // topSimplified is either a former sub-expression, or new. // try to reuse evaluator if available, or a make a new one, and use it ExpressionLiteralSplitterStepSolver nextStepSolver = getEvaluatorFor(exhaustivelyTopSimplifiedAfterSubExpressionEvaluation, true /* already top-simplified */); result = nextStepSolver.step(context); } } } else { result = new Solution(exhaustivelyTopSimplifiedExpression); } return result; } private ExpressionLiteralSplitterStepSolver getEvaluatorFor(Expression anotherExpression, boolean alreadyExhaustivelyTopSimplified) { ExpressionLiteralSplitterStepSolver result = evaluators.get(anotherExpression); if (result == null) { result = cloneWithAnotherExpression(anotherExpression, alreadyExhaustivelyTopSimplified); setEvaluatorFor(anotherExpression, result); } return result; } private void setEvaluatorFor(Expression expression, ExpressionLiteralSplitterStepSolver stepSolver) { // make new map based on old one, without altering it evaluators = stackedHashMap(new IdentityWrapper(expression), stepSolver, evaluators); } @Override public String toString() { return "Evaluate " + expression + " from " + subExpressionIndex + "-th sub-expression on"; } private static boolean isQuantifierOverFunctions(QuantifiedExpression quantifiedExpression, Context context) { boolean result = false; for (Expression typeExpression : IndexExpressions.getIndexDomains(quantifiedExpression)) { if (context.getType(typeExpression) instanceof FunctionType) { result = true; break; } } return result; } private static Solution getQuantificationOverFunctionsSolutionUsingBruteForce(Expression expression, Context context) { BruteForceCommonInterpreter bruteForceCommonInterpreter = new BruteForceCommonInterpreter(); Expression quantifierFreeExpression = bruteForceCommonInterpreter.apply(expression, context); Solution result = new Solution(quantifierFreeExpression); return result; } private static Map<Expression, AssociativeCommutativeGroup> fromFunctorToGroup = map( makeSymbol(SUM), new Sum(), makeSymbol(MAX), new Max(), makeSymbol(PRODUCT), new Product() ); }
- midway through re-organization of EvaluatorStepSolver
src/main/java/com/sri/ai/grinder/sgdpllt/core/solver/EvaluatorStepSolver.java
- midway through re-organization of EvaluatorStepSolver
Java
isc
54cd1df099f00d457ab471648058b7f7a0d6c844
0
maandree/sha3sum,maandree/sha3sum
/** * sha3sum – SHA-3 (Keccak) checksum calculator * * Copyright © 2013 Mattias Andrée (maandree@member.fsf.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.*; import java.util.*; /** * SHA-3/Keccak checksum calculator * * @author Mattias Andrée <a href="mailto:maandree@member.fsf.org">maandree@member.fsf.org</a> */ public class sha3sum { /** * This is the main entry point of the program * * @param args Command line arguments * @throws IOException On I/O error (such as broken pipes) */ public static void main(String[] args) throws IOException { run("sha3sum", args); } /** * Run the program * * @param cmd The command * @param argv Command line arguments * @throws IOException On I/O error (such as broken pipes) */ public static void run(String cmd, String[] argv) throws IOException { if (cmd.indexOf('/') >= 0) cmd = cmd.substring(cmd.lastIndexOf('/') + 1); if (cmd.endsWith(".jar")) cmd = cmd.substring(0, cmd.length() - 4); cmd = cmd.intern(); Integer O = null; int _o = 512; /* --outputsize */ Integer S = null; int _s = 1600; /* --statesize */ Integer R = null; int _r = _s - (_o << 1); /* --bitrate */ Integer C = null; int _c = _s - _r; /* --capacity */ Integer W = null; int _w = _s / 25; /* --wordsize */ Integer I = null; int _i = 1; /* --iterations */ int o = 0, s = 0, r = 0, c = 0, w = 0, i = 0; if (cmd == "sha3-224sum") o = _o = 224; else if (cmd == "sha3-256sum") o = _o = 256; else if (cmd == "sha3-384sum") o = _o = 384; else if (cmd == "sha3-512sum") o = _o = 512; boolean binary = false; int multi = 0; String[] files = new String[argv.length + 1]; int fptr = 0; boolean dashed = false; String[] linger = null; String[] args = new String[argv.length + 1]; System.arraycopy(argv, 0, args, 0, argv.length); for (int a = 0, an = args.length; a < an; a++) { String arg = args[a]; arg = arg == null ? null : arg.intern(); if (linger != null) { linger[0] = linger[0].intern(); if ((linger[0] == "-h") || (linger[0] == "--help")) { System.out.println(""); System.out.println("SHA-3/Keccak checksum calculator"); System.out.println(""); System.out.println("USAGE: sha3sum [option...] < file"); System.out.println(" sha3sum [option...] file..."); System.out.println(""); System.out.println(""); System.out.println("OPTIONS:"); System.out.println(" -r BITRATE"); System.out.println(" --bitrate The bitrate to use for SHA-3. (default: " + _r + ")"); System.out.println(" "); System.out.println(" -c CAPACITY"); System.out.println(" --capacity The capacity to use for SHA-3. (default: " + _c + ")"); System.out.println(" "); System.out.println(" -w WORDSIZE"); System.out.println(" --wordsize The word size to use for SHA-3. (default: " + _w + ")"); System.out.println(" "); System.out.println(" -o OUTPUTSIZE"); System.out.println(" --outputsize The output size to use for SHA-3. (default: " + _o + ")"); System.out.println(" "); System.out.println(" -s STATESIZE"); System.out.println(" --statesize The state size to use for SHA-3. (default: " + _s + ")"); System.out.println(" "); System.out.println(" -i ITERATIONS"); System.out.println(" --iterations The number of hash iterations to run. (default: " + _i + ")"); System.out.println(" "); System.out.println(" -b"); System.out.println(" --binary Print the checksum in binary, rather than hexadecimal."); System.out.println(" "); System.out.println(" -m"); System.out.println(" --multi Print the chechsum at all iterations."); System.out.println(""); System.out.println(""); System.out.println("COPYRIGHT:"); System.out.println(""); System.out.println("Copyright © 2013 Mattias Andrée (maandree@member.fsf.org)"); System.out.println(""); System.out.println("This program is free software: you can redistribute it and/or modify"); System.out.println("it under the terms of the GNU General Public License as published by"); System.out.println("the Free Software Foundation, either version 3 of the License, or"); System.out.println("(at your option) any later version."); System.out.println(""); System.out.println("This program is distributed in the hope that it will be useful,"); System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of"); System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); System.out.println("GNU General Public License for more details."); System.out.println(""); System.out.println("You should have received a copy of the GNU General Public License"); System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>."); System.out.println(""); System.exit(2); } else { if (linger[1] == null) { linger[1] = arg; arg = null; } if ((linger[0] == "-r") || (linger[0] == "--bitrate")) R = Integer.valueOf(linger[1]); else if ((linger[0] == "-c") || (linger[0] == "--capacity")) C = Integer.valueOf(linger[1]); else if ((linger[0] == "-w") || (linger[0] == "--wordsize")) W = Integer.valueOf(linger[1]); else if ((linger[0] == "-o") || (linger[0] == "--outputsize")) O = Integer.valueOf(linger[1]); else if ((linger[0] == "-s") || (linger[0] == "--statesize")) S = Integer.valueOf(linger[1]); else if ((linger[0] == "-i") || (linger[0] == "--iterations")) I = Integer.valueOf(linger[1]); else { System.err.println(cmd + ": unrecognised option: " + linger[0]); System.exit(1); } } linger = null; if (arg == null) continue; } if (arg == null) continue; if (dashed) files[fptr++] = arg == "-" ? null : arg; else if (arg == "--") dashed = true; else if (arg == "-") files[fptr++] = null; else if (arg.startsWith("--")) if (arg.indexOf('=') >= 0) linger = new String[] { arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1) }; else if (arg == "--binary") binary = true; else if (arg == "--multi") multi++; else linger = new String[] { arg, null }; else if (arg.startsWith("-")) { arg = arg.substring(1); if (arg.charAt(0) == 'b') { binary = true; arg = arg.substring(1); } else if (arg.charAt(0) == 'm') { multi++; arg = arg.substring(1); } else if (arg.length() == 1) linger = new String[] { "-" + arg, null }; else linger = new String[] { "-" + arg.charAt(0), arg.substring(1) }; } else files[fptr++] = arg; } i = I == null ? _i : I.intValue(); if (S != null) { s = S.intValue(); if ((s <= 0) || (s > 1600) || (s % 25 != 0)) { System.err.println("The state size must be a positive multiple of 25 and is limited to 1600."); System.exit(6); } } if (W != null) { w = W.intValue(); if ((w <= 0) || (w > 64)) { System.err.println("The word size must be positive and is limited to 64."); System.exit(6); } if ((S != null) && (s != w * 25)) { System.err.println("The state size must be 25 times of the word size."); System.exit(6); } else if (S == null) s = new Integer(w * 25); } if (C != null) { c = C.intValue(); if ((c <= 0) || ((c & 7) != 0)) { System.err.println("The capacity must be a positive multiple of 8."); System.exit(6); } } if (R != null) { r = R.intValue(); if ((r <= 0) || ((r & 7) != 0)) { System.err.println("The bitrate must be a positive multiple of 8."); System.exit(6); } } if (O != null) { o = O.intValue(); if (o <= 0) { System.err.println("The output size must be positive."); System.exit(6); } } if ((R == null) && (C == null) && (O == null)) // s? { r = ((c = (o = ((((s = S == null ? _s : s) << 5) / 100 + 7) >> 3) << 3) << 1) - s); o = o < 8 ? 8 : o; } else if ((R == null) && (C == null)) // !o s? { r = _r; c = _c; s = S == null ? (r + c) : s; } else if (R == null) // !c o? s? { r = (s = S == null ? _s : s) - c; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } else if (C == null) // !r o? s? { c = (s = S == null ? _s : s) - r; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } else // !r !c o? s? { s = S == null ? (r + c) : s; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } if (r > s) { System.err.println("The bitrate must not be higher than the state size."); System.exit(6); } if (c > s) { System.err.println("The capacity must not be higher than the state size."); System.exit(6); } if (r + c != s) { System.err.println("The sum of the bitrate and the capacity must equal the state size."); System.exit(6); } System.err.println("Bitrate: " + r); System.err.println("Capacity: " + c); System.err.println("Word size: " + w); System.err.println("State size: " + s); System.err.println("Output size: " + o); System.err.println("Iterations: " + i); if (fptr == 0) files[fptr++] = null; if (i < 1) { System.err.println(cmd + ": sorry, I will only do at least one iteration!"); System.exit(3); } byte[] stdin = null; boolean fail = false; String filename; for (int f = 0; f < fptr; f++) { if (((filename = files[f]) == null) && (stdin != null)) { System.out.write(stdin); continue; } String rc = ""; String fn = filename == null ? "/dev/stdin" : filename; InputStream file = null; try { file = new FileInputStream(fn); SHA3.initialise(r, c, o); int blksize = 4096; /** XXX os.stat(os.path.realpath(fn)).st_size; **/ byte[] chunk = new byte[blksize]; for (;;) { int read = file.read(chunk, 0, blksize); if (read <= 0) break; SHA3.update(chunk, read); } byte[] bs = SHA3.digest(); if (multi == 0) { for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); } if (binary) { if (filename == null) stdin = bs; System.out.write(bs); } else { for (int b = 0, bn = bs.length; b < bn; b++) { rc += "0123456789ABCDEF".charAt((bs[b] >> 4) & 15); rc += "0123456789ABCDEF".charAt(bs[b] & 15); } rc += " " + (filename == null ? "-" : filename) + "\n"; if (filename == null) stdin = rc.getBytes("UTF-8"); System.out.print(rc); } } else if (binary) { System.out.write(bs); for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); System.out.write(bs = SHA3.digest(bs)); } } else if (multi == 1) { byte[] out = new byte[(bs.length << 1) + 1]; for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } out[out.length - 1] = '\n'; System.out.write(out); for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } System.out.write(out); } } else { HashSet<String> got = new HashSet<String>(); String loop = null; byte[] out = new byte[(bs.length << 1)]; for (int _ = 0; _ < i; _++) { if (_ > 0) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); } for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } String now = new String(out, "UTF-8"); if (loop == null) if (got.contains(now)) loop = now; else got.add(now); if ((loop != null) && (loop.equals(now))) now = "\033[31m" + now + "\033[00m"; System.out.println(now); } if (loop != null) System.out.println("\033[31;31mLoop found\033[00m"); } System.out.flush(); } catch (final IOException err) { System.err.println(cmd + ": cannot read file: " + filename + ": " + err); fail = true; } finally { if (file != null) try { file.close(); } catch (final Throwable ignore) { //ignore } } } System.out.flush(); if (fail) System.exit(5); } }
pure-java/sha3sum.java
/** * sha3sum – SHA-3 (Keccak) checksum calculator * * Copyright © 2013 Mattias Andrée (maandree@member.fsf.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.*; import java.util.*; /** * SHA-3/Keccak checksum calculator * * @author Mattias Andrée <a href="mailto:maandree@member.fsf.org">maandree@member.fsf.org</a> */ public class sha3sum { /** * This is the main entry point of the program * * @param args Command line arguments * @throws IOException On I/O error (such as broken pipes) */ public static void main(String[] args) throws IOException { run("sha3sum", args); } /** * Run the program * * @param cmd The command * @param argv Command line arguments * @throws IOException On I/O error (such as broken pipes) */ public static void run(String cmd, String[] argv) throws IOException { if (cmd.indexOf('/') >= 0) cmd = cmd.substring(cmd.lastIndexOf('/') + 1); if (cmd.endsWith(".jar")) cmd = cmd.substring(0, cmd.length() - 4); cmd = cmd.intern(); Integer O = null; int _o = 512; /* --outputsize */ Integer S = null; int _s = 1600; /* --statesize */ Integer R = null; int _r = _s - (_o << 1); /* --bitrate */ Integer C = null; int _c = _s - _r; /* --capacity */ Integer W = null; int _w = _s / 25; /* --wordsize */ Integer I = null; int _i = 1; /* --iterations */ int o = 0, s = 0, r = 0, c = 0, w = 0, i = 0; if (cmd == "sha3-224sum") o = _o = 224; else if (cmd == "sha3-256sum") o = _o = 256; else if (cmd == "sha3-384sum") o = _o = 384; else if (cmd == "sha3-512sum") o = _o = 512; boolean binary = false; int multi = 0; String[] files = new String[argv.length + 1]; int fptr = 0; boolean dashed = false; String[] linger = null; String[] args = new String[argv.length + 1]; System.arraycopy(argv, 0, args, 0, argv.length); for (int a = 0, an = args.length; a < an; a++) { String arg = args[a]; arg = arg == null ? null : arg.intern(); if (linger != null) { linger[0] = linger[0].intern(); if ((linger[0] == "-h") || (linger[0] == "--help")) { System.out.println(""); System.out.println("SHA-3/Keccak checksum calculator"); System.out.println(""); System.out.println("USAGE: sha3sum [option...] < file"); System.out.println(" sha3sum [option...] file..."); System.out.println(""); System.out.println(""); System.out.println("OPTIONS:"); System.out.println(" -r BITRATE"); System.out.println(" --bitrate The bitrate to use for SHA-3. (default: " + _r + ")"); System.out.println(" "); System.out.println(" -c CAPACITY"); System.out.println(" --capacity The capacity to use for SHA-3. (default: " + _c + ")"); System.out.println(" "); System.out.println(" -w WORDSIZE"); System.out.println(" --wordsize The word size to use for SHA-3. (default: " + _w + ")"); System.out.println(" "); System.out.println(" -o OUTPUTSIZE"); System.out.println(" --outputsize The output size to use for SHA-3. (default: " + _o + ")"); System.out.println(" "); System.out.println(" -s STATESIZE"); System.out.println(" --statesize The state size to use for SHA-3. (default: " + _s + ")"); System.out.println(" "); System.out.println(" -i ITERATIONS"); System.out.println(" --iterations The number of hash iterations to run. (default: " + _i + ")"); System.out.println(" "); System.out.println(" -b"); System.out.println(" --binary Print the checksum in binary, rather than hexadecimal."); System.out.println(" "); System.out.println(" -m"); System.out.println(" --multi Print the chechsum at all iterations."); System.out.println(""); System.out.println(""); System.out.println("COPYRIGHT:"); System.out.println(""); System.out.println("Copyright © 2013 Mattias Andrée (maandree@member.fsf.org)"); System.out.println(""); System.out.println("This program is free software: you can redistribute it and/or modify"); System.out.println("it under the terms of the GNU General Public License as published by"); System.out.println("the Free Software Foundation, either version 3 of the License, or"); System.out.println("(at your option) any later version."); System.out.println(""); System.out.println("This program is distributed in the hope that it will be useful,"); System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of"); System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); System.out.println("GNU General Public License for more details."); System.out.println(""); System.out.println("You should have received a copy of the GNU General Public License"); System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>."); System.out.println(""); System.exit(2); } else { if (linger[1] == null) { linger[1] = arg; arg = null; } if ((linger[0] == "-r") || (linger[0] == "--bitrate")) R = Integer.valueOf(linger[1]); else if ((linger[0] == "-c") || (linger[0] == "--capacity")) C = Integer.valueOf(linger[1]); else if ((linger[0] == "-w") || (linger[0] == "--wordsize")) W = Integer.valueOf(linger[1]); else if ((linger[0] == "-o") || (linger[0] == "--outputsize")) O = Integer.valueOf(linger[1]); else if ((linger[0] == "-s") || (linger[0] == "--statesize")) S = Integer.valueOf(linger[1]); else if ((linger[0] == "-i") || (linger[0] == "--iterations")) I = Integer.valueOf(linger[1]); else { System.err.println(cmd + ": unrecognised option: " + linger[0]); System.exit(1); } } linger = null; if (arg == null) continue; } if (arg == null) continue; if (dashed) files[fptr++] = arg == "-" ? null : arg; else if (arg == "--") dashed = true; else if (arg == "-") files[fptr++] = null; else if (arg.startsWith("--")) if (arg.indexOf('=') >= 0) linger = new String[] { arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1) }; else if (arg == "--binary") binary = true; else if (arg == "--multi") multi++; else linger = new String[] { arg, null }; else if (arg.startsWith("-")) { arg = arg.substring(1); if (arg.charAt(0) == 'b') { binary = true; arg = arg.substring(1); } else if (arg.charAt(0) == 'm') { multi++; arg = arg.substring(1); } else if (arg.length() == 1) linger = new String[] { "-" + arg, null }; else linger = new String[] { "-" + arg.charAt(0), arg.substring(1) }; } else files[fptr++] = arg; } i = I == null ? _i : I.intValue(); if (S != null) { s = S.intValue(); if ((s <= 0) || (s > 1600) || (s % 25 != 0)) { System.err.println("The state size must be a positive multiple of 25 and is limited to 1600."); System.exit(6); } } if (W != null) { w = W.intValue(); if ((w <= 0) || (w > 64)) { System.err.println("The word size must be positive and is limited to 64."); System.exit(6); } if ((S != null) && (s != w * 25)) { System.err.println("The state size must be 25 times of the word size."); System.exit(6); } else if (S == null) s = new Integer(w * 25); } if (C != null) { c = C.intValue(); if ((c <= 0) || ((c & 7) != 0)) { System.err.println("The capacity must be a positive multiple of 8."); System.exit(6); } } if (R != null) { r = R.intValue(); if ((r <= 0) || ((r & 7) != 0)) { System.err.println("The bitrate must be a positive multiple of 8."); System.exit(6); } } if (O != null) { o = O.intValue(); if (o <= 0) { System.err.println("The output size must be positive."); System.exit(6); } } if ((R == null) && (C == null) && (O == null)) // s? { r = ((c = (o = ((((s = S == null ? _s : s) << 5) / 100 + 7) >> 3) << 3) << 1) - s); o = o < 8 ? 8 : o; } else if ((R == null) && (C == null)) // !o s? { r = _r; c = _c; s = S == null ? (r + c) : s; } else if (R == null) // !c o? s? { r = (s = S == null ? _s : s) - c; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } else if (C == null) // !r o? s? { c = (s = S == null ? _s : s) - r; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } else // !r !c o? s? { s = S == null ? (r + c) : s; o = O == null ? (c == 8 ? 8 : (c << 1)) : o; } if (r > s) { System.err.println("The bitrate must not be higher than the state size."); System.exit(6); } if (c > s) { System.err.println("The capacity must not be higher than the state size."); System.exit(6); } if (r + c != s) { System.err.println("The sum of the bitrate and the capacity must equal the state size."); System.exit(6); } System.err.println("Bitrate: " + r); System.err.println("Capacity: " + c); System.err.println("Word size: " + w); System.err.println("State size: " + s); System.err.println("Output size: " + o); System.err.println("Iterations: " + i); if (fptr == 0) files[fptr++] = null; if (i < 1) { System.err.println(cmd + ": sorry, I will only do at least one iteration!"); System.exit(3); } byte[] stdin = null; boolean fail = false; String filename; for (int f = 0; f < fptr; f++) { if (((filename = files[f]) == null) && (stdin != null)) { System.out.write(stdin); continue; } String rc = ""; String fn = filename == null ? "/dev/stdin" : filename; InputStream file = null; try { file = new FileInputStream(fn); SHA3.initialise(r, c, o); int blksize = 4096; /** XXX os.stat(os.path.realpath(fn)).st_size; **/ byte[] chunk = new byte[blksize]; for (;;) { int read = file.read(chunk, 0, blksize); if (read <= 0) break; SHA3.update(chunk, read); } byte[] bs = SHA3.digest(); if (multi == 0) { for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); } if (binary) { if (filename == null) stdin = bs; System.out.write(bs); } else { for (int b = 0, bn = bs.length; b < bn; b++) { rc += "0123456789ABCDEF".charAt((bs[b] >> 4) & 15); rc += "0123456789ABCDEF".charAt(bs[b] & 15); } rc += " " + (filename == null ? "-" : filename) + "\n"; if (filename == null) stdin = rc.getBytes("UTF-8"); System.out.print(rc); } } else if (binary) { System.out.write(bs); for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); System.out.write(bs = SHA3.digest(bs)); } } else if (multi == 1) { byte[] out = new byte[(bs.length << 1) + 1]; for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } out[out.length - 1] = '\n'; System.out.write(out); for (int _ = 1; _ < i; _++) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } System.out.write(out); } } else { HashSet<String> got = new HashSet<String>(); String loop = null; byte[] out = new byte[(bs.length << 1)]; for (int _ = 0; _ < i; _++) { if (_ > 0) { SHA3.initialise(r, c, o); bs = SHA3.digest(bs); } for (int b = 0, bn = bs.length; b < bn; b++) { out[ b << 1 ] = (byte)("0123456789ABCDEF".charAt((bs[b] >> 4) & 15)); out[(b << 1) | 1] = (byte)("0123456789ABCDEF".charAt(bs[b] & 15)); } String now = new String(out, "UTF-8"); if (loop == null) if (got.contains(now)) loop = now; else got.add(now); if ((loop != null) && (loop.equals(now))) now = "\033[31m" + now + "\033[00m"; System.out.println(now); } } System.out.flush(); } catch (final IOException err) { System.err.println(cmd + ": cannot read file: " + filename + ": " + err); fail = true; } finally { if (file != null) try { file.close(); } catch (final Throwable ignore) { //ignore } } } System.out.flush(); if (fail) System.exit(5); } }
m Signed-off-by: Mattias Andrée <3d72f033b30d63e7ff5f0b71398e9c45b66386a1@operamail.com>
pure-java/sha3sum.java
m
Java
mit
4162f73a581c45c7b792cdb075e8a4d82cd5e04d
0
mockito/mockito,ze-pequeno/mockito,ze-pequeno/mockito,mockito/mockito,hansjoachim/mockito,lukasz-szewc/mockito,bric3/mockito,bric3/mockito,hansjoachim/mockito,terebesirobert/mockito,lukasz-szewc/mockito,mockito/mockito,bric3/mockito
package org.mockito; import org.mockito.internal.matchers.Any; import org.mockito.internal.matchers.Contains; import org.mockito.internal.matchers.EndsWith; import org.mockito.internal.matchers.Equals; import org.mockito.internal.matchers.InstanceOf; import org.mockito.internal.matchers.Matches; import org.mockito.internal.matchers.NotNull; import org.mockito.internal.matchers.Null; import org.mockito.internal.matchers.Same; import org.mockito.internal.matchers.StartsWith; import org.mockito.internal.matchers.apachecommons.ReflectionEquals; import org.mockito.internal.util.Primitives; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; import static org.mockito.internal.util.Primitives.defaultValue; /** * Allow flexible verification or stubbing. See also {@link AdditionalMatchers}. * * <p> * {@link Mockito} extends ArgumentMatchers so to get access to all matchers just import Mockito class statically. * * <pre class="code"><code class="java"> * //stubbing using anyInt() argument matcher * when(mockedList.get(anyInt())).thenReturn("element"); * * //following prints "element" * System.out.println(mockedList.get(999)); * * //you can also verify using argument matcher * verify(mockedList).get(anyInt()); * </code></pre> * * <p> * Since Mockito <code>any(Class)</code> and <code>anyInt</code> family matchers perform a type check, thus they won't * match <code>null</code> arguments. Instead use the <code>isNull</code> matcher. * * <pre class="code"><code class="java"> * // stubbing using anyBoolean() argument matcher * when(mock.dryRun(anyBoolean())).thenReturn("state"); * * // below the stub won't match, and won't return "state" * mock.dryRun(null); * * // either change the stub * when(mock.dryRun(isNull())).thenReturn("state"); * mock.dryRun(null); // ok * * // or fix the code ;) * when(mock.dryRun(anyBoolean())).thenReturn("state"); * mock.dryRun(true); // ok * * </code></pre> * * The same apply for verification. * </p> * * * Scroll down to see all methods - full list of matchers. * * <p> * <b>Warning:</b><br/> * * If you are using argument matchers, <b>all arguments</b> have to be provided by matchers. * * E.g: (example shows verification but the same applies to stubbing): * </p> * * <pre class="code"><code class="java"> * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>); * //above is correct - eq() is also an argument matcher * * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>); * //above is incorrect - exception will be thrown because third argument is given without argument matcher. * </code></pre> * * <p> * Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers. * Internally, they record a matcher on a stack and return a dummy value (usually null). * This implementation is due static type safety imposed by java compiler. * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method. * </p> * * <h1>Custom Argument ArgumentMatchers</h1> * <p> * It is important to understand the use cases and available options for dealing with non-trivial arguments * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples. * </p> */ @SuppressWarnings("unchecked") public class ArgumentMatchers { /** * Matches <strong>anything</strong>, including nulls and varargs. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)} * </p> * * <p> * <strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li> * <li>Since mockito 2.0 {@link #any(Class)} is not anymore an alias of this method.</li> * </ul> * </p> * * @return <code>null</code>. * * @see #any(Class) * @see #anyObject() * @see #anyVararg() * @see #anyChar() * @see #anyInt() * @see #anyBoolean() * @see #anyCollectionOf(Class) */ public static <T> T any() { return anyObject(); } /** * Matches anything, including <code>null</code>. * * <p> * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}. * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>null</code>. * @see #any() * @see #any(Class) * @see #notNull() * @see #notNull(Class) * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only) */ @Deprecated public static <T> T anyObject() { reportMatcher(Any.ANY); return null; } /** * Matches any object of given type, excluding nulls. * * <p> * This matcher will perform a type check with the given type, thus excluding values. * See examples in javadoc for {@link ArgumentMatchers} class. * * This is an alias of: {@link #isA(Class)}} * </p> * * <p> * Since Mockito 2.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value. * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p><strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family.</li> * <li>Since Mockito 2.0 this method will perform a type check thus <code>null</code> values are not authorized.</li> * <li>Since mockito 2.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li> * </ul> * </p> * * @param <T> The accepted type * @param type the class of the accepted type. * @return <code>null</code>. * @see #any() * @see #anyObject() * @see #anyVararg() * @see #isA(Class) * @see #notNull() * @see #notNull(Class) * @see #isNull() * @see #isNull(Class) */ public static <T> T any(Class<T> type) { reportMatcher(new InstanceOf.VarArgAware(type, "<any " + type.getCanonicalName() + ">")); return defaultValue(type); } /** * <code>Object</code> argument that implements the given class. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param <T> the accepted type. * @param type the class of the accepted type. * @return <code>null</code>. * @see #any(Class) */ public static <T> T isA(Class<T> type) { reportMatcher(new InstanceOf(type)); return defaultValue(type); } /** * Any vararg, meaning any number and values of arguments. * * <p> * Example: * <pre class="code"><code class="java"> * //verification: * mock.foo(1, 2); * mock.foo(1, 2, 3, 4); * * verify(mock, times(2)).foo(anyVararg()); * * //stubbing: * when(mock.foo(anyVararg()).thenReturn(100); * * //prints 100 * System.out.println(mock.foo(1, 2)); * //also prints 100 * System.out.println(mock.foo(1, 2, 3, 4)); * </code></pre> * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>null</code>. * @see #any() * @see #any(Class) * @deprecated as of 2.0 use {@link #any()} */ @Deprecated public static <T> T anyVararg() { any(); return null; } /** * Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code> * * <p> * Since Mockito 2.0, only allow valued <code>Boolean</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>false</code>. * @see #isNull() * @see #isNull(Class) */ public static boolean anyBoolean() { reportMatcher(new InstanceOf(Boolean.class, "<any boolean>")); return false; } /** * Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Byte</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static byte anyByte() { reportMatcher(new InstanceOf(Byte.class, "<any byte>")); return 0; } /** * Any <code>char</code> or <strong>non-null</strong> <code>Character</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Character</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static char anyChar() { reportMatcher(new InstanceOf(Character.class, "<any char>")); return 0; } /** * Any int or <strong>non-null</strong> <code>Integer</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Integer</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static int anyInt() { reportMatcher(new InstanceOf(Integer.class, "<any integer>")); return 0; } /** * Any <code>long</code> or <strong>non-null</strong> <code>Long</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Long</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static long anyLong() { reportMatcher(new InstanceOf(Long.class, "<any long>")); return 0; } /** * Any <code>float</code> or <strong>non-null</strong> <code>Float</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Float</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static float anyFloat() { reportMatcher(new InstanceOf(Float.class, "<any float>")); return 0; } /** * Any <code>double</code> or <strong>non-null</strong> <code>Double</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Double</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static double anyDouble() { reportMatcher(new InstanceOf(Double.class, "<any double>")); return 0; } /** * Any <code>short</code> or <strong>non-null</strong> <code>Short</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Short</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static short anyShort() { reportMatcher(new InstanceOf(Short.class, "<any short>")); return 0; } /** * Any <strong>non-null</strong> <code>String</code> * * <p> * Since Mockito 2.0, only allow non-null <code>String</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty String ("") * @see #isNull() * @see #isNull(Class) */ public static String anyString() { reportMatcher(new InstanceOf(String.class, "<any string>")); return ""; } /** * Any <strong>non-null</strong> <code>List</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>List</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty List. * @see #anyListOf(Class) * @see #isNull() * @see #isNull(Class) */ public static List anyList() { reportMatcher(new InstanceOf(List.class, "<any List>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>List</code>. * * Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to * <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * * <p> * This method doesn't do type checks of the list content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>List</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the list to avoid casting * @return empty List. * @see #anyList() * @see #isNull() * @see #isNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> List<T> anyListOf(Class<T> clazz) { return anyList(); } /** * Any <strong>non-null</strong> <code>Set</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Set</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Set * @see #anySetOf(Class) * @see #isNull() * @see #isNull(Class) */ public static Set anySet() { reportMatcher(new InstanceOf(Set.class, "<any set>")); return new HashSet(0); } /** * Any <strong>non-null</strong> <code>Set</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anySet()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the set content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Set</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the Set to avoid casting * @return empty Set * @see #anySet() * @see #isNull() * @see #isNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> Set<T> anySetOf(Class<T> clazz) { return anySet(); } /** * Any <strong>non-null</strong> <code>Map</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Map</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Map. * @see #anyMapOf(Class, Class) * @see #isNull() * @see #isNull(Class) */ public static Map anyMap() { reportMatcher(new InstanceOf(Map.class, "<any map>")); return new HashMap(0); } /** * Any <strong>non-null</strong> <code>Map</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyMap()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the map content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Map</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param keyClazz Type of the map key to avoid casting * @param valueClazz Type of the value to avoid casting * @return empty Map. * @see #anyMap() * @see #isNull() * @see #isNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) { return anyMap(); } /** * Any <strong>non-null</strong> <code>Collection</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Collection</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Collection. * @see #anyCollectionOf(Class) * @see #isNull() * @see #isNull(Class) */ public static Collection anyCollection() { reportMatcher(new InstanceOf(Collection.class, "<any collection>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>Collection</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyCollection()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the collection content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Collection</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the collection to avoid casting * @return empty Collection. * @see #anyCollection() * @see #isNull() * @see #isNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> Collection<T> anyCollectionOf(Class<T> clazz) { return anyCollection(); } /** * Any <strong>non-null</strong> <code>Iterable</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Iterable</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Iterable. * @see #anyIterableOf(Class) * @see #isNull() * @see #isNull(Class) * @since 2.0.0 */ public static Collection anyIterable() { reportMatcher(new InstanceOf(Iterable.class, "<any iterable>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>Iterable</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyIterable()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the iterable content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>String</code>. * As strings are nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the collection to avoid casting * @return empty Iterable. * @see #anyIterable() * @see #isNull() * @see #isNull(Class) * @since 2.0.0 * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> Iterable<T> anyIterableOf(Class<T> clazz) { return anyIterable(); } /** * <code>boolean</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static boolean eq(boolean value) { reportMatcher(new Equals(value)); return false; } /** * <code>byte</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static byte eq(byte value) { reportMatcher(new Equals(value)); return 0; } /** * <code>char</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static char eq(char value) { reportMatcher(new Equals(value)); return 0; } /** * <code>double</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static double eq(double value) { reportMatcher(new Equals(value)); return 0; } /** * <code>float</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static float eq(float value) { reportMatcher(new Equals(value)); return 0; } /** * <code>int</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static int eq(int value) { reportMatcher(new Equals(value)); return 0; } /** * <code>long</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static long eq(long value) { reportMatcher(new Equals(value)); return 0; } /** * <code>short</code> argument that is equal to the given value. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param value the given value. * @return <code>0</code>. */ public static short eq(short value) { reportMatcher(new Equals(value)); return 0; } /** * Object argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>null</code>. */ public static <T> T eq(T value) { reportMatcher(new Equals(value)); if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } /** * Object argument that is reflection-equal to the given value with support for excluding * selected fields from a class. * * <p> * This matcher can be used when equals() is not implemented on compared objects. * Matcher uses java reflection API to compare fields of wanted and actual object. * </p> * * <p> * Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from * apache commons library. * <p> * <b>Warning</b> The equality check is shallow! * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @param excludeFields fields to exclude, if field does not exist it is ignored. * @return <code>null</code>. */ public static <T> T refEq(T value, String... excludeFields) { reportMatcher(new ReflectionEquals(value, excludeFields)); return null; } /** * Object argument that is the same as the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param <T> the type of the object, it is passed through to prevent casts. * @param value the given value. * @return <code>null</code>. */ public static <T> T same(T value) { reportMatcher(new Same(value)); if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } /** * <code>null</code> argument. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. * @see #isNull(Class) * @see #isNotNull() * @see #isNotNull(Class) */ public static <T> T isNull() { reportMatcher(Null.NULL); return null; } /** * <code>null</code> argument. * * <p> * The class argument is provided to avoid casting. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. * @see #isNull() * @see #isNotNull() * @see #isNotNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> T isNull(Class<T> clazz) { return isNull(); } /** * Not <code>null</code> argument. * * <p> * Alias to {@link ArgumentMatchers#isNotNull()} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. */ public static <T> T notNull() { reportMatcher(NotNull.NOT_NULL); return null; } /** * Not <code>null</code> argument, not necessary of the given class. * * <p> * The class argument is provided to avoid casting. * * Alias to {@link ArgumentMatchers#isNotNull(Class)} * <p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. * @see #isNotNull() * @see #isNull() * @see #isNull(Class) * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> T notNull(Class<T> clazz) { return notNull(); } /** * Not <code>null</code> argument. * * <p> * Alias to {@link ArgumentMatchers#notNull()} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. * @see #isNotNull(Class) * @see #isNull() * @see #isNull(Class) */ public static <T> T isNotNull() { return notNull(); } /** * Not <code>null</code> argument, not necessary of the given class. * * <p> * The class argument is provided to avoid casting. * Alias to {@link ArgumentMatchers#notNull(Class)} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ public static <T> T isNotNull(Class<T> clazz) { return notNull(clazz); } /** * <code>String</code> argument that contains the given substring. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param substring the substring. * @return empty String (""). */ public static String contains(String substring) { reportMatcher(new Contains(substring)); return ""; } /** * <code>String</code> argument that matches the given regular expression. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param regex the regular expression. * @return empty String (""). */ public static String matches(String regex) { reportMatcher(new Matches(regex)); return ""; } /** * <code>String</code> argument that ends with the given suffix. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param suffix the suffix. * @return empty String (""). */ public static String endsWith(String suffix) { reportMatcher(new EndsWith(suffix)); return ""; } /** * <code>String</code> argument that starts with the given prefix. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param prefix the prefix. * @return empty String (""). */ public static String startsWith(String prefix) { reportMatcher(new StartsWith(prefix)); return ""; } /** * Allows creating custom argument matchers. * * <p> * This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide. * <b>NullPointerException</b> auto-unboxing caveat is described below. * </p> * * <p> * It is important to understand the use cases and available options for dealing with non-trivial arguments * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples. * </p> * * <p> * <b>NullPointerException</b> auto-unboxing caveat. * In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method. * This way you will avoid <code>NullPointerException</code> during auto-unboxing. * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem. * Hopefully, the javadoc describes the problem and solution well. * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatcher} class * </p> * * @param matcher decides whether argument matches * @return <code>null</code>. */ public static <T> T argThat(ArgumentMatcher<T> matcher) { reportMatcher(matcher); return null; } /** * Allows creating custom <code>char</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static char charThat(ArgumentMatcher<Character> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>boolean</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>false</code>. */ public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) { reportMatcher(matcher); return false; } /** * Allows creating custom <code>byte</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static byte byteThat(ArgumentMatcher<Byte> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>short</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static short shortThat(ArgumentMatcher<Short> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>int</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static int intThat(ArgumentMatcher<Integer> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>long</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static long longThat(ArgumentMatcher<Long> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>float</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static float floatThat(ArgumentMatcher<Float> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>double</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static double doubleThat(ArgumentMatcher<Double> matcher) { reportMatcher(matcher); return 0; } private static void reportMatcher(ArgumentMatcher<?> matcher) { mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher); } }
src/main/java/org/mockito/ArgumentMatchers.java
package org.mockito; import org.mockito.internal.matchers.Any; import org.mockito.internal.matchers.Contains; import org.mockito.internal.matchers.EndsWith; import org.mockito.internal.matchers.Equals; import org.mockito.internal.matchers.InstanceOf; import org.mockito.internal.matchers.Matches; import org.mockito.internal.matchers.NotNull; import org.mockito.internal.matchers.Null; import org.mockito.internal.matchers.Same; import org.mockito.internal.matchers.StartsWith; import org.mockito.internal.matchers.apachecommons.ReflectionEquals; import org.mockito.internal.util.Primitives; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; import static org.mockito.internal.util.Primitives.defaultValue; /** * Allow flexible verification or stubbing. See also {@link AdditionalMatchers}. * * <p> * {@link Mockito} extends ArgumentMatchers so to get access to all matchers just import Mockito class statically. * * <pre class="code"><code class="java"> * //stubbing using anyInt() argument matcher * when(mockedList.get(anyInt())).thenReturn("element"); * * //following prints "element" * System.out.println(mockedList.get(999)); * * //you can also verify using argument matcher * verify(mockedList).get(anyInt()); * </code></pre> * * <p> * Since Mockito <code>any(Class)</code> and <code>anyInt</code> family matchers perform a type check, thus they won't * match <code>null</code> arguments. Instead use the <code>isNull</code> matcher. * * <pre class="code"><code class="java"> * // stubbing using anyBoolean() argument matcher * when(mock.dryRun(anyBoolean())).thenReturn("state"); * * // below the stub won't match, and won't return "state" * mock.dryRun(null); * * // either change the stub * when(mock.dryRun(isNull())).thenReturn("state"); * mock.dryRun(null); // ok * * // or fix the code ;) * when(mock.dryRun(anyBoolean())).thenReturn("state"); * mock.dryRun(true); // ok * * </code></pre> * * The same apply for verification. * </p> * * * Scroll down to see all methods - full list of matchers. * * <p> * <b>Warning:</b><br/> * * If you are using argument matchers, <b>all arguments</b> have to be provided by matchers. * * E.g: (example shows verification but the same applies to stubbing): * </p> * * <pre class="code"><code class="java"> * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>); * //above is correct - eq() is also an argument matcher * * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>); * //above is incorrect - exception will be thrown because third argument is given without argument matcher. * </code></pre> * * <p> * Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers. * Internally, they record a matcher on a stack and return a dummy value (usually null). * This implementation is due static type safety imposed by java compiler. * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method. * </p> * * <h1>Custom Argument ArgumentMatchers</h1> * <p> * It is important to understand the use cases and available options for dealing with non-trivial arguments * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples. * </p> */ @SuppressWarnings("unchecked") public class ArgumentMatchers { /** * Matches <strong>anything</strong>, including nulls and varargs. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)} * </p> * * <p> * <strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li> * <li>Since mockito 2.0 {@link #any(Class)} is not anymore an alias of this method.</li> * </ul> * </p> * * @return <code>null</code>. * * @see #any(Class) * @see #anyObject() * @see #anyVararg() * @see #anyChar() * @see #anyInt() * @see #anyBoolean() * @see #anyCollectionOf(Class) */ public static <T> T any() { return anyObject(); } /** * Matches anything, including <code>null</code>. * * <p> * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}. * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>null</code>. * @see #any() * @see #any(Class) * @see #notNull() * @see #notNull(Class) * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only) */ @Deprecated public static <T> T anyObject() { reportMatcher(Any.ANY); return null; } /** * Matches any object of given type, excluding nulls. * * <p> * This matcher will perform a type check with the given type, thus excluding values. * See examples in javadoc for {@link ArgumentMatchers} class. * * This is an alias of: {@link #isA(Class)}} * </p> * * <p> * Since Mockito 2.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value. * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p><strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family.</li> * <li>Since Mockito 2.0 this method will perform a type check thus <code>null</code> values are not authorized.</li> * <li>Since mockito 2.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li> * </ul> * </p> * * @param <T> The accepted type * @param type the class of the accepted type. * @return <code>null</code>. * @see #any() * @see #anyObject() * @see #anyVararg() * @see #isA(Class) * @see #notNull() * @see #notNull(Class) * @see #isNull() * @see #isNull(Class) */ public static <T> T any(Class<T> type) { reportMatcher(new InstanceOf.VarArgAware(type, "<any " + type.getCanonicalName() + ">")); return defaultValue(type); } /** * <code>Object</code> argument that implements the given class. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param <T> the accepted type. * @param type the class of the accepted type. * @return <code>null</code>. * @see #any(Class) */ public static <T> T isA(Class<T> type) { reportMatcher(new InstanceOf(type)); return defaultValue(type); } /** * Any vararg, meaning any number and values of arguments. * * <p> * Example: * <pre class="code"><code class="java"> * //verification: * mock.foo(1, 2); * mock.foo(1, 2, 3, 4); * * verify(mock, times(2)).foo(anyVararg()); * * //stubbing: * when(mock.foo(anyVararg()).thenReturn(100); * * //prints 100 * System.out.println(mock.foo(1, 2)); * //also prints 100 * System.out.println(mock.foo(1, 2, 3, 4)); * </code></pre> * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>null</code>. * @see #any() * @see #any(Class) * @deprecated as of 2.0 use {@link #any()} */ @Deprecated public static <T> T anyVararg() { any(); return null; } /** * Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code> * * <p> * Since Mockito 2.0, only allow valued <code>Boolean</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>false</code>. * @see #isNull() * @see #isNull(Class) */ public static boolean anyBoolean() { reportMatcher(new InstanceOf(Boolean.class, "<any boolean>")); return false; } /** * Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Byte</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static byte anyByte() { reportMatcher(new InstanceOf(Byte.class, "<any byte>")); return 0; } /** * Any <code>char</code> or <strong>non-null</strong> <code>Character</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Character</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static char anyChar() { reportMatcher(new InstanceOf(Character.class, "<any char>")); return 0; } /** * Any int or <strong>non-null</strong> <code>Integer</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Integer</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static int anyInt() { reportMatcher(new InstanceOf(Integer.class, "<any integer>")); return 0; } /** * Any <code>long</code> or <strong>non-null</strong> <code>Long</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Long</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static long anyLong() { reportMatcher(new InstanceOf(Long.class, "<any long>")); return 0; } /** * Any <code>float</code> or <strong>non-null</strong> <code>Float</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Float</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static float anyFloat() { reportMatcher(new InstanceOf(Float.class, "<any float>")); return 0; } /** * Any <code>double</code> or <strong>non-null</strong> <code>Double</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Double</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static double anyDouble() { reportMatcher(new InstanceOf(Double.class, "<any double>")); return 0; } /** * Any <code>short</code> or <strong>non-null</strong> <code>Short</code>. * * <p> * Since Mockito 2.0, only allow valued <code>Short</code>, thus <code>null</code> is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return <code>0</code>. * @see #isNull() * @see #isNull(Class) */ public static short anyShort() { reportMatcher(new InstanceOf(Short.class, "<any short>")); return 0; } /** * Any <strong>non-null</strong> <code>String</code> * * <p> * Since Mockito 2.0, only allow non-null <code>String</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty String ("") * @see #isNull() * @see #isNull(Class) */ public static String anyString() { reportMatcher(new InstanceOf(String.class, "<any string>")); return ""; } /** * Any <strong>non-null</strong> <code>List</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>List</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty List. * @see #anyListOf(Class) * @see #isNull() * @see #isNull(Class) */ public static List anyList() { reportMatcher(new InstanceOf(List.class, "<any List>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>List</code>. * * Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to * <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * * <p> * This method doesn't do type checks of the list content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>List</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the list to avoid casting * @return empty List. * @see #anyList() * @see #isNull() * @see #isNull(Class) */ public static <T> List<T> anyListOf(Class<T> clazz) { return anyList(); } /** * Any <strong>non-null</strong> <code>Set</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Set</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Set * @see #anySetOf(Class) * @see #isNull() * @see #isNull(Class) */ public static Set anySet() { reportMatcher(new InstanceOf(Set.class, "<any set>")); return new HashSet(0); } /** * Any <strong>non-null</strong> <code>Set</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anySet()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the set content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Set</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the Set to avoid casting * @return empty Set * @see #anySet() * @see #isNull() * @see #isNull(Class) */ public static <T> Set<T> anySetOf(Class<T> clazz) { return anySet(); } /** * Any <strong>non-null</strong> <code>Map</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Map</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Map. * @see #anyMapOf(Class, Class) * @see #isNull() * @see #isNull(Class) */ public static Map anyMap() { reportMatcher(new InstanceOf(Map.class, "<any map>")); return new HashMap(0); } /** * Any <strong>non-null</strong> <code>Map</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyMap()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the map content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Map</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param keyClazz Type of the map key to avoid casting * @param valueClazz Type of the value to avoid casting * @return empty Map. * @see #anyMap() * @see #isNull() * @see #isNull(Class) */ public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) { return anyMap(); } /** * Any <strong>non-null</strong> <code>Collection</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Collection</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Collection. * @see #anyCollectionOf(Class) * @see #isNull() * @see #isNull(Class) */ public static Collection anyCollection() { reportMatcher(new InstanceOf(Collection.class, "<any collection>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>Collection</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyCollection()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the collection content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>Collection</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the collection to avoid casting * @return empty Collection. * @see #anyCollection() * @see #isNull() * @see #isNull(Class) */ public static <T> Collection<T> anyCollectionOf(Class<T> clazz) { return anyCollection(); } /** * Any <strong>non-null</strong> <code>Iterable</code>. * * <p> * Since Mockito 2.0, only allow non-null <code>Iterable</code>. * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @return empty Iterable. * @see #anyIterableOf(Class) * @see #isNull() * @see #isNull(Class) * @since 2.0.0 */ public static Collection anyIterable() { reportMatcher(new InstanceOf(Iterable.class, "<any iterable>")); return new ArrayList(0); } /** * Any <strong>non-null</strong> <code>Iterable</code>. * * <p> * Generic friendly alias to {@link ArgumentMatchers#anyIterable()}. * It's an alternative to <code>&#064;SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings. * </p> * * <p> * This method doesn't do type checks of the iterable content with the given type parameter, it is only there * to avoid casting in the code. * </p> * * <p> * Since Mockito 2.0, only allow non-null <code>String</code>. * As strings are nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito * 1.x. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class. * </p> * * @param clazz Type owned by the collection to avoid casting * @return empty Iterable. * @see #anyIterable() * @see #isNull() * @see #isNull(Class) * @since 2.0.0 */ public static <T> Iterable<T> anyIterableOf(Class<T> clazz) { return anyIterable(); } /** * <code>boolean</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static boolean eq(boolean value) { reportMatcher(new Equals(value)); return false; } /** * <code>byte</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static byte eq(byte value) { reportMatcher(new Equals(value)); return 0; } /** * <code>char</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static char eq(char value) { reportMatcher(new Equals(value)); return 0; } /** * <code>double</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static double eq(double value) { reportMatcher(new Equals(value)); return 0; } /** * <code>float</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static float eq(float value) { reportMatcher(new Equals(value)); return 0; } /** * <code>int</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static int eq(int value) { reportMatcher(new Equals(value)); return 0; } /** * <code>long</code> argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>0</code>. */ public static long eq(long value) { reportMatcher(new Equals(value)); return 0; } /** * <code>short</code> argument that is equal to the given value. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param value the given value. * @return <code>0</code>. */ public static short eq(short value) { reportMatcher(new Equals(value)); return 0; } /** * Object argument that is equal to the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @return <code>null</code>. */ public static <T> T eq(T value) { reportMatcher(new Equals(value)); if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } /** * Object argument that is reflection-equal to the given value with support for excluding * selected fields from a class. * * <p> * This matcher can be used when equals() is not implemented on compared objects. * Matcher uses java reflection API to compare fields of wanted and actual object. * </p> * * <p> * Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from * apache commons library. * <p> * <b>Warning</b> The equality check is shallow! * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param value the given value. * @param excludeFields fields to exclude, if field does not exist it is ignored. * @return <code>null</code>. */ public static <T> T refEq(T value, String... excludeFields) { reportMatcher(new ReflectionEquals(value, excludeFields)); return null; } /** * Object argument that is the same as the given value. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param <T> the type of the object, it is passed through to prevent casts. * @param value the given value. * @return <code>null</code>. */ public static <T> T same(T value) { reportMatcher(new Same(value)); if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } /** * <code>null</code> argument. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. * @see #isNull(Class) * @see #isNotNull() * @see #isNotNull(Class) */ public static <T> T isNull() { reportMatcher(Null.NULL); return null; } /** * <code>null</code> argument. * * <p> * The class argument is provided to avoid casting. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. * @see #isNull() * @see #isNotNull() * @see #isNotNull(Class) */ public static <T> T isNull(Class<T> clazz) { reportMatcher(Null.NULL); return null; } /** * Not <code>null</code> argument. * * <p> * Alias to {@link ArgumentMatchers#isNotNull()} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. */ public static <T> T notNull() { reportMatcher(NotNull.NOT_NULL); return null; } /** * Not <code>null</code> argument, not necessary of the given class. * * <p> * The class argument is provided to avoid casting. * * Alias to {@link ArgumentMatchers#isNotNull(Class)} * <p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. * @see #isNotNull() * @see #isNull() * @see #isNull(Class) */ public static <T> T notNull(Class<T> clazz) { reportMatcher(NotNull.NOT_NULL); return null; } /** * Not <code>null</code> argument. * * <p> * Alias to {@link ArgumentMatchers#notNull()} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @return <code>null</code>. * @see #isNotNull(Class) * @see #isNull() * @see #isNull(Class) */ public static <T> T isNotNull() { return notNull(); } /** * Not <code>null</code> argument, not necessary of the given class. * * <p> * The class argument is provided to avoid casting. * Alias to {@link ArgumentMatchers#notNull(Class)} * </p> * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * @param clazz Type to avoid casting * @return <code>null</code>. */ public static <T> T isNotNull(Class<T> clazz) { return notNull(clazz); } /** * <code>String</code> argument that contains the given substring. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param substring the substring. * @return empty String (""). */ public static String contains(String substring) { reportMatcher(new Contains(substring)); return ""; } /** * <code>String</code> argument that matches the given regular expression. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param regex the regular expression. * @return empty String (""). */ public static String matches(String regex) { reportMatcher(new Matches(regex)); return ""; } /** * <code>String</code> argument that ends with the given suffix. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param suffix the suffix. * @return empty String (""). */ public static String endsWith(String suffix) { reportMatcher(new EndsWith(suffix)); return ""; } /** * <code>String</code> argument that starts with the given prefix. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param prefix the prefix. * @return empty String (""). */ public static String startsWith(String prefix) { reportMatcher(new StartsWith(prefix)); return ""; } /** * Allows creating custom argument matchers. * * <p> * This API has changed in 2.0, please read {@link ArgumentMatcher} for rationale and migration guide. * <b>NullPointerException</b> auto-unboxing caveat is described below. * </p> * * <p> * It is important to understand the use cases and available options for dealing with non-trivial arguments * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach * for given scenario and produce highest quality test (clean and maintainable). * Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples. * </p> * * <p> * <b>NullPointerException</b> auto-unboxing caveat. * In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method. * This way you will avoid <code>NullPointerException</code> during auto-unboxing. * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem. * Hopefully, the javadoc describes the problem and solution well. * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker. * </p> * * <p> * See examples in javadoc for {@link ArgumentMatcher} class * </p> * * @param matcher decides whether argument matches * @return <code>null</code>. */ public static <T> T argThat(ArgumentMatcher<T> matcher) { reportMatcher(matcher); return null; } /** * Allows creating custom <code>char</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static char charThat(ArgumentMatcher<Character> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>boolean</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>false</code>. */ public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) { reportMatcher(matcher); return false; } /** * Allows creating custom <code>byte</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static byte byteThat(ArgumentMatcher<Byte> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>short</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static short shortThat(ArgumentMatcher<Short> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>int</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static int intThat(ArgumentMatcher<Integer> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>long</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static long longThat(ArgumentMatcher<Long> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>float</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static float floatThat(ArgumentMatcher<Float> matcher) { reportMatcher(matcher); return 0; } /** * Allows creating custom <code>double</code> argument matchers. * * Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat. * <p> * See examples in javadoc for {@link ArgumentMatchers} class * * @param matcher decides whether argument matches * @return <code>0</code>. */ public static double doubleThat(ArgumentMatcher<Double> matcher) { reportMatcher(matcher); return 0; } private static void reportMatcher(ArgumentMatcher<?> matcher) { mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher); } }
Adds deprecation for generic method to avoid casting, as it is not anymore necessary in Java 8
src/main/java/org/mockito/ArgumentMatchers.java
Adds deprecation for generic method to avoid casting, as it is not anymore necessary in Java 8
Java
mit
404bdf9713a94646d955460db308bfea30c963bb
0
GilbertoRP/SemNomeAindaCartolaFC
package com.SemNomeAindaCartolaFC.Athletes; import org.json.*; public class AthleteFactory { public Athlete createAthleteFrom(JSONObject athleteData) { Athlete athlete = new Athlete(); athlete.name = athleteData.getString("nome"); athlete.id = athleteData.getInt("atleta_id"); athlete.nick = athleteData.getString("apelido"); athlete.photoURL = athleteData.getString("foto"); athlete.price = athleteData.getDouble("preco_num"); athlete.variation = athleteData.getDouble("variacao_num"); athlete.mean = athleteData.getDouble("media_num"); athlete.gamesPlayed = athleteData.getInt("jogos_num"); athlete.position_id = athleteData.getInt("posicao_id"); athlete.orderingKey = athlete.mean * 3 + athlete.variation * 2 + athlete.price * 1; return athlete; } }
src/com/SemNomeAindaCartolaFC/Athletes/AthleteFactory.java
package com.SemNomeAindaCartolaFC.Athletes; import org.json.*; public class AthleteFactory { public Athlete createAthleteFrom(JSONObject athleteData) { Athlete athlete = new Athlete(); athlete.name = athleteData.getString("name"); athlete.id = athleteData.getInt("id"); athlete.nick = athleteData.getString("nick"); athlete.photoURL = athleteData.getString("photoURL"); athlete.price = athleteData.getDouble("price"); athlete.variation = athleteData.getDouble("variation"); athlete.mean = athleteData.getDouble("mean"); athlete.gamesPlayed = athleteData.getInt("gamesPlayed"); athlete.position_id = athleteData.getInt("position_id"); athlete.orderingKey = athleteData.getDouble("orderingKey"); return athlete; } }
Chg: OrderingKey generated when factory creates an athlete.
src/com/SemNomeAindaCartolaFC/Athletes/AthleteFactory.java
Chg: OrderingKey generated when factory creates an athlete.
Java
mit
89237fff9589fdc1a125fdaf78823e7761bfd6dd
0
TextFileDataTools/text-file-data-tools,stexfires/stexfires,stexfires/stexfires
package org.textfiledatatools.util; import java.util.Objects; import java.util.function.IntPredicate; import java.util.function.Predicate; /** * @author Mathias Kalb * @since 0.1 */ public enum StringCheckType { NULL, NOT_NULL, EMPTY, ALPHABETIC, ASCII, DIGIT, LETTER, LETTER_OR_DIGIT, LOWER_CASE, SPACE_CHAR, UPPER_CASE, WHITESPACE; private static final int FIRST_NON_ASCII_CHAR = 128; public static Predicate<String> stringPredicate(StringCheckType stringCheckType) { Objects.requireNonNull(stringCheckType); return value -> check(value, stringCheckType); } private static boolean check(String value, StringCheckType stringCheckType) { Objects.requireNonNull(stringCheckType); switch (stringCheckType) { case NULL: return value == null; case NOT_NULL: return value != null; case EMPTY: return (value != null) && value.isEmpty(); case ALPHABETIC: return checkAllChars(value, Character::isAlphabetic); case ASCII: return checkAllChars(value, c -> c < FIRST_NON_ASCII_CHAR); case DIGIT: return checkAllChars(value, Character::isDigit); case LETTER: return checkAllChars(value, Character::isLetter); case LETTER_OR_DIGIT: return checkAllChars(value, Character::isLetterOrDigit); case LOWER_CASE: return checkAllChars(value, Character::isLowerCase); case SPACE_CHAR: return checkAllChars(value, Character::isSpaceChar); case UPPER_CASE: return checkAllChars(value, Character::isUpperCase); case WHITESPACE: return checkAllChars(value, Character::isWhitespace); default: return false; } } private static boolean checkAllChars(String value, IntPredicate predicate) { return (value != null) && !value.isEmpty() && value.chars().allMatch(predicate); } public Predicate<String> stringPredicate() { return value -> check(value, this); } public boolean check(String value) { return check(value, this); } }
src/main/java/org/textfiledatatools/util/StringCheckType.java
package org.textfiledatatools.util; import java.util.Objects; import java.util.function.IntPredicate; import java.util.function.Predicate; /** * @author Mathias Kalb * @since 0.1 */ public enum StringCheckType { NULL, NOT_NULL, EMPTY, ALPHABETIC, ASCII, DIGIT, LETTER, LETTER_OR_DIGIT, LOWER_CASE, SPACE_CHAR, UPPER_CASE, WHITESPACE; public static Predicate<String> stringPredicate(StringCheckType stringCheckType) { Objects.requireNonNull(stringCheckType); return value -> check(value, stringCheckType); } private static boolean check(String value, StringCheckType stringCheckType) { Objects.requireNonNull(stringCheckType); switch (stringCheckType) { case NULL: return value == null; case NOT_NULL: return value != null; case EMPTY: return (value != null) && value.isEmpty(); case ALPHABETIC: return checkAllChars(value, Character::isAlphabetic); case ASCII: return checkAllChars(value, c -> c < 128); case DIGIT: return checkAllChars(value, Character::isDigit); case LETTER: return checkAllChars(value, Character::isLetter); case LETTER_OR_DIGIT: return checkAllChars(value, Character::isLetterOrDigit); case LOWER_CASE: return checkAllChars(value, Character::isLowerCase); case SPACE_CHAR: return checkAllChars(value, Character::isSpaceChar); case UPPER_CASE: return checkAllChars(value, Character::isUpperCase); case WHITESPACE: return checkAllChars(value, Character::isWhitespace); default: return false; } } private static boolean checkAllChars(String value, IntPredicate predicate) { return (value != null) && !value.isEmpty() && value.chars().allMatch(predicate); } public Predicate<String> stringPredicate() { return value -> check(value, this); } public boolean check(String value) { return check(value, this); } }
Extract Constant 128
src/main/java/org/textfiledatatools/util/StringCheckType.java
Extract Constant 128
Java
mit
996a9c375a14b17089e9f25e1af075797993253f
0
tqn/javaclass-game
import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.util.ArrayList; public class WorldObject { private static final Double[] ORIGIN = { Double.valueOf(0), Double.valueOf(0) }; protected ArrayList<Shape> shapes; protected ArrayList<AffineTransform> transforms; protected ArrayList<Double[]> centers; protected ArrayList<Color> colors; protected AffineTransform transform; protected Double[] center; public WorldObject() { this(null); } public WorldObject(GeneralPath p) { this((Shape) p); } public WorldObject(GeneralPath p, AffineTransform at) { this((Shape) p, at); } public WorldObject(Shape s) { this(s, new AffineTransform()); } public WorldObject(Shape s, AffineTransform at) { // make non null if (at == null) { at = new AffineTransform(); } this.shapes = new ArrayList<>(); this.transforms = new ArrayList<>(); this.centers = new ArrayList<>(); this.colors = new ArrayList<>(); if (s != null) { this.shapes.add(s); this.transforms.add(new AffineTransform()); this.centers.add(ORIGIN); this.colors.add(Color.BLACK); // the center of the whole object Rectangle2D bb = s.getBounds2D(); this.center = new Double[] { bb.getCenterX(), bb.getCenterY() }; } else { // default center 0,0 this.center = ORIGIN; } // the transform of the whole object this.transform = at; } public void render(Graphics2D g) { for (int i = 0; i < shapes.size(); i++) { Shape s = shapes.get(i); // transform each individual Shape s = transforms.get(i).createTransformedShape(s); // transform the object s = transform.createTransformedShape(s); g.setColor(colors.get(i)); g.fill(s); } } public Shape renderMesh(Shape s) { int index = shapes.indexOf(s); return transforms.get(index).createTransformedShape(shapes.get(index)); } public ArrayList<Shape> getShapes() { return shapes; } public Shape addShape(Shape s) { getShapes().add(s); Rectangle2D bb = s.getBounds2D(); Double[] center = {Double.valueOf(bb.getCenterX()), Double.valueOf(bb.getCenterY())}; setTransform(s, new AffineTransform()); setCenter(s, center); setColor(s, Color.BLACK); return s; } public Shape lastShape() { return getShapes().get(shapes.size() - 1); } public AffineTransform getTransform() { return transform; } public AffineTransform getTransform(Shape s) { return transforms.get(shapes.indexOf(s)); } public void setTransform(Shape s, AffineTransform at) { int index = shapes.indexOf(s); if (index >= transforms.size()) { transforms.add(at); } else { transforms.set(index, at); } } public Double[] getCenter(Shape s) { return centers.get(shapes.indexOf(s)); } public void setCenter(Shape s, Double[] center) { int index = shapes.indexOf(s); if (index >= centers.size()) { centers.add(center); } else { centers.set(index, center); } } public Color getColor(Shape s) { return colors.get(shapes.indexOf(s)); } public void setColor(Shape s, Color color) { int index = shapes.indexOf(s); if (index >= colors.size()) { colors.add(color); } else { colors.set(index, color); } } public Double[] getCenter() { return center; } public void setCenter(Double[] center) { this.center = center; } }
src/WorldObject.java
import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.util.ArrayList; public class WorldObject { private static final Double[] ORIGIN = { Double.valueOf(0), Double.valueOf(0) }; protected ArrayList<Shape> shapes; protected ArrayList<AffineTransform> transforms; protected ArrayList<Double[]> centers; protected ArrayList<Color> colors; protected AffineTransform transform; public WorldObject() { this(new GeneralPath()); } public WorldObject(GeneralPath p) { this((Shape) p); } public WorldObject(GeneralPath p, AffineTransform at) { this((Shape) p, at); } public WorldObject(Shape s) { this(s, new AffineTransform()); } public WorldObject(Shape s, AffineTransform at) { this.shapes = new ArrayList<>(); this.transforms = new ArrayList<>(); this.centers = new ArrayList<>(); this.colors = new ArrayList<>(); this.shapes.add(s); this.transforms.add(new AffineTransform()); this.centers.add(ORIGIN); this.colors.add(Color.BLACK); // the transform of the whole object this.transform = at; } public void render(Graphics2D g) { for (int i = 0; i < shapes.size(); i++) { Shape s = shapes.get(i); // transform each individual Shape s = transforms.get(i).createTransformedShape(s); // transform the object s = transform.createTransformedShape(s); g.setColor(colors.get(i)); g.fill(s); } } public Shape renderMesh(Shape s) { int index = shapes.indexOf(s); return transforms.get(index).createTransformedShape(shapes.get(index)); } public ArrayList<Shape> getShapes() { return shapes; } public Shape addShape(Shape s) { getShapes().add(s); Rectangle2D bb = s.getBounds2D(); Double[] center = {Double.valueOf(bb.getCenterX()), Double.valueOf(bb.getCenterY())}; setTransform(s, new AffineTransform()); setCenter(s, center); setColor(s, Color.BLACK); return s; } public Shape lastShape() { return getShapes().get(shapes.size() - 1); } public AffineTransform getTransform() { return transform; } public AffineTransform getTransform(Shape s) { return transforms.get(shapes.indexOf(s)); } public void setTransform(Shape s, AffineTransform at) { int index = shapes.indexOf(s); if (index >= transforms.size()) { transforms.add(at); } else { transforms.set(index, at); } } public Double[] getCenter(Shape s) { return centers.get(shapes.indexOf(s)); } public void setCenter(Shape s, Double[] center) { int index = shapes.indexOf(s); if (index >= centers.size()) { centers.add(center); } else { centers.set(index, center); } } public Color getColor(Shape s) { return colors.get(shapes.indexOf(s)); } public void setColor(Shape s, Color color) { int index = shapes.indexOf(s); if (index >= colors.size()) { colors.add(color); } else { colors.set(index, color); } } }
Added general center property to WorldObject You can use the center to rotate around and for other transformations
src/WorldObject.java
Added general center property to WorldObject
Java
mit
a306725bae9cb8b6d148cf547c07784076f7b338
0
talandar/ProgressiveDifficulty,talandar/ProgressiveDifficulty
package derpatiel.progressivediff; import derpatiel.progressivediff.util.LOG; import derpatiel.progressivediff.util.MobNBTHandler; import net.minecraft.advancements.Advancement; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.ForgeRegistries; import org.apache.commons.lang3.builder.Diff; import javax.annotation.Nullable; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.List; /** * Created by Jim on 5/7/2017. */ public class ServerCommand extends CommandBase { private String[] usage = new String[]{ "progdiff (Progressive Difficulty) help:", "\"progdiff sync\" sync the config for the server", " Useful for testing difficulty configs.", "\"progdiff killmodified\" kill modified mobs in the ", " same dimension as the player", "\"progdiff advancements\" print a list of all loaded", " advancements to the configuration directory as", " progdiff_advancements.txt", " (filters out advancements under minecraft:recipes/*)" }; @Override public String getName() { return "progdiff"; } @Override public String getUsage(ICommandSender sender) { return "\"progdiff [sync|killmodified|advancements]\""; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if(args.length==0 || args.length>1){ sendChat(sender,usage); }else if(args[0].equalsIgnoreCase("sync")){ DifficultyConfiguration.syncConfig(); sendChat(sender, new String[]{"Synced config."}); }else if(args[0].equalsIgnoreCase("killmodified")){ sendChat(sender, new String[]{"Killing all modified mobs in this dimension."}); MobNBTHandler.getModifiedEntities(sender.getEntityWorld()).stream().forEach(mob->{ mob.setDead(); }); }else if(args[0].equalsIgnoreCase("advancements")){ File configDir = DifficultyConfiguration.config.getConfigFile().getParentFile(); File advancementsFile = new File(configDir,"progdiff_advancements.txt"); try(BufferedWriter writer = new BufferedWriter(new FileWriter(advancementsFile))){ for(Advancement advancement : sender.getServer().getAdvancementManager().getAdvancements()){ String id = advancement.getId().toString(); if(!id.startsWith("minecraft:recipes")) { writer.write(advancement.getId().toString()); writer.newLine(); } } }catch(Exception e){ sendChat(sender, new String[]{ "There was a problem writing the advancements file.", }); if(advancementsFile.exists()){ try { advancementsFile.delete(); }catch(Exception e2){ sendChat(sender, new String[]{ "There was a problem deleting the broken file.", "Please manually delete the \"progdiff_advancements.txt\" file before trying again." }); } } } }else{ sendChat(sender,usage); } } private void sendChat(ICommandSender sender, String[] msg){ EntityPlayer player = (EntityPlayer)sender.getCommandSenderEntity(); for (String str : msg) { TextComponentString line = new TextComponentString(str); player.sendMessage(line); } } @Override public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { String[] validCompletions = new String[]{ "sync", "killmodified", "advancements" }; return CommandBase.getListOfStringsMatchingLastWord(args, validCompletions); } return CommandBase.getListOfStringsMatchingLastWord(args, new String[0]); } }
src/main/java/derpatiel/progressivediff/ServerCommand.java
package derpatiel.progressivediff; import derpatiel.progressivediff.util.LOG; import derpatiel.progressivediff.util.MobNBTHandler; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.ForgeRegistries; import javax.annotation.Nullable; import java.util.Iterator; import java.util.List; /** * Created by Jim on 5/7/2017. */ public class ServerCommand extends CommandBase { private String[] usage = new String[]{ "progdiff (Progressive Difficulty) help:", "\"progdiff sync\" sync the config for the server", " Useful for testing difficulty configs.", }; @Override public String getName() { return "progdiff"; } @Override public String getUsage(ICommandSender sender) { return "\"progdiff [sync|killmodified]\""; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if(args.length==0 || args.length>1){ sendChat(sender,usage); } if(args[0].equalsIgnoreCase("sync")){ DifficultyConfiguration.syncConfig(); sendChat(sender, new String[]{"Synced config."}); }else if(args[0].equalsIgnoreCase("killmodified")){ sendChat(sender, new String[]{"Killing all modified mobs in this dimension."}); MobNBTHandler.getModifiedEntities(sender.getEntityWorld()).stream().forEach(mob->{ mob.setDead(); }); }else{ sendChat(sender,usage); } } private void sendChat(ICommandSender sender, String[] msg){ EntityPlayer player = (EntityPlayer)sender.getCommandSenderEntity(); for (String str : msg) { TextComponentString line = new TextComponentString(str); player.sendMessage(line); } } @Override public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { String[] validCompletions = new String[]{ "sync", "killmodified" }; return CommandBase.getListOfStringsMatchingLastWord(args, validCompletions); } return CommandBase.getListOfStringsMatchingLastWord(args, new String[0]); } }
create new console command for printing advancements
src/main/java/derpatiel/progressivediff/ServerCommand.java
create new console command for printing advancements
Java
mit
85b412aaed7c832a5d8fb90a0cd63ec741e6cad6
0
shitikanth/jabref,ayanai1/jabref,Braunch/jabref,obraliar/jabref,zellerdev/jabref,Mr-DLib/jabref,Mr-DLib/jabref,motokito/jabref,Mr-DLib/jabref,tobiasdiez/jabref,motokito/jabref,jhshinn/jabref,obraliar/jabref,jhshinn/jabref,obraliar/jabref,jhshinn/jabref,JabRef/jabref,JabRef/jabref,tobiasdiez/jabref,grimes2/jabref,grimes2/jabref,Braunch/jabref,tschechlovdev/jabref,shitikanth/jabref,zellerdev/jabref,obraliar/jabref,mredaelli/jabref,Braunch/jabref,motokito/jabref,mredaelli/jabref,jhshinn/jabref,ayanai1/jabref,mairdl/jabref,mairdl/jabref,Siedlerchr/jabref,motokito/jabref,tschechlovdev/jabref,ayanai1/jabref,obraliar/jabref,shitikanth/jabref,mairdl/jabref,zellerdev/jabref,tschechlovdev/jabref,Braunch/jabref,bartsch-dev/jabref,JabRef/jabref,bartsch-dev/jabref,ayanai1/jabref,grimes2/jabref,sauliusg/jabref,sauliusg/jabref,bartsch-dev/jabref,tschechlovdev/jabref,zellerdev/jabref,sauliusg/jabref,sauliusg/jabref,oscargus/jabref,mairdl/jabref,Siedlerchr/jabref,ayanai1/jabref,Mr-DLib/jabref,mredaelli/jabref,motokito/jabref,Siedlerchr/jabref,oscargus/jabref,shitikanth/jabref,oscargus/jabref,Siedlerchr/jabref,oscargus/jabref,mredaelli/jabref,JabRef/jabref,tobiasdiez/jabref,bartsch-dev/jabref,grimes2/jabref,grimes2/jabref,bartsch-dev/jabref,tobiasdiez/jabref,shitikanth/jabref,jhshinn/jabref,zellerdev/jabref,Braunch/jabref,oscargus/jabref,mairdl/jabref,mredaelli/jabref,tschechlovdev/jabref,Mr-DLib/jabref
/* Copyright (C) 2003 Morten O. Alver and Nizar N. Batada All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref; import java.util.*; import java.io.*; import java.net.*; import java.util.regex.*; import org.xml.sax.*; // for medline import org.xml.sax.helpers.*; //for medline import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; /* // int jabrefframe BibtexDatabase database=new BibtexDatabase(); String filename=Globals.getNewFile(); ArrayList bibitems=readISI(filename); // is there a getFileName(); Iterator it = bibitems.iterator(); while(it.hasNext()){ BibtexEntry entry = (BibtexEntry)it.next(); entry.setId(Util.createId(entry.getType(), database); try { database.insertEntry(entry); } catch (KeyCollisionException ex) { } } */ public class ImportFormatReader { /** * Describe <code>fixAuthor</code> method here. * * @param in a <code>String</code> value * @return a <code>String</code> value // input format string: LN FN [and LN, FN]* // output format string: FN LN [and FN LN]* */ static String fixAuthor_nocomma(String in){ StringBuffer sb=new StringBuffer(); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ //System.out.println(authors[i]); authors[i]=authors[i].trim(); String[] t = authors[i].split(" "); sb.append( t[1].trim() + " " + t[0].trim()); if(i==authors.length-1) sb.append("."); else sb.append(" and "); } return sb.toString(); } //======================================================== // rearranges the author names // input format string: LN, FN [and LN, FN]* // output format string: FN LN [and FN LN]* //======================================================== public static String fixAuthor(String in){ //Util.pr("firstnamefirst"); StringBuffer sb=new StringBuffer(); //System.out.println("FIX AUTHOR: in= " + in); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ String[] t = authors[i].split(","); if(t.length < 2) return in; // something went wrong or there is no "," sb.append( t[1].trim() + " " + t[0].trim()); if(i != authors.length-1 ) // put back the " and " sb.append(" and "); } return sb.toString(); } //======================================================== // rearranges the author names // input format string: LN, FN [and LN, FN]* // output format string: LN, FN [and LN, FN]* //======================================================== public static String fixAuthor_lastnameFirst(String in){ //Util.pr("lastnamefirst: in"); StringBuffer sb=new StringBuffer(); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ String[] t = authors[i].split(","); if(t.length < 2) { // The name is without a comma, so it must be rearranged. t = authors[i].split(" "); if (t.length > 1) { sb.append(t[t.length - 1]+ ","); // Last name for (int j=0; j<t.length-1; j++) sb.append(" "+t[j]); } else sb.append(t[0]); } else { // The name is written with last name first, so it's ok. sb.append(authors[i]); } if(i !=authors.length-1) sb.append(" and "); } //Util.pr(in+" -> "+sb.toString()); return sb.toString(); } //============================================================ // given a filename, parses the file (assuming scifinder) // returns null if unable to find any entries or if the // file is not in scifinder format //============================================================ static ArrayList readScifinder( String filename) { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split("START_RECORD"); int rowNum=0; HashMap hm=new HashMap(); for(int i=1; i<entries.length; i++){ String[] fields = entries[i].split("FIELD "); String Type=""; hm.clear(); // reset for(int j=0; j<fields.length; j++){ String tmp[]=fields[j].split(":"); if(tmp.length > 1){//==2 if(tmp[0].equals("Author")) hm.put( "author", tmp[1].replaceAll(";"," and ") ); else if(tmp[0].equals("Title")) hm.put("title",tmp[1]); else if(tmp[0].equals("Journal Title")) hm.put("journal",tmp[1]); else if(tmp[0].equals("Volume")) hm.put("volume",tmp[1]); else if(tmp[0].equals("Page")) hm.put("pages",tmp[1]); else if(tmp[0].equals("Publication Year")) hm.put("year",tmp[1]); else if(tmp[0].equals("Abstract")) hm.put("abstract",tmp[1]); else if(tmp[0].equals("Supplementary Terms")) hm.put("keywords",tmp[1]); else if(tmp[0].equals("Document Type")) Type=tmp[1].replaceAll("Journal","article"); } } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static ArrayList readISI( String filename) //jbm for new Bibitem { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader( filename)); //Pattern fieldPattern = Pattern.compile("^AU |^TI |^SO |^DT |^C1 |^AB |^ID |^BP |^PY |^SE |^PY |^VL |^IS "); String str; while ((str = in.readLine()) != null) { if(str.length() <3) continue; // begining of a new item if( str.substring(0,3).equals("PT ")){ sb.append("::"+str); } else{ String beg = str.substring(0,3).trim(); // I could have used the fieldPattern regular expression instead however this seems to be // quick and dirty and it works! if(beg.length()==2) { sb.append(" ## ");// mark the begining of each field sb.append(str); }else{ sb.append("EOLEOL");// mark the end of each line sb.append(str.substring(2,str.length()));//remove the initial " " } } } in.close(); } catch (IOException e) { //JOptionPane.showMessageDialog(null, "Error: reading " + filename ); System.err.println("Error reading file: " + filename); return null; } String[] entries = sb.toString().split("::"); // skip the first entry as it is either empty or has document header int rowNum = 0; HashMap hm=new HashMap(); for(int i=1; i<entries.length; i++){ String[] fields = entries[i].split(" ## "); String Type="",PT="",pages=""; hm.clear(); for(int j=0; j<fields.length; j++){ String beg=fields[j].substring(0,2); if(beg.equals("PT")){ PT = fields[j].substring(2,fields[j].length()).trim().replaceAll("Journal","article"); Type = "article"; //make all of them PT? } else if(beg.equals("AU")) hm.put( "author", fixAuthor( fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," and ") )); else if(beg.equals("TI")) hm.put("title", fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("SO")){ // journal name hm.put("journal",fields[j].substring(2,fields[j].length()).trim()); } else if(beg.equals("ID")) hm.put( "keywords",fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("AB")) hm.put("abstract", fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("BP")) //hm.put("pages", fields[j].substring(2,fields[j].length()).trim()); pages=fields[j].substring(2,fields[j].length()).trim(); else if(beg.equals("EP")){ pages=pages + "--" + fields[j].substring(2,fields[j].length()).trim(); } else if(beg.equals("IS")) hm.put( "number",fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("PY")) hm.put("year", fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("VL")) hm.put( "volume",fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("DT")){ Type = fields[j].substring(2,fields[j].length()).trim(); if(!Type.equals("Article") && !PT.equals("Journal"))//Article")) Type="misc"; else Type="article"; }//ignore else if(beg.equals("CR")) //cited references hm.put("CitedReferences",fields[j].substring(2,fields[j].length()).replaceAll("EOLEOL"," ; ").trim()); } hm.put("pages",pages); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static Pattern ovid_src_pat= Pattern.compile("Source ([ \\w&\\-]+)\\.[ ]+([0-9]+)\\(([\\w\\-]+)\\):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])"); static Pattern ovid_src_pat_no_issue= Pattern.compile("Source ([ \\w&\\-]+)\\.[ ]+([0-9]+):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])"); static ArrayList readOvid( String filename){ ArrayList bibitems = new ArrayList(); File f=new File(filename); int rowNum=0; if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error: " + filename + " is not a valid file and|or is not readable."); return null; } try{ BufferedReader in = new BufferedReader(new FileReader(filename)); String line; StringBuffer sb=new StringBuffer(); while((line=in.readLine()) != null){ if(line.length()>0 && line.charAt(0) != ' ') sb.append("__NEWFIELD__"); sb.append(line); } in.close(); String items[]=sb.toString().split("<[0-9]+>"); String key=""; String BibManKey=""; for(int i =1; i<items.length; i++){ HashMap h=new HashMap(); String[] fields=items[i].split("__NEWFIELD__"); for(int j=0; j<fields.length; j++){ fields[j]=fields[j].trim(); if(fields[j].indexOf("Author") == 0 && fields[j].indexOf("Author Keywords") ==-1 && fields[j].indexOf("Author e-mail") ==-1){ String author; boolean isComma=false; if( fields[j].indexOf(";") > 0){ //LN FN; [LN FN;]* author = fields[j].substring(7,fields[j].length()).replaceAll("[^\\.A-Za-z,;\\- ]","").replaceAll(";"," and "); } else{// LN FN. [LN FN.]* isComma=true; author = fields[j].substring(7,fields[j].length()).replaceAll("\\."," and").replaceAll(" and$",""); } if(author.split(" and ").length > 1){ // single author or no ";" if(isComma==false) h.put("author", fixAuthor( author) ); else h.put("author", fixAuthor_nocomma( author) ); } else h.put("author",author); } else if(fields[j].indexOf("Title") == 0) h.put("title", fields[j].substring(6,fields[j].length()).replaceAll("\\[.+\\]","") ); else if(fields[j].indexOf("Source") == 0){ String s=fields[j]; Matcher matcher = ovid_src_pat.matcher(s); boolean matchfound = matcher.find(); if(matchfound){ h.put("journal", matcher.group(1)); h.put("volume", matcher.group(2)); h.put("issue", matcher.group(3)); h.put("pages", matcher.group(4)); h.put("year", matcher.group(5)); }else{// may be missing the issue matcher = ovid_src_pat_no_issue.matcher(s); matchfound = matcher.find(); if(matchfound){ h.put("journal", matcher.group(1)); h.put("volume", matcher.group(2)); h.put("pages", matcher.group(3)); h.put("year", matcher.group(4)); } } } else if(fields[j].indexOf("Abstract")==0) h.put("abstract",fields[j].substring(9,fields[j].length())); //else if(fields[j].indexOf("References")==0) // h.put("references", fields[j].substring( 11,fields[j].length())); } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType("article")); // id assumes an existing database so don't create one here b.setField( h); bibitems.add( b ); } } catch(IOException ex){ return null; } return bibitems; } static File checkAndCreateFile(String filename){ File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); Globals.logger( "Error " + filename + " is not a valid file and|or is not readable."); return null; }else return f; } // check here for details on the format // http://www.ecst.csuchico.edu/~jacobsd/bib/formats/endnote.html static ArrayList readEndnote(String filename){ String ENDOFRECORD="__EOREOR__"; ArrayList bibitems = new ArrayList(); File f = checkAndCreateFile( filename );// will return null if file is not readable if(f==null) return null; StringBuffer sb = new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; boolean first = true; while ((str = in.readLine()) != null) { str = str.trim(); // if(str.equals("")) continue; if(str.indexOf("%0")==0){ if (first) { first = false; } else { sb.append(ENDOFRECORD); } sb.append(str); }else sb.append(str); sb.append("\n"); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split(ENDOFRECORD); int rowNum=0; HashMap hm=new HashMap(); String Author="",Type="",Editor=""; for(int i=0; i<entries.length; i++){ hm.clear(); Author=""; Type="";Editor=""; String[] fields = entries[i].substring(1).split("\n%"); //String lastPrefix = ""; for(int j=0; j <fields.length; j++){ if(fields[j].length() < 3) continue; /* Details of Refer format for Journal Article and Book: Generic Ref Journal Article Book Code Author %A Author Author Year %D Year Year Title %T Title Title Secondary Author %E Series Editor Secondary Title %B Journal Series Title Place Published %C City Publisher %I Publisher Volume %V Volume Volume Number of Volumes %6 Number of Volumes Number %N Issue Pages %P Pages Number of Pages Edition %7 Edition Subsidiary Author %? Translator Alternate Title %J Alternate Journal Label %F Label Label Keywords %K Keywords Keywords Abstract %X Abstract Abstract Notes %O Notes Notes */ String prefix=fields[j].substring(0,1); String val = fields[j].substring(2); if( prefix.equals("A")){ if( Author.equals("")) Author=val; else Author += " and " + val; } else if(prefix.equals("Y")){ if( Editor.equals("")) Editor=val; else Editor += " and " + val; } else if(prefix.equals("T")) hm.put("title", Globals.putBracesAroundCapitals(val)); else if(prefix.equals("0")){ if(val.indexOf("Journal")==0) Type="article"; else if((val.indexOf("Book")==0) || (val.indexOf("Edited Book")==0)) Type="book"; else if( val.indexOf("Conference")==0)// Proceedings Type="inproceedings"; else if( val.indexOf("Report")==0) // Techreport Type="techreport"; else Type = "misc"; // } else if(prefix.equals("7")) hm.put("edition",val); else if(prefix.equals("C")) hm.put("address",val); else if(prefix.equals("D")) hm.put("year",val); else if(prefix.equals("8")) hm.put("date",val); else if(prefix.equals("J")) { // "Alternate journal. Let's set it only if no journal // has been set with %B. if (hm.get("journal") == null) hm.put("journal", val); } else if (prefix.equals("B")) { // This prefix stands for "journal" in a journal entry, and // "series" in a book entry. if (Type.equals("article")) hm.put("journal", val); else if (Type.equals("book") || Type.equals("inbook")) hm.put("series", val); else /* if (Type.equals("inproceedings"))*/ hm.put("booktitle", val); } else if(prefix.equals("I")) hm.put("publisher",val); else if(prefix.equals("P")) hm.put("pages",val); else if(prefix.equals("V")) hm.put("volume",val); else if(prefix.equals("N")) hm.put("number",val); else if(prefix.equals("U")) hm.put("url",val); else if(prefix.equals("O")) hm.put("note",val); else if(prefix.equals("K")) hm.put("keywords", val); else if(prefix.equals("X")) hm.put("abstract",val); else if(prefix.equals("9")) { //Util.pr(val); if (val.indexOf("Ph.D.")==0) Type = "phdthesis"; } else if(prefix.equals("F")) hm.put (Globals.KEY_FIELD,Util.checkLegalKey(val)); } //fixauthorscomma if (!Author.equals("")) hm.put("author",fixAuthor(Author)); if( !Editor.equals("")) hm.put("editor",fixAuthor(Editor)); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); //if (hm.isEmpty()) if (b.getAllFields().length > 0) bibitems.add(b); } return bibitems; } //======================================================== // //======================================================== static ArrayList readReferenceManager10(String filename) { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while ((str = in.readLine()) != null) { sb.append(str); sb.append("\n"); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split("ER -"); int rowNum=0; HashMap hm=new HashMap(); for(int i=0; i<entries.length-1; i++){ String Type="",Author="",StartPage="",EndPage=""; hm.clear(); String[] fields = entries[i].split("\n"); for(int j=0; j <fields.length; j++){ if(fields[j].length() < 2) continue; else{ String lab = fields[j].substring(0,2); String val = fields[j].substring(6).trim(); if(lab.equals("TY")){ if(val.equals("BOOK")) Type = "book"; else if (val.equals("JOUR")) Type = "article"; else Type = "other"; }else if(lab.equals("T1")) hm.put("title",val);//Title = val; else if(lab.equals("A1") ||lab.equals("AU")){ if( Author.equals("")) // don't add " and " for the first author Author=val; else Author += " and " + val; }else if( lab.equals("JA") || lab.equals("JF") || lab.equals("JO")) hm.put("journal",val); else if(lab.equals("SP")) StartPage=val; else if(lab.equals("EP")) EndPage=val; else if(lab.equals("VL")) hm.put("volume",val); else if(lab.equals("N2") || lab.equals("AB")) hm.put("abstract",val); else if(lab.equals("UR")) hm.put("url",val); else if((lab.equals("Y1")||lab.equals("PY"))&& val.length()>=4) hm.put("year",val.substring(0,4)); } } // fix authors Author = fixAuthor(Author); if(Author.endsWith(".")) hm.put("author", Author.substring(0,Author.length()-1)); else hm.put("author", Author); hm.put("pages",StartPage+"--"+EndPage); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static ArrayList readMedline(String filename) { File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it creates parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object ArrayList bibItems=null; try{ SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions MedlineHandler handler = new MedlineHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse(new File(filename), handler); // When you're done, report the results stored by your handler object bibItems = handler.getItems(); } catch(javax.xml.parsers.ParserConfigurationException e1){} catch(org.xml.sax.SAXException e2){} catch(java.io.IOException e3){} return bibItems; } //================================================== // //================================================== static ArrayList fetchMedline(String id) { ArrayList bibItems=null; try { String baseUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=citation&id=" + id; URL url = new URL( baseUrl ); HttpURLConnection data = (HttpURLConnection)url.openConnection(); // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it creates parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions MedlineHandler handler = new MedlineHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse( data.getInputStream(), handler); // When you're done, report the results stored by your handler object bibItems = handler.getItems(); } catch(javax.xml.parsers.ParserConfigurationException e1){} catch(org.xml.sax.SAXException e2){} catch(java.io.IOException e3){} return bibItems; } //======================================================== // //======================================================== static ArrayList readINSPEC( String filename) { ArrayList bibitems = new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while((str=in.readLine())!=null){ if(str.length() < 2) continue; if(str.indexOf("Record")==0) sb.append("__::__"+str); else sb.append("__NEWFIELD__"+str); } in.close(); String[] entries = sb.toString().split("__::__"); String Type=""; int rowNum=0; HashMap h=new HashMap(); for(int i=0; i<entries.length; i++){ if(entries[i].indexOf("Record") != 0) continue; h.clear(); String[] fields = entries[i].split("__NEWFIELD__"); for(int j=0; j<fields.length; j++){ //System.out.println(fields[j]); String s = fields[j]; String f3 = s.substring(0,2); String frest = s.substring(5); if(f3.equals("TI")) h.put("title", frest); else if(f3.equals("PY")) h.put("year", frest); else if(f3.equals("AU")) h.put("author", fixAuthor(frest.replaceAll(",-",", ").replaceAll(";"," and "))); else if(f3.equals("AB")) h.put("abstract", frest); else if(f3.equals("ID")) h.put("keywords", frest); else if(f3.equals("SO")){ int m = frest.indexOf("."); if(m >= 0){ String jr = frest.substring(0,m); h.put("journal",jr.replaceAll("-"," ")); frest = frest.substring(m); m = frest.indexOf(";"); if(m>=5){ String yr = frest.substring(m-5,m); h.put("year",yr); frest = frest.substring(m); m = frest.indexOf(":"); if(m>=0){ String pg = frest.substring(m+1).trim(); h.put("pages",pg); h.put("volume",frest.substring(1,m)); } } } } else if(f3.equals("RT")){ frest=frest.trim(); if(frest.equals("Journal-Paper")) Type="article"; else if(frest.equals("Conference-Paper") || frest.equals("Conference-Paper; Journal-Paper")) Type="inproceedings"; else Type=frest.replaceAll(" ",""); } } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( h); bibitems.add( b ); } } catch(IOException e){ return null;} return bibitems; } //================================================== // //================================================== }
src/java/net/sf/jabref/ImportFormatReader.java
/* Copyright (C) 2003 Morten O. Alver and Nizar N. Batada All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref; import java.util.*; import java.io.*; import java.net.*; import java.util.regex.*; import org.xml.sax.*; // for medline import org.xml.sax.helpers.*; //for medline import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; /* // int jabrefframe BibtexDatabase database=new BibtexDatabase(); String filename=Globals.getNewFile(); ArrayList bibitems=readISI(filename); // is there a getFileName(); Iterator it = bibitems.iterator(); while(it.hasNext()){ BibtexEntry entry = (BibtexEntry)it.next(); entry.setId(Util.createId(entry.getType(), database); try { database.insertEntry(entry); } catch (KeyCollisionException ex) { } } */ public class ImportFormatReader { /** * Describe <code>fixAuthor</code> method here. * * @param in a <code>String</code> value * @return a <code>String</code> value // input format string: LN FN [and LN, FN]* // output format string: FN LN [and FN LN]* */ static String fixAuthor_nocomma(String in){ StringBuffer sb=new StringBuffer(); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ //System.out.println(authors[i]); authors[i]=authors[i].trim(); String[] t = authors[i].split(" "); sb.append( t[1].trim() + " " + t[0].trim()); if(i==authors.length-1) sb.append("."); else sb.append(" and "); } return sb.toString(); } //======================================================== // rearranges the author names // input format string: LN, FN [and LN, FN]* // output format string: FN LN [and FN LN]* //======================================================== public static String fixAuthor(String in){ //Util.pr("firstnamefirst"); StringBuffer sb=new StringBuffer(); //System.out.println("FIX AUTHOR: in= " + in); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ String[] t = authors[i].split(","); if(t.length < 2) return in; // something went wrong or there is no "," sb.append( t[1].trim() + " " + t[0].trim()); if(i != authors.length-1 ) // put back the " and " sb.append(" and "); } return sb.toString(); } //======================================================== // rearranges the author names // input format string: LN, FN [and LN, FN]* // output format string: LN, FN [and LN, FN]* //======================================================== public static String fixAuthor_lastnameFirst(String in){ //Util.pr("lastnamefirst: in"); StringBuffer sb=new StringBuffer(); String[] authors = in.split(" and "); for(int i=0; i<authors.length; i++){ String[] t = authors[i].split(","); if(t.length < 2) { // The name is without a comma, so it must be rearranged. t = authors[i].split(" "); if (t.length > 1) { sb.append(t[t.length - 1]+ ","); // Last name for (int j=0; j<t.length-1; j++) sb.append(" "+t[j]); } else sb.append(t[0]); } else { // The name is written with last name first, so it's ok. sb.append(authors[i]); } if(i !=authors.length-1) sb.append(" and "); } //Util.pr(in+" -> "+sb.toString()); return sb.toString(); } //============================================================ // given a filename, parses the file (assuming scifinder) // returns null if unable to find any entries or if the // file is not in scifinder format //============================================================ static ArrayList readScifinder( String filename) { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split("START_RECORD"); int rowNum=0; HashMap hm=new HashMap(); for(int i=1; i<entries.length; i++){ String[] fields = entries[i].split("FIELD "); String Type=""; hm.clear(); // reset for(int j=0; j<fields.length; j++){ String tmp[]=fields[j].split(":"); if(tmp.length > 1){//==2 if(tmp[0].equals("Author")) hm.put( "author", tmp[1].replaceAll(";"," and ") ); else if(tmp[0].equals("Title")) hm.put("title",tmp[1]); else if(tmp[0].equals("Journal Title")) hm.put("journal",tmp[1]); else if(tmp[0].equals("Volume")) hm.put("volume",tmp[1]); else if(tmp[0].equals("Page")) hm.put("pages",tmp[1]); else if(tmp[0].equals("Publication Year")) hm.put("year",tmp[1]); else if(tmp[0].equals("Abstract")) hm.put("abstract",tmp[1]); else if(tmp[0].equals("Supplementary Terms")) hm.put("keywords",tmp[1]); else if(tmp[0].equals("Document Type")) Type=tmp[1].replaceAll("Journal","article"); } } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static ArrayList readISI( String filename) //jbm for new Bibitem { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader( filename)); //Pattern fieldPattern = Pattern.compile("^AU |^TI |^SO |^DT |^C1 |^AB |^ID |^BP |^PY |^SE |^PY |^VL |^IS "); String str; while ((str = in.readLine()) != null) { if(str.length() <3) continue; // begining of a new item if( str.substring(0,3).equals("PT ")){ sb.append("::"+str); } else{ String beg = str.substring(0,3).trim(); // I could have used the fieldPattern regular expression instead however this seems to be // quick and dirty and it works! if(beg.length()==2) { sb.append(" ## ");// mark the begining of each field sb.append(str); }else{ sb.append("EOLEOL");// mark the end of each line sb.append(str.substring(2,str.length()));//remove the initial " " } } } in.close(); } catch (IOException e) { //JOptionPane.showMessageDialog(null, "Error: reading " + filename ); System.err.println("Error reading file: " + filename); return null; } String[] entries = sb.toString().split("::"); // skip the first entry as it is either empty or has document header int rowNum = 0; HashMap hm=new HashMap(); for(int i=1; i<entries.length; i++){ String[] fields = entries[i].split(" ## "); String Type="",PT="",pages=""; hm.clear(); for(int j=0; j<fields.length; j++){ String beg=fields[j].substring(0,2); if(beg.equals("PT")){ PT = fields[j].substring(2,fields[j].length()).trim().replaceAll("Journal","article"); Type = "article"; //make all of them PT? } else if(beg.equals("AU")) hm.put( "author", fixAuthor( fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," and ") )); else if(beg.equals("TI")) hm.put("title", fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("SO")){ // journal name hm.put("journal",fields[j].substring(2,fields[j].length()).trim()); } else if(beg.equals("ID")) hm.put( "keywords",fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("AB")) hm.put("abstract", fields[j].substring(2,fields[j].length()).trim().replaceAll("EOLEOL"," ")); else if(beg.equals("BP")) //hm.put("pages", fields[j].substring(2,fields[j].length()).trim()); pages=fields[j].substring(2,fields[j].length()).trim(); else if(beg.equals("EP")){ pages=pages + "--" + fields[j].substring(2,fields[j].length()).trim(); } else if(beg.equals("IS")) hm.put( "number",fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("PY")) hm.put("year", fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("VL")) hm.put( "volume",fields[j].substring(2,fields[j].length()).trim()); else if(beg.equals("DT")){ Type = fields[j].substring(2,fields[j].length()).trim(); if(!Type.equals("Article") && !PT.equals("Journal"))//Article")) Type="misc"; else Type="article"; }//ignore else if(beg.equals("CR")) //cited references hm.put("CitedReferences",fields[j].substring(2,fields[j].length()).replaceAll("EOLEOL"," ; ").trim()); } hm.put("pages",pages); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static Pattern ovid_src_pat= Pattern.compile("Source ([ \\w&\\-]+)\\.[ ]+([0-9]+)\\(([\\w\\-]+)\\):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])"); static Pattern ovid_src_pat_no_issue= Pattern.compile("Source ([ \\w&\\-]+)\\.[ ]+([0-9]+):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])"); static ArrayList readOvid( String filename){ ArrayList bibitems = new ArrayList(); File f=new File(filename); int rowNum=0; if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error: " + filename + " is not a valid file and|or is not readable."); return null; } try{ BufferedReader in = new BufferedReader(new FileReader(filename)); String line; StringBuffer sb=new StringBuffer(); while((line=in.readLine()) != null){ if(line.length()>0 && line.charAt(0) != ' ') sb.append("__NEWFIELD__"); sb.append(line); } in.close(); String items[]=sb.toString().split("<[0-9]+>"); String key=""; String BibManKey=""; for(int i =1; i<items.length; i++){ HashMap h=new HashMap(); String[] fields=items[i].split("__NEWFIELD__"); for(int j=0; j<fields.length; j++){ fields[j]=fields[j].trim(); if(fields[j].indexOf("Author") == 0 && fields[j].indexOf("Author Keywords") ==-1 && fields[j].indexOf("Author e-mail") ==-1){ String author; boolean isComma=false; if( fields[j].indexOf(";") > 0){ //LN FN; [LN FN;]* author = fields[j].substring(7,fields[j].length()).replaceAll("[^\\.A-Za-z,;\\- ]","").replaceAll(";"," and "); } else{// LN FN. [LN FN.]* isComma=true; author = fields[j].substring(7,fields[j].length()).replaceAll("\\."," and").replaceAll(" and$",""); } if(author.split(" and ").length > 1){ // single author or no ";" if(isComma==false) h.put("author", fixAuthor( author) ); else h.put("author", fixAuthor_nocomma( author) ); } else h.put("author",author); } else if(fields[j].indexOf("Title") == 0) h.put("title", fields[j].substring(6,fields[j].length()).replaceAll("\\[.+\\]","") ); else if(fields[j].indexOf("Source") == 0){ String s=fields[j]; Matcher matcher = ovid_src_pat.matcher(s); boolean matchfound = matcher.find(); if(matchfound){ h.put("journal", matcher.group(1)); h.put("volume", matcher.group(2)); h.put("issue", matcher.group(3)); h.put("pages", matcher.group(4)); h.put("year", matcher.group(5)); }else{// may be missing the issue matcher = ovid_src_pat_no_issue.matcher(s); matchfound = matcher.find(); if(matchfound){ h.put("journal", matcher.group(1)); h.put("volume", matcher.group(2)); h.put("pages", matcher.group(3)); h.put("year", matcher.group(4)); } } } else if(fields[j].indexOf("Abstract")==0) h.put("abstract",fields[j].substring(9,fields[j].length())); //else if(fields[j].indexOf("References")==0) // h.put("references", fields[j].substring( 11,fields[j].length())); } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType("article")); // id assumes an existing database so don't create one here b.setField( h); bibitems.add( b ); } } catch(IOException ex){ return null; } return bibitems; } static File checkAndCreateFile(String filename){ File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); Globals.logger( "Error " + filename + " is not a valid file and|or is not readable."); return null; }else return f; } // check here for details on the format // http://www.ecst.csuchico.edu/~jacobsd/bib/formats/endnote.html static ArrayList readEndnote(String filename){ String ENDOFRECORD="__EOREOR__"; ArrayList bibitems = new ArrayList(); File f = checkAndCreateFile( filename );// will return null if file is not readable if(f==null) return null; StringBuffer sb = new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; boolean first = true; while ((str = in.readLine()) != null) { str = str.trim(); // if(str.equals("")) continue; if(str.indexOf("%0")==0){ if (first) { first = false; } else { sb.append(ENDOFRECORD); } sb.append(str); }else sb.append(str); sb.append("\n"); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split(ENDOFRECORD); int rowNum=0; HashMap hm=new HashMap(); String Author="",Type="",Editor=""; for(int i=0; i<entries.length; i++){ hm.clear(); Author=""; Type="";Editor=""; String[] fields = entries[i].substring(1).split("\n%"); //String lastPrefix = ""; for(int j=0; j <fields.length; j++){ if(fields[j].length() < 3) continue; /* Details of Refer format for Journal Article and Book: Generic Ref Journal Article Book Code Author %A Author Author Year %D Year Year Title %T Title Title Secondary Author %E Series Editor Secondary Title %B Journal Series Title Place Published %C City Publisher %I Publisher Volume %V Volume Volume Number of Volumes %6 Number of Volumes Number %N Issue Pages %P Pages Number of Pages Edition %7 Edition Subsidiary Author %? Translator Alternate Title %J Alternate Journal Label %F Label Label Keywords %K Keywords Keywords Abstract %X Abstract Abstract Notes %O Notes Notes */ String prefix=fields[j].substring(0,1); String val = fields[j].substring(2); if( prefix.equals("A")){ if( Author.equals("")) Author=val; else Author += " and " + val; } else if(prefix.equals("Y")){ if( Editor.equals("")) Editor=val; else Editor += " and " + val; } else if(prefix.equals("T")) hm.put("title", Globals.putBracesAroundCapitals(val)); else if(prefix.equals("0")){ if(val.indexOf("Journal")==0) Type="article"; else if((val.indexOf("Book")==0) || (val.indexOf("Edited Book")==0)) Type="book"; else if( val.indexOf("Conference")==0)// Proceedings Type="inproceedings"; else if( val.indexOf("Report")==0) // Techreport Type="techreport"; else Type = "misc"; // } else if(prefix.equals("7")) hm.put("edition",val); else if(prefix.equals("C")) hm.put("address",val); else if(prefix.equals("D")) hm.put("year",val); else if(prefix.equals("8")) hm.put("date",val); else if(prefix.equals("J")) { // "Alternate journal. Let's set it only if no journal // has been set with %B. if (hm.get("journal") == null) hm.put("journal", val); } else if (prefix.equals("B")) { // This prefix stands for "journal" in a journal entry, and // "series" in a book entry. if (Type.equals("article")) hm.put("journal", val); else if (Type.equals("book") || Type.equals("inbook")) hm.put("series", val); else /* if (Type.equals("inproceedings"))*/ hm.put("booktitle", val); } else if(prefix.equals("I")) hm.put("publisher",val); else if(prefix.equals("P")) hm.put("pages",val); else if(prefix.equals("V")) hm.put("volume",val); else if(prefix.equals("N")) hm.put("number",val); else if(prefix.equals("U")) hm.put("url",val); else if(prefix.equals("O")) hm.put("note",val); else if(prefix.equals("K")) hm.put("keywords", val); else if(prefix.equals("X")) hm.put("abstract",val); else if(prefix.equals("9")) { //Util.pr(val); if (val.indexOf("Ph.D.")==0) Type = "phdthesis"; } else if(prefix.equals("F")) hm.put (Globals.KEY_FIELD,Util.checkLegalKey(val)); } //fixauthorscomma if (!Author.equals("")) hm.put("author",fixAuthor(Author)); if( !Editor.equals("")) hm.put("editor",fixAuthor(Editor)); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); //if (hm.isEmpty()) if (b.getAllFields().length > 0) bibitems.add(b); } return bibitems; } //======================================================== // //======================================================== static ArrayList readReferenceManager10(String filename) { ArrayList bibitems=new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try{ BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while ((str = in.readLine()) != null) { sb.append(str); sb.append("\n"); } in.close(); } catch(IOException e){return null;} String [] entries=sb.toString().split("ER -"); int rowNum=0; HashMap hm=new HashMap(); for(int i=0; i<entries.length-1; i++){ String Type="",Author="",StartPage="",EndPage=""; hm.clear(); String[] fields = entries[i].split("\n"); for(int j=0; j <fields.length; j++){ if(fields[j].length() < 2) continue; else{ String lab = fields[j].substring(0,2); String val = fields[j].substring(6).trim(); if(lab.equals("TY")){ if(val.equals("BOOK")) Type = "book"; else if (val.equals("JOUR")) Type = "article"; else Type = "other"; }else if(lab.equals("T1")) hm.put("title",val);//Title = val; else if(lab.equals("A1") ||lab.equals("AU")){ val = val.substring(0,val.length()-1); if( Author.equals("")) // don't add " and " for the first author Author=val; else Author += " and " + val; }else if( lab.equals("JA") || lab.equals("JF") || lab.equals("JO")) hm.put("journal",val); else if(lab.equals("SP")) StartPage=val; else if(lab.equals("EP")) EndPage=val; else if(lab.equals("VL")) hm.put("volume",val); else if(lab.equals("N2") || lab.equals("AB")) hm.put("abstract",val); else if(lab.equals("UR")) hm.put("url",val); else if((lab.equals("Y1")||lab.equals("PY"))&& val.length()>=4) hm.put("year",val.substring(0,4)); } } // fix authors Author = fixAuthor(Author); if(Author.endsWith(".")) hm.put("author", Author.substring(0,Author.length()-1)); else hm.put("author", Author); hm.put("pages",StartPage+"--"+EndPage); BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( hm); bibitems.add( b ); } return bibitems; } //================================================== // //================================================== static ArrayList readMedline(String filename) { File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it creates parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object ArrayList bibItems=null; try{ SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions MedlineHandler handler = new MedlineHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse(new File(filename), handler); // When you're done, report the results stored by your handler object bibItems = handler.getItems(); } catch(javax.xml.parsers.ParserConfigurationException e1){} catch(org.xml.sax.SAXException e2){} catch(java.io.IOException e3){} return bibItems; } //================================================== // //================================================== static ArrayList fetchMedline(String id) { ArrayList bibItems=null; try { String baseUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=citation&id=" + id; URL url = new URL( baseUrl ); HttpURLConnection data = (HttpURLConnection)url.openConnection(); // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it creates parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions MedlineHandler handler = new MedlineHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse( data.getInputStream(), handler); // When you're done, report the results stored by your handler object bibItems = handler.getItems(); } catch(javax.xml.parsers.ParserConfigurationException e1){} catch(org.xml.sax.SAXException e2){} catch(java.io.IOException e3){} return bibItems; } //======================================================== // //======================================================== static ArrayList readINSPEC( String filename) { ArrayList bibitems = new ArrayList(); File f = new File(filename); if(!f.exists() && !f.canRead() && !f.isFile()){ System.err.println("Error " + filename + " is not a valid file and|or is not readable."); return null; } StringBuffer sb=new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader( filename)); String str; while((str=in.readLine())!=null){ if(str.length() < 2) continue; if(str.indexOf("Record")==0) sb.append("__::__"+str); else sb.append("__NEWFIELD__"+str); } in.close(); String[] entries = sb.toString().split("__::__"); String Type=""; int rowNum=0; HashMap h=new HashMap(); for(int i=0; i<entries.length; i++){ if(entries[i].indexOf("Record") != 0) continue; h.clear(); String[] fields = entries[i].split("__NEWFIELD__"); for(int j=0; j<fields.length; j++){ //System.out.println(fields[j]); String s = fields[j]; String f3 = s.substring(0,2); String frest = s.substring(5); if(f3.equals("TI")) h.put("title", frest); else if(f3.equals("PY")) h.put("year", frest); else if(f3.equals("AU")) h.put("author", fixAuthor(frest.replaceAll(",-",", ").replaceAll(";"," and "))); else if(f3.equals("AB")) h.put("abstract", frest); else if(f3.equals("ID")) h.put("keywords", frest); else if(f3.equals("SO")){ int m = frest.indexOf("."); if(m >= 0){ String jr = frest.substring(0,m); h.put("journal",jr.replaceAll("-"," ")); frest = frest.substring(m); m = frest.indexOf(";"); if(m>=5){ String yr = frest.substring(m-5,m); h.put("year",yr); frest = frest.substring(m); m = frest.indexOf(":"); if(m>=0){ String pg = frest.substring(m+1).trim(); h.put("pages",pg); h.put("volume",frest.substring(1,m)); } } } } else if(f3.equals("RT")){ frest=frest.trim(); if(frest.equals("Journal-Paper")) Type="article"; else if(frest.equals("Conference-Paper") || frest.equals("Conference-Paper; Journal-Paper")) Type="inproceedings"; else Type=frest.replaceAll(" ",""); } } BibtexEntry b=new BibtexEntry(Globals.DEFAULT_BIBTEXENTRY_ID, Globals.getEntryType(Type)); // id assumes an existing database so don't create one here b.setField( h); bibitems.add( b ); } } catch(IOException e){ return null;} return bibitems; } //================================================== // //================================================== }
RIS author name fix
src/java/net/sf/jabref/ImportFormatReader.java
RIS author name fix
Java
mpl-2.0
ca21a1a436538d456dc2a0580edf50617618a4a4
0
BrightSpots/rcv
package com.rcv; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; /** * Created by Jon on 8/27/17. * * Helper class to read and parse an xlsl "Maine Style" Cast Vote Record File? * * Whole lotta assumptions going on here: * We assume one contest per file * we assume the first sheet is the only one we're interested in * we assume the first column contains ballot ids, second column contains precinct id and third column contains ballot style. * we assume columns after ballot style are the ballot selections ordered by rank, low to high, left to right * we assume the strings "undervote" or "overvote" mean no vote * we assume a non-existant cell (image of a ballot mark when workbook is opened in excel?) means no vote * */ public class CVRReader { public List<CastVoteRecord> castVoteRecords = new ArrayList<>(); // call this to parse the given file path into a CastVoteRecordList suitable for tabulation // Note: this is specific for the Maine example file we were provided public void parseCVRFile( String excelFilePath, int firstVoteColumnIndex, int allowableRanks, List<String>options, String undeclaredOption, String overvoteFlag, String undervoteFlag) { Sheet contestSheet = getBallotSheet(excelFilePath); if (contestSheet == null) { RCVLogger.log("invalid RCV format: could not obtain ballot data."); System.exit(1); } // validate header Iterator<org.apache.poi.ss.usermodel.Row> iterator = contestSheet.iterator(); org.apache.poi.ss.usermodel.Row headerRow = iterator.next(); if (headerRow == null || contestSheet.getLastRowNum() < 2) { RCVLogger.log("invalid RCV format: not enough rows:%d", contestSheet.getLastRowNum()); System.exit(1); } // extract file name -- this along with ballot index will be used to generate ballot IDs File inFile = new File(excelFilePath); String cvrFileName = inFile.getName(); int ballotIndex = 1; // Iterate through all rows and create a CastVoteRecord for each row while (iterator.hasNext()) { org.apache.poi.ss.usermodel.Row castVoteRecord = iterator.next(); // TODO: determine how ballot IDs will be handled for different ballot styles String ballotID = String.format("%s(%d)",cvrFileName,ballotIndex++); // create object for this row ArrayList<ContestRanking> rankings = new ArrayList<>(); // create an object to store CVR data for auditing ArrayList<String> fullCVRData = new ArrayList<>(); // Iterate all expected cells in this row: for (int cellIndex = 0; cellIndex < firstVoteColumnIndex + allowableRanks; cellIndex++) { // cache all cvr cell data for audit report Cell cvrDataCell = castVoteRecord.getCell(cellIndex); if(cvrDataCell == null) { fullCVRData.add("empty cell"); } else if(cvrDataCell.getCellType() == Cell.CELL_TYPE_NUMERIC) { double data = cvrDataCell.getNumericCellValue(); fullCVRData.add(Double.toString(data)); } else if (cvrDataCell.getCellType() == Cell.CELL_TYPE_STRING) { fullCVRData.add(cvrDataCell.getStringCellValue()); } else { fullCVRData.add("unexpected data type"); } // if we haven't reached a vote cell continue to the next cell if(cellIndex < firstVoteColumnIndex) { continue; } // rank for this cell int rank = cellIndex - firstVoteColumnIndex + 1; String candidate; if (cvrDataCell == null) { // empty cells are treated as undeclared write-ins (for Portland / ES&S) candidate = undeclaredOption; RCVLogger.log("Empty cell -- treating as UWI"); } else { if (cvrDataCell.getCellType() != Cell.CELL_TYPE_STRING) { RCVLogger.log("unexpected cell type at ranking %d ballot %f", rank, ballotID); continue; } candidate = cvrDataCell.getStringCellValue().trim(); if (candidate.equals(undervoteFlag)) { continue; } else if (candidate.equals(overvoteFlag)) { candidate = Tabulator.explicitOvervoteFlag; } else if (!options.contains(candidate)) { if (!candidate.equals(undeclaredOption)) { RCVLogger.log("no match for candidate: %s", candidate); } candidate = undeclaredOption; } } // create and add ranking to this ballot ContestRanking ranking = new ContestRanking(rank, candidate); rankings.add(ranking); } CastVoteRecord cvr = new CastVoteRecord(ballotID, rankings, fullCVRData); castVoteRecords.add(cvr); } // parsing complete } // helper function to wrap file IO with error handling private static Sheet getBallotSheet(String excelFilePath) { FileInputStream inputStream; try { inputStream = new FileInputStream(new File(excelFilePath)); } catch (IOException ex) { RCVLogger.log("failed to open CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } Workbook workbook; try { workbook = new XSSFWorkbook(inputStream); } catch (IOException ex) { RCVLogger.log("failed to parse CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } Sheet firstSheet = workbook.getSheetAt(0); try { inputStream.close(); workbook.close(); } catch (IOException ex) { RCVLogger.log("error closing CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } return firstSheet; } }
src/com/rcv/CVRReader.java
package com.rcv; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; /** * Created by Jon on 8/27/17. * * Helper class to read and parse an xlsl "Maine Style" Cast Vote Record File? * * Whole lotta assumptions going on here: * We assume one contest per file * we assume the first sheet is the only one we're interested in * we assume the first column contains ballot ids, second column contains precinct id and third column contains ballot style. * we assume columns after ballot style are the ballot selections ordered by rank, low to high, left to right * we assume the strings "undervote" or "overvote" mean no vote * we assume a non-existant cell (image of a ballot mark when workbook is opened in excel?) means no vote * */ public class CVRReader { public List<CastVoteRecord> castVoteRecords = new ArrayList<>(); // call this to parse the given file path into a CastVoteRecordList suitable for tabulation // Note: this is specific for the Maine example file we were provided public boolean parseCVRFile( String excelFilePath, int firstVoteColumnIndex, int allowableRanks, List<String>options, String undeclaredOption, String overvoteFlag, String undervoteFlag) { Sheet contestSheet = getBallotSheet(excelFilePath); if (contestSheet == null) { RCVLogger.log("invalid RCV format: could not obtain ballot data."); System.exit(1); } // validate header Iterator<org.apache.poi.ss.usermodel.Row> iterator = contestSheet.iterator(); org.apache.poi.ss.usermodel.Row headerRow = iterator.next(); if (headerRow == null || contestSheet.getLastRowNum() < 2) { RCVLogger.log("invalid RCV format: not enough rows:%d", contestSheet.getLastRowNum()); System.exit(1); } // extract file name -- this along with ballot index will be used to generate ballot IDs File inFile = new File(excelFilePath); String cvrFileName = inFile.getName(); int ballotIndex = 1; // Iterate through all rows and create a CastVoteRecord for each row while (iterator.hasNext()) { org.apache.poi.ss.usermodel.Row castVoteRecord = iterator.next(); // TODO: determine how ballot IDs will be handled for different ballot styles String ballotID = String.format("%s(%d)",cvrFileName,ballotIndex++); // create object for this row ArrayList<ContestRanking> rankings = new ArrayList<>(); // create an object to store CVR data for auditing ArrayList<String> fullCVRData = new ArrayList<>(); // Iterate cells in this row: for (int cellIndex = 0; cellIndex < firstVoteColumnIndex + allowableRanks; cellIndex++) { // cache cell data for audit report Cell dataCell = castVoteRecord.getCell(cellIndex); if(dataCell == null) { fullCVRData.add("empty cell"); } else if(dataCell.getCellType() == Cell.CELL_TYPE_NUMERIC) { double data = dataCell.getNumericCellValue(); fullCVRData.add(new String(Double.toString(data))); } else if (dataCell.getCellType() == Cell.CELL_TYPE_STRING) { fullCVRData.add(dataCell.getStringCellValue()); } else { fullCVRData.add("unexpected data type"); } // if we haven't reached a vote cell continue to the next cell if(cellIndex < firstVoteColumnIndex) { continue; } // vote processing // rank for this cell int rank = cellIndex - firstVoteColumnIndex + 1; // cell for this rank Cell cellForRanking = castVoteRecord.getCell(cellIndex); String candidate; if (cellForRanking == null) { // empty cells are treated as undeclared write-ins (for Portland / ES&S) candidate = undeclaredOption; RCVLogger.log("Empty cell -- treating as UWI"); } else { if (cellForRanking.getCellType() != Cell.CELL_TYPE_STRING) { RCVLogger.log("unexpected cell type at ranking %d ballot %f", rank, ballotID); continue; } candidate = cellForRanking.getStringCellValue().trim(); if (candidate.equals(undervoteFlag)) { continue; } else if (candidate.equals(overvoteFlag)) { candidate = Tabulator.explicitOvervoteFlag; } else if (!options.contains(candidate)) { if (!candidate.equals(undeclaredOption)) { RCVLogger.log("no match for candidate: %s", candidate); } candidate = undeclaredOption; } } // create and add ranking to this ballot ContestRanking ranking = new ContestRanking(rank, candidate); rankings.add(ranking); } CastVoteRecord cvr = new CastVoteRecord(ballotID, rankings, fullCVRData); castVoteRecords.add(cvr); } // parsing succeeded return true; } // helper function to wrap file IO with error handling private static Sheet getBallotSheet(String excelFilePath) { FileInputStream inputStream; try { inputStream = new FileInputStream(new File(excelFilePath)); } catch (IOException ex) { RCVLogger.log("failed to open CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } Workbook workbook; try { workbook = new XSSFWorkbook(inputStream); } catch (IOException ex) { RCVLogger.log("failed to parse CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } Sheet firstSheet = workbook.getSheetAt(0); try { inputStream.close(); workbook.close(); } catch (IOException ex) { RCVLogger.log("error closing CVR file: %s, %s", excelFilePath, ex.getMessage()); return null; } return firstSheet; } }
cleanup for PR #22
src/com/rcv/CVRReader.java
cleanup for PR #22
Java
agpl-3.0
3b3e618aa82317789cde39427bfd28ce13cc6702
0
yamcs/yamcs,dhosa/yamcs,yamcs/yamcs,dhosa/yamcs,yamcs/yamcs,fqqb/yamcs,dhosa/yamcs,yamcs/yamcs,m-sc/yamcs,m-sc/yamcs,dhosa/yamcs,fqqb/yamcs,fqqb/yamcs,yamcs/yamcs,m-sc/yamcs,bitblit11/yamcs,m-sc/yamcs,m-sc/yamcs,m-sc/yamcs,fqqb/yamcs,bitblit11/yamcs,bitblit11/yamcs,bitblit11/yamcs,bitblit11/yamcs,dhosa/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs
package org.yamcs.api.ws; import java.net.URI; import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.util.concurrent.Future; /** * Netty-implementation of a Yamcs web socket client */ public class WebSocketClient { private static final Logger log = LoggerFactory.getLogger(WebSocketClient.class); private WebSocketClientCallbackListener callback; private EventLoopGroup group = new NioEventLoopGroup(); private URI uri; private Channel nettyChannel; private String userAgent; private AtomicBoolean connected = new AtomicBoolean(false); private AtomicBoolean enableReconnection = new AtomicBoolean(true); private AtomicInteger seqId = new AtomicInteger(1); private String username = null; private String password = null; // Keeps track of sent subscriptions, so that we can do a resend when we get // an InvalidException on some of them :-( private ConcurrentHashMap<Integer, WebSocketRequest> upstreamRequestBySeqId = new ConcurrentHashMap<>(); // public WebSocketClient(YamcsConnectionProperties yprops, WebSocketClientCallbackListener callback) { // this.uri = yprops.webSocketURI(); // this.callback = callback; // } public WebSocketClient(YamcsConnectionProperties yprops, WebSocketClientCallbackListener callback, String username, String password) { this.uri = yprops.webSocketURI(); this.callback = callback; this.username = username; this.password = password; } /** * Formatted as app/version. No spaces. */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public void connect() { enableReconnection.set(false); createBootstrap(); } public void connect(boolean enableReconnection) { this.enableReconnection.set(enableReconnection); createBootstrap(); } void setConnected(boolean connected) { this.connected.set(connected); } public boolean isConnected() { return connected.get(); } private void createBootstrap() { HttpHeaders header = new DefaultHttpHeaders(); if (userAgent != null) { header.add(HttpHeaders.Names.USER_AGENT, userAgent); } if(username != null) { String credentialsClear = username; if(password != null) credentialsClear += ":" + password; String credentialsB64 = new String(Base64.getEncoder().encode(credentialsClear.getBytes())); String authorization = "Basic " + credentialsB64; header.add(HttpHeaders.Names.AUTHORIZATION, authorization); } WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, header); final WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(handshaker, this, callback); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new HttpClientCodec(), new HttpObjectAggregator(8192), // new WebSocketClientCompressionHandler(), webSocketHandler); } }); log.info("WebSocket Client connecting"); try { ChannelFuture future = bootstrap.connect(uri.getHost(), uri.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess() && (enableReconnection.get())) { // Set-up reconnection attempts every second during initial set-up. log.info("reconnect.."); group.schedule(() -> createBootstrap(), 1L, TimeUnit.SECONDS); } } }); future.sync(); nettyChannel = future.sync().channel(); } catch (InterruptedException e) { System.out.println("interrupted while trying to connect"); e.printStackTrace(); } } /** * Adds said event to the queue. As soon as the web socket is established, queue will be * iterated. */ public void sendRequest(final WebSocketRequest request) { group.execute(new Runnable() { @Override public void run() { doSendRequest(request); } }); } /** * Really does send the request upstream */ private void doSendRequest(WebSocketRequest request) { int id = seqId.incrementAndGet(); upstreamRequestBySeqId.put(id, request); log.debug("Sending request {}", request); nettyChannel.writeAndFlush(request.toWebSocketFrame(id)); } WebSocketRequest getUpstreamRequest(int seqId) { return upstreamRequestBySeqId.get(seqId); } void forgetUpstreamRequest(int seqId) { upstreamRequestBySeqId.remove(seqId); } boolean isReconnectionEnabled() { return enableReconnection.get(); } public void disconnect() { if (connected.compareAndSet(true, false)) { enableReconnection.set(false); log.info("WebSocket Client sending close"); nettyChannel.writeAndFlush(new CloseWebSocketFrame()); // WebSocketClientHandler will close the channel when the server responds to the // CloseWebSocketFrame nettyChannel.closeFuture().awaitUninterruptibly(); } else { log.debug("Close requested, but connection was already closed"); } } /** * @return the Future which is notified when the executor has been terminated. */ public Future<?> shutdown() { return group.shutdownGracefully(); } }
yamcs-api/src/main/java/org/yamcs/api/ws/WebSocketClient.java
package org.yamcs.api.ws; import java.net.URI; import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.util.concurrent.Future; /** * Netty-implementation of a Yamcs web socket client */ public class WebSocketClient { private static final Logger log = LoggerFactory.getLogger(WebSocketClient.class); private WebSocketClientCallbackListener callback; private EventLoopGroup group = new NioEventLoopGroup(); private URI uri; private Channel nettyChannel; private String userAgent; private AtomicBoolean connected = new AtomicBoolean(false); private AtomicBoolean enableReconnection = new AtomicBoolean(true); private AtomicInteger seqId = new AtomicInteger(1); private String username = null; private String password = null; // Keeps track of sent subscriptions, so that we can do a resend when we get // an InvalidException on some of them :-( private ConcurrentHashMap<Integer, WebSocketRequest> upstreamRequestBySeqId = new ConcurrentHashMap<>(); // public WebSocketClient(YamcsConnectionProperties yprops, WebSocketClientCallbackListener callback) { // this.uri = yprops.webSocketURI(); // this.callback = callback; // } public WebSocketClient(YamcsConnectionProperties yprops, WebSocketClientCallbackListener callback, String username, String password) { this.uri = yprops.webSocketURI(); this.callback = callback; this.username = username; this.password = password; } /** * Formatted as app/version. No spaces. */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public void connect() { enableReconnection.set(true); createBootstrap(); } void setConnected(boolean connected) { this.connected.set(connected); } public boolean isConnected() { return connected.get(); } private void createBootstrap() { HttpHeaders header = new DefaultHttpHeaders(); if (userAgent != null) { header.add(HttpHeaders.Names.USER_AGENT, userAgent); } if(username != null) { String credentialsClear = username; if(password != null) credentialsClear += ":" + password; String credentialsB64 = new String(Base64.getEncoder().encode(credentialsClear.getBytes())); String authorization = "Basic " + credentialsB64; header.add(HttpHeaders.Names.AUTHORIZATION, authorization); } WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, header); final WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(handshaker, this, callback); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new HttpClientCodec(), new HttpObjectAggregator(8192), // new WebSocketClientCompressionHandler(), webSocketHandler); } }); log.info("WebSocket Client connecting"); try { ChannelFuture future = bootstrap.connect(uri.getHost(), uri.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { // Set-up reconnection attempts every second during initial set-up. log.info("reconnect.."); //group.schedule(() -> createBootstrap(), 1L, TimeUnit.SECONDS); } } }); future.sync(); nettyChannel = future.sync().channel(); } catch (InterruptedException e) { System.out.println("interrupted while trying to connect"); e.printStackTrace(); } } /** * Adds said event to the queue. As soon as the web socket is established, queue will be * iterated. */ public void sendRequest(final WebSocketRequest request) { group.execute(new Runnable() { @Override public void run() { doSendRequest(request); } }); } /** * Really does send the request upstream */ private void doSendRequest(WebSocketRequest request) { int id = seqId.incrementAndGet(); upstreamRequestBySeqId.put(id, request); log.debug("Sending request {}", request); nettyChannel.writeAndFlush(request.toWebSocketFrame(id)); } WebSocketRequest getUpstreamRequest(int seqId) { return upstreamRequestBySeqId.get(seqId); } void forgetUpstreamRequest(int seqId) { upstreamRequestBySeqId.remove(seqId); } boolean isReconnectionEnabled() { return enableReconnection.get(); } public void disconnect() { if (connected.compareAndSet(true, false)) { enableReconnection.set(false); log.info("WebSocket Client sending close"); nettyChannel.writeAndFlush(new CloseWebSocketFrame()); // WebSocketClientHandler will close the channel when the server responds to the // CloseWebSocketFrame nettyChannel.closeFuture().awaitUninterruptibly(); } else { log.debug("Close requested, but connection was already closed"); } } /** * @return the Future which is notified when the executor has been terminated. */ public Future<?> shutdown() { return group.shutdownGracefully(); } }
Enable reconnection in WebSocketClient
yamcs-api/src/main/java/org/yamcs/api/ws/WebSocketClient.java
Enable reconnection in WebSocketClient
Java
agpl-3.0
f151e4e115cf90881b0c487e3fbbb2a972630abb
0
platinumjesus/chat-system
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.*; public class Client extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Connection con; private String name; private final int port = 4001; private boolean clientAccepted; private InetAddress host; private ArrayList<String> history; final JTextArea textArea = new JTextArea(25, 80); final JTextField userInputField = new JTextField(45); public Client() throws UnknownHostException, IOException { super(); this.con = null; this.name = null; clientAccepted = false; initialize(); run(); } /** * Launch the application. * * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { new Client(); } /** * Initialize the contents of the frame. * * @throws IOException * @throws UnknownHostException */ private void initialize() throws UnknownHostException, IOException { history = new ArrayList<String>(); JTextPane hostname = new JTextPane(); hostname.setText("localhost"); JTextPane username = new JTextPane(); username.setText("Username.."); hostname.setPreferredSize(new Dimension(150, 20)); username.setPreferredSize(new Dimension(150, 20)); JPanel inputPanel = new JPanel(); inputPanel.add(username); inputPanel.add(Box.createHorizontalStrut(20)); inputPanel.add(hostname); inputPanel.setPreferredSize(new Dimension(350, 50)); // At initialization, ask the user for username and host. int answ = JOptionPane.showConfirmDialog(this, inputPanel, "Enter credentials", JOptionPane.YES_NO_OPTION); if (answ == JOptionPane.NO_OPTION) { System.exit(1); } else { this.setName(username.getText()); if (hostname.getText().isEmpty()) { JOptionPane.showMessageDialog(null, hostname.getText() + " is not a valid IP address."); System.exit(1); } else { try { host = InetAddress.getByName(hostname.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, host.toString() + " is not correct"); System.err .println("An error occurred while looking up for the Host."); e.printStackTrace(); System.exit(1); } if (!host.isReachable(20)) { JOptionPane.showMessageDialog(null, host.toString() + " is not reachable"); System.exit(1); } } // Handshake with Server if (host != null) { try { con = new Connection(new Socket(host, port)); this.setCon(con); clientAccepted = true; textArea.append("Welcome " + this.getName() + " you are connected to \nHostname: " + con.getNewConnection().getInetAddress() .getHostName() + "\nPort: " + con.getNewConnection().getPort() + "\n"); } catch (IOException e) { System.err .println("An error occurred while creating the I/O streams: the socket is closed or it is not connected."); e.printStackTrace(); } } } System.out.println("Connection established."); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(500, 100)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); scrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); System.out.println("GUI instantiated"); this.setLayout(new FlowLayout()); this.getContentPane().add(userInputField, SwingConstants.CENTER); this.getContentPane().add(scrollPane, SwingConstants.CENTER); userInputField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String fromUser = userInputField.getText(); if (fromUser != null) { Message s = new Message(fromUser, name, host, port); // textArea.append(s.toString()); try { con.createPrintWriter().writeUTF(s.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); history.add(s.toString()); } } }); this.setVisible(true); this.setSize(600, 170); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); } /** * Receive messages * * @throws IOException */ public void run() throws IOException { DataInputStream in = con.createBufferedReader(); while (true) { try{ String fromServer = in.readUTF(); if (fromServer != null) { synchronized (history) { if (!history.contains(fromServer)) { textArea.append(fromServer.toString() + "\n"); textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); } else { textArea.append("\tME:"); textArea.append(fromServer + "\n"); textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); } System.out.println("Tot. messages sent:" + history.size()); System.out.println("Last Message:" + history.get(history.size() - 1)); } } }catch(EOFException e){ System.out.println("[ERROR] "+host+" no longer available. Closing.."); System.exit(-1); } } } // Getters and Setters public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isClientAccepted() { return clientAccepted; } public void setClientAccepted(boolean clientAccepted) { this.clientAccepted = clientAccepted; } }
chat-system/src/Client.java
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.*; public class Client extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Connection con; private String name; private final int port = 4001; private boolean clientAccepted; private InetAddress host; private ArrayList<String> history; final JTextArea textArea = new JTextArea(25, 80); final JTextField userInputField = new JTextField(45); public Client() throws UnknownHostException, IOException { super(); this.con = null; this.name = null; clientAccepted = false; initialize(); run(); } /** * Launch the application. * * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { new Client(); } /** * Initialize the contents of the frame. * * @throws IOException * @throws UnknownHostException */ private void initialize() throws UnknownHostException, IOException { history = new ArrayList<String>(); JTextPane hostname = new JTextPane(); hostname.setText("localhost"); JTextPane username = new JTextPane(); username.setText("Username.."); hostname.setPreferredSize(new Dimension(150, 20)); username.setPreferredSize(new Dimension(150, 20)); JPanel inputPanel = new JPanel(); inputPanel.add(username); inputPanel.add(Box.createHorizontalStrut(20)); inputPanel.add(hostname); inputPanel.setPreferredSize(new Dimension(350, 50)); // At initialization, ask the user for username and host. int answ = JOptionPane.showConfirmDialog(this, inputPanel, "Enter credentials", JOptionPane.YES_NO_OPTION); if (answ == JOptionPane.NO_OPTION) { System.exit(1); } else { this.setName(username.getText()); if (hostname.getText().isEmpty()) { JOptionPane.showMessageDialog(null, hostname.getText() + " is not a valid IP address."); System.exit(1); } else { try { host = InetAddress.getByName(hostname.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, host.toString() + " is not correct"); System.err .println("An error occurred while looking up for the Host."); e.printStackTrace(); System.exit(1); } if (!host.isReachable(20)) { JOptionPane.showMessageDialog(null, host.toString() + " is not reachable"); System.exit(1); } } // Handshake with Server if (host != null) { try { con = new Connection(new Socket(host, port)); this.setCon(con); clientAccepted = true; textArea.append("Welcome " + this.getName() + " you are connected to \nHostname: " + con.getNewConnection().getInetAddress() .getHostName() + "\nPort: " + con.getNewConnection().getPort() + "\n"); } catch (IOException e) { System.err .println("An error occurred while creating the I/O streams: the socket is closed or it is not connected."); e.printStackTrace(); } } } System.out.println("Connection established."); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(500, 100)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); scrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); System.out.println("GUI instantiated"); this.setLayout(new FlowLayout()); this.getContentPane().add(userInputField, SwingConstants.CENTER); this.getContentPane().add(scrollPane, SwingConstants.CENTER); userInputField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String fromUser = userInputField.getText(); if (fromUser != null) { Message s = new Message(fromUser, name, host, port); // textArea.append(s.toString()); try { con.createPrintWriter().writeUTF(s.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); history.add(s.toString()); } } }); this.setVisible(true); this.setSize(600, 170); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); } /** * Receive messages * * @throws IOException */ public void run() throws IOException { DataInputStream in = con.createBufferedReader(); while (true) { if(con.getNewConnection().isClosed()){ System.out.println("Server : "+host+" no longer available. Closing.."); System.exit(-1); } String fromServer = in.readUTF(); if (fromServer != null) { synchronized (history) { if (!history.contains(fromServer)) { textArea.append(fromServer.toString() + "\n"); textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); } else { textArea.append("\tME:"); textArea.append(fromServer + "\n"); textArea.setCaretPosition(textArea.getDocument() .getLength()); userInputField.setText(""); } System.out.println("Tot. messages sent:" + history.size()); System.out.println("Last Message:" + history.get(history.size() - 1)); } } } } // Getters and Setters public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isClientAccepted() { return clientAccepted; } public void setClientAccepted(boolean clientAccepted) { this.clientAccepted = clientAccepted; } }
handling EOEF
chat-system/src/Client.java
handling EOEF
Java
agpl-3.0
9b5cac996918118a061e94f742818b0e09724cc1
0
kuali/kfs-git-training
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.coa.businessobject; public class ObjectLevel { private String chartOfAccountsCode; private String financialObjectLevelCode; private String financialObjectLevelName; private String financialObjectLevelShortNm; private boolean active; private String financialReportingSortCode; private String financialConsolidationObjectCode; private ObjectConsolidation financialConsolidationObject = new ObjectConsolidation(); private Chart chartOfAccounts; /** * @param chartOfAccountsCode * @param financialObjectLevelCode * @param financialObjectLevelName * @param financialObjectLevelShortNm * @param active * @param financialReportingSortCode * @param financialConsolidationObjectCode * @param financialConsolidationObject * @param chartOfAccounts */ public ObjectLevel() { LOG.log(Level.INFO, "An object of class "+getClass().getName()+" has been instantiated"); } /** * Gets the financialObjectLevelCode attribute. * * @return Returns the financialObjectLevelCode */ public String getFinancialObjectLevelCode() { return financialObjectLevelCode; } /** * Sets the financialObjectLevelCode attribute. * * @param financialObjectLevelCode The financialObjectLevelCode to set. */ public void setFinancialObjectLevelCode(String financialObjectLevelCode) { this.financialObjectLevelCode = financialObjectLevelCode; } /** * Gets the financialObjectLevelName attribute. * * @return Returns the financialObjectLevelName */ public String getFinancialObjectLevelName() { return financialObjectLevelName; } /** * Sets the financialObjectLevelName attribute. * * @param financialObjectLevelName The financialObjectLevelName to set. */ public void setFinancialObjectLevelName(String financialObjectLevelName) { this.financialObjectLevelName = financialObjectLevelName; } /** * Gets the financialObjectLevelShortNm attribute. * * @return Returns the financialObjectLevelShortNm */ public String getFinancialObjectLevelShortNm() { return financialObjectLevelShortNm; } /** * Sets the financialObjectLevelShortNm attribute. * * @param financialObjectLevelShortNm The financialObjectLevelShortNm to set. */ public void setFinancialObjectLevelShortNm(String financialObjectLevelShortNm) { this.financialObjectLevelShortNm = financialObjectLevelShortNm; } /** * Gets the financialObjectLevelActiveIndicator attribute. * * @return Returns the financialObjectLevelActiveIndicator */ public boolean isActive() { return active; } /** * Sets the financialObjectLevelActiveIndicator attribute. * * @param financialObjectLevelActiveIndicator The financialObjectLevelActiveIndicator to set. */ public void setActive(boolean financialObjectLevelActiveIndicator) { this.active = financialObjectLevelActiveIndicator; } /** * Gets the financialReportingSortCode attribute. * * @return Returns the financialReportingSortCode */ public String getFinancialReportingSortCode() { return financialReportingSortCode; } /** * Sets the financialReportingSortCode attribute. * * @param financialReportingSortCode The financialReportingSortCode to set. */ public void setFinancialReportingSortCode(String financialReportingSortCode) { this.financialReportingSortCode = financialReportingSortCode; } public String getConsolidatedObjectCode() { return financialConsolidationObject.getFinancialReportingSortCode(); } /** * Gets the financialConsolidationObject attribute. * * @return Returns the financialConsolidationObject */ public ObjectConsolidation getFinancialConsolidationObject() { return financialConsolidationObject; } /** * Sets the financialConsolidationObject attribute. * * @param financialConsolidationObject The financialConsolidationObject to set. */ public void setFinancialConsolidationObject(ObjectConsolidation financialConsolidationObject) { this.financialConsolidationObject = financialConsolidationObject; } public String getChartOfAccountsCode() { return chartOfAccountsCode; } /** * Gets the chartOfAccounts attribute. * * @return Returns the chartOfAccounts */ public Chart getChartOfAccounts() { return chartOfAccounts; } /** * Sets the chartOfAccounts attribute. * * @param chartOfAccounts The chartOfAccounts to set. * @deprecated */ public void setChartOfAccounts(Chart chartOfAccounts) { this.chartOfAccounts = chartOfAccounts; } /** * @return Returns the financialConsolidationObjectCode. */ public String getFinancialConsolidationObjectCode() { return financialConsolidationObjectCode; } /** * @param financialConsolidationObjectCode The financialConsolidationObjectCode to set. */ public void setFinancialConsolidationObjectCode(String financialConsolidationObjectCode) { this.financialConsolidationObjectCode = financialConsolidationObjectCode; } public void setChartOfAccountsCode(String chart) { this.chartOfAccountsCode = chart; } }
src/main/java/org/kuali/kfs/coa/businessobject/ObjectLevel.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.coa.businessobject; import src.main.java.org.kuali.kfs.sys.context.SpringContext; import src.main.java.org.kuali.kfs.gl.businessobject.SufficientFundRebuild; public class ObjectLevel { Logger LOG = Logger.getLogger({your class name}.class.getName()); private String chartOfAccountsCode; private String financialObjectLevelCode; private String financialObjectLevelName; private String financialObjectLevelShortNm; private boolean active; private String financialReportingSortCode; private String financialConsolidationObjectCode; private ObjectConsolidation financialConsolidationObject = new ObjectConsolidation(); private Chart chartOfAccounts; <<<<<<< HEAD /** ======= /** * @param chartOfAccountsCode * @param financialObjectLevelCode * @param financialObjectLevelName * @param financialObjectLevelShortNm * @param active * @param financialReportingSortCode * @param financialConsolidationObjectCode * @param financialConsolidationObject * @param chartOfAccounts */ public ObjectLevel() { LOG.log(Level.INFO, "An object of class "+getClass().getName()+" has been instantiated"); } /** >>>>>>> added constructor added code * Gets the financialObjectLevelCode attribute. * * @return Returns the financialObjectLevelCode */ public String getFinancialObjectLevelCode() { return financialObjectLevelCode; } /** * Sets the financialObjectLevelCode attribute. * * @param financialObjectLevelCode The financialObjectLevelCode to set. */ public void setFinancialObjectLevelCode(String financialObjectLevelCode) { this.financialObjectLevelCode = financialObjectLevelCode; } /** * Gets the financialObjectLevelName attribute. * * @return Returns the financialObjectLevelName */ public String getFinancialObjectLevelName() { return financialObjectLevelName; } /** * Sets the financialObjectLevelName attribute. * * @param financialObjectLevelName The financialObjectLevelName to set. */ public void setFinancialObjectLevelName(String financialObjectLevelName) { this.financialObjectLevelName = financialObjectLevelName; } /** * Gets the financialObjectLevelShortNm attribute. * * @return Returns the financialObjectLevelShortNm */ public String getFinancialObjectLevelShortNm() { return financialObjectLevelShortNm; } /** * Sets the financialObjectLevelShortNm attribute. * * @param financialObjectLevelShortNm The financialObjectLevelShortNm to set. */ public void setFinancialObjectLevelShortNm(String financialObjectLevelShortNm) { this.financialObjectLevelShortNm = financialObjectLevelShortNm; } /** * Gets the financialObjectLevelActiveIndicator attribute. * * @return Returns the financialObjectLevelActiveIndicator */ public boolean isActive() { return active; } /** * Sets the financialObjectLevelActiveIndicator attribute. * * @param financialObjectLevelActiveIndicator The financialObjectLevelActiveIndicator to set. */ public void setActive(boolean financialObjectLevelActiveIndicator) { this.active = financialObjectLevelActiveIndicator; } /** * Gets the financialReportingSortCode attribute. * * @return Returns the financialReportingSortCode */ public String getFinancialReportingSortCode() { return financialReportingSortCode; } /** * Sets the financialReportingSortCode attribute. * * @param financialReportingSortCode The financialReportingSortCode to set. */ public void setFinancialReportingSortCode(String financialReportingSortCode) { this.financialReportingSortCode = financialReportingSortCode; } public String getConsolidatedObjectCode() { return financialConsolidationObject.getFinancialReportingSortCode(); } /** * Gets the financialConsolidationObject attribute. * * @return Returns the financialConsolidationObject */ public ObjectConsolidation getFinancialConsolidationObject() { return financialConsolidationObject; } /** * Sets the financialConsolidationObject attribute. * * @param financialConsolidationObject The financialConsolidationObject to set. */ public void setFinancialConsolidationObject(ObjectConsolidation financialConsolidationObject) { this.financialConsolidationObject = financialConsolidationObject; } public String getChartOfAccountsCode() { return chartOfAccountsCode; } /** * Gets the chartOfAccounts attribute. * * @return Returns the chartOfAccounts */ public Chart getChartOfAccounts() { return chartOfAccounts; } /** * Sets the chartOfAccounts attribute. * * @param chartOfAccounts The chartOfAccounts to set. * @deprecated */ public void setChartOfAccounts(Chart chartOfAccounts) { this.chartOfAccounts = chartOfAccounts; } /** * @return Returns the financialConsolidationObjectCode. */ public String getFinancialConsolidationObjectCode() { return financialConsolidationObjectCode; } /** * @param financialConsolidationObjectCode The financialConsolidationObjectCode to set. */ public void setFinancialConsolidationObjectCode(String financialConsolidationObjectCode) { this.financialConsolidationObjectCode = financialConsolidationObjectCode; } public void setChartOfAccountsCode(String chart) { this.chartOfAccountsCode = chart; } }
added two commits
src/main/java/org/kuali/kfs/coa/businessobject/ObjectLevel.java
added two commits
Java
lgpl-2.1
d797a50418589129c538233b3f0a9398dc0a13d6
0
ivassile/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,darranl/wildfly-core,aloubyansky/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,jamezp/wildfly-core,luck3y/wildfly-core,bstansberry/wildfly-core,darranl/wildfly-core,JiriOndrusek/wildfly-core,aloubyansky/wildfly-core,aloubyansky/wildfly-core,soul2zimate/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core,JiriOndrusek/wildfly-core,bstansberry/wildfly-core,jamezp/wildfly-core,JiriOndrusek/wildfly-core,jfdenise/wildfly-core,darranl/wildfly-core,jamezp/wildfly-core,jfdenise/wildfly-core,jfdenise/wildfly-core,bstansberry/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core,yersan/wildfly-core
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deployment; /** * An enumeration of the phases of a deployment unit's processing cycle. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public enum Phase { /* == TEMPLATE == * Upon entry, this phase performs the following actions: * <ul> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ /** * This phase creates the initial root structure. Depending on the service for this phase will ensure that the * deployment unit's initial root structure is available and accessible. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li> * <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments: * <ul> * <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * </ul> * <p> */ STRUCTURE(null), /** * This phase assembles information from the root structure to prepare for adding and processing additional external * structure, such as from class path entries and other similar mechanisms. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li> * <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li> * <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li> * </ul> * <p> */ PARSE(null), /** * In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>Any additional external structure is mounted during {@link #XXX}</li> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ DEPENDENCIES(null), CONFIGURE_MODULE(null), POST_MODULE(null), INSTALL(null), CLEANUP(null), ; /** * This is the key for the attachment to use as the phase's "value". The attachment is taken from * the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified. */ private final AttachmentKey<?> phaseKey; private Phase(final AttachmentKey<?> key) { phaseKey = key; } /** * Get the next phase, or {@code null} if none. * * @return the next phase, or {@code null} if there is none */ public Phase next() { final int ord = ordinal() + 1; final Phase[] phases = Phase.values(); return ord == phases.length ? null : phases[ord]; } /** * Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value * of this phase. * * @return the key */ public AttachmentKey<?> getPhaseKey() { return phaseKey; } // STRUCTURE public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0000; public static final int STRUCTURE_MOUNT = 0x0001; public static final int STRUCTURE_MANIFEST = 0x0100; // must be before osgi public static final int STRUCTURE_JDBC_DRIVER = 0x0150; public static final int STRUCTURE_OSGI_MANIFEST = 0x0200; public static final int STRUCTURE_RAR = 0x0300; public static final int STRUCTURE_WAR = 0x0500; public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600; public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700; public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800; public static final int STRUCTURE_EAR = 0x0900; public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x0A00; public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00; public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x0C00; public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x0C01; public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00; public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x0E00; public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0F00; public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1000; public static final int STRUCTURE_EE_MODULE_INIT = 0x1100; // PARSE public static final int PARSE_EE_MODULE_NAME = 0x0100; public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200; public static final int PARSE_STRUCTURE_DESCRIPTOR = 0x0201; public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300; public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301; public static final int PARSE_EAR_LIB_CLASS_PATH = 0x0400; public static final int PARSE_ADDITIONAL_MODULES = 0x0500; public static final int PARSE_CLASS_PATH = 0x0600; public static final int PARSE_EXTENSION_LIST = 0x0700; public static final int PARSE_EXTENSION_NAME = 0x0800; public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900; public static final int PARSE_OSGI_XSERVICE_PROPERTIES = 0x0A00; public static final int PARSE_OSGI_DEPLOYMENT = 0x0A80; public static final int PARSE_WEB_DEPLOYMENT = 0x0B00; public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00; public static final int PARSE_ANNOTATION_WAR = 0x0D00; public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00; public static final int PARSE_TLD_DEPLOYMENT = 0x0F00; public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000; // create and attach EJB metadata for EJB deployments public static final int PARSE_EJB_DEPLOYMENT = 0x1100; public static final int PARSE_EJB_CREATE_COMPONENT_DESCRIPTIONS = 0x1150; public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200; public static final int PARSE_EJB_MDB_DD = 0x1300; // create and attach the component description out of EJB annotations public static final int PARSE_EJB_ANNOTATION = 0x1400; public static final int PARSE_MESSAGE_DRIVEN_ANNOTATION = 0x1500; public static final int PARSE_EJB_TRANSACTION_MANAGEMENT = 0x1600; public static final int PARSE_EJB_BUSINESS_VIEW_ANNOTATION = 0x1700; public static final int PARSE_WS_EJB_INTEGRATION = 0x1701; public static final int PARSE_EJB_STARTUP_ANNOTATION = 0x1800; public static final int PARSE_EJB_SECURITY_DOMAIN_ANNOTATION = 0x1801; public static final int PARSE_EJB_CONCURRENCY_MANAGEMENT_ANNOTATION = 0x1900; public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901; public static final int PARSE_REMOVE_METHOD_ANNOTAION = 0x1902; public static final int PARSE_EJB_DECLARE_ROLES_ANNOTATION = 0x1903; public static final int PARSE_EJB_RUN_AS_ANNOTATION = 0x1904; public static final int PARSE_EJB_DENY_ALL_ANNOTATION = 0x1905; public static final int PARSE_EJB_ROLES_ALLOWED_ANNOTATION = 0x1906; public static final int PARSE_EJB_PERMIT_ALL_ANNOTATION = 0x1907; // should be after ConcurrencyManagement annotation processor public static final int PARSE_EJB_LOCK_ANNOTATION = 0x1A00; public static final int PARSE_EJB_STATEFUL_TIMEOUT_ANNOTATION = 0x1A01; // should be after ConcurrencyManagement annotation processor public static final int PARSE_EJB_ACCESS_TIMEOUT_ANNOTATION = 0x1B00; // should be after all views are known public static final int PARSE_EJB_TRANSACTION_ATTR_ANNOTATION = 0x1C00; public static final int PARSE_EJB_SESSION_SYNCHRONIZATION = 0x1C50; public static final int PARSE_EJB_RESOURCE_ADAPTER_ANNOTATION = 0x1D00; public static final int PARSE_EJB_ASYNCHRONOUS_ANNOTATION = 0x1E00; public static final int PARSE_WEB_COMPONENTS = 0x1F00; public static final int PARSE_WEB_MERGE_METADATA = 0x2000; public static final int PARSE_JSF_VERSION = 0x2001; public static final int PARSE_RA_DEPLOYMENT = 0x2100; public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200; public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300; public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x2400; public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500; public static final int PARSE_RESOURCE_ADAPTERS = 0x2600; public static final int PARSE_DATA_SOURCES = 0x2700; public static final int PARSE_ARQUILLIAN_RUNWITH = 0x2800; public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900; public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00; public static final int PARSE_WELD_DEPLOYMENT = 0x2B00; public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10; public static final int PARSE_WEBSERVICES_XML = 0x2C00; public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00; public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00; public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01; public static final int PARSE_PERSISTENCE_UNIT = 0x2F00; public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000; public static final int PARSE_INTERCEPTORS_ANNOTATION = 0x3100; public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200; public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300; public static final int PARSE_RESOURCE_INJECTION_WEBSERVICE_CONTEXT_ANNOTATION = 0x3401; public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500; public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501; public static final int PARSE_EJB_SECURITY_IDENTITY_DD = 0x3502; public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600; // should be after all components are known public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3700; public static final int PARSE_WEB_SERVICE_INJECTION_ANNOTATION = 0x3800; // DEPENDENCIES public static final int DEPENDENCIES_EJB = 0x0000; public static final int DEPENDENCIES_MODULE = 0x0100; public static final int DEPENDENCIES_DS = 0x0200; public static final int DEPENDENCIES_RAR_CONFIG = 0x0300; public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400; public static final int DEPENDENCIES_SAR_MODULE = 0x0500; public static final int DEPENDENCIES_WAR_MODULE = 0x0600; public static final int DEPENDENCIES_ARQUILLIAN = 0x0700; public static final int DEPENDENCIES_CLASS_PATH = 0x0800; public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900; public static final int DEPENDENCIES_WELD = 0x0A00; public static final int DEPENDENCIES_SEAM = 0x0A01; public static final int DEPENDENCIES_NAMING = 0x0B00; public static final int DEPENDENCIES_WS = 0x0C00; public static final int DEPENDENCIES_JAXRS = 0x0D00; public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00; // Sets up appropriate module dependencies for EJB deployments public static final int DEPENDENCIES_JPA = 0x1000; public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100; public static final int DEPENDENCIES_JDK = 0x1200; //must be last public static final int DEPENDENCIES_MODULE_INFO_SERVICE = 0x1300; // CONFIGURE_MODULE public static final int CONFIGURE_MODULE_SPEC = 0x0100; // POST_MODULE public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100; public static final int POST_MODULE_REFLECTION_INDEX = 0x0200; public static final int POST_MODULE_TRANSFORMER = 0x0201; public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300; public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0400; public static final int POST_MODULE_EJB_DD_REMOVE_METHOD = 0x0500; public static final int POST_MODULE_EJB_EXCLUDE_LIST_DD = 0x0501; public static final int POST_MODULE_EJB_METHOD_PERMISSION_DD = 0x0502; public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600; public static final int POST_MODULE_EJB_DD_CONCURRENCY = 0x0601; public static final int POST_MODULE_WELD_EJB_INTERCEPTORS_INTEGRATION = 0x0700; public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800; public static final int POST_MODULE_AGGREGATE_COMPONENT_INDEX = 0x0900; public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00; public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00; public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00; public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00; public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00; // should come before ejb jndi bindings processor public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000; public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100; public static final int POST_MODULE_EJB_MODULE_CONFIGURATION = 0x1200; public static final int POST_INITIALIZE_IN_ORDER = 0x1300; public static final int POST_MODULE_ENV_ENTRY = 0x1400; public static final int POST_MODULE_EJB_REF = 0x1500; public static final int POST_MODULE_PERSISTENCE_REF = 0x1600; public static final int POST_MODULE_DATASOURCE_REF = 0x1700; public static final int POST_MODULE_WS_JMS_INTEGRATION = 0x1800; public static final int POST_MODULE_RESOLVE_EJB_INJECTIONS = 0x1900; public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00; public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00; public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00; // INSTALL public static final int INSTALL_JNDI_DEPENDENCY_SETUP = 0x0100; public static final int INSTALL_JPA_INTERCEPTORS = 0x0200; public static final int INSTALL_APP_CONTEXT = 0x0300; public static final int INSTALL_MODULE_CONTEXT = 0x0400; public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500; public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600; public static final int INSTALL_OSGI_MODULE = 0x0650; public static final int INSTALL_WS_DEPLOYMENT_TYPE_DETECTOR = 0x0700; public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x0701; public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x0710; // IMPORTANT: WS integration installs deployment aspects dynamically // so consider INSTALL 0x0710 - 0x07FF reserved for WS subsystem! public static final int INSTALL_RA_DEPLOYMENT = 0x0800; public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900; public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0A00; public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00; public static final int INSTALL_EE_COMP_LAZY_BINDING_SOURCE_HANDLER = 0x0C00; public static final int INSTALL_WS_LAZY_BINDING_SOURCE_HANDLER = 0x0D00; public static final int INSTALL_EE_CLASS_CONFIG = 0x1100; public static final int INSTALL_EE_MODULE_CONFIG = 0x1101; public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200; public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210; public static final int INSTALL_PERSISTENTUNIT = 0x1220; public static final int INSTALL_EE_COMPONENT = 0x1230; public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300; public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500; public static final int INSTALL_JSF_ANNOTATIONS = 0x1600; public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1700; public static final int INSTALL_JDBC_DRIVER = 0x1800; public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900; public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1A00; public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00; public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00; public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01; public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00; // CLEANUP public static final int CLEANUP_REFLECTION_INDEX = 0x0100; }
server/src/main/java/org/jboss/as/server/deployment/Phase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deployment; import sun.tools.tree.FinallyStatement; /** * An enumeration of the phases of a deployment unit's processing cycle. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public enum Phase { /* == TEMPLATE == * Upon entry, this phase performs the following actions: * <ul> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ /** * This phase creates the initial root structure. Depending on the service for this phase will ensure that the * deployment unit's initial root structure is available and accessible. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li> * <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments: * <ul> * <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * </ul> * <p> */ STRUCTURE(null), /** * This phase assembles information from the root structure to prepare for adding and processing additional external * structure, such as from class path entries and other similar mechanisms. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li> * <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li> * <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li> * </ul> * <p> */ PARSE(null), /** * In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>Any additional external structure is mounted during {@link #XXX}</li> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ DEPENDENCIES(null), CONFIGURE_MODULE(null), POST_MODULE(null), INSTALL(null), CLEANUP(null), ; /** * This is the key for the attachment to use as the phase's "value". The attachment is taken from * the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified. */ private final AttachmentKey<?> phaseKey; private Phase(final AttachmentKey<?> key) { phaseKey = key; } /** * Get the next phase, or {@code null} if none. * * @return the next phase, or {@code null} if there is none */ public Phase next() { final int ord = ordinal() + 1; final Phase[] phases = Phase.values(); return ord == phases.length ? null : phases[ord]; } /** * Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value * of this phase. * * @return the key */ public AttachmentKey<?> getPhaseKey() { return phaseKey; } // STRUCTURE public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0000; public static final int STRUCTURE_MOUNT = 0x0001; public static final int STRUCTURE_MANIFEST = 0x0100; // must be before osgi public static final int STRUCTURE_JDBC_DRIVER = 0x0150; public static final int STRUCTURE_OSGI_MANIFEST = 0x0200; public static final int STRUCTURE_RAR = 0x0300; public static final int STRUCTURE_WAR = 0x0500; public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600; public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700; public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800; public static final int STRUCTURE_EAR = 0x0900; public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x0A00; public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00; public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x0C00; public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x0C01; public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00; public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x0E00; public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0F00; public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1000; public static final int STRUCTURE_EE_MODULE_INIT = 0x1100; // PARSE public static final int PARSE_EE_MODULE_NAME = 0x0100; public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200; public static final int PARSE_STRUCTURE_DESCRIPTOR = 0x0201; public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300; public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301; public static final int PARSE_EAR_LIB_CLASS_PATH = 0x0400; public static final int PARSE_ADDITIONAL_MODULES = 0x0500; public static final int PARSE_CLASS_PATH = 0x0600; public static final int PARSE_EXTENSION_LIST = 0x0700; public static final int PARSE_EXTENSION_NAME = 0x0800; public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900; public static final int PARSE_OSGI_XSERVICE_PROPERTIES = 0x0A00; public static final int PARSE_OSGI_DEPLOYMENT = 0x0A80; public static final int PARSE_WEB_DEPLOYMENT = 0x0B00; public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00; public static final int PARSE_ANNOTATION_WAR = 0x0D00; public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00; public static final int PARSE_TLD_DEPLOYMENT = 0x0F00; public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000; // create and attach EJB metadata for EJB deployments public static final int PARSE_EJB_DEPLOYMENT = 0x1100; public static final int PARSE_EJB_CREATE_COMPONENT_DESCRIPTIONS = 0x1150; public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200; public static final int PARSE_EJB_MDB_DD = 0x1300; // create and attach the component description out of EJB annotations public static final int PARSE_EJB_ANNOTATION = 0x1400; public static final int PARSE_MESSAGE_DRIVEN_ANNOTATION = 0x1500; public static final int PARSE_EJB_TRANSACTION_MANAGEMENT = 0x1600; public static final int PARSE_EJB_BUSINESS_VIEW_ANNOTATION = 0x1700; public static final int PARSE_WS_EJB_INTEGRATION = 0x1701; public static final int PARSE_EJB_STARTUP_ANNOTATION = 0x1800; public static final int PARSE_EJB_SECURITY_DOMAIN_ANNOTATION = 0x1801; public static final int PARSE_EJB_CONCURRENCY_MANAGEMENT_ANNOTATION = 0x1900; public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901; public static final int PARSE_REMOVE_METHOD_ANNOTAION = 0x1902; public static final int PARSE_EJB_DECLARE_ROLES_ANNOTATION = 0x1903; public static final int PARSE_EJB_RUN_AS_ANNOTATION = 0x1904; public static final int PARSE_EJB_DENY_ALL_ANNOTATION = 0x1905; public static final int PARSE_EJB_ROLES_ALLOWED_ANNOTATION = 0x1906; public static final int PARSE_EJB_PERMIT_ALL_ANNOTATION = 0x1907; // should be after ConcurrencyManagement annotation processor public static final int PARSE_EJB_LOCK_ANNOTATION = 0x1A00; public static final int PARSE_EJB_STATEFUL_TIMEOUT_ANNOTATION = 0x1A01; // should be after ConcurrencyManagement annotation processor public static final int PARSE_EJB_ACCESS_TIMEOUT_ANNOTATION = 0x1B00; // should be after all views are known public static final int PARSE_EJB_TRANSACTION_ATTR_ANNOTATION = 0x1C00; public static final int PARSE_EJB_SESSION_SYNCHRONIZATION = 0x1C50; public static final int PARSE_EJB_RESOURCE_ADAPTER_ANNOTATION = 0x1D00; public static final int PARSE_EJB_ASYNCHRONOUS_ANNOTATION = 0x1E00; public static final int PARSE_WEB_COMPONENTS = 0x1F00; public static final int PARSE_WEB_MERGE_METADATA = 0x2000; public static final int PARSE_JSF_VERSION = 0x2001; public static final int PARSE_RA_DEPLOYMENT = 0x2100; public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200; public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300; public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x2400; public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500; public static final int PARSE_RESOURCE_ADAPTERS = 0x2600; public static final int PARSE_DATA_SOURCES = 0x2700; public static final int PARSE_ARQUILLIAN_RUNWITH = 0x2800; public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900; public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00; public static final int PARSE_WELD_DEPLOYMENT = 0x2B00; public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10; public static final int PARSE_WEBSERVICES_XML = 0x2C00; public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00; public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00; public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01; public static final int PARSE_PERSISTENCE_UNIT = 0x2F00; public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000; public static final int PARSE_INTERCEPTORS_ANNOTATION = 0x3100; public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200; public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300; public static final int PARSE_RESOURCE_INJECTION_WEBSERVICE_CONTEXT_ANNOTATION = 0x3401; public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500; public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501; public static final int PARSE_EJB_SECURITY_IDENTITY_DD = 0x3502; public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600; // should be after all components are known public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3700; public static final int PARSE_WEB_SERVICE_INJECTION_ANNOTATION = 0x3800; // DEPENDENCIES public static final int DEPENDENCIES_EJB = 0x0000; public static final int DEPENDENCIES_MODULE = 0x0100; public static final int DEPENDENCIES_DS = 0x0200; public static final int DEPENDENCIES_RAR_CONFIG = 0x0300; public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400; public static final int DEPENDENCIES_SAR_MODULE = 0x0500; public static final int DEPENDENCIES_WAR_MODULE = 0x0600; public static final int DEPENDENCIES_ARQUILLIAN = 0x0700; public static final int DEPENDENCIES_CLASS_PATH = 0x0800; public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900; public static final int DEPENDENCIES_WELD = 0x0A00; public static final int DEPENDENCIES_SEAM = 0x0A01; public static final int DEPENDENCIES_NAMING = 0x0B00; public static final int DEPENDENCIES_WS = 0x0C00; public static final int DEPENDENCIES_JAXRS = 0x0D00; public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00; // Sets up appropriate module dependencies for EJB deployments public static final int DEPENDENCIES_JPA = 0x1000; public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100; public static final int DEPENDENCIES_JDK = 0x1200; //must be last public static final int DEPENDENCIES_MODULE_INFO_SERVICE = 0x1300; // CONFIGURE_MODULE public static final int CONFIGURE_MODULE_SPEC = 0x0100; // POST_MODULE public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100; public static final int POST_MODULE_REFLECTION_INDEX = 0x0200; public static final int POST_MODULE_TRANSFORMER = 0x0201; public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300; public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0400; public static final int POST_MODULE_EJB_DD_REMOVE_METHOD = 0x0500; public static final int POST_MODULE_EJB_EXCLUDE_LIST_DD = 0x0501; public static final int POST_MODULE_EJB_METHOD_PERMISSION_DD = 0x0502; public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600; public static final int POST_MODULE_EJB_DD_CONCURRENCY = 0x0601; public static final int POST_MODULE_WELD_EJB_INTERCEPTORS_INTEGRATION = 0x0700; public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800; public static final int POST_MODULE_AGGREGATE_COMPONENT_INDEX = 0x0900; public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00; public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00; public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00; public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00; public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00; // should come before ejb jndi bindings processor public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000; public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100; public static final int POST_MODULE_EJB_MODULE_CONFIGURATION = 0x1200; public static final int POST_INITIALIZE_IN_ORDER = 0x1300; public static final int POST_MODULE_ENV_ENTRY = 0x1400; public static final int POST_MODULE_EJB_REF = 0x1500; public static final int POST_MODULE_PERSISTENCE_REF = 0x1600; public static final int POST_MODULE_DATASOURCE_REF = 0x1700; public static final int POST_MODULE_WS_JMS_INTEGRATION = 0x1800; public static final int POST_MODULE_RESOLVE_EJB_INJECTIONS = 0x1900; public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00; public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00; public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00; // INSTALL public static final int INSTALL_JNDI_DEPENDENCY_SETUP = 0x0100; public static final int INSTALL_JPA_INTERCEPTORS = 0x0200; public static final int INSTALL_APP_CONTEXT = 0x0300; public static final int INSTALL_MODULE_CONTEXT = 0x0400; public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500; public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600; public static final int INSTALL_OSGI_MODULE = 0x0650; public static final int INSTALL_WS_DEPLOYMENT_TYPE_DETECTOR = 0x0700; public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x0701; public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x0710; // IMPORTANT: WS integration installs deployment aspects dynamically // so consider INSTALL 0x0710 - 0x07FF reserved for WS subsystem! public static final int INSTALL_RA_DEPLOYMENT = 0x0800; public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900; public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0A00; public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00; public static final int INSTALL_EE_COMP_LAZY_BINDING_SOURCE_HANDLER = 0x0C00; public static final int INSTALL_WS_LAZY_BINDING_SOURCE_HANDLER = 0x0D00; public static final int INSTALL_EE_CLASS_CONFIG = 0x1100; public static final int INSTALL_EE_MODULE_CONFIG = 0x1101; public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200; public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210; public static final int INSTALL_PERSISTENTUNIT = 0x1220; public static final int INSTALL_EE_COMPONENT = 0x1230; public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300; public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500; public static final int INSTALL_JSF_ANNOTATIONS = 0x1600; public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1700; public static final int INSTALL_JDBC_DRIVER = 0x1800; public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900; public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1A00; public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00; public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00; public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01; public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00; // CLEANUP public static final int CLEANUP_REFLECTION_INDEX = 0x0100; }
Clean out imports of sun jdk classes was: 71841d65070b62081c10d31598d4e8dbb2e9c37c
server/src/main/java/org/jboss/as/server/deployment/Phase.java
Clean out imports of sun jdk classes
Java
lgpl-2.1
a2bfcece91998a861a8eabc4080533f29dc2f5b0
0
ebollens/ccnmp,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,cawka/ndnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx
/* * A CCNx library test. * * Copyright (C) 2011 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package org.ccnx.ccn.test.io.content; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import java.util.TreeSet; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.Assert; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.impl.CCNFlowControl.SaveType; import org.ccnx.ccn.impl.security.keys.BasicKeyManager; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.CCNStringObject; import org.ccnx.ccn.io.content.LocalCopyListener; import org.ccnx.ccn.io.content.LocalCopyWrapper; import org.ccnx.ccn.profiles.ccnd.CCNDaemonException; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager.ForwardingEntry; import org.ccnx.ccn.profiles.repo.RepositoryControl; import org.ccnx.ccn.profiles.repo.RepositoryOperations; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.MalformedContentNameStringException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Test RepositoryControl, LocalCopyListener, and LocalCopyWrapper to make sure * there are no dangling faces in ccnd when they stop. * * In general, the tests go like this: * - Create an Interest listener for our object * - Ask the repo to sync it * - Create the object and save it in the Interest handler. * - At each step, use the ccnd xml export to verify that the proper number of * prefixes are registered. */ public class LocalCopyTestRepo { CCNHandle readhandle; CCNHandle listenerhandle; int readFaceId; int listenerFaceId; BasicKeyManager km; final static Random _rnd = new Random(); final static String _prefix = String.format("/test_%016X", _rnd.nextLong()); // by faceid final HashMap<Integer,TreeSet<ContentName>> fentries = new HashMap<Integer, TreeSet<ContentName>>(); @Before public void setUp() throws Exception { System.out.println("*****************************************************"); Log.setLevel(Log.FAC_ALL, Level.WARNING); km = new BasicKeyManager(); km.initialize(); KeyManager.setDefaultKeyManager(km); readhandle = CCNHandle.open(km); listenerhandle = CCNHandle.open(km); // Setup a prefix to get my face readFaceId = getFaceId(readhandle, "read"); listenerFaceId = getFaceId(listenerhandle, "listener"); System.out.println(String.format("Face IDs: read %d, listen %d", readFaceId, listenerFaceId)); } @After public void tearDown() throws Exception { listenerhandle.close(); readhandle.close(); KeyManager.closeDefaultKeyManager(); } // @Test // public void testDumpFaces() throws Exception { // getfaces(); // } @Test public void testRepositoryControlObject() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); RepositoryControl.localRepoSync(readhandle, so_in); Thread.sleep(3000); System.out.println("======= After localRepoSync on string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } @Test public void testLocalCopyWrapper() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); LocalCopyWrapper lcw = new LocalCopyWrapper(so_in); Thread.sleep(3000); System.out.println("======= After LocalCopyWrapper on string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); lcw.close(); System.out.println("======= After LocalCopyWrapper close"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } @Test public void testLocalCopyListener() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); LocalCopyListener.startBackup(so_in); Thread.sleep(3000); System.out.println("======= After LocalCopyListener.startBackup"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } @Test public void testLocalCopyWrapperWithSave() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); so_in.setupSave(SaveType.LOCALREPOSITORY); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(2, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); LocalCopyWrapper lcw = new LocalCopyWrapper(so_in); Thread.sleep(3000); System.out.println("======= After LocalCopyWrapper on string object"); getfaces(); Assert.assertEquals(2, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); // Now modify the string object and save again. so_in.setData(String.format("%016X", _rnd.nextLong())); lcw.save(); Thread.sleep(3000); System.out.println("======= After LocalCopyWrapper save"); getfaces(); Assert.assertEquals(2, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); lcw.close(); System.out.println("======= After LocalCopyWrapper close"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } // ============================================================================================== /** * Interest listener to create random objects for the repo to sync * @author mmosko * */ private class MyListener implements CCNFilterListener { // These are the replies we have sent // public ConcurrentHashMap<ContentName, String> replies = new ConcurrentHashMap<ContentName, String>(); public HashSet<ContentName> replies = new HashSet<ContentName>(); public void open() throws MalformedContentNameStringException, IOException, InterruptedException { listenerhandle.registerFilter(ContentName.fromNative(_prefix), this); Thread.sleep(100); } public void close() throws MalformedContentNameStringException { listenerhandle.unregisterFilter(ContentName.fromNative(_prefix), this); } @Override public boolean handleInterest(Interest interest) { // Ignore start write requests if( RepositoryOperations.isStartWriteOperation(interest) ) return false; if( RepositoryOperations.isCheckedWriteOperation(interest) ) return false; synchronized(replies) { if( replies.contains(interest.name())) return false; System.out.println("handleInterest: " + interest.toString()); try { String s = interest.name().toString(); CCNStringObject so = new CCNStringObject(interest.name(), s, SaveType.RAW, listenerhandle); so.save(); so.close(); replies.add(interest.name()); return true; } catch (IOException e) { e.printStackTrace(); } return false; } } } /* <ccnd> <identity><ccndid>0E0BBF5633A562DDD2D354150FBB6D0055042A389F10700D5C010DA621B6586E</ccndid> <apiversion>3002</apiversion> <starttime>1303848970.212333</starttime> <now>1303852704.538848</now> </identity> <cobs> <accessioned>302</accessioned> <stored>302</stored> <stale>47</stale> <sparse>0</sparse> <duplicate>0</duplicate> <sent>352</sent> </cobs> <interests> <names>15</names> <pending>0</pending> <propagating>0</propagating> <noted>0</noted> <accepted>376</accepted> <dropped>0</dropped> <sent>600</sent> <stuffed>0</stuffed> </interests> <faces> <face> <faceid>0</faceid> <faceflags>000c</faceflags> <pending>0</pending> <recvcount>0</recvcount> <meters> <bytein><total>45140</total><persec>0</persec></bytein><byteout><total>26665</total><persec>0</persec></byteout><datain><total>46</total><persec>0</persec></datain><introut><total>51</total><persec>0</persec></introut><dataout><total>0</total><persec>0</persec></dataout><intrin><total>0</total><persec>0</persec></intrin> </meters> </face> <face><faceid>1</faceid><faceflags>400c</faceflags><pending>0</pending><recvcount>0</recvcount></face> <face><faceid>2</faceid><faceflags>5012</faceflags><pending>0</pending><recvcount>0</recvcount><ip>0.0.0.0:9695</ip></face> <face><faceid>3</faceid><faceflags>5010</faceflags><pending>0</pending><recvcount>0</recvcount><ip>0.0.0.0:9695</ip></face> <face><faceid>4</faceid><faceflags>4042</faceflags><pending>0</pending><recvcount>0</recvcount><ip>[::]:9695</ip></face> <face><faceid>5</faceid><faceflags>4040</faceflags><pending>0</pending><recvcount>0</recvcount><ip>[::]:9695</ip></face> <face> <faceid>6</faceid> <faceflags>1014</faceflags> <pending>0</pending> <recvcount>6</recvcount> <ip>127.0.0.1:57037</ip> <meters><bytein><total>1949</total><persec>0</persec></bytein><byteout><total>4006</total><persec>0</persec></byteout><datain><total>1</total><persec>0</persec></datain><introut><total>1</total><persec>0</persec></introut><dataout><total>5</total><persec>0</persec></dataout><intrin><total>5</total><persec>0</persec></intrin> </meters> </face> <face><faceid>7</faceid><faceflags>1014</faceflags><pending>0</pending><recvcount>14</recvcount><ip>127.0.0.1:57040</ip><meters><bytein><total>4121</total><persec>0</persec></bytein><byteout><total>36582</total><persec>0</persec></byteout><datain><total>5</total><persec>0</persec></datain><introut><total>273</total><persec>0</persec></introut><dataout><total>7</total><persec>0</persec></dataout><intrin><total>9</total><persec>0</persec></intrin> </meters></face> </faces> <forwarding> <fentry> <prefix>ccnx:/%C1.M.S.localhost/%C1.M.SRV/ccnd</prefix> <dest><faceid>0</faceid> <flags>3</flags> <expires>2147479917</expires> </dest> </fentry> <fentry><prefix>ccnx:/ccnx/ping</prefix><dest><faceid>0</faceid><flags>3</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/ccnx/%0E%0B%BFV3%A5b%DD%D2%D3T%15%0F%BBm%00U%04%2A8%9F%10p%0D%5C%01%0D%A6%21%B6Xn</prefix><dest><faceid>0</faceid><flags>17</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/ccnx.org/Users/Repository/Keys/%C1.M.K%00%00%96%96c1%3D%A5%D5%E4%C8%29B%08%B1t%80D%1D%2A%BC3%BA%9A6%90N%09%8D%A2t%27%24</prefix><dest><faceid>6</faceid><flags>3</flags><expires>2147479922</expires></dest></fentry><fentry><prefix>ccnx:/</prefix><dest><faceid>7</faceid><flags>43</flags><expires>2147479927</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.neighborhood</prefix><dest><faceid>0</faceid><flags>3</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.localhost</prefix><dest><faceid>0</faceid><flags>23</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.localhost/%C1.M.SRV/repository/KEY</prefix><dest><faceid>6</faceid><flags>3</flags><expires>2147479922</expires></dest></fentry> </forwarding> </ccnd> */ private void getfaces() throws ParserConfigurationException, SAXException, IOException, MalformedContentNameStringException, DOMException { javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.Document document; synchronized(fentries) { fentries.clear(); document = parser.parse("http://localhost:9695/?f=xml"); NodeList nodes = document.getElementsByTagName("fentry"); System.out.println("fentry count: " + nodes.getLength()); for(int i = 0; i< nodes.getLength(); i++) { // System.out.println("Parsing entry " + i); Node node = nodes.item(i); FEntry fentry = new FEntry(node); for(Dest dest : fentry.dests) { TreeSet<ContentName> regs = fentries.get(dest.faceid); if( null == regs ) { regs = new TreeSet<ContentName>(); fentries.put(dest.faceid, regs); } regs.add(fentry.entryprefix); } } // for(Integer faceid : fentries.keySet() ) { // dumpreg(faceid); // } } } private static class Dest { int faceid = -1; int flags = 0; long expires = -1; public Dest(Node node) { if( node.getNodeName() != "dest" ) throw new ClassCastException("node is not of type 'dest': " + node.getNodeName()); NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if( child.getNodeName() == "faceid" ) faceid = Integer.parseInt(child.getTextContent()); if( child.getNodeName() == "flags" ) flags = Integer.parseInt(child.getTextContent()); if( child.getNodeName() == "expires" ) expires = Long.parseLong(child.getTextContent()); } } public String toString() { return String.format("faceid %d flags %08X expires %d", faceid, flags, expires); } } private static class FEntry { ContentName entryprefix = null; LinkedList<Dest> dests = new LinkedList<Dest>(); public FEntry(final Node node) throws MalformedContentNameStringException, DOMException { if( node.getNodeName() != "fentry" ) throw new ClassCastException("node is not of type 'fentry'"); NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if( child.getNodeName() == "dest" ) { Dest dest = new Dest(child); // System.out.println("adding: " + dest.toString()); dests.add(dest); } if( child.getNodeName() == "prefix" ) { entryprefix = ContentName.fromURI(child.getTextContent()); // System.out.println("prefix " + entryprefix.toURIString()); } } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("prefix: "); sb.append(entryprefix.toURIString()); sb.append('\n'); for(Dest dest : dests) { sb.append(" faceid: "); sb.append(dest.faceid); sb.append('\n'); } return sb.toString(); } } private int getFaceId(CCNHandle handle, String type) throws CCNDaemonException { PrefixRegistrationManager prm = new PrefixRegistrationManager(handle); String reg = String.format("ccnx:%s/%s_%016X", _prefix, type, _rnd.nextLong()); ForwardingEntry entry = prm.selfRegisterPrefix(reg); return entry.getFaceID(); } /** * * @param faceid * @return the # of prefixes registered on the face */ private int dumpreg(int faceid) { int count = 0; synchronized(fentries) { TreeSet<ContentName> regs = fentries.get(faceid); System.out.println("Registrations for faceid " + faceid); for(ContentName name : regs) { System.out.println(" " + name.toURIString()); count++; } } return count; } }
javasrc/src/org/ccnx/ccn/test/io/content/LocalCopyTestRepo.java
/* * A CCNx library test. * * Copyright (C) 2011 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package org.ccnx.ccn.test.io.content; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import java.util.TreeSet; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.Assert; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.impl.CCNFlowControl.SaveType; import org.ccnx.ccn.impl.security.keys.BasicKeyManager; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.CCNStringObject; import org.ccnx.ccn.io.content.LocalCopyListener; import org.ccnx.ccn.io.content.LocalCopyWrapper; import org.ccnx.ccn.profiles.ccnd.CCNDaemonException; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager.ForwardingEntry; import org.ccnx.ccn.profiles.repo.RepositoryControl; import org.ccnx.ccn.profiles.repo.RepositoryOperations; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.MalformedContentNameStringException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Test RepositoryControl, LocalCopyListener, and LocalCopyWrapper to make sure * there are no dangling faces in ccnd when they stop. * * In general, the tests go like this: * - Create an Interest listener for our object * - Ask the repo to sync it * - Create the object and save it in the Interest handler. * - At each step, use the ccnd xml export to verify that the proper number of * prefixes are registered. */ public class LocalCopyTestRepo { CCNHandle readhandle; CCNHandle listenerhandle; int readFaceId; int listenerFaceId; BasicKeyManager km; final static Random _rnd = new Random(); final static String _prefix = String.format("/test_%016X", _rnd.nextLong()); // by faceid final HashMap<Integer,TreeSet<ContentName>> fentries = new HashMap<Integer, TreeSet<ContentName>>(); @Before public void setUp() throws Exception { System.out.println("*****************************************************"); Log.setLevel(Log.FAC_ALL, Level.WARNING); km = new BasicKeyManager(); km.initialize(); KeyManager.setDefaultKeyManager(km); readhandle = CCNHandle.open(km); listenerhandle = CCNHandle.open(km); // Setup a prefix to get my face readFaceId = getFaceId(readhandle, "read"); listenerFaceId = getFaceId(listenerhandle, "listener"); System.out.println(String.format("Face IDs: read %d, listen %d", readFaceId, listenerFaceId)); } @After public void tearDown() throws Exception { listenerhandle.close(); readhandle.close(); KeyManager.closeDefaultKeyManager(); } // @Test // public void testDumpFaces() throws Exception { // getfaces(); // } @Test public void testRepositoryControlObject() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); RepositoryControl.localRepoSync(readhandle, so_in); Thread.sleep(3000); System.out.println("======= After localRepoSync on string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } @Test public void testLocalCopyWrapper() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); LocalCopyWrapper lcw = new LocalCopyWrapper(so_in); Thread.sleep(3000); System.out.println("======= After LocalCopyWrapper on string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); lcw.close(); System.out.println("======= After LocalCopyWrapper close"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } @Test public void testLocalCopyListener() throws Exception { MyListener listener = new MyListener(); try { listener.open(); String namestring = String.format("%s/obj_%016X", _prefix, _rnd.nextLong()); ContentName name = ContentName.fromNative(namestring); CCNStringObject so_in = new CCNStringObject(name, readhandle); Thread.sleep(3000); System.out.println("======= After reading string object"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); LocalCopyListener.startBackup(so_in); Thread.sleep(3000); System.out.println("======= After LocalCopyListener.startBackup"); getfaces(); Assert.assertEquals(1, dumpreg(readFaceId)); Assert.assertEquals(2, dumpreg(listenerFaceId)); } finally { listener.close(); } } // ============================================================================================== /** * Interest listener to create random objects for the repo to sync * @author mmosko * */ private class MyListener implements CCNFilterListener { // These are the replies we have sent // public ConcurrentHashMap<ContentName, String> replies = new ConcurrentHashMap<ContentName, String>(); public HashSet<ContentName> replies = new HashSet<ContentName>(); public void open() throws MalformedContentNameStringException, IOException, InterruptedException { listenerhandle.registerFilter(ContentName.fromNative(_prefix), this); Thread.sleep(100); } public void close() throws MalformedContentNameStringException { listenerhandle.unregisterFilter(ContentName.fromNative(_prefix), this); } @Override public boolean handleInterest(Interest interest) { // Ignore start write requests if( RepositoryOperations.isStartWriteOperation(interest) ) return false; if( RepositoryOperations.isCheckedWriteOperation(interest) ) return false; synchronized(replies) { if( replies.contains(interest.name())) return false; System.out.println("handleInterest: " + interest.toString()); try { String s = interest.name().toString(); CCNStringObject so = new CCNStringObject(interest.name(), s, SaveType.RAW, listenerhandle); so.save(); so.close(); replies.add(interest.name()); return true; } catch (IOException e) { e.printStackTrace(); } return false; } } } /* <ccnd> <identity><ccndid>0E0BBF5633A562DDD2D354150FBB6D0055042A389F10700D5C010DA621B6586E</ccndid> <apiversion>3002</apiversion> <starttime>1303848970.212333</starttime> <now>1303852704.538848</now> </identity> <cobs> <accessioned>302</accessioned> <stored>302</stored> <stale>47</stale> <sparse>0</sparse> <duplicate>0</duplicate> <sent>352</sent> </cobs> <interests> <names>15</names> <pending>0</pending> <propagating>0</propagating> <noted>0</noted> <accepted>376</accepted> <dropped>0</dropped> <sent>600</sent> <stuffed>0</stuffed> </interests> <faces> <face> <faceid>0</faceid> <faceflags>000c</faceflags> <pending>0</pending> <recvcount>0</recvcount> <meters> <bytein><total>45140</total><persec>0</persec></bytein><byteout><total>26665</total><persec>0</persec></byteout><datain><total>46</total><persec>0</persec></datain><introut><total>51</total><persec>0</persec></introut><dataout><total>0</total><persec>0</persec></dataout><intrin><total>0</total><persec>0</persec></intrin> </meters> </face> <face><faceid>1</faceid><faceflags>400c</faceflags><pending>0</pending><recvcount>0</recvcount></face> <face><faceid>2</faceid><faceflags>5012</faceflags><pending>0</pending><recvcount>0</recvcount><ip>0.0.0.0:9695</ip></face> <face><faceid>3</faceid><faceflags>5010</faceflags><pending>0</pending><recvcount>0</recvcount><ip>0.0.0.0:9695</ip></face> <face><faceid>4</faceid><faceflags>4042</faceflags><pending>0</pending><recvcount>0</recvcount><ip>[::]:9695</ip></face> <face><faceid>5</faceid><faceflags>4040</faceflags><pending>0</pending><recvcount>0</recvcount><ip>[::]:9695</ip></face> <face> <faceid>6</faceid> <faceflags>1014</faceflags> <pending>0</pending> <recvcount>6</recvcount> <ip>127.0.0.1:57037</ip> <meters><bytein><total>1949</total><persec>0</persec></bytein><byteout><total>4006</total><persec>0</persec></byteout><datain><total>1</total><persec>0</persec></datain><introut><total>1</total><persec>0</persec></introut><dataout><total>5</total><persec>0</persec></dataout><intrin><total>5</total><persec>0</persec></intrin> </meters> </face> <face><faceid>7</faceid><faceflags>1014</faceflags><pending>0</pending><recvcount>14</recvcount><ip>127.0.0.1:57040</ip><meters><bytein><total>4121</total><persec>0</persec></bytein><byteout><total>36582</total><persec>0</persec></byteout><datain><total>5</total><persec>0</persec></datain><introut><total>273</total><persec>0</persec></introut><dataout><total>7</total><persec>0</persec></dataout><intrin><total>9</total><persec>0</persec></intrin> </meters></face> </faces> <forwarding> <fentry> <prefix>ccnx:/%C1.M.S.localhost/%C1.M.SRV/ccnd</prefix> <dest><faceid>0</faceid> <flags>3</flags> <expires>2147479917</expires> </dest> </fentry> <fentry><prefix>ccnx:/ccnx/ping</prefix><dest><faceid>0</faceid><flags>3</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/ccnx/%0E%0B%BFV3%A5b%DD%D2%D3T%15%0F%BBm%00U%04%2A8%9F%10p%0D%5C%01%0D%A6%21%B6Xn</prefix><dest><faceid>0</faceid><flags>17</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/ccnx.org/Users/Repository/Keys/%C1.M.K%00%00%96%96c1%3D%A5%D5%E4%C8%29B%08%B1t%80D%1D%2A%BC3%BA%9A6%90N%09%8D%A2t%27%24</prefix><dest><faceid>6</faceid><flags>3</flags><expires>2147479922</expires></dest></fentry><fentry><prefix>ccnx:/</prefix><dest><faceid>7</faceid><flags>43</flags><expires>2147479927</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.neighborhood</prefix><dest><faceid>0</faceid><flags>3</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.localhost</prefix><dest><faceid>0</faceid><flags>23</flags><expires>2147479917</expires></dest></fentry><fentry><prefix>ccnx:/%C1.M.S.localhost/%C1.M.SRV/repository/KEY</prefix><dest><faceid>6</faceid><flags>3</flags><expires>2147479922</expires></dest></fentry> </forwarding> </ccnd> */ private void getfaces() throws ParserConfigurationException, SAXException, IOException, MalformedContentNameStringException, DOMException { javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.Document document; synchronized(fentries) { fentries.clear(); document = parser.parse("http://localhost:9695/?f=xml"); NodeList nodes = document.getElementsByTagName("fentry"); System.out.println("fentry count: " + nodes.getLength()); for(int i = 0; i< nodes.getLength(); i++) { // System.out.println("Parsing entry " + i); Node node = nodes.item(i); FEntry fentry = new FEntry(node); for(Dest dest : fentry.dests) { TreeSet<ContentName> regs = fentries.get(dest.faceid); if( null == regs ) { regs = new TreeSet<ContentName>(); fentries.put(dest.faceid, regs); } regs.add(fentry.entryprefix); } } // for(Integer faceid : fentries.keySet() ) { // dumpreg(faceid); // } } } private static class Dest { int faceid = -1; int flags = 0; long expires = -1; public Dest(Node node) { if( node.getNodeName() != "dest" ) throw new ClassCastException("node is not of type 'dest': " + node.getNodeName()); NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if( child.getNodeName() == "faceid" ) faceid = Integer.parseInt(child.getTextContent()); if( child.getNodeName() == "flags" ) flags = Integer.parseInt(child.getTextContent()); if( child.getNodeName() == "expires" ) expires = Long.parseLong(child.getTextContent()); } } public String toString() { return String.format("faceid %d flags %08X expires %d", faceid, flags, expires); } } private static class FEntry { ContentName entryprefix = null; LinkedList<Dest> dests = new LinkedList<Dest>(); public FEntry(final Node node) throws MalformedContentNameStringException, DOMException { if( node.getNodeName() != "fentry" ) throw new ClassCastException("node is not of type 'fentry'"); NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if( child.getNodeName() == "dest" ) { Dest dest = new Dest(child); // System.out.println("adding: " + dest.toString()); dests.add(dest); } if( child.getNodeName() == "prefix" ) { entryprefix = ContentName.fromURI(child.getTextContent()); // System.out.println("prefix " + entryprefix.toURIString()); } } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("prefix: "); sb.append(entryprefix.toURIString()); sb.append('\n'); for(Dest dest : dests) { sb.append(" faceid: "); sb.append(dest.faceid); sb.append('\n'); } return sb.toString(); } } private int getFaceId(CCNHandle handle, String type) throws CCNDaemonException { PrefixRegistrationManager prm = new PrefixRegistrationManager(handle); String reg = String.format("ccnx:%s/%s_%016X", _prefix, type, _rnd.nextLong()); ForwardingEntry entry = prm.selfRegisterPrefix(reg); return entry.getFaceID(); } /** * * @param faceid * @return the # of prefixes registered on the face */ private int dumpreg(int faceid) { int count = 0; synchronized(fentries) { TreeSet<ContentName> regs = fentries.get(faceid); System.out.println("Registrations for faceid " + faceid); for(ContentName name : regs) { System.out.println(" " + name.toURIString()); count++; } } return count; } }
Refs #100464. Added test for LCW that sets a savetype. This creates an extra face registration that stays around until lcw.close().
javasrc/src/org/ccnx/ccn/test/io/content/LocalCopyTestRepo.java
Refs #100464. Added test for LCW that sets a savetype. This creates an extra face registration that stays around until lcw.close().
Java
lgpl-2.1
f7cf3d3f2c9b3d5b2eb98f4824319daffb8d67fd
0
Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,justincc/intermine,joshkh/intermine,joshkh/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,elsiklab/intermine,justincc/intermine,julie-sullivan/phytomine,zebrafishmine/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,joshkh/intermine,kimrutherford/intermine,JoeCarlson/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,elsiklab/intermine,elsiklab/intermine,drhee/toxoMine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,JoeCarlson/intermine,joshkh/intermine,JoeCarlson/intermine,JoeCarlson/intermine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,julie-sullivan/phytomine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,julie-sullivan/phytomine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,zebrafishmine/intermine,drhee/toxoMine,elsiklab/intermine,drhee/toxoMine,tomck/intermine,julie-sullivan/phytomine,justincc/intermine,zebrafishmine/intermine,julie-sullivan/phytomine,justincc/intermine,zebrafishmine/intermine,tomck/intermine,kimrutherford/intermine,drhee/toxoMine,kimrutherford/intermine,tomck/intermine,tomck/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,julie-sullivan/phytomine,joshkh/intermine,joshkh/intermine,julie-sullivan/phytomine,drhee/toxoMine,tomck/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,elsiklab/intermine
package org.flymine.codegen; // Most of this code originated in the ArgoUML project, which carries // the following copyright // // Copyright (c) 1996-2001 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. import ru.novosoft.uml.xmi.XMIReader; import ru.novosoft.uml.foundation.core.*; import ru.novosoft.uml.foundation.data_types.*; import ru.novosoft.uml.model_management.*; import ru.novosoft.uml.foundation.extension_mechanisms.*; import java.io.File; import java.util.StringTokenizer; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.LinkedHashSet; import java.util.ArrayList; import java.util.Collection; import org.xml.sax.InputSource; public class JavaModelOutput extends ModelOutput { private static final boolean OJB = true; public JavaModelOutput(MModel mmodel) { super(mmodel); } protected String generateOperation(MOperation op) { StringBuffer sb = new StringBuffer(); String nameStr = generateName(op.getName()); String clsName = generateName(op.getOwner().getName()); // modifiers sb.append(INDENT); sb.append(generateConcurrency(op)); sb.append(generateAbstractness(op)); sb.append(generateChangeability(op)); sb.append(generateScope(op)); sb.append(generateVisibility(op)); // return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); if (returnType == null && !nameStr.equals(clsName)) { sb.append("void "); } else if (returnType != null) { sb.append(generateClassifierRef(returnType)).append(' '); } } // method name sb.append(nameStr); // parameters List params = new ArrayList(op.getParameters()); params.remove(rp); sb.append('('); if (params != null) { for (int i = 0; i < params.size(); i++) { MParameter p = (MParameter) params.get(i); if (i > 0) { sb.append(", "); } sb.append(generateParameter(p)); } } sb.append(')'); return sb.toString(); } protected String generateAttribute (MAttribute attr) { StringBuffer sb = new StringBuffer(); MClassifier owner = attr.getOwner(); // modifiers sb.append(INDENT); sb.append(generateVisibility(attr)); sb.append(generateScope(attr)); sb.append(generateChangability(attr)); // type MClassifier type = attr.getType(); if (type != null) { sb.append(generateClassifierRef(type)).append(' '); } // field name sb.append(generateName(attr.getName())); // initial value MExpression init = attr.getInitialValue(); if (init != null) { String initStr = generateExpression(init).trim(); if (initStr.length() > 0) { sb.append(" = ").append(initStr); } } sb.append(";\n") .append(generateGetSet(generateNoncapitalName(attr.getName()), generateClassifierRef(type))) .append("\n"); return sb.toString(); } protected String generateParameter(MParameter param) { StringBuffer sb = new StringBuffer(); // type sb.append(generateClassifierRef(param.getType())).append(' '); // name sb.append(generateName(param.getName())); return sb.toString(); } protected String generateClassifier(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateClassifierStart(cls)) .append(generateClassifierBody(cls)) .append(generateClassifierEnd(cls)); return sb.toString(); } protected String generateAssociationEnd(MAssociationEnd ae) { if (!ae.isNavigable()) { return ""; } StringBuffer sb = new StringBuffer(); String type = ""; String impl = ""; String name = ""; String construct = ""; //sb.append(INDENT + generateVisibility(ae.getVisibility())); if (MScopeKind.CLASSIFIER.equals(ae.getTargetScope())) { sb.append("static "); } MMultiplicity m = ae.getMultiplicity(); if (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m)) { type = generateClassifierRef(ae.getType()); } else { if(ae.getOrdering()==null || ae.getOrdering().getName().equals("unordered")) { type="Set"; impl="HashSet"; } else { type = "List"; impl = "ArrayList"; } name = "s"; construct = " = new " + impl + "()"; } String n = ae.getName(); MAssociation asc = ae.getAssociation(); String ascName = asc.getName(); if (n != null && n.length() > 0) { name = n + name; } else if (ascName != null && ascName.length() > 0) { name = ascName + name; } else { name = generateClassifierRef(ae.getType()) + name; } if (OJB && (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m))) { sb.append(INDENT + "protected int ") .append(generateNoncapitalName(name) + "Id;\n"); } sb.append(INDENT + "protected ") .append(type) .append(' ') .append(generateNoncapitalName(name)) .append(construct) .append(";\n") .append(generateGetSet(generateNoncapitalName(name), type)) .append("\n"); return sb.toString(); } protected void generateFileStart(File path) { } protected void generateFile(MClassifier cls, File path) { String filename = cls.getName() + ".java"; int lastIndex = -1; do { if (!path.isDirectory()) { if (!path.mkdir()) { LOG.debug(" could not make directory " + path); return; } } String packagePath = getPackagePath(cls); if (lastIndex == packagePath.length()) { break; } int index = packagePath.indexOf (".", lastIndex + 1); if (index == -1) { index = packagePath.length(); } path = new File(path, packagePath.substring (lastIndex + 1, index)); lastIndex = index; } while (true); path = new File(path, filename); initFile(path); String header = generateHeader(cls); String src = generate(cls); outputToFile(path, header + src); } protected void generateFileEnd(File path) { } //================================================================= private String generateHeader (MClassifier cls) { StringBuffer sb = new StringBuffer(); String packagePath = getPackagePath(cls); if (packagePath.length() > 0) { sb.append("package ").append(packagePath).append(";\n\n"); } sb.append("import java.util.*;\n\n"); return sb.toString(); } private StringBuffer generateClassifierStart (MClassifier cls) { StringBuffer sb = new StringBuffer (); String sClassifierKeyword = null; if (cls instanceof MClassImpl) { sClassifierKeyword = "class"; } else if (cls instanceof MInterface) { sClassifierKeyword = "interface"; } // Now add visibility sb.append(generateVisibility(cls.getVisibility())); // Add other modifiers if (cls.isAbstract() && !(cls instanceof MInterface)) { sb.append("abstract "); } if (cls.isLeaf()) { sb.append("final "); } // add classifier keyword and classifier name sb.append (sClassifierKeyword) .append(" ") .append (generateName(cls.getName())); // add base class/interface String baseClass = generateGeneralization(cls.getGeneralizations()); if (!baseClass.equals("")) { sb.append (" ") .append ("extends ") .append (baseClass); } // add implemented interfaces, if needed if (cls instanceof MClass) { String interfaces = generateSpecification((MClass) cls); if (!interfaces.equals ("")) { sb.append (" ") .append ("implements ") .append (interfaces); } } // add opening brace sb.append("\n{\n"); if (OJB && sClassifierKeyword.equals("class")) { if (baseClass.equals("")) { sb.append(INDENT + "protected int id;\n"); } if (!baseClass.equals("") || cls.getSpecializations().size() > 0) { sb.append(INDENT + "protected String ojbConcreteClass = \"" + generateQualified(cls) + "\";\n"); } } return sb.append("\n"); } private String generateGetSet(String name, String type) { StringBuffer sb = new StringBuffer(); // Get method sb.append(INDENT) .append("public "); if (type != null) { sb.append(type).append(' '); } sb.append("get").append(generateCapitalName(name)).append("() { ") .append("return this.").append(generateName(name)).append("; }\n"); // Set method sb.append(INDENT) .append("public void ") .append("set").append(generateCapitalName(name)).append("("); if (type != null) { sb.append(type).append(" "); } sb.append(generateName(name)).append(") { ") .append("this.").append(generateName(name)).append("=") .append(generateName(name)).append("; }\n"); return sb.toString(); } private String generateEquals(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public boolean equals(Object o) {\n") .append(INDENT+INDENT+"if (!(o instanceof " + cls.getName() + ")) return false;\n") .append(INDENT+INDENT+"if (id!=0 && id==(("+cls.getName()+")o).id) return true;\n") .append(INDENT+INDENT+"return "); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); if (getAllAttributes(cls).containsKey(field) && isPrimitive(((MAttribute) getAllAttributes(cls).get(field)).getType().getName())) { sb.append("((" + cls.getName() + ")o)." + field + "==" + field); } else { //sb.append(field + ".equals(((" + cls.getName() + ")o).get" + generateCapitalName(field) + "())"); //TODO use the previous line in preference to the following two... //our "key" fields can be null at present - if they are then don't do comparison String thatField = "((" + cls.getName() + ")o).get" + generateCapitalName(field) + "()"; sb.append("(" + thatField + " == null ? (" + field + " == null) : " + thatField + ".equals(" + field + "))"); } if (iter.hasNext()) { sb.append(" && "); } } sb.append("; }\n"); } return sb.toString(); } private String generateHashCode(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public int hashCode() {\n") .append(INDENT+INDENT+"if (id!=0) return id;\n") .append(INDENT+INDENT+"return "); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); if (getAllAttributes(cls).containsKey(field) && isPrimitive(((MAttribute) getAllAttributes(cls).get(field)).getType().getName())) { if (((MAttribute) getAllAttributes(cls).get(field)).getType().getName().equals("boolean")) { sb.append("(" + field + " ? 0 : 1)"); } else { sb.append(field); } } else { //sb.append(field + ".hashCode()"); //TODO same as above sb.append("(" + field + " == null ? 0 : " + field + ".hashCode())"); } if (iter.hasNext()) { sb.append(" ^ "); } } sb.append("; }\n"); } return sb.toString(); } private String generateToString(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public String toString() { ") .append("return \"" + cls.getName() + " [\"") .append(OJB ? "+id" : "+get" + generateCapitalName(cls.getName()) + "Id()") .append("+\"] \"+"); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); sb.append(field); if (iter.hasNext()) { sb.append("+\", \"+"); } } sb.append("; }\n"); } return sb.toString(); } private StringBuffer generateClassifierEnd(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateEquals(cls)) .append("\n") .append(generateHashCode(cls)) .append("\n") .append(generateToString(cls)) .append("}"); return sb; } private StringBuffer generateClassifierBody(MClassifier cls) { StringBuffer sb = new StringBuffer(); // (attribute) fields Collection strs = getAttributes(cls); if (!strs.isEmpty()) { Iterator strIter = strs.iterator(); while (strIter.hasNext()) { sb.append(generate((MStructuralFeature) strIter.next())); } } // (association) fields Collection ends = new ArrayList(cls.getAssociationEnds()); if (!ends.isEmpty()) { Iterator endIter = ends.iterator(); while (endIter.hasNext()) { MAssociationEnd ae = (MAssociationEnd) endIter.next(); sb.append(generateAssociationEnd(ae.getOppositeEnd())); } } // methods Collection behs = getOperations(cls); if (!behs.isEmpty()) { sb.append('\n'); Iterator behEnum = behs.iterator(); while (behEnum.hasNext()) { MBehavioralFeature bf = (MBehavioralFeature) behEnum.next(); sb.append(generate(bf)); if ((cls instanceof MClassImpl) && (bf instanceof MOperation) && (!((MOperation) bf).isAbstract())) { sb.append(" {\n") .append(generateMethodBody((MOperation) bf)) .append(INDENT) .append("}\n"); } else { sb.append(";\n"); } } } return sb; } private String generateMethodBody (MOperation op) { if (op != null) { Collection methods = op.getMethods(); Iterator i = methods.iterator(); MMethod m = null; while (i != null && i.hasNext()) { m = (MMethod) i.next(); if (m != null) { if (m.getBody() != null) { return m.getBody().getBody(); } else { return ""; } } } // pick out return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); return generateDefaultReturnStatement (returnType); } } return generateDefaultReturnStatement (null); } private String generateDefaultReturnStatement(MClassifier cls) { if (cls == null) { return ""; } String clsName = cls.getName(); if (clsName.equals("void")) { return ""; } if (clsName.equals("char")) { return INDENT + "return 'x';\n"; } if (clsName.equals("int")) { return INDENT + "return 0;\n"; } if (clsName.equals("boolean")) { return INDENT + "return false;\n"; } if (clsName.equals("byte")) { return INDENT + "return 0;\n"; } if (clsName.equals("long")) { return INDENT + "return 0;\n"; } if (clsName.equals("float")) { return INDENT + "return 0.0;\n"; } if (clsName.equals("double")) { return INDENT + "return 0.0;\n"; } return INDENT + "return null;\n"; } private String generateSpecification(MClass cls) { Collection realizations = getSpecifications(cls); if (realizations == null) { return ""; } StringBuffer sb = new StringBuffer(); Iterator clsEnum = realizations.iterator(); while (clsEnum.hasNext()) { MInterface i = (MInterface) clsEnum.next(); sb.append(generateClassifierRef(i)); if (clsEnum.hasNext()) { sb.append(", "); } } return sb.toString(); } private String generateVisibility(MVisibilityKind vis) { if (MVisibilityKind.PUBLIC.equals(vis)) { return "public "; } if (MVisibilityKind.PRIVATE.equals(vis)) { return "private "; } if (MVisibilityKind.PROTECTED.equals(vis)) { return "protected "; } return ""; } private String generateVisibility(MFeature f) { return generateVisibility(f.getVisibility()); } private String generateScope(MFeature f) { MScopeKind scope = f.getOwnerScope(); if (MScopeKind.CLASSIFIER.equals(scope)) { return "static "; } return ""; } private String generateAbstractness(MOperation op) { if (op.isAbstract()) { return "abstract "; } return ""; } private String generateChangeability(MOperation op) { if (op.isLeaf()) { return "final "; } return ""; } private String generateChangability(MStructuralFeature sf) { MChangeableKind ck = sf.getChangeability(); //if (ck == null) return ""; if (MChangeableKind.FROZEN.equals(ck)) { return "final "; } //if (MChangeableKind.ADDONLY.equals(ck)) return "final "; return ""; } private String generateConcurrency(MOperation op) { if (op.getConcurrency() != null && op.getConcurrency().getValue() == MCallConcurrencyKind._GUARDED) { return "synchronized "; } return ""; } private Collection getKeys(MClassifier cls) { Set keyFields = new LinkedHashSet(); Collection tvs = cls.getTaggedValues(); if (tvs != null && tvs.size() > 0) { Iterator iter = tvs.iterator(); while (iter.hasNext()) { MTaggedValue tv = (MTaggedValue) iter.next(); if (tv.getTag().equals("key")) { StringTokenizer st = new StringTokenizer(tv.getValue(), ", "); while (st.hasMoreElements()) { keyFields.add(st.nextElement()); } } } } Iterator parents = cls.getGeneralizations().iterator(); if (parents.hasNext()) { keyFields.addAll(getKeys((MClassifier) ((MGeneralization) parents.next()).getParent())); } return keyFields; } private boolean isPrimitive(String type) { return type.equals("char") || type.equals("byte") || type.equals("short") || type.equals("int") || type.equals("long") || type.equals("float") || type.equals("double") || type.equals("boolean") ? true : false; } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: JavaModelOutput <project name> <input dir> <output dir>"); System.exit(1); } String projectName = args[0]; String inputDir = args[1]; String outputDir = args[2]; File xmiFile = new File(inputDir, projectName + "_.xmi"); InputSource source = new InputSource(xmiFile.toURL().toString()); File path = new File(outputDir); new JavaModelOutput(new XMIReader().parse(source)).output(path); } }
intermine/src/java/org/intermine/codegen/JavaModelOutput.java
package org.flymine.codegen; // Most of this code originated in the ArgoUML project, which carries // the following copyright // // Copyright (c) 1996-2001 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. import ru.novosoft.uml.xmi.XMIReader; import ru.novosoft.uml.foundation.core.*; import ru.novosoft.uml.foundation.data_types.*; import ru.novosoft.uml.model_management.*; import ru.novosoft.uml.foundation.extension_mechanisms.*; import java.io.File; import java.util.StringTokenizer; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.LinkedHashSet; import java.util.ArrayList; import java.util.Collection; import org.xml.sax.InputSource; public class JavaModelOutput extends ModelOutput { private static final boolean OJB = true; public JavaModelOutput(MModel mmodel) { super(mmodel); } protected String generateOperation(MOperation op) { StringBuffer sb = new StringBuffer(); String nameStr = generateName(op.getName()); String clsName = generateName(op.getOwner().getName()); // modifiers sb.append(INDENT); sb.append(generateConcurrency(op)); sb.append(generateAbstractness(op)); sb.append(generateChangeability(op)); sb.append(generateScope(op)); sb.append(generateVisibility(op)); // return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); if (returnType == null && !nameStr.equals(clsName)) { sb.append("void "); } else if (returnType != null) { sb.append(generateClassifierRef(returnType)).append(' '); } } // method name sb.append(nameStr); // parameters List params = new ArrayList(op.getParameters()); params.remove(rp); sb.append('('); if (params != null) { for (int i = 0; i < params.size(); i++) { MParameter p = (MParameter) params.get(i); if (i > 0) { sb.append(", "); } sb.append(generateParameter(p)); } } sb.append(')'); return sb.toString(); } protected String generateAttribute (MAttribute attr) { StringBuffer sb = new StringBuffer(); MClassifier owner = attr.getOwner(); // modifiers sb.append(INDENT); sb.append(generateVisibility(attr)); sb.append(generateScope(attr)); sb.append(generateChangability(attr)); // type MClassifier type = attr.getType(); if (type != null) { sb.append(generateClassifierRef(type)).append(' '); } // field name sb.append(generateName(attr.getName())); // initial value MExpression init = attr.getInitialValue(); if (init != null) { String initStr = generateExpression(init).trim(); if (initStr.length() > 0) { sb.append(" = ").append(initStr); } } sb.append(";\n") .append(generateGetSet(generateNoncapitalName(attr.getName()), generateClassifierRef(type))) .append("\n"); return sb.toString(); } protected String generateParameter(MParameter param) { StringBuffer sb = new StringBuffer(); // type sb.append(generateClassifierRef(param.getType())).append(' '); // name sb.append(generateName(param.getName())); return sb.toString(); } protected String generateClassifier(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateClassifierStart(cls)) .append(generateClassifierBody(cls)) .append(generateClassifierEnd(cls)); return sb.toString(); } protected String generateAssociationEnd(MAssociationEnd ae) { if (!ae.isNavigable()) { return ""; } StringBuffer sb = new StringBuffer(); String type = ""; String impl = ""; String name = ""; String construct = ""; //sb.append(INDENT + generateVisibility(ae.getVisibility())); if (MScopeKind.CLASSIFIER.equals(ae.getTargetScope())) { sb.append("static "); } MMultiplicity m = ae.getMultiplicity(); if (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m)) { type = generateClassifierRef(ae.getType()); } else { if(ae.getOrdering()==null || ae.getOrdering().getName().equals("unordered")) { type="Set"; impl="HashSet"; } else { type = "List"; impl = "ArrayList"; } name = "s"; construct = " = new " + impl + "()"; } String n = ae.getName(); MAssociation asc = ae.getAssociation(); String ascName = asc.getName(); if (n != null && n.length() > 0) { name = n + name; } else if (ascName != null && ascName.length() > 0) { name = ascName + name; } else { name = generateClassifierRef(ae.getType()) + name; } if (OJB && (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m))) { sb.append(INDENT + "protected int ") .append(generateNoncapitalName(name) + "Id;\n"); } sb.append(INDENT + "protected ") .append(type) .append(' ') .append(generateNoncapitalName(name)) .append(construct) .append(";\n") .append(generateGetSet(generateNoncapitalName(name), type)) .append("\n"); return sb.toString(); } protected void generateFileStart(File path) { } protected void generateFile(MClassifier cls, File path) { String filename = cls.getName() + ".java"; int lastIndex = -1; do { if (!path.isDirectory()) { if (!path.mkdir()) { LOG.debug(" could not make directory " + path); return; } } String packagePath = getPackagePath(cls); if (lastIndex == packagePath.length()) { break; } int index = packagePath.indexOf (".", lastIndex + 1); if (index == -1) { index = packagePath.length(); } path = new File(path, packagePath.substring (lastIndex + 1, index)); lastIndex = index; } while (true); path = new File(path, filename); initFile(path); String header = generateHeader(cls); String src = generate(cls); outputToFile(path, header + src); } protected void generateFileEnd(File path) { } //================================================================= private String generateHeader (MClassifier cls) { StringBuffer sb = new StringBuffer(); String packagePath = getPackagePath(cls); if (packagePath.length() > 0) { sb.append("package ").append(packagePath).append(";\n\n"); } sb.append("import java.util.*;\n\n"); return sb.toString(); } private StringBuffer generateClassifierStart (MClassifier cls) { StringBuffer sb = new StringBuffer (); String sClassifierKeyword = null; if (cls instanceof MClassImpl) { sClassifierKeyword = "class"; } else if (cls instanceof MInterface) { sClassifierKeyword = "interface"; } // Now add visibility sb.append(generateVisibility(cls.getVisibility())); // Add other modifiers if (cls.isAbstract() && !(cls instanceof MInterface)) { sb.append("abstract "); } if (cls.isLeaf()) { sb.append("final "); } // add classifier keyword and classifier name sb.append (sClassifierKeyword) .append(" ") .append (generateName(cls.getName())); // add base class/interface String baseClass = generateGeneralization(cls.getGeneralizations()); if (!baseClass.equals("")) { sb.append (" ") .append ("extends ") .append (baseClass); } // add implemented interfaces, if needed if (cls instanceof MClass) { String interfaces = generateSpecification((MClass) cls); if (!interfaces.equals ("")) { sb.append (" ") .append ("implements ") .append (interfaces); } } // add opening brace sb.append("\n{\n"); if (OJB && sClassifierKeyword.equals("class")) { if (baseClass.equals("")) { sb.append(INDENT + "protected int id;\n"); } if (!baseClass.equals("") || cls.getSpecializations().size() > 0) { sb.append(INDENT + "protected String ojbConcreteClass = \"" + generateQualified(cls) + "\";\n"); } } return sb.append("\n"); } private String generateGetSet(String name, String type) { StringBuffer sb = new StringBuffer(); // Get method sb.append(INDENT) .append("public "); if (type != null) { sb.append(type).append(' '); } sb.append("get").append(generateCapitalName(name)).append("() { ") .append("return this.").append(generateName(name)).append("; }\n"); // Set method sb.append(INDENT) .append("public void ") .append("set").append(generateCapitalName(name)).append("("); if (type != null) { sb.append(type).append(" "); } sb.append(generateName(name)).append(") { ") .append("this.").append(generateName(name)).append("=") .append(generateName(name)).append("; }\n"); return sb.toString(); } private String generateEquals(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public boolean equals(Object o) {\n") .append(INDENT+INDENT+"if (!(o instanceof " + cls.getName() + ")) return false;\n") .append(INDENT+INDENT+"if (id!=0 && id==(("+cls.getName()+")o).id) return true;\n") .append(INDENT+INDENT+"return "); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); if (getAllAttributes(cls).containsKey(field) && isPrimitive(((MAttribute) getAllAttributes(cls).get(field)).getType().getName())) { sb.append("((" + cls.getName() + ")o)." + field + "==" + field); } else { //sb.append(field + ".equals(((" + cls.getName() + ")o).get" + generateCapitalName(field) + "())"); //TODO use the previous line in preference to the following two... //our "key" fields can be null at present - if they are then don't do comparison String thatField = "((" + cls.getName() + ")o).get" + generateCapitalName(field) + "()"; sb.append("(" + thatField + " == null ? (" + field + " == null) : " + thatField + ".equals(" + field + "))"); } if (iter.hasNext()) { sb.append(" && "); } } sb.append("; }\n"); } return sb.toString(); } private String generateHashCode(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public int hashCode() { return "); sb.append("id"); // Iterator iter = keyFields.iterator(); // while (iter.hasNext()) { // String field = (String) iter.next(); // if (getAllAttributes(cls).containsKey(field) // && isPrimitive(((MAttribute) getAllAttributes(cls).get(field)).getType().getName())) { // if (((MAttribute) getAllAttributes(cls).get(field)).getType().getName().equals("boolean")) { // sb.append("(" + field + " ? 0 : 1)"); // } else { // sb.append(field); // } // } else { // //sb.append(field + ".hashCode()"); // //TODO same as above // sb.append("(" + field + " == null ? 0 : " + field + ".hashCode())"); // } // if (iter.hasNext()) { // sb.append(" ^ "); // } // } sb.append("; }\n"); } return sb.toString(); } private String generateToString(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public String toString() { ") .append("return \"" + cls.getName() + " [\"") .append(OJB ? "+id" : "+get" + generateCapitalName(cls.getName()) + "Id()") .append("+\"] \"+"); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); sb.append(field); if (iter.hasNext()) { sb.append("+\", \"+"); } } sb.append("; }\n"); } return sb.toString(); } private StringBuffer generateClassifierEnd(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateEquals(cls)) .append("\n") .append(generateHashCode(cls)) .append("\n") .append(generateToString(cls)) .append("}"); return sb; } private StringBuffer generateClassifierBody(MClassifier cls) { StringBuffer sb = new StringBuffer(); // (attribute) fields Collection strs = getAttributes(cls); if (!strs.isEmpty()) { Iterator strIter = strs.iterator(); while (strIter.hasNext()) { sb.append(generate((MStructuralFeature) strIter.next())); } } // (association) fields Collection ends = new ArrayList(cls.getAssociationEnds()); if (!ends.isEmpty()) { Iterator endIter = ends.iterator(); while (endIter.hasNext()) { MAssociationEnd ae = (MAssociationEnd) endIter.next(); sb.append(generateAssociationEnd(ae.getOppositeEnd())); } } // methods Collection behs = getOperations(cls); if (!behs.isEmpty()) { sb.append('\n'); Iterator behEnum = behs.iterator(); while (behEnum.hasNext()) { MBehavioralFeature bf = (MBehavioralFeature) behEnum.next(); sb.append(generate(bf)); if ((cls instanceof MClassImpl) && (bf instanceof MOperation) && (!((MOperation) bf).isAbstract())) { sb.append(" {\n") .append(generateMethodBody((MOperation) bf)) .append(INDENT) .append("}\n"); } else { sb.append(";\n"); } } } return sb; } private String generateMethodBody (MOperation op) { if (op != null) { Collection methods = op.getMethods(); Iterator i = methods.iterator(); MMethod m = null; while (i != null && i.hasNext()) { m = (MMethod) i.next(); if (m != null) { if (m.getBody() != null) { return m.getBody().getBody(); } else { return ""; } } } // pick out return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); return generateDefaultReturnStatement (returnType); } } return generateDefaultReturnStatement (null); } private String generateDefaultReturnStatement(MClassifier cls) { if (cls == null) { return ""; } String clsName = cls.getName(); if (clsName.equals("void")) { return ""; } if (clsName.equals("char")) { return INDENT + "return 'x';\n"; } if (clsName.equals("int")) { return INDENT + "return 0;\n"; } if (clsName.equals("boolean")) { return INDENT + "return false;\n"; } if (clsName.equals("byte")) { return INDENT + "return 0;\n"; } if (clsName.equals("long")) { return INDENT + "return 0;\n"; } if (clsName.equals("float")) { return INDENT + "return 0.0;\n"; } if (clsName.equals("double")) { return INDENT + "return 0.0;\n"; } return INDENT + "return null;\n"; } private String generateSpecification(MClass cls) { Collection realizations = getSpecifications(cls); if (realizations == null) { return ""; } StringBuffer sb = new StringBuffer(); Iterator clsEnum = realizations.iterator(); while (clsEnum.hasNext()) { MInterface i = (MInterface) clsEnum.next(); sb.append(generateClassifierRef(i)); if (clsEnum.hasNext()) { sb.append(", "); } } return sb.toString(); } private String generateVisibility(MVisibilityKind vis) { if (MVisibilityKind.PUBLIC.equals(vis)) { return "public "; } if (MVisibilityKind.PRIVATE.equals(vis)) { return "private "; } if (MVisibilityKind.PROTECTED.equals(vis)) { return "protected "; } return ""; } private String generateVisibility(MFeature f) { return generateVisibility(f.getVisibility()); } private String generateScope(MFeature f) { MScopeKind scope = f.getOwnerScope(); if (MScopeKind.CLASSIFIER.equals(scope)) { return "static "; } return ""; } private String generateAbstractness(MOperation op) { if (op.isAbstract()) { return "abstract "; } return ""; } private String generateChangeability(MOperation op) { if (op.isLeaf()) { return "final "; } return ""; } private String generateChangability(MStructuralFeature sf) { MChangeableKind ck = sf.getChangeability(); //if (ck == null) return ""; if (MChangeableKind.FROZEN.equals(ck)) { return "final "; } //if (MChangeableKind.ADDONLY.equals(ck)) return "final "; return ""; } private String generateConcurrency(MOperation op) { if (op.getConcurrency() != null && op.getConcurrency().getValue() == MCallConcurrencyKind._GUARDED) { return "synchronized "; } return ""; } private Collection getKeys(MClassifier cls) { Set keyFields = new LinkedHashSet(); Collection tvs = cls.getTaggedValues(); if (tvs != null && tvs.size() > 0) { Iterator iter = tvs.iterator(); while (iter.hasNext()) { MTaggedValue tv = (MTaggedValue) iter.next(); if (tv.getTag().equals("key")) { StringTokenizer st = new StringTokenizer(tv.getValue(), ", "); while (st.hasMoreElements()) { keyFields.add(st.nextElement()); } } } } Iterator parents = cls.getGeneralizations().iterator(); if (parents.hasNext()) { keyFields.addAll(getKeys((MClassifier) ((MGeneralization) parents.next()).getParent())); } return keyFields; } private boolean isPrimitive(String type) { return type.equals("char") || type.equals("byte") || type.equals("short") || type.equals("int") || type.equals("long") || type.equals("float") || type.equals("double") || type.equals("boolean") ? true : false; } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: JavaModelOutput <project name> <input dir> <output dir>"); System.exit(1); } String projectName = args[0]; String inputDir = args[1]; String outputDir = args[2]; File xmiFile = new File(inputDir, projectName + "_.xmi"); InputSource source = new InputSource(xmiFile.toURL().toString()); File path = new File(outputDir); new JavaModelOutput(new XMIReader().parse(source)).output(path); } }
provide a better .hashCode function
intermine/src/java/org/intermine/codegen/JavaModelOutput.java
provide a better .hashCode function
Java
apache-2.0
6dd519ac75db061a042da0f633e5373c2a6ab263
0
geothomasp/kualico-rice-kc,jwillia/kc-rice1,shahess/rice,geothomasp/kualico-rice-kc,smith750/rice,sonamuthu/rice-1,cniesen/rice,shahess/rice,rojlarge/rice-kc,gathreya/rice-kc,gathreya/rice-kc,UniversityOfHawaiiORS/rice,cniesen/rice,ewestfal/rice,shahess/rice,sonamuthu/rice-1,shahess/rice,jwillia/kc-rice1,kuali/kc-rice,sonamuthu/rice-1,ewestfal/rice-svn2git-test,gathreya/rice-kc,smith750/rice,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,bsmith83/rice-1,kuali/kc-rice,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,bhutchinson/rice,ewestfal/rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,jwillia/kc-rice1,bsmith83/rice-1,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,cniesen/rice,bsmith83/rice-1,rojlarge/rice-kc,cniesen/rice,ewestfal/rice,gathreya/rice-kc,geothomasp/kualico-rice-kc,rojlarge/rice-kc,shahess/rice,bhutchinson/rice,bhutchinson/rice,smith750/rice,bsmith83/rice-1,bhutchinson/rice,kuali/kc-rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,ewestfal/rice,kuali/kc-rice,sonamuthu/rice-1,rojlarge/rice-kc,ewestfal/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,smith750/rice,smith750/rice,cniesen/rice,kuali/kc-rice,bhutchinson/rice
/** * Copyright 2005-2014 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.krad.labs.inquiries; import org.junit.Test; /** * @author Kuali Rice Team (rice.collab@kuali.org) */ public class LabsInquiryAttributionDefinitionFormattingAft extends LabsInquiryBase { /** * /kr-krad/kradsampleapp?viewId=KradInquirySample-PageR2C1 */ public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=KradInquirySample-PageR2C1"; @Override protected String getBookmarkUrl() { return BOOKMARK_URL; } @Override protected void navigate() throws Exception { navigateToInquiry("Inquiry - AttributionDefinition Formatting"); } protected void testInquiryAttributionDefinitionFormatting() throws InterruptedException { // Inquiry - AttributionDefinition Formatting waitAndClickByLinkText("Inquiry - AttributionDefinition Formatting"); // Lightbox waitAndClickLinkContainingText("10000"); gotoLightBox(); String[][] lightBoxLabeledText = {{"Id:", "10000"}, {"Travel Authorization Document:", "10000"}, {"Travel Company Name:", "Discount Travel"}, {"Expense Type:", "ME"}, {"Expense Description:", "Family Related"}, // {"Expense Date:", getDateTomorrow()}, {"Expense Amount:", "1,278.97"}, {"Reimbursable:", "true"}, {"Taxable:", "true"}}; assertLabeledTextPresent(lightBoxLabeledText); clickCollapseAll(); assertLabeledTextNotPresent(lightBoxLabeledText); clickExpandAll(); assertLabeledTextPresent(lightBoxLabeledText); waitAndClickButtonByText(CLOSE); selectTopFrame(); assertLabeledTextPresent(lightBoxLabeledText); waitAndClickButtonByText("< Back"); //Inquiry - AttributionDefinition Formatting (Partial Attribute Masking, Additional Display Attribute Name) waitAndClickByLinkText("Inquiry - AttributionDefinition Formatting (Partial Attribute Masking, Additional Display Attribute Name)"); String[][] LabeledText = {{"Id:", "1"}, {"Document Number:", "??"}, {"Principal Id:", "fred"}, {"Traveler Name:", ""}, {"Traveler User ID:", ""}, {"First and Last Name (additionalDisplayAttributeName example):", "Test *-* Traveler"}, {"Middle Name:", "A"}, {"Last Name:", "Traveler"}, {"Street Address Line1:", "123 Nowhere St."}, {"Street Address Line2:", ""}, {"City Name:", "Davis"}, {"State", "CA"}, {"Zip:", "95616"}, {"Country:", "US"}, {"Email Address:", ""}, {"Gender:", "M"}, {"Phone Number:", "(xxx)xxx-xxxx"}, {"Traveler Type Code:", "123"}, {"Customer Number:", "CUST"}, {"Drivers License:", "*****45678"}, {"Drivers License Exp Date:", "06/30/2015"}, {"Active:", "true"}, {"Non Resident Alien:", "false"}, {"Liability Insurance:", "false"},}; assertLabeledTextPresent(LabeledText); } @Test public void testInquiryAttributionDefinitionFormattingBookmark() throws Exception { testInquiryAttributionDefinitionFormatting(); passed(); } @Test public void testInquiryAttributionDefinitionFormattingNav() throws Exception { testInquiryAttributionDefinitionFormatting(); passed(); } }
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/labs/inquiries/LabsInquiryAttributionDefinitionFormattingAft.java
/** * Copyright 2005-2014 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.krad.labs.inquiries; import org.junit.Test; /** * @author Kuali Rice Team (rice.collab@kuali.org) */ public class LabsInquiryAttributionDefinitionFormattingAft extends LabsInquiryBase { /** * /kr-krad/kradsampleapp?viewId=KradInquirySample-PageR2C1 */ public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=KradInquirySample-PageR2C1"; @Override protected String getBookmarkUrl() { return BOOKMARK_URL; } @Override protected void navigate() throws Exception { navigateToInquiry("Inquiry - AttributionDefinition Formatting"); } protected void testInquiryAttributionDefinitionFormatting() throws InterruptedException { // Inquiry - AttributionDefinition Formatting waitAndClickByLinkText("Inquiry - AttributionDefinition Formatting"); // Lightbox waitAndClickLinkContainingText("10000"); gotoLightBox(); String[][] lightBoxLabeledText = {{"Id:", "10000"}, {"Travel Authorization Document:", "10000"}, {"Travel Company Name:", "Discount Travel"}, {"Expense Type:", "ME"}, {"Expense Description:", "Family Related"}, // {"Expense Date:", getDateTomorrow()}, {"Expense Amount:", "1,278.97"}, {"Reimbursable:", "true"}, {"Taxable:", "true"}}; assertLabeledTextPresent(lightBoxLabeledText); clickCollapseAll(); assertLabeledTextNotPresent(lightBoxLabeledText); clickExpandAll(); assertLabeledTextPresent(lightBoxLabeledText); waitAndClickButtonByText(CLOSE); selectTopFrame(); assertLabeledTextPresent(lightBoxLabeledText); waitAndClickButtonByText("< Back"); //Inquiry - AttributionDefinition Formatting (Partial Attribute Masking, Additional Display Attribute Name) waitAndClickByLinkText("Inquiry - AttributionDefinition Formatting (Partial Attribute Masking, Additional Display Attribute Name)"); String[][] LabeledText = {{"Id:", "1"}, {"Document Number:", "??"}, {"Principal Id:", "fred"}, {"Traveler Name:", ""}, {"Traveler User ID:", ""}, {"First and Last Name (additionalDisplayAttributeName example):", "Test *-* Traveler"}, {"Middle Name:", "A"}, {"Last Name:", "Traveler"}, {"Street Address Line1:", "123 Nowhere St."}, {"Street Address Line2:", ""}, {"City Name:", "Davis"}, {"State", "CA"}, {"Zip:", "95616"}, {"Country:", "US"}, {"Email Address:", ""}, {"Gender:", "M"}, {"Phone Number:", "(xxx)xxx-xxxx"}, {"Traveler Type Code:", "123"}, {"Customer Number:", "CUST"}, {"Drivers License:", "*****45678"}, {"Drivers License Exp Date:", "11/08/2018"}, {"Active:", "true"}, {"Non Resident Alien:", "false"}, {"Liability Insurance:", "false"},}; assertLabeledTextPresent(LabeledText); } @Test public void testInquiryAttributionDefinitionFormattingBookmark() throws Exception { testInquiryAttributionDefinitionFormatting(); passed(); } @Test public void testInquiryAttributionDefinitionFormattingNav() throws Exception { testInquiryAttributionDefinitionFormatting(); passed(); } }
RICEQA-268 : Analyze CI Failures for 2.4.0-rc1 QA Sprint 6
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/labs/inquiries/LabsInquiryAttributionDefinitionFormattingAft.java
RICEQA-268 : Analyze CI Failures for 2.4.0-rc1 QA Sprint 6
Java
apache-2.0
ccda2c4e7c01259b95424cb89575f5fb228f2575
0
ascrutae/sky-walking,ascrutae/sky-walking,ascrutae/sky-walking,OpenSkywalking/skywalking,apache/skywalking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,OpenSkywalking/skywalking,apache/skywalking,apache/skywalking
/* * 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.skywalking.apm.collector.analysis.metric.provider.worker.instance.refmetric; import org.apache.skywalking.apm.collector.analysis.metric.define.graph.MetricWorkerIdDefine; import org.apache.skywalking.apm.collector.analysis.worker.model.base.AbstractLocalAsyncWorkerProvider; import org.apache.skywalking.apm.collector.analysis.worker.model.base.WorkerException; import org.apache.skywalking.apm.collector.analysis.worker.model.impl.AggregationWorker; import org.apache.skywalking.apm.collector.core.annotations.trace.GraphComputingMetric; import org.apache.skywalking.apm.collector.core.module.ModuleManager; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.table.instance.InstanceReferenceMetric; import org.apache.skywalking.apm.collector.storage.table.instance.InstanceReferenceMetricTable; import org.apache.skywalking.apm.collector.storage.table.service.ServiceReferenceMetric; /** * @author peng-yongsheng */ public class InstanceReferenceMinuteMetricAggregationWorker extends AggregationWorker<ServiceReferenceMetric, InstanceReferenceMetric> { private InstanceReferenceMinuteMetricAggregationWorker(ModuleManager moduleManager) { super(moduleManager); } @Override public int id() { return MetricWorkerIdDefine.INSTANCE_REFERENCE_MINUTE_METRIC_AGGREGATION_WORKER_ID; } @Override protected InstanceReferenceMetric transform(ServiceReferenceMetric serviceReferenceMetric) { String metricId = serviceReferenceMetric.getFrontInstanceId() + Const.ID_SPLIT + serviceReferenceMetric.getBehindInstanceId() + Const.ID_SPLIT + serviceReferenceMetric.getSourceValue(); String id = serviceReferenceMetric.getTimeBucket() + Const.ID_SPLIT + metricId; InstanceReferenceMetric instanceReferenceMetric = new InstanceReferenceMetric(); instanceReferenceMetric.setId(id); instanceReferenceMetric.setMetricId(metricId); instanceReferenceMetric.setFrontApplicationId(serviceReferenceMetric.getFrontApplicationId()); instanceReferenceMetric.setFrontInstanceId(serviceReferenceMetric.getFrontInstanceId()); instanceReferenceMetric.setBehindApplicationId(serviceReferenceMetric.getBehindApplicationId()); instanceReferenceMetric.setBehindInstanceId(serviceReferenceMetric.getBehindInstanceId()); instanceReferenceMetric.setSourceValue(serviceReferenceMetric.getSourceValue()); instanceReferenceMetric.setTransactionCalls(serviceReferenceMetric.getTransactionCalls()); instanceReferenceMetric.setTransactionErrorCalls(serviceReferenceMetric.getTransactionErrorCalls()); instanceReferenceMetric.setTransactionDurationSum(serviceReferenceMetric.getTransactionDurationSum()); instanceReferenceMetric.setTransactionErrorDurationSum(serviceReferenceMetric.getTransactionErrorDurationSum()); instanceReferenceMetric.setBusinessTransactionCalls(serviceReferenceMetric.getBusinessTransactionCalls()); instanceReferenceMetric.setBusinessTransactionErrorCalls(serviceReferenceMetric.getBusinessTransactionErrorCalls()); instanceReferenceMetric.setBusinessTransactionDurationSum(serviceReferenceMetric.getBusinessTransactionDurationSum()); instanceReferenceMetric.setBusinessTransactionErrorDurationSum(serviceReferenceMetric.getBusinessTransactionErrorDurationSum()); instanceReferenceMetric.setMqTransactionCalls(serviceReferenceMetric.getMqTransactionCalls()); instanceReferenceMetric.setMqTransactionErrorCalls(serviceReferenceMetric.getMqTransactionErrorCalls()); instanceReferenceMetric.setMqTransactionDurationSum(serviceReferenceMetric.getMqTransactionDurationSum()); instanceReferenceMetric.setMqTransactionErrorDurationSum(serviceReferenceMetric.getMqTransactionErrorDurationSum()); instanceReferenceMetric.setTimeBucket(serviceReferenceMetric.getTimeBucket()); return instanceReferenceMetric; } public static class Factory extends AbstractLocalAsyncWorkerProvider<ServiceReferenceMetric, InstanceReferenceMetric, InstanceReferenceMinuteMetricAggregationWorker> { public Factory(ModuleManager moduleManager) { super(moduleManager); } @Override public InstanceReferenceMinuteMetricAggregationWorker workerInstance(ModuleManager moduleManager) { return new InstanceReferenceMinuteMetricAggregationWorker(moduleManager); } @Override public int queueSize() { return 1024; } } @GraphComputingMetric(name = "/aggregate/onWork/" + InstanceReferenceMetricTable.TABLE) @Override protected void onWork(ServiceReferenceMetric message) throws WorkerException { super.onWork(message); } }
apm-collector/apm-collector-analysis/analysis-metric/metric-provider/src/main/java/org/apache/skywalking/apm/collector/analysis/metric/provider/worker/instance/refmetric/InstanceReferenceMinuteMetricAggregationWorker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.collector.analysis.metric.provider.worker.instance.refmetric; import org.apache.skywalking.apm.collector.analysis.metric.define.graph.MetricWorkerIdDefine; import org.apache.skywalking.apm.collector.analysis.worker.model.base.AbstractLocalAsyncWorkerProvider; import org.apache.skywalking.apm.collector.analysis.worker.model.base.WorkerException; import org.apache.skywalking.apm.collector.analysis.worker.model.impl.AggregationWorker; import org.apache.skywalking.apm.collector.core.annotations.trace.GraphComputingMetric; import org.apache.skywalking.apm.collector.core.module.ModuleManager; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.table.instance.InstanceReferenceMetric; import org.apache.skywalking.apm.collector.storage.table.instance.InstanceReferenceMetricTable; import org.apache.skywalking.apm.collector.storage.table.service.ServiceReferenceMetric; /** * @author peng-yongsheng */ public class InstanceReferenceMinuteMetricAggregationWorker extends AggregationWorker<ServiceReferenceMetric, InstanceReferenceMetric> { private InstanceReferenceMinuteMetricAggregationWorker(ModuleManager moduleManager) { super(moduleManager); } @Override public int id() { return MetricWorkerIdDefine.INSTANCE_REFERENCE_MINUTE_METRIC_AGGREGATION_WORKER_ID; } @Override protected InstanceReferenceMetric transform(ServiceReferenceMetric serviceReferenceMetric) { String metricId = serviceReferenceMetric.getFrontInstanceId() + Const.ID_SPLIT + serviceReferenceMetric.getBehindInstanceId() + Const.ID_SPLIT + serviceReferenceMetric.getSourceValue(); String id = serviceReferenceMetric.getTimeBucket() + Const.ID_SPLIT + metricId; InstanceReferenceMetric instanceReferenceMetric = new InstanceReferenceMetric(); instanceReferenceMetric.setId(id); instanceReferenceMetric.setMetricId(metricId); instanceReferenceMetric.setFrontApplicationId(serviceReferenceMetric.getFrontApplicationId()); instanceReferenceMetric.setFrontInstanceId(serviceReferenceMetric.getFrontInstanceId()); instanceReferenceMetric.setBehindApplicationId(serviceReferenceMetric.getBehindApplicationId()); instanceReferenceMetric.setBehindInstanceId(serviceReferenceMetric.getBehindInstanceId()); instanceReferenceMetric.setSourceValue(serviceReferenceMetric.getSourceValue()); instanceReferenceMetric.setTransactionCalls(serviceReferenceMetric.getTransactionCalls()); instanceReferenceMetric.setTransactionErrorCalls(serviceReferenceMetric.getTransactionErrorCalls()); instanceReferenceMetric.setTransactionDurationSum(serviceReferenceMetric.getTransactionDurationSum()); instanceReferenceMetric.setTransactionErrorDurationSum(serviceReferenceMetric.getTransactionErrorDurationSum()); instanceReferenceMetric.setBusinessTransactionCalls(serviceReferenceMetric.getBusinessTransactionCalls()); instanceReferenceMetric.setBusinessTransactionErrorCalls(instanceReferenceMetric.getBusinessTransactionErrorCalls()); instanceReferenceMetric.setBusinessTransactionDurationSum(instanceReferenceMetric.getBusinessTransactionDurationSum()); instanceReferenceMetric.setBusinessTransactionErrorDurationSum(instanceReferenceMetric.getBusinessTransactionErrorDurationSum()); instanceReferenceMetric.setMqTransactionCalls(instanceReferenceMetric.getMqTransactionCalls()); instanceReferenceMetric.setMqTransactionErrorCalls(instanceReferenceMetric.getMqTransactionErrorCalls()); instanceReferenceMetric.setMqTransactionDurationSum(instanceReferenceMetric.getMqTransactionDurationSum()); instanceReferenceMetric.setMqTransactionErrorDurationSum(instanceReferenceMetric.getMqTransactionErrorDurationSum()); instanceReferenceMetric.setTimeBucket(serviceReferenceMetric.getTimeBucket()); return instanceReferenceMetric; } public static class Factory extends AbstractLocalAsyncWorkerProvider<ServiceReferenceMetric, InstanceReferenceMetric, InstanceReferenceMinuteMetricAggregationWorker> { public Factory(ModuleManager moduleManager) { super(moduleManager); } @Override public InstanceReferenceMinuteMetricAggregationWorker workerInstance(ModuleManager moduleManager) { return new InstanceReferenceMinuteMetricAggregationWorker(moduleManager); } @Override public int queueSize() { return 1024; } } @GraphComputingMetric(name = "/aggregate/onWork/" + InstanceReferenceMetricTable.TABLE) @Override protected void onWork(ServiceReferenceMetric message) throws WorkerException { super.onWork(message); } }
refrence may be always 0 (#1125)
apm-collector/apm-collector-analysis/analysis-metric/metric-provider/src/main/java/org/apache/skywalking/apm/collector/analysis/metric/provider/worker/instance/refmetric/InstanceReferenceMinuteMetricAggregationWorker.java
refrence may be always 0 (#1125)
Java
apache-2.0
21ef8ff7358504647b4be60bcec04b826974f0d7
0
sangramjadhav/testrs
231a7f50-2ece-11e5-905b-74de2bd44bed
hello.java
2319d33e-2ece-11e5-905b-74de2bd44bed
231a7f50-2ece-11e5-905b-74de2bd44bed
hello.java
231a7f50-2ece-11e5-905b-74de2bd44bed
Java
apache-2.0
8e18054f3b6cd6fa619853354678d4d528345315
0
jmhanna/commons-csv,chronoangelus/commons-csv,harikrishna1947a/csv,mohanaraosv/commons-csv,fabriciobressan/crossover_question2,SCORPIO12/Case2,warriorno22/commons-csv,quettech/qa2,Aweitzel86/TestCase2.1,parmarsumit/commons-csv,afafhassan/commons-csv,muhammadallee/commons-csv,harikrishna1947a/csv,shubhcollaborator/common-csvnew,COTechTrial/case2,warriorno22/commons-csv,jtardaguila/test2,dakinyade/commons-csv,shacore10/commons-csv,jtardaguila/test2,mirasrael/commons-csv,muhammadallee/commons-csv,expertryk/commons-csv,chio003/Test2,amee-trivedi/commons-csv,apache/commons-csv,mohanaraosv/commons-csv,lihenu/Crossover_project,fadysamirzakarya/commons-csv,shashankasharma/commons-csv,parmarsumit/commons-csv,khalilrahman/commons-csv,Elttbakh/Test02,quettech/csv-import,fadysamirzakarya/common-csv-2,UzumakiMansi/commons-csv,sufianqayyum131/PRODSUP-002,AndrewGuthua/CrossOverTest2,quettech/qa2,DGAlexandru/commons-csv,sruputway/commons-csv_test,AndrewGuthua/CrossOverTest2,festusjejelowo/commons-csv,najamalvi/PRODSUP-002,DGAlexandru/commons-csv,expertryk/commons-csv,gargchap/gargvaibhav,chio003/Test2,najamalvi/PRODSUP-002,iffi101/commons-csv,RavinaDhruve/commons-csv,pvllnspk/commons-csv,Elttbakh/Test03,SCORPIO12/Case2,catconst/commons-csv,RavinaDhruve/commons-csv,fabriciobressan/crossover_question2,pvllnspk/commons-csv,iffi101/commons-csv,Elttbakh/Test03,amee-trivedi/commons-csv,viliescu/PRODSUP-002,Aweitzel86/TestCase2.1,sruputway/commons-csv_test,shubhcollaborator/common-csvnew,UzumakiMansi/commons-csv,fadysamirzakarya/common-csv-2,mbreslow/commons-csv,shacore10/commons-csv,arunnairvyaj/commons-csv-trunk,syedbilalmasaud/case2,catconst/commons-csv,fadysamirzakarya/commons-csv,chronoangelus/commons-csv,dakinyade/commons-csv,shashankasharma/commons-csv,GauriGNaik/commons-csv,UzumakiMansi/commons-csv,Elttbakh/Test02,jmhanna/commons-csv,shadykandeel/commons-csv,shashankasharma/commons-csv,COTechTrial/case2,gargchap/gargvaibhav,viliescu/PRODSUP-002,rayiss/commons-csv,arunpaulonline/test2,mbreslow/commons-csv,apache/commons-csv,arunnairvyaj/commons-csv-trunk,catconst/commons-csv,mirasrael/commons-csv,khalilrahman/commons-csv,thanhnbt/commons-csv,shadykandeel/commons-csv,afafhassan/commons-csv,rayiss/commons-csv,syedbilalmasaud/case2,lihenu/Crossover_project,thanhnbt/commons-csv,quettech/csv-import,shashankasharma/commons-csv,festusjejelowo/commons-csv,arunpaulonline/test2,sufianqayyum131/PRODSUP-002,GauriGNaik/commons-csv
/* * 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.csv; import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.END_OF_STREAM; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Constants.UNDEFINED; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.INVALID; import static org.apache.commons.csv.Token.Type.TOKEN; import java.io.IOException; /** * * * @version $Id$ */ final class Lexer { /** * Constant char to use for disabling comments, escapes and encapsulation. The value -2 is used because it * won't be confused with an EOF signal (-1), and because the Unicode value {@code FFFE} would be encoded as two * chars (using surrogates) and thus there should never be a collision with a real text char. */ private static final char DISABLED = '\ufffe'; private final char delimiter; private final char escape; private final char quoteChar; private final char commentStart; private final boolean ignoreSurroundingSpaces; private final boolean ignoreEmptyLines; /** The input stream */ private final ExtendedBufferedReader reader; /** INTERNAL API. but ctor needs to be called dynamically by PerformanceTest class */ Lexer(final CSVFormat format, final ExtendedBufferedReader reader) { this.reader = reader; this.delimiter = format.getDelimiter(); this.escape = mapNullToDisabled(format.getEscape()); this.quoteChar = mapNullToDisabled(format.getQuoteChar()); this.commentStart = mapNullToDisabled(format.getCommentStart()); this.ignoreSurroundingSpaces = format.getIgnoreSurroundingSpaces(); this.ignoreEmptyLines = format.getIgnoreEmptyLines(); } /** * Returns the next token. * <p/> * A token corresponds to a term, a record change or an end-of-file indicator. * * @param token * an existing Token object to reuse. The caller is responsible to initialize the Token. * @return the next token found * @throws java.io.IOException * on stream access error */ Token nextToken(final Token token) throws IOException { // get the last read char (required for empty line detection) int lastChar = reader.getLastChar(); // read the next char and set eol int c = reader.read(); /* * Note: The following call will swallow LF if c == CR. But we don't need to know if the last char was CR or LF * - they are equivalent here. */ boolean eol = readEndOfLine(c); // empty line detection: eol AND (last char was EOL or beginning) if (ignoreEmptyLines) { while (eol && isStartOfLine(lastChar)) { // go on char ahead ... lastChar = c; c = reader.read(); eol = readEndOfLine(c); // reached end of file without any content (empty line at the end) if (isEndOfFile(c)) { token.type = EOF; // don't set token.isReady here because no content return token; } } } // did we reach eof during the last iteration already ? EOF if (isEndOfFile(lastChar) || (!isDelimiter(lastChar) && isEndOfFile(c))) { token.type = EOF; // don't set token.isReady here because no content return token; } if (isStartOfLine(lastChar) && isCommentStart(c)) { final String line = reader.readLine(); if (line == null) { token.type = EOF; // don't set token.isReady here because no content return token; } final String comment = line.trim(); token.content.append(comment); token.type = COMMENT; return token; } // important: make sure a new char gets consumed in each iteration while (token.type == INVALID) { // ignore whitespaces at beginning of a token if (ignoreSurroundingSpaces) { while (isWhitespace(c) && !eol) { c = reader.read(); eol = readEndOfLine(c); } } // ok, start of token reached: encapsulated, or token if (isDelimiter(c)) { // empty token return TOKEN("") token.type = TOKEN; } else if (eol) { // empty token return EORECORD("") // noop: token.content.append(""); token.type = EORECORD; } else if (isQuoteChar(c)) { // consume encapsulated token parseEncapsulatedToken(token); } else if (isEndOfFile(c)) { // end of file return EOF() // noop: token.content.append(""); token.type = EOF; token.isReady = true; // there is data at EOF } else { // next token must be a simple token // add removed blanks when not ignoring whitespace chars... parseSimpleToken(token, c); } } return token; } /** * Parses a simple token. * <p/> * Simple token are tokens which are not surrounded by encapsulators. A simple token might contain escaped * delimiters (as \, or \;). The token is finished when one of the following conditions become true: * <ul> * <li>end of line has been reached (EORECORD)</li> * <li>end of stream has been reached (EOF)</li> * <li>an unescaped delimiter has been reached (TOKEN)</li> * </ul> * * @param token * the current token * @param ch * the current character * @return the filled token * @throws IOException * on stream access error */ private Token parseSimpleToken(final Token token, int ch) throws IOException { // Faster to use while(true)+break than while(token.type == INVALID) while (true) { if (readEndOfLine(ch)) { token.type = EORECORD; break; } else if (isEndOfFile(ch)) { token.type = EOF; token.isReady = true; // There is data at EOF break; } else if (isDelimiter(ch)) { token.type = TOKEN; break; } else if (isEscape(ch)) { final int unescaped = readEscape(); if (unescaped == Constants.END_OF_STREAM) { // unexpected char after escape token.content.append((char) ch).append((char) reader.getLastChar()); } else { token.content.append((char) unescaped); } ch = reader.read(); // continue } else { token.content.append((char) ch); ch = reader.read(); // continue } } if (ignoreSurroundingSpaces) { trimTrailingSpaces(token.content); } return token; } /** * Parses an encapsulated token. * <p/> * Encapsulated tokens are surrounded by the given encapsulating-string. The encapsulator itself might be included * in the token using a doubling syntax (as "", '') or using escaping (as in \", \'). Whitespaces before and after * an encapsulated token are ignored. The token is finished when one of the following conditions become true: * <ul> * <li>an unescaped encapsulator has been reached, and is followed by optional whitespace then:</li> * <ul> * <li>delimiter (TOKEN)</li> * <li>end of line (EORECORD)</li> * </ul> * <li>end of stream has been reached (EOF)</li> </ul> * * @param token * the current token * @return a valid token object * @throws IOException * on invalid state: EOF before closing encapsulator or invalid character before delimiter or EOL */ private Token parseEncapsulatedToken(final Token token) throws IOException { // save current line number in case needed for IOE final long startLineNumber = getCurrentLineNumber(); int c; while (true) { c = reader.read(); if (isEscape(c)) { final int unescaped = readEscape(); if (unescaped == Constants.END_OF_STREAM) { // unexpected char after escape token.content.append((char) c).append((char) reader.getLastChar()); } else { token.content.append((char) unescaped); } } else if (isQuoteChar(c)) { if (isQuoteChar(reader.lookAhead())) { // double or escaped encapsulator -> add single encapsulator to token c = reader.read(); token.content.append((char) c); } else { // token finish mark (encapsulator) reached: ignore whitespace till delimiter while (true) { c = reader.read(); if (isDelimiter(c)) { token.type = TOKEN; return token; } else if (isEndOfFile(c)) { token.type = EOF; token.isReady = true; // There is data at EOF return token; } else if (readEndOfLine(c)) { token.type = EORECORD; return token; } else if (!isWhitespace(c)) { // error invalid char between token and next delimiter throw new IOException("(line " + getCurrentLineNumber() + ") invalid char between encapsulated token and delimiter"); } } } } else if (isEndOfFile(c)) { // error condition (end of file before end of token) throw new IOException("(startline " + startLineNumber + ") EOF reached before encapsulated token finished"); } else { // consume character token.content.append((char) c); } } } private char mapNullToDisabled(final Character c) { return c == null ? DISABLED : c.charValue(); } /** * Returns the current line number * * @return the current line number */ long getCurrentLineNumber() { return reader.getCurrentLineNumber(); } // TODO escape handling needs more work /** * Handle an escape sequence. * The current character must be the escape character. * On return, the next character is available by calling {@link ExtendedBufferedReader#getLastChar()} * on the input stream. * * @return the unescaped character (as an int) or {@link Constants#END_OF_STREAM} if char following the escape is * invalid. * @throws IOException if there is a problem reading the stream or the end of stream is detected: * the escape character is not allowed at end of strem */ int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int ch = reader.read(); switch (ch) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF; case CR: case LF: case FF: // TODO is this correct? case TAB: // TODO is this correct? Do tabs need to be escaped? case BACKSPACE: // TODO is this correct? return ch; case END_OF_STREAM: throw new IOException("EOF whilst processing escape sequence"); default: // Now check for meta-characters if (isMetaChar(ch)) { return ch; } // indicate unexpected char - available from in.getLastChar() return END_OF_STREAM; } } void trimTrailingSpaces(final StringBuilder buffer) { int length = buffer.length(); while (length > 0 && Character.isWhitespace(buffer.charAt(length - 1))) { length = length - 1; } if (length != buffer.length()) { buffer.setLength(length); } } /** * Greedily accepts \n, \r and \r\n This checker consumes silently the second control-character... * * @return true if the given or next character is a line-terminator */ boolean readEndOfLine(int ch) throws IOException { // check if we have \r\n... if (ch == CR && reader.lookAhead() == LF) { // note: does not change ch outside of this method! ch = reader.read(); } return ch == LF || ch == CR; } boolean isClosed() { return reader.isClosed(); } /** * @return true if the given char is a whitespace character */ boolean isWhitespace(final int ch) { return !isDelimiter(ch) && Character.isWhitespace((char) ch); } /** * Checks if the current character represents the start of a line: a CR, LF or is at the start of the file. * * @param ch the character to check * @return true if the character is at the start of a line. */ boolean isStartOfLine(final int ch) { return ch == LF || ch == CR || ch == UNDEFINED; } /** * @return true if the given character indicates end of file */ boolean isEndOfFile(final int ch) { return ch == END_OF_STREAM; } boolean isDelimiter(final int ch) { return ch == delimiter; } boolean isEscape(final int ch) { return ch == escape; } boolean isQuoteChar(final int ch) { return ch == quoteChar; } boolean isCommentStart(final int ch) { return ch == commentStart; } private boolean isMetaChar(final int ch) { return ch == delimiter || ch == escape || ch == quoteChar || ch == commentStart; } /** * Closes resources. * * @throws IOException * If an I/O error occurs */ void close() throws IOException { reader.close(); } }
src/main/java/org/apache/commons/csv/Lexer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.END_OF_STREAM; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Constants.UNDEFINED; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.INVALID; import static org.apache.commons.csv.Token.Type.TOKEN; import java.io.IOException; /** * * * @version $Id$ */ final class Lexer { /** * Constant char to use for disabling comments, escapes and encapsulation. The value -2 is used because it * won't be confused with an EOF signal (-1), and because the Unicode value {@code FFFE} would be encoded as two * chars (using surrogates) and thus there should never be a collision with a real text char. */ private static final char DISABLED = '\ufffe'; private final char delimiter; private final char escape; private final char quoteChar; private final char commentStart; private final boolean ignoreSurroundingSpaces; private final boolean ignoreEmptyLines; /** The input stream */ private final ExtendedBufferedReader in; /** INTERNAL API. but ctor needs to be called dynamically by PerformanceTest class */ Lexer(final CSVFormat format, final ExtendedBufferedReader in) { this.in = in; this.delimiter = format.getDelimiter(); this.escape = mapNullToDisabled(format.getEscape()); this.quoteChar = mapNullToDisabled(format.getQuoteChar()); this.commentStart = mapNullToDisabled(format.getCommentStart()); this.ignoreSurroundingSpaces = format.getIgnoreSurroundingSpaces(); this.ignoreEmptyLines = format.getIgnoreEmptyLines(); } /** * Returns the next token. * <p/> * A token corresponds to a term, a record change or an end-of-file indicator. * * @param token * an existing Token object to reuse. The caller is responsible to initialize the Token. * @return the next token found * @throws java.io.IOException * on stream access error */ Token nextToken(final Token token) throws IOException { // get the last read char (required for empty line detection) int lastChar = in.getLastChar(); // read the next char and set eol int c = in.read(); /* * Note: The following call will swallow LF if c == CR. But we don't need to know if the last char was CR or LF * - they are equivalent here. */ boolean eol = readEndOfLine(c); // empty line detection: eol AND (last char was EOL or beginning) if (ignoreEmptyLines) { while (eol && isStartOfLine(lastChar)) { // go on char ahead ... lastChar = c; c = in.read(); eol = readEndOfLine(c); // reached end of file without any content (empty line at the end) if (isEndOfFile(c)) { token.type = EOF; // don't set token.isReady here because no content return token; } } } // did we reach eof during the last iteration already ? EOF if (isEndOfFile(lastChar) || (!isDelimiter(lastChar) && isEndOfFile(c))) { token.type = EOF; // don't set token.isReady here because no content return token; } if (isStartOfLine(lastChar) && isCommentStart(c)) { final String line = in.readLine(); if (line == null) { token.type = EOF; // don't set token.isReady here because no content return token; } final String comment = line.trim(); token.content.append(comment); token.type = COMMENT; return token; } // important: make sure a new char gets consumed in each iteration while (token.type == INVALID) { // ignore whitespaces at beginning of a token if (ignoreSurroundingSpaces) { while (isWhitespace(c) && !eol) { c = in.read(); eol = readEndOfLine(c); } } // ok, start of token reached: encapsulated, or token if (isDelimiter(c)) { // empty token return TOKEN("") token.type = TOKEN; } else if (eol) { // empty token return EORECORD("") // noop: token.content.append(""); token.type = EORECORD; } else if (isQuoteChar(c)) { // consume encapsulated token parseEncapsulatedToken(token); } else if (isEndOfFile(c)) { // end of file return EOF() // noop: token.content.append(""); token.type = EOF; token.isReady = true; // there is data at EOF } else { // next token must be a simple token // add removed blanks when not ignoring whitespace chars... parseSimpleToken(token, c); } } return token; } /** * Parses a simple token. * <p/> * Simple token are tokens which are not surrounded by encapsulators. A simple token might contain escaped * delimiters (as \, or \;). The token is finished when one of the following conditions become true: * <ul> * <li>end of line has been reached (EORECORD)</li> * <li>end of stream has been reached (EOF)</li> * <li>an unescaped delimiter has been reached (TOKEN)</li> * </ul> * * @param token * the current token * @param ch * the current character * @return the filled token * @throws IOException * on stream access error */ private Token parseSimpleToken(final Token token, int ch) throws IOException { // Faster to use while(true)+break than while(token.type == INVALID) while (true) { if (readEndOfLine(ch)) { token.type = EORECORD; break; } else if (isEndOfFile(ch)) { token.type = EOF; token.isReady = true; // There is data at EOF break; } else if (isDelimiter(ch)) { token.type = TOKEN; break; } else if (isEscape(ch)) { final int unescaped = readEscape(); if (unescaped == Constants.END_OF_STREAM) { // unexpected char after escape token.content.append((char) ch).append((char) in.getLastChar()); } else { token.content.append((char) unescaped); } ch = in.read(); // continue } else { token.content.append((char) ch); ch = in.read(); // continue } } if (ignoreSurroundingSpaces) { trimTrailingSpaces(token.content); } return token; } /** * Parses an encapsulated token. * <p/> * Encapsulated tokens are surrounded by the given encapsulating-string. The encapsulator itself might be included * in the token using a doubling syntax (as "", '') or using escaping (as in \", \'). Whitespaces before and after * an encapsulated token are ignored. The token is finished when one of the following conditions become true: * <ul> * <li>an unescaped encapsulator has been reached, and is followed by optional whitespace then:</li> * <ul> * <li>delimiter (TOKEN)</li> * <li>end of line (EORECORD)</li> * </ul> * <li>end of stream has been reached (EOF)</li> </ul> * * @param token * the current token * @return a valid token object * @throws IOException * on invalid state: EOF before closing encapsulator or invalid character before delimiter or EOL */ private Token parseEncapsulatedToken(final Token token) throws IOException { // save current line number in case needed for IOE final long startLineNumber = getCurrentLineNumber(); int c; while (true) { c = in.read(); if (isEscape(c)) { final int unescaped = readEscape(); if (unescaped == Constants.END_OF_STREAM) { // unexpected char after escape token.content.append((char) c).append((char) in.getLastChar()); } else { token.content.append((char) unescaped); } } else if (isQuoteChar(c)) { if (isQuoteChar(in.lookAhead())) { // double or escaped encapsulator -> add single encapsulator to token c = in.read(); token.content.append((char) c); } else { // token finish mark (encapsulator) reached: ignore whitespace till delimiter while (true) { c = in.read(); if (isDelimiter(c)) { token.type = TOKEN; return token; } else if (isEndOfFile(c)) { token.type = EOF; token.isReady = true; // There is data at EOF return token; } else if (readEndOfLine(c)) { token.type = EORECORD; return token; } else if (!isWhitespace(c)) { // error invalid char between token and next delimiter throw new IOException("(line " + getCurrentLineNumber() + ") invalid char between encapsulated token and delimiter"); } } } } else if (isEndOfFile(c)) { // error condition (end of file before end of token) throw new IOException("(startline " + startLineNumber + ") EOF reached before encapsulated token finished"); } else { // consume character token.content.append((char) c); } } } private char mapNullToDisabled(final Character c) { return c == null ? DISABLED : c.charValue(); } /** * Returns the current line number * * @return the current line number */ long getCurrentLineNumber() { return in.getCurrentLineNumber(); } // TODO escape handling needs more work /** * Handle an escape sequence. * The current character must be the escape character. * On return, the next character is available by calling {@link ExtendedBufferedReader#getLastChar()} * on the input stream. * * @return the unescaped character (as an int) or {@link Constants#END_OF_STREAM} if char following the escape is * invalid. * @throws IOException if there is a problem reading the stream or the end of stream is detected: * the escape character is not allowed at end of strem */ int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int ch = in.read(); switch (ch) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF; case CR: case LF: case FF: // TODO is this correct? case TAB: // TODO is this correct? Do tabs need to be escaped? case BACKSPACE: // TODO is this correct? return ch; case END_OF_STREAM: throw new IOException("EOF whilst processing escape sequence"); default: // Now check for meta-characters if (isMetaChar(ch)) { return ch; } // indicate unexpected char - available from in.getLastChar() return END_OF_STREAM; } } void trimTrailingSpaces(final StringBuilder buffer) { int length = buffer.length(); while (length > 0 && Character.isWhitespace(buffer.charAt(length - 1))) { length = length - 1; } if (length != buffer.length()) { buffer.setLength(length); } } /** * Greedily accepts \n, \r and \r\n This checker consumes silently the second control-character... * * @return true if the given or next character is a line-terminator */ boolean readEndOfLine(int ch) throws IOException { // check if we have \r\n... if (ch == CR && in.lookAhead() == LF) { // note: does not change ch outside of this method! ch = in.read(); } return ch == LF || ch == CR; } boolean isClosed() { return in.isClosed(); } /** * @return true if the given char is a whitespace character */ boolean isWhitespace(final int ch) { return !isDelimiter(ch) && Character.isWhitespace((char) ch); } /** * Checks if the current character represents the start of a line: a CR, LF or is at the start of the file. * * @param ch the character to check * @return true if the character is at the start of a line. */ boolean isStartOfLine(final int ch) { return ch == LF || ch == CR || ch == UNDEFINED; } /** * @return true if the given character indicates end of file */ boolean isEndOfFile(final int ch) { return ch == END_OF_STREAM; } boolean isDelimiter(final int ch) { return ch == delimiter; } boolean isEscape(final int ch) { return ch == escape; } boolean isQuoteChar(final int ch) { return ch == quoteChar; } boolean isCommentStart(final int ch) { return ch == commentStart; } private boolean isMetaChar(final int ch) { return ch == delimiter || ch == escape || ch == quoteChar || ch == commentStart; } /** * Closes resources. * * @throws IOException * If an I/O error occurs */ void close() throws IOException { in.close(); } }
Better ivar name. git-svn-id: 77bd0fb3f0b1af3312cb764eaf99792cfc1ce6c4@1585096 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/csv/Lexer.java
Better ivar name.
Java
apache-2.0
6998c949c7ad6f0e96c4a2f3e4bcf313ec524d72
0
dkandalov/pomodoro-tm,dkandalov/pomodoro-tm
/* * 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 pomodoro; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import pomodoro.modalwindow.ModalDialog; import pomodoro.model.ControlThread; import pomodoro.model.PomodoroModel; import pomodoro.model.PomodoroModelState; import pomodoro.model.Settings; import pomodoro.settings.SettingsPresenter; import pomodoro.toolkitwindow.PomodoroToolWindows; import javax.swing.*; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; /** * User: dima * Date: May 30, 2010 */ public class PomodoroComponent implements ApplicationComponent, Configurable { private ControlThread controlThread; private PomodoroModel model; private SettingsPresenter settingsPresenter; @Override public void initComponent() { Settings settings = getSettings(); settingsPresenter = new SettingsPresenter(settings); model = new PomodoroModel(settings, ServiceManager.getService(PomodoroModelState.class)); PomodoroToolWindows toolWindows = new PomodoroToolWindows(); settings.setChangeListener(toolWindows); new UserNotifier(settings, model); ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() { @Override public void projectOpened(Project project) { StatusBar statusBar = statusBarFor(project); statusBar.addWidget(new PomodoroWidget(), "before Position", project); } }); controlThread = new ControlThread(model); controlThread.start(); } public static Settings getSettings() { return ServiceManager.getService(Settings.class); } @Override public void disposeComponent() { controlThread.shouldStop(); } @NotNull @Override public String getComponentName() { return "Pomodoro"; } public PomodoroModel getModel() { return model; } @Nls @Override public String getDisplayName() { return settingsPresenter.getDisplayName(); } @Override public String getHelpTopic() { return settingsPresenter.getHelpTopic(); } @Override public JComponent createComponent() { return settingsPresenter.createComponent(); } @Override public boolean isModified() { return settingsPresenter.isModified(); } @Override public void apply() throws ConfigurationException { settingsPresenter.apply(); } @Override public void reset() { settingsPresenter.reset(); } @Override public void disposeUIResources() { settingsPresenter.disposeUIResources(); } private static StatusBar statusBarFor(Project project) { return WindowManager.getInstance().getStatusBar(project); } private static class UserNotifier { // TODO sound playback seems to be slow for the first time private final AudioClip ringSound1 = Applet.newAudioClip(getClass().getResource("/resources/ring.wav")); private final AudioClip ringSound2 = Applet.newAudioClip(getClass().getResource("/resources/ring2.wav")); private final AudioClip ringSound3 = Applet.newAudioClip(getClass().getResource("/resources/ring3.wav")); private ModalDialog modalDialog; public UserNotifier(final Settings settings, final PomodoroModel model) { model.addUpdateListener(this, new Runnable() { @Override public void run() { switch (model.getState()) { case STOP: if (model.getLastState() == PomodoroModel.PomodoroState.BREAK && !model.wasManuallyStopped()) { playRingSound(settings.getRingVolume()); if (settings.isBlockDuringBreak()) unblockIntelliJ(); } break; case BREAK: if (model.getLastState() != PomodoroModel.PomodoroState.BREAK) { playRingSound(settings.getRingVolume()); if (settings.isPopupEnabled()) showPopupNotification(); if (settings.isBlockDuringBreak()) blockIntelliJ(); } break; } } }); } private void blockIntelliJ() { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { DataContext dataContext = DataManager.getInstance().getDataContext(IdeFocusManager.getGlobalInstance().getFocusOwner()); Project project = PlatformDataKeys.PROJECT.getData(dataContext); Window window = WindowManager.getInstance().getFrame(project); modalDialog = new ModalDialog(window); modalDialog.show(); } }); } private void unblockIntelliJ() { if (modalDialog == null) return; // can happen if user turns on this option during break modalDialog.hide(); } private void playRingSound(int ringVolume) { switch (ringVolume) { case 0: // ring is disabled break; case 1: ringSound1.play(); break; case 2: ringSound2.play(); break; case 3: ringSound3.play(); break; default: throw new IllegalStateException(); } } private void showPopupNotification() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult(); Project project = PlatformDataKeys.PROJECT.getData(dataContext); if (project == null) return; String statusMessage = UIBundle.message("notification.text"); ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); if (hasPomodoroToolWindow(toolWindowManager)) { toolWindowManager.notifyByBalloon(PomodoroToolWindows.TOOL_WINDOW_ID, MessageType.INFO, statusMessage); } else { toolWindowManager.notifyByBalloon("Project", MessageType.INFO, statusMessage); } } private boolean hasPomodoroToolWindow(ToolWindowManager toolWindowManager) { for (String id : toolWindowManager.getToolWindowIds()) { if (PomodoroToolWindows.TOOL_WINDOW_ID.equals(id)) { return true; } } return false; } }); } } }
src/pomodoro/PomodoroComponent.java
/* * 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 pomodoro; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import pomodoro.modalwindow.ModalDialog; import pomodoro.model.ControlThread; import pomodoro.model.PomodoroModel; import pomodoro.model.PomodoroModelState; import pomodoro.model.Settings; import pomodoro.settings.SettingsPresenter; import pomodoro.toolkitwindow.PomodoroToolWindows; import javax.swing.*; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; /** * User: dima * Date: May 30, 2010 */ public class PomodoroComponent implements ApplicationComponent, Configurable { private ControlThread controlThread; private PomodoroModel model; private SettingsPresenter settingsPresenter; @Override public void initComponent() { Settings settings = getSettings(); settingsPresenter = new SettingsPresenter(settings); model = new PomodoroModel(settings, ServiceManager.getService(PomodoroModelState.class)); PomodoroToolWindows toolWindows = new PomodoroToolWindows(); settings.setChangeListener(toolWindows); new UserNotifier(settings, model); ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() { @Override public void projectOpened(Project project) { StatusBar statusBar = statusBarFor(project); statusBar.addWidget(new PomodoroWidget(), "before Position", project); } }); controlThread = new ControlThread(model); controlThread.start(); } public static Settings getSettings() { return ServiceManager.getService(Settings.class); } @Override public void disposeComponent() { controlThread.shouldStop(); } @NotNull @Override public String getComponentName() { return "Pomodoro"; } public PomodoroModel getModel() { return model; } @Nls @Override public String getDisplayName() { return settingsPresenter.getDisplayName(); } @Override public String getHelpTopic() { return settingsPresenter.getHelpTopic(); } @Override public JComponent createComponent() { return settingsPresenter.createComponent(); } @Override public boolean isModified() { return settingsPresenter.isModified(); } @Override public void apply() throws ConfigurationException { settingsPresenter.apply(); } @Override public void reset() { settingsPresenter.reset(); } @Override public void disposeUIResources() { settingsPresenter.disposeUIResources(); } private static StatusBar statusBarFor(Project project) { return WindowManager.getInstance().getStatusBar(project); } private static class UserNotifier { // TODO sound playback seems to be slow for the first time private final AudioClip ringSound1 = Applet.newAudioClip(getClass().getResource("/resources/ring.wav")); private final AudioClip ringSound2 = Applet.newAudioClip(getClass().getResource("/resources/ring2.wav")); private final AudioClip ringSound3 = Applet.newAudioClip(getClass().getResource("/resources/ring3.wav")); private ModalDialog modalDialog; public UserNotifier(final Settings settings, final PomodoroModel model) { model.addUpdateListener(this, new Runnable() { @Override public void run() { switch (model.getState()) { case STOP: if (model.getLastState() == PomodoroModel.PomodoroState.BREAK && !model.wasManuallyStopped()) { playRingSound(settings.getRingVolume()); if (settings.isBlockDuringBreak()) unblockIntelliJ(); } break; case BREAK: if (model.getLastState() != PomodoroModel.PomodoroState.BREAK) { playRingSound(settings.getRingVolume()); if (settings.isPopupEnabled()) showPopupNotification(); if (settings.isBlockDuringBreak()) blockIntelliJ(); } break; } } }); } private void blockIntelliJ() { DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResultSync(); Project project = PlatformDataKeys.PROJECT.getData(dataContext); Window window = WindowManager.getInstance().getFrame(project); modalDialog = new ModalDialog(window); modalDialog.show(); } private void unblockIntelliJ() { if (modalDialog == null) return; // can happen if user turns on this option during break modalDialog.hide(); } private void playRingSound(int ringVolume) { switch (ringVolume) { case 0: // ring is disabled break; case 1: ringSound1.play(); break; case 2: ringSound2.play(); break; case 3: ringSound3.play(); break; default: throw new IllegalStateException(); } } private void showPopupNotification() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult(); Project project = PlatformDataKeys.PROJECT.getData(dataContext); if (project == null) return; String statusMessage = UIBundle.message("notification.text"); ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); if (hasPomodoroToolWindow(toolWindowManager)) { toolWindowManager.notifyByBalloon(PomodoroToolWindows.TOOL_WINDOW_ID, MessageType.INFO, statusMessage); } else { toolWindowManager.notifyByBalloon("Project", MessageType.INFO, statusMessage); } } private boolean hasPomodoroToolWindow(ToolWindowManager toolWindowManager) { for (String id : toolWindowManager.getToolWindowIds()) { if (PomodoroToolWindows.TOOL_WINDOW_ID.equals(id)) { return true; } } return false; } }); } } }
blocking dialog fix so that it appears when IDE doesn't have focus
src/pomodoro/PomodoroComponent.java
blocking dialog fix so that it appears when IDE doesn't have focus
Java
apache-2.0
0b9ab71c662ff253e57c5406bc1e50d0546ef488
0
eFaps/eFaps-WebApp,eFaps/eFaps-WebApp,eFaps/eFaps-WebApp
/* * Copyright 2003 - 2012 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.ui.wicket.models.objects; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.apache.wicket.RestartResponseException; import org.apache.wicket.util.io.IClusterable; import org.efaps.admin.datamodel.Attribute; import org.efaps.admin.datamodel.Type; import org.efaps.admin.datamodel.ui.FieldValue; import org.efaps.admin.event.EventDefinition; import org.efaps.admin.event.EventType; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.ui.AbstractCommand; import org.efaps.admin.ui.AbstractCommand.SortDirection; import org.efaps.admin.ui.Image; import org.efaps.admin.ui.field.Field; import org.efaps.admin.ui.field.Filter; import org.efaps.db.Context; import org.efaps.db.Instance; import org.efaps.db.MultiPrintQuery; import org.efaps.ui.wicket.models.cell.UIHiddenCell; import org.efaps.ui.wicket.models.cell.UITableCell; import org.efaps.ui.wicket.models.objects.UITableHeader.FilterType; import org.efaps.ui.wicket.pages.error.ErrorPage; import org.efaps.ui.wicket.util.FilterDefault; import org.efaps.util.DateTimeUtil; import org.efaps.util.EFapsException; import org.efaps.util.cache.CacheReloadException; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.Interval; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO description! * * @author The eFaps Team * @version $Id$ */ public class UITable extends AbstractUIHeaderObject { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(UITable.class); /** * Serial Id. */ private static final long serialVersionUID = 1L; /** * Map contains the applied filters to this table. */ private final Map<String, TableFilter> filters = new HashMap<String, TableFilter>(); /** * Map is used to store the filters in relation to a field name. It is used * temporarily when the table is (due to a database based filter) requeried, * to be able to set the filters to the headers by copying it from the old * header to the new one. * * @see #getInstanceListsOld() * @see #execute4InstanceOld() */ private final Map<String, TableFilter> filterTempCache = new HashMap<String, TableFilter>(); /** * All evaluated rows of this table are stored in this list. * * @see #getValues */ private final List<UIRow> values = new ArrayList<UIRow>(); /** * Thie Row is used in case of edit to create new empty rows. */ private UIRow emptyRow; /** * Constructor setting the uuid and Key of the instance. * * @param _commandUUID UUID of the Command * @param _instanceKey Key of the instance * @throws EFapsException on error */ public UITable(final UUID _commandUUID, final String _instanceKey) throws EFapsException { super(_commandUUID, _instanceKey); initialise(); } /** * Constructor setting the uuid and Key of the instance. * * @param _commandUUID UUID of the Command * @param _instanceKey Key of the instance * @param _openerId id of the opener * @throws EFapsException on error */ public UITable(final UUID _commandUUID, final String _instanceKey, final String _openerId) throws EFapsException { super(_commandUUID, _instanceKey, _openerId); initialise(); } /** * Method that initializes the TableModel. * * @throws EFapsException on error */ private void initialise() throws EFapsException { final AbstractCommand command = getCommand(); if (command == null) { setShowCheckBoxes(false); } else { // set target table if (command.getTargetTable() != null) { setTableUUID(command.getTargetTable().getUUID()); if (Context.getThreadContext().containsSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER))) { @SuppressWarnings("unchecked") final Map<String, TableFilter> sessfilter = (Map<String, TableFilter>) Context.getThreadContext() .getSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER)); for (final Field field : command.getTargetTable().getFields()) { if (sessfilter.containsKey(field.getName())) { final TableFilter filter = sessfilter.get(field.getName()); filter.setHeaderFieldId(field.getId()); this.filters.put(field.getName(), filter); } } } else { // add the filter here, if it is a required filter that must be // applied against the database for (final Field field : command.getTargetTable().getFields()) { if (field.getFilter().isRequired() && field.getFilter().getBase().equals(Filter.Base.DATABASE)) { this.filters.put(field.getName(), new TableFilter()); } } } } // set default sort if (command.getTargetTableSortKey() != null) { setSortKeyInternal(command.getTargetTableSortKey()); setSortDirection(command.getTargetTableSortDirection()); } setShowCheckBoxes(command.isTargetShowCheckBoxes()); // get the User specific Attributes if exist overwrite the defaults try { if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))) { setSortKeyInternal(Context.getThreadContext().getUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))); } if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTDIRECTION))) { setSortDirection(SortDirection.getEnum(Context.getThreadContext() .getUserAttribute(getCacheKey(UITable.UserCacheKey.SORTDIRECTION)))); } } catch (final EFapsException e) { // we don't throw an error because this are only Usersettings UITable.LOG.error("error during the retrieve of UserAttributes", e); } } } /** * Method to get the list of instance. * * @return List of instances * @throws EFapsException on error */ @SuppressWarnings("unchecked") protected List<Instance> getInstanceList() throws EFapsException { // get the filters that must be applied against the database final Map<String, Map<String, Object>> dataBasefilters = new HashMap<String, Map<String, Object>>(); final Iterator<Entry<String, TableFilter>> iter = this.filters.entrySet().iterator(); this.filterTempCache.clear(); while (iter.hasNext()) { final Entry<String, TableFilter> entry = iter.next(); if (entry.getValue().getUiTableHeader() == null || (entry.getValue().getUiTableHeader() != null && entry.getValue().getUiTableHeader().getFilter().getBase().equals(Filter.Base.DATABASE))) { final Map<String, Object> map = entry.getValue().getMap4esjp(); dataBasefilters.put(entry.getKey(), map); } this.filterTempCache.put(entry.getKey(), entry.getValue()); iter.remove(); } final List<Return> ret = getCommand().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(), ParameterValues.OTHERS, dataBasefilters); List<Instance> lists = null; if (ret.size() < 1) { throw new EFapsException(UITable.class, "getInstanceList"); } else { lists = (List<Instance>) ret.get(0).get(ReturnValues.VALUES); } return lists; } /** * {@inheritDoc} */ @Override public void execute() { try { if (isCreateMode()) { execute4NoInstance(); } else { final List<Instance> instances = getInstanceList(); if (instances.isEmpty() && isEditMode()) { execute4NoInstance(); } else { execute4Instance(instances); } } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } super.setInitialized(true); } /** * @param _instances list of instances the table is executed for * @throws EFapsException on error */ private void execute4Instance(final List<Instance> _instances) throws EFapsException { final Set<String>altOIDSel = new HashSet<String>(); // evaluate for all expressions in the table final MultiPrintQuery multi = new MultiPrintQuery(_instances); final List<Integer> userWidthList = getUserWidths(); final List<Field> fields = getUserSortedColumns(); int i = 0; Type type; if (_instances.size() > 0) { type = _instances.get(0).getType(); } else { type = getTypeFromEvent(); } for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode())) { Attribute attr = null; if (_instances.size() > 0) { if (field.getSelect() != null) { multi.addSelect(field.getSelect()); } else if (field.getAttribute() != null) { multi.addAttribute(field.getAttribute()); } else if (field.getPhrase() != null) { multi.addPhrase(field.getName(), field.getPhrase()); } if (field.getSelectAlternateOID() != null) { multi.addSelect(field.getSelectAlternateOID()); altOIDSel.add(field.getSelectAlternateOID()); } } if (field.getAttribute() != null && type != null) { attr = type.getAttribute(field.getAttribute()); } SortDirection sortdirection = SortDirection.NONE; if (field.getName().equals(getSortKey())) { sortdirection = getSortDirection(); } if (field.getFilter().getAttributes() != null) { if (field.getFilter().getAttributes().contains(",")) { if (field.getFilter().getAttributes().contains("/")) { attr = Attribute.get(field.getFilter().getAttributes().split(",")[0]); } else { attr = type.getAttribute(field.getFilter().getAttributes().split(",")[0]); } } else { if (field.getFilter().getAttributes().contains("/")) { attr = Attribute.get(field.getFilter().getAttributes()); } else { attr = type.getAttribute(field.getFilter().getAttributes()); } } } if (!field.isHiddenDisplay(getMode())) { final UITableHeader uiTableHeader = new UITableHeader(field, sortdirection, attr); if (this.filterTempCache.containsKey(uiTableHeader.getFieldName())) { this.filters.put(uiTableHeader.getFieldName(), this.filterTempCache.get(uiTableHeader.getFieldName())); uiTableHeader.setFilterApplied(true); } else if (uiTableHeader.getFilter().isRequired()) { this.filters.put(uiTableHeader.getFieldName(), new TableFilter(uiTableHeader)); } getHeaders().add(uiTableHeader); if (!field.isFixedWidth()) { if (userWidthList != null && userWidthList.size() > i) { if (isShowCheckBoxes() && userWidthList.size() > i + 1) { uiTableHeader.setWidth(userWidthList.get(i + 1)); } else { uiTableHeader.setWidth(userWidthList.get(i)); } } setWidthWeight(getWidthWeight() + field.getWidth()); } } i++; } } multi.execute(); if (!altOIDSel.isEmpty()) { final List<Instance> inst = new ArrayList<Instance>(); for (final String sel : altOIDSel) { inst.addAll(multi.getInstances4Select(sel)); } checkAccessToInstances(inst); } executeRowResult(multi, fields); if (getSortKey() != null) { sort(); } } /** * @param _multi Query * @param _fields Fields * @throws EFapsException on error */ private void executeRowResult(final MultiPrintQuery _multi, final List<Field> _fields) throws EFapsException { boolean first = true; while (_multi.next()) { Instance instance = _multi.getCurrentInstance(); final UIRow row = new UIRow(this, instance.getKey()); String strValue = ""; if (isEditMode() && first) { this.emptyRow = new UIRow(this); } for (final Field field : _fields) { if (field.getSelectAlternateOID() != null) { instance = Instance.get(_multi.<String> getSelect(field.getSelectAlternateOID())); } else { instance = _multi.getCurrentInstance(); } if (field.hasAccess(getMode(), instance, getCommand()) && !field.isNoneDisplay(getMode())) { Object value = null; Attribute attr = null; if (field.getSelect() != null) { value = _multi.<Object> getSelect(field.getSelect()); attr = _multi.getAttribute4Select(field.getSelect()); } else if (field.getAttribute() != null) { value = _multi.<Object> getAttribute(field.getAttribute()); attr = _multi.getAttribute4Attribute(field.getAttribute()); } else if (field.getPhrase() != null) { value = _multi.getPhrase(field.getName()); } final FieldValue fieldvalue = new FieldValue(field, attr, value, instance, getInstance(), new ArrayList<Instance>(_multi.getInstanceList()), this); String htmlTitle = null; boolean hidden = false; if (isPrintMode()) { strValue = fieldvalue.getStringValue(getMode()); } else { if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) { strValue = fieldvalue.getEditHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { strValue = fieldvalue.getHiddenHtml(getMode()); hidden = true; } else { strValue = fieldvalue.getReadOnlyHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } } if (strValue == null) { strValue = ""; } String icon = field.getIcon(); if (field.isShowTypeIcon()) { final Image image = Image.getTypeIcon(instance.getType()); if (image != null) { icon = image.getUrl(); } } if (hidden) { row.addHidden(new UIHiddenCell(this, fieldvalue, null, strValue)); } else { row.add(new UITableCell(this, fieldvalue, instance, strValue, htmlTitle, icon)); } // in case of edit mode an empty version of the first row // isw stored, and can be used // to create new rows if (isEditMode() && first) { final FieldValue fldVal = new FieldValue(field, attr); final String cellvalue; final String cellTitle; if (field.isEditableDisplay(getMode())) { cellvalue = fldVal.getEditHtml(getMode()); cellTitle = fldVal.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { cellvalue = fldVal.getHiddenHtml(getMode()); cellTitle = ""; } else { cellvalue = fldVal.getReadOnlyHtml(getMode()); cellTitle = fldVal.getStringValue(getMode()); } if (hidden) { this.emptyRow.addHidden(new UIHiddenCell(this, fldVal, null, cellvalue)); } else { this.emptyRow.add(new UITableCell(this, fldVal, null, cellvalue, cellTitle, icon)); } } } } this.values.add(row); first = false; } } /** * Executes this model for the case that no instance is given. Currently * only create! * * @throws EFapsException on error */ private void execute4NoInstance() throws EFapsException { final List<Field> fields = getUserSortedColumns(); final List<Integer> userWidthList = getUserWidths(); int i = 1; for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) { SortDirection sortdirection = SortDirection.NONE; if (field.getName().equals(getSortKey())) { sortdirection = getSortDirection(); } final UITableHeader headermodel = new UITableHeader(field, sortdirection, null); headermodel.setSortable(false); headermodel.setFilter(false); getHeaders().add(headermodel); if (!field.isFixedWidth()) { if (userWidthList != null && ((isShowCheckBoxes() && (i + 1) < userWidthList.size()) || (!isShowCheckBoxes() && i < userWidthList.size()))) { if (isShowCheckBoxes()) { headermodel.setWidth(userWidthList.get(i + 1)); } else { headermodel.setWidth(userWidthList.get(i)); } } setWidthWeight(getWidthWeight() + field.getWidth()); } i++; } } final Type type = getTypeFromEvent(); final UIRow row = new UIRow(this); Attribute attr = null; for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode())) { attr = null; if (field.getAttribute() != null && type != null) { attr = type.getAttribute(field.getAttribute()); } final FieldValue fieldvalue = new FieldValue(field, attr, null, null, getInstance(), null, this); String htmlValue; String htmlTitle = null; boolean hidden = false; if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) { htmlValue = fieldvalue.getEditHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { htmlValue = fieldvalue.getHiddenHtml(getMode()); hidden = true; } else { htmlValue = fieldvalue.getReadOnlyHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } if (htmlValue == null) { htmlValue = ""; } if (hidden) { row.addHidden(new UIHiddenCell(this, fieldvalue, null, htmlValue)); } else { final UITableCell cell = new UITableCell(this, fieldvalue, null, htmlValue, htmlTitle, null); row.add(cell); } } } this.values.add(row); if (getSortKey() != null) { sort(); } } /** * Method used to evaluate the type for this table from the connected * events. * * @return type if found * @throws EFapsException on error */ private Type getTypeFromEvent() throws EFapsException { final List<EventDefinition> events = getEvents(EventType.UI_TABLE_EVALUATE); String typeName = null; if (events.size() > 1) { throw new EFapsException(this.getClass(), "execute4NoInstance.moreThanOneEvaluate"); } else { final EventDefinition event = events.get(0); //TODO remove deprecated Types if (event.getProperty("Types") != null) { typeName = event.getProperty("Types").split(";")[0]; } // test for basic or abstract types if (event.getProperty("Type") != null) { typeName = event.getProperty("Type"); } // no type yet search alternatives if (typeName == null) { for (int i = 1; i < 100; i++) { final String nameTmp = "Type" + String.format("%02d", i); if (event.getProperty(nameTmp) != null) { typeName = event.getProperty(nameTmp); } else { break; } } } } return typeName == null ? null : Type.get(typeName); } /** * Getter method for the instance variable {@link #emptyRow}. * * @return value of instance variable {@link #emptyRow} */ public UIRow getEmptyRow() { return this.emptyRow; } /** * Add a filterlist to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _list lsi of value to filter * */ public void addFilterList(final UITableHeader _uitableHeader, final Set<?> _list) { final TableFilter filter = new TableFilter(_uitableHeader, _list); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a range to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _from from value * @throws EFapsException on error * */ public void addFilterTextLike(final UITableHeader _uitableHeader, final String _from) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _from); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a range to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _from from value * @param _to to value * @throws EFapsException on error * */ public void addFilterRange(final UITableHeader _uitableHeader, final String _from, final String _to) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _from, _to); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a classification based filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _uiClassification classification based filters * @throws EFapsException on error * */ public void addFilterClassifcation(final UITableHeader _uitableHeader, final UIClassification _uiClassification) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _uiClassification); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Method to get a Filter from the list of filters belonging to this * UITable. * * @param _uitableHeader UitableHeader this filter belongs to * @return filter * @throws EFapsException on error */ public TableFilter getFilter(final UITableHeader _uitableHeader) throws EFapsException { TableFilter ret = this.filters.get(_uitableHeader.getFieldName()); if (ret != null && ret.getUiTableHeader() == null) { ret = new TableFilter(_uitableHeader); this.filters.put(_uitableHeader.getFieldName(), ret); } return ret; } /** * Get the List of values for a PICKERLIST. * * @param _uitableHeader UitableHeader this filter belongs to * @return List of Values */ public List<String> getFilterPickList(final UITableHeader _uitableHeader) { final List<String> ret = new ArrayList<String>(); for (final UIRow rowmodel : this.values) { final List<UITableCell> cells = rowmodel.getValues(); for (final UITableCell cell : cells) { if (cell.getFieldId() == _uitableHeader.getFieldId()) { final String value = cell.getCellTitle(); if (!ret.contains(value)) { ret.add(value); } break; } } } Collections.sort(ret); return ret; } /** * Store the Filter in the Session. */ private void storeFilters() { final Map<String, TableFilter> sessFilter = new HashMap<String, TableFilter>(); for (final Entry<String, TableFilter> entry : this.filters.entrySet()) { sessFilter.put(entry.getKey(), entry.getValue()); } try { Context.getThreadContext().setSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER), sessFilter); } catch (final EFapsException e) { UITable.LOG.error("Error storing Filtermap for Table called by Command with UUID: {}", getCommandUUID(), e); } } /** * This is the getter method for the instance variable {@link #values}. * * @return value of instance variable {@link #values} * @throws EFapsException * @see #values * @see #setValues */ public List<UIRow> getValues() { List<UIRow> ret = new ArrayList<UIRow>(); if (isFiltered()) { for (final UIRow row : this.values) { boolean filtered = false; for (final TableFilter filter : this.filters.values()) { filtered = filter.filterRow(row); if (filtered) { break; } } if (!filtered) { ret.add(row); } } } else { ret = this.values; } setSize(ret.size()); return ret; } /** * Are the values of the Rows filtered or not. * * @return true if filtered, else false */ @Override public boolean isFiltered() { return !this.filters.isEmpty(); } /** * Method to remove a filter from the filters. * * @param _uiTableHeader UITableHeader the filter is removed for */ public void removeFilter(final UITableHeader _uiTableHeader) { this.filters.remove(_uiTableHeader.getFieldName()); final UITableHeader orig = getHeader4Id(_uiTableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(false); } storeFilters(); } /** * {@inheritDoc} */ @Override public void resetModel() { super.setInitialized(false); this.values.clear(); getHeaders().clear(); getHiddenCells().clear(); } /** * Method to get the events that are related to this UITable. * * @param _eventType eventype to get * @return List of events * @throws CacheReloadException on error */ protected List<EventDefinition> getEvents(final EventType _eventType) throws CacheReloadException { return this.getCommand().getEvents(_eventType); } /** * The instance method sorts the table values depending on the sort key in * {@link #sortKey} and the sort direction in {@link #sortDirection}. * @throws EFapsException on error */ @Override public void sort() throws EFapsException { if (getSortKey() != null && getSortKey().length() > 0) { int sortKeyTmp = 0; final List<Field> fields = getUserSortedColumns(); for (int i = 0; i < fields.size(); i++) { final Field field = fields.get(i); if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) { if (field.getName().equals(getSortKey())) { break; } sortKeyTmp++; } } if (sortKeyTmp < getTable().getFields().size()) { final int index = sortKeyTmp; Collections.sort(this.values, new Comparator<UIRow>() { @Override public int compare(final UIRow _rowModel1, final UIRow _rowModel2) { FieldValue fValue1 = null; FieldValue fValue2 = null; try { final UITableCell cellModel1 = _rowModel1.getValues().get(index); fValue1 = new FieldValue(getTable().getFields().get(index), cellModel1 .getUiClass(), cellModel1.getCompareValue() != null ? cellModel1 .getCompareValue() : cellModel1.getCellValue()); final UITableCell cellModel2 = _rowModel2.getValues().get(index); fValue2 = new FieldValue(getTable().getFields().get(index), cellModel2 .getUiClass(), cellModel2.getCompareValue() != null ? cellModel2 .getCompareValue() : cellModel2.getCellValue()); } catch (final CacheReloadException e) { UITable.LOG.error("Error during sorting for table", e); } return fValue1.compareTo(fValue2); } }); if (getSortDirection() == SortDirection.DESCENDING) { Collections.reverse(this.values); } } } } /** * Class represents one filter applied to this UITable. */ public class TableFilter implements IClusterable { /** * Key to the value for "from" in the map for the esjp. */ public static final String FROM = "from"; /** * Key to the value for "to" in the map for the esjp. */ public static final String TO = "to"; /** * Key to the value for "to" in the map for the esjp. */ public static final String LIST = "list"; /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * Set of value for the filter. Only used for filter using a PICKERLIST or CLASSIFICATION. */ private Set<?> filterList; /** * Value of the from Field from the website. */ private String from; /** * Value of the to Field from the website. */ private String to; /** * DateTime value for {@link #from} in case that the filter is for a * date field. */ private DateTime dateFrom; /** * DateTime value for {@link #to} in case that the filter is for a date * field. */ private DateTime dateTo; /** * Id of the field this header belongs to. */ private long headerFieldId; /** * Type of the Filter. */ private final FilterType filterType; /** * Constructor is used for a database based filter in case that it is * required. */ public TableFilter() { this.headerFieldId = 0; this.filterType = null; } /** * Constructor is used in case that a filter is required, during loading * the date first time for a memory base filter. * * @param _uitableHeader UITableHeader this filter lies in * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); if (_uitableHeader.getFilter().getDefaultValue() != null) { if (_uitableHeader.getFilterType().equals(FilterType.DATE)) { final String filter = _uitableHeader.getFilter().getDefaultValue(); final String[] parts = filter.split(":"); final String range = parts[0]; final int fromSub = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; final int rangeCount = parts.length > 2 ? Integer.parseInt(parts[2]) : 1; final FilterDefault def = FilterDefault.valueOf(range.toUpperCase()); DateMidnight tmp = DateTimeUtil.translateFromUI(new DateTime()).toDateMidnight(); switch (def) { case TODAY: this.dateFrom = tmp.toDateTime().minusDays(fromSub); this.dateTo = this.dateFrom.plusDays(rangeCount).plusSeconds(1); break; case WEEK: tmp = tmp.minusDays(tmp.getDayOfWeek() - 1); this.dateFrom = tmp.toDateTime().minusWeeks(fromSub); this.dateTo = this.dateFrom.toDateTime().plusWeeks(rangeCount); break; case MONTH: tmp = tmp.minusDays(tmp.getDayOfMonth() - 1); this.dateFrom = tmp.toDateTime().minusMonths(fromSub); this.dateTo = this.dateFrom.toDateTime().plusMonths(rangeCount); break; case YEAR: tmp = tmp.minusDays(tmp.getDayOfYear() - 1); this.dateFrom = tmp.toDateTime().minusYears(fromSub); this.dateTo = this.dateFrom.toDateTime().plusYears(rangeCount); break; default: break; } } } } /** * Standard Constructor for a Filter containing a range. * * @param _uitableHeader UITableHeader this filter lies in * @param _from value for from * @param _to value for to * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader, final String _from, final String _to) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.from = _from; this.to = _to; if (_uitableHeader.getFilterType().equals(FilterType.DATE)) { this.dateFrom = DateTimeUtil.translateFromUI(_from); this.dateTo = DateTimeUtil.translateFromUI(_to); this.dateTo = this.dateTo == null ? null : this.dateTo.plusDays(1); } } /** * Standard Constructor for a Filter containing a range. * * @param _uitableHeader UITableHeader this filter lies in * @param _from value for from * @param _to value for to * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader, final String _from) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.from = _from; } /** * Standard Constructor for a Filter using a PICKLIST. * * @param _uitableHeader UITableHeader this filter lies in * @param _filterList set of values for the filter */ public TableFilter(final UITableHeader _uitableHeader, final Set<?> _filterList) { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.filterList = _filterList; } /** * Standard Constructor for a Filter using a CLASSICIATION. * * @param _uitableHeader UITableHeader this filter lies in * @param _uiClassification set of values for the filter */ public TableFilter(final UITableHeader _uitableHeader, final UIClassification _uiClassification) { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); final Set<UUID> list = new HashSet<UUID>(); if (_uiClassification.isSelected()) { list.add(_uiClassification.getClassificationUUID()); } for (final UIClassification uiClass : _uiClassification.getDescendants()) { if (uiClass.isSelected()) { list.add(uiClass.getClassificationUUID()); } } this.filterList = list; } /** * Getter method for instance variable {@link #uiTableHeader}. * * @return value of instance variable {@link #uiTableHeader} */ public UITableHeader getUiTableHeader() { return getHeader4Id(this.headerFieldId); } /** * Method to get the map that must be passed for this filter to the * esjp. * * @return Map */ public Map<String, Object> getMap4esjp() { final Map<String, Object> ret = new HashMap<String, Object>(); if (this.filterList == null) { ret.put(UITable.TableFilter.FROM, this.from); ret.put(UITable.TableFilter.TO, this.to); } else { ret.put(UITable.TableFilter.LIST, this.filterList); } return ret; } /** * Method is used for memory based filters to filter one row. * * @param _uiRow UIRow to filter * @return false if the row must be shown to the user, true if the row * must be filtered */ public boolean filterRow(final UIRow _uiRow) { boolean ret = false; if (this.headerFieldId > 0 && Field.get(this.headerFieldId).getFilter().getBase().equals(Filter.Base.MEMORY)) { final List<UITableCell> cells = _uiRow.getValues(); for (final UITableCell cell : cells) { if (cell.getFieldId() == this.headerFieldId) { if (this.filterList != null) { final String value = cell.getCellTitle(); if (!this.filterList.contains(value)) { ret = true; } } else if (this.filterType.equals(FilterType.DATE)) { if (this.dateFrom == null || this.dateTo == null) { ret = true; } else { final Interval interval = new Interval(this.dateFrom, this.dateTo); final DateTime value = (DateTime) cell.getCompareValue(); if (!(interval.contains(value) || value.isEqual(this.dateFrom) || value.isEqual(this.dateTo))) { ret = true; } } } break; } } } return ret; } /** * Getter method for instance variable {@link #dateFrom}. * * @return value of instance variable {@link #dateFrom} */ public DateTime getDateFrom() { return this.dateFrom; } /** * Getter method for instance variable {@link #dateTo}. * * @return value of instance variable {@link #dateTo} */ public DateTime getDateTo() { return this.dateTo; } /** * Getter method for the instance variable {@link #from}. * * @return value of instance variable {@link #from} */ public String getFrom() { return this.from; } /** * Setter method for instance variable {@link #headerFieldId}. * * @param _headerFieldId value for instance variable {@link #headerFieldId} */ protected void setHeaderFieldId(final long _headerFieldId) { this.headerFieldId = _headerFieldId; } /** * Getter method for the instance variable {@link #filterList}. * * @return value of instance variable {@link #filterList} */ public Set<?> getFilterList() { return this.filterList; } } }
src/main/java/org/efaps/ui/wicket/models/objects/UITable.java
/* * Copyright 2003 - 2012 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.ui.wicket.models.objects; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.apache.wicket.RestartResponseException; import org.apache.wicket.util.io.IClusterable; import org.efaps.admin.datamodel.Attribute; import org.efaps.admin.datamodel.Type; import org.efaps.admin.datamodel.ui.FieldValue; import org.efaps.admin.event.EventDefinition; import org.efaps.admin.event.EventType; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.ui.AbstractCommand; import org.efaps.admin.ui.AbstractCommand.SortDirection; import org.efaps.admin.ui.Image; import org.efaps.admin.ui.field.Field; import org.efaps.admin.ui.field.Filter; import org.efaps.db.Context; import org.efaps.db.Instance; import org.efaps.db.MultiPrintQuery; import org.efaps.ui.wicket.models.cell.UIHiddenCell; import org.efaps.ui.wicket.models.cell.UITableCell; import org.efaps.ui.wicket.models.objects.UITableHeader.FilterType; import org.efaps.ui.wicket.pages.error.ErrorPage; import org.efaps.ui.wicket.util.FilterDefault; import org.efaps.util.DateTimeUtil; import org.efaps.util.EFapsException; import org.efaps.util.cache.CacheReloadException; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.Interval; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO description! * * @author The eFaps Team * @version $Id$ */ public class UITable extends AbstractUIHeaderObject { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(UITable.class); /** * Serial Id. */ private static final long serialVersionUID = 1L; /** * Map contains the applied filters to this table. */ private final Map<String, TableFilter> filters = new HashMap<String, TableFilter>(); /** * Map is used to store the filters in relation to a field name. It is used * temporarily when the table is (due to a database based filter) requeried, * to be able to set the filters to the headers by copying it from the old * header to the new one. * * @see #getInstanceListsOld() * @see #execute4InstanceOld() */ private final Map<String, TableFilter> filterTempCache = new HashMap<String, TableFilter>(); /** * All evaluated rows of this table are stored in this list. * * @see #getValues */ private final List<UIRow> values = new ArrayList<UIRow>(); /** * Thie Row is used in case of edit to create new empty rows. */ private UIRow emptyRow; /** * Constructor setting the uuid and Key of the instance. * * @param _commandUUID UUID of the Command * @param _instanceKey Key of the instance * @throws EFapsException on error */ public UITable(final UUID _commandUUID, final String _instanceKey) throws EFapsException { super(_commandUUID, _instanceKey); initialise(); } /** * Constructor setting the uuid and Key of the instance. * * @param _commandUUID UUID of the Command * @param _instanceKey Key of the instance * @param _openerId id of the opener * @throws EFapsException on error */ public UITable(final UUID _commandUUID, final String _instanceKey, final String _openerId) throws EFapsException { super(_commandUUID, _instanceKey, _openerId); initialise(); } /** * Method that initializes the TableModel. * * @throws EFapsException on error */ private void initialise() throws EFapsException { final AbstractCommand command = getCommand(); if (command == null) { setShowCheckBoxes(false); } else { // set target table if (command.getTargetTable() != null) { setTableUUID(command.getTargetTable().getUUID()); if (Context.getThreadContext().containsSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER))) { @SuppressWarnings("unchecked") final Map<String, TableFilter> sessfilter = (Map<String, TableFilter>) Context.getThreadContext() .getSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER)); for (final Field field : command.getTargetTable().getFields()) { if (sessfilter.containsKey(field.getName())) { final TableFilter filter = sessfilter.get(field.getName()); filter.setHeaderFieldId(field.getId()); this.filters.put(field.getName(), filter); } } } else { // add the filter here, if it is a required filter that must be // applied against the database for (final Field field : command.getTargetTable().getFields()) { if (field.getFilter().isRequired() && field.getFilter().getBase().equals(Filter.Base.DATABASE)) { this.filters.put(field.getName(), new TableFilter()); } } } } // set default sort if (command.getTargetTableSortKey() != null) { setSortKeyInternal(command.getTargetTableSortKey()); setSortDirection(command.getTargetTableSortDirection()); } setShowCheckBoxes(command.isTargetShowCheckBoxes()); // get the User specific Attributes if exist overwrite the defaults try { if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))) { setSortKeyInternal(Context.getThreadContext().getUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))); } if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTDIRECTION))) { setSortDirection(SortDirection.getEnum(Context.getThreadContext() .getUserAttribute(getCacheKey(UITable.UserCacheKey.SORTDIRECTION)))); } } catch (final EFapsException e) { // we don't throw an error because this are only Usersettings UITable.LOG.error("error during the retrieve of UserAttributes", e); } } } /** * Method to get the list of instance. * * @return List of instances * @throws EFapsException on error */ @SuppressWarnings("unchecked") protected List<Instance> getInstanceList() throws EFapsException { // get the filters that must be applied against the database final Map<String, Map<String, Object>> dataBasefilters = new HashMap<String, Map<String, Object>>(); final Iterator<Entry<String, TableFilter>> iter = this.filters.entrySet().iterator(); this.filterTempCache.clear(); while (iter.hasNext()) { final Entry<String, TableFilter> entry = iter.next(); if (entry.getValue().getUiTableHeader() == null || (entry.getValue().getUiTableHeader() != null && entry.getValue().getUiTableHeader().getFilter().getBase().equals(Filter.Base.DATABASE))) { final Map<String, Object> map = entry.getValue().getMap4esjp(); dataBasefilters.put(entry.getKey(), map); } this.filterTempCache.put(entry.getKey(), entry.getValue()); iter.remove(); } final List<Return> ret = getCommand().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(), ParameterValues.OTHERS, dataBasefilters); List<Instance> lists = null; if (ret.size() < 1) { throw new EFapsException(UITable.class, "getInstanceList"); } else { lists = (List<Instance>) ret.get(0).get(ReturnValues.VALUES); } return lists; } /** * {@inheritDoc} */ @Override public void execute() { try { if (isCreateMode()) { execute4NoInstance(); } else { final List<Instance> instances = getInstanceList(); if (instances.isEmpty() && isEditMode()) { execute4NoInstance(); } else { execute4Instance(instances); } } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } super.setInitialized(true); } /** * @param _instances list of instances the table is executed for * @throws EFapsException on error */ private void execute4Instance(final List<Instance> _instances) throws EFapsException { final Set<String>altOIDSel = new HashSet<String>(); // evaluate for all expressions in the table final MultiPrintQuery multi = new MultiPrintQuery(_instances); final List<Integer> userWidthList = getUserWidths(); final List<Field> fields = getUserSortedColumns(); int i = 0; Type type; if (_instances.size() > 0) { type = _instances.get(0).getType(); } else { type = getTypeFromEvent(); } for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode())) { Attribute attr = null; if (_instances.size() > 0) { if (field.getSelect() != null) { multi.addSelect(field.getSelect()); } else if (field.getAttribute() != null) { multi.addAttribute(field.getAttribute()); } else if (field.getPhrase() != null) { multi.addPhrase(field.getName(), field.getPhrase()); } if (field.getSelectAlternateOID() != null) { multi.addSelect(field.getSelectAlternateOID()); altOIDSel.add(field.getSelectAlternateOID()); } } if (field.getAttribute() != null && type != null) { attr = type.getAttribute(field.getAttribute()); } SortDirection sortdirection = SortDirection.NONE; if (field.getName().equals(getSortKey())) { sortdirection = getSortDirection(); } if (field.getFilter().getAttributes() != null) { if (field.getFilter().getAttributes().contains(",")) { if (field.getFilter().getAttributes().contains("/")) { attr = Attribute.get(field.getFilter().getAttributes().split(",")[0]); } else { attr = type.getAttribute(field.getFilter().getAttributes().split(",")[0]); } } else { if (field.getFilter().getAttributes().contains("/")) { attr = Attribute.get(field.getFilter().getAttributes()); } else { attr = type.getAttribute(field.getFilter().getAttributes()); } } } if (!field.isHiddenDisplay(getMode())) { final UITableHeader uiTableHeader = new UITableHeader(field, sortdirection, attr); if (this.filterTempCache.containsKey(uiTableHeader.getFieldName())) { this.filters.put(uiTableHeader.getFieldName(), this.filterTempCache.get(uiTableHeader.getFieldName())); uiTableHeader.setFilterApplied(true); } else if (uiTableHeader.getFilter().isRequired()) { this.filters.put(uiTableHeader.getFieldName(), new TableFilter(uiTableHeader)); } getHeaders().add(uiTableHeader); if (!field.isFixedWidth()) { if (userWidthList != null && userWidthList.size() > i) { if (isShowCheckBoxes() && userWidthList.size() > i + 1) { uiTableHeader.setWidth(userWidthList.get(i + 1)); } else { uiTableHeader.setWidth(userWidthList.get(i)); } } setWidthWeight(getWidthWeight() + field.getWidth()); } } i++; } } multi.execute(); if (!altOIDSel.isEmpty()) { final List<Instance> inst = new ArrayList<Instance>(); for (final String sel : altOIDSel) { inst.addAll(multi.getInstances4Select(sel)); } checkAccessToInstances(inst); } executeRowResult(multi, fields); if (getSortKey() != null) { sort(); } } /** * @param _multi Query * @param _fields Fields * @throws EFapsException on error */ private void executeRowResult(final MultiPrintQuery _multi, final List<Field> _fields) throws EFapsException { boolean first = true; while (_multi.next()) { Instance instance = _multi.getCurrentInstance(); final UIRow row = new UIRow(this, instance.getKey()); String strValue = ""; if (isEditMode() && first) { this.emptyRow = new UIRow(this); } for (final Field field : _fields) { if (field.getSelectAlternateOID() != null) { instance = Instance.get(_multi.<String> getSelect(field.getSelectAlternateOID())); } else { instance = _multi.getCurrentInstance(); } if (field.hasAccess(getMode(), instance, getCommand()) && !field.isNoneDisplay(getMode())) { Object value = null; Attribute attr = null; if (field.getSelect() != null) { value = _multi.<Object> getSelect(field.getSelect()); attr = _multi.getAttribute4Select(field.getSelect()); } else if (field.getAttribute() != null) { value = _multi.<Object> getAttribute(field.getAttribute()); attr = _multi.getAttribute4Attribute(field.getAttribute()); } else if (field.getPhrase() != null) { value = _multi.getPhrase(field.getName()); } final FieldValue fieldvalue = new FieldValue(field, attr, value, instance, getInstance(), new ArrayList<Instance>(_multi.getInstanceList()), this); String htmlTitle = null; boolean hidden = false; if (isPrintMode()) { strValue = fieldvalue.getStringValue(getMode()); } else { if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) { strValue = fieldvalue.getEditHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { strValue = fieldvalue.getHiddenHtml(getMode()); hidden = true; } else { strValue = fieldvalue.getReadOnlyHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } } if (strValue == null) { strValue = ""; } String icon = field.getIcon(); if (field.isShowTypeIcon()) { final Image image = Image.getTypeIcon(instance.getType()); if (image != null) { icon = image.getUrl(); } } if (hidden) { row.addHidden(new UIHiddenCell(this, fieldvalue, null, strValue)); } else { row.add(new UITableCell(this, fieldvalue, instance, strValue, htmlTitle, icon)); } // in case of edit mode an empty version of the first row // isw stored, and can be used // to create new rows if (isEditMode() && first) { final FieldValue fldVal = new FieldValue(field, attr); final String cellvalue; final String cellTitle; if (field.isEditableDisplay(getMode())) { cellvalue = fldVal.getEditHtml(getMode()); cellTitle = fldVal.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { cellvalue = fldVal.getHiddenHtml(getMode()); cellTitle = ""; } else { cellvalue = fldVal.getReadOnlyHtml(getMode()); cellTitle = fldVal.getStringValue(getMode()); } if (hidden) { this.emptyRow.addHidden(new UIHiddenCell(this, fldVal, null, cellvalue)); } else { this.emptyRow.add(new UITableCell(this, fldVal, null, cellvalue, cellTitle, icon)); } } } } this.values.add(row); first = false; } } /** * Executes this model for the case that no instance is given. Currently * only create! * * @throws EFapsException on error */ private void execute4NoInstance() throws EFapsException { final List<Field> fields = getUserSortedColumns(); final List<Integer> userWidthList = getUserWidths(); int i = 1; for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) { SortDirection sortdirection = SortDirection.NONE; if (field.getName().equals(getSortKey())) { sortdirection = getSortDirection(); } final UITableHeader headermodel = new UITableHeader(field, sortdirection, null); headermodel.setSortable(false); headermodel.setFilter(false); getHeaders().add(headermodel); if (!field.isFixedWidth()) { if (userWidthList != null && ((isShowCheckBoxes() && (i + 1) < userWidthList.size()) || (!isShowCheckBoxes() && i < userWidthList.size()))) { if (isShowCheckBoxes()) { headermodel.setWidth(userWidthList.get(i + 1)); } else { headermodel.setWidth(userWidthList.get(i)); } } setWidthWeight(getWidthWeight() + field.getWidth()); } i++; } } final Type type = getTypeFromEvent(); final UIRow row = new UIRow(this); Attribute attr = null; for (final Field field : fields) { if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode())) { attr = null; if (field.getAttribute() != null && type != null) { attr = type.getAttribute(field.getAttribute()); } final FieldValue fieldvalue = new FieldValue(field, attr, null, null, getInstance(), null, this); String htmlValue; String htmlTitle = null; boolean hidden = false; if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) { htmlValue = fieldvalue.getEditHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } else if (field.isHiddenDisplay(getMode())) { htmlValue = fieldvalue.getHiddenHtml(getMode()); hidden = true; } else { htmlValue = fieldvalue.getReadOnlyHtml(getMode()); htmlTitle = fieldvalue.getStringValue(getMode()); } if (htmlValue == null) { htmlValue = ""; } if (hidden) { row.addHidden(new UIHiddenCell(this, fieldvalue, null, htmlValue)); } else { final UITableCell cell = new UITableCell(this, fieldvalue, null, htmlValue, htmlTitle, null); row.add(cell); } } } this.values.add(row); if (getSortKey() != null) { sort(); } } /** * Method used to evaluate the type for this table from the connected * events. * * @return type if found * @throws EFapsException on error */ private Type getTypeFromEvent() throws EFapsException { final List<EventDefinition> events = getEvents(EventType.UI_TABLE_EVALUATE); String typeName = null; if (events.size() > 1) { throw new EFapsException(this.getClass(), "execute4NoInstance.moreThanOneEvaluate"); } else { final EventDefinition event = events.get(0); //TODO remove deprecated Types if (event.getProperty("Types") != null) { typeName = event.getProperty("Types").split(";")[0]; } // test for basic or abstract types if (event.getProperty("Type") != null) { typeName = event.getProperty("Type"); } // no type yet search alternatives if (typeName == null) { for (int i = 1; i < 100; i++) { final String nameTmp = "Type" + String.format("%02d", i); if (event.getProperty(nameTmp) != null) { typeName = event.getProperty(nameTmp); } else { break; } } } } return typeName == null ? null : Type.get(typeName); } /** * Getter method for the instance variable {@link #emptyRow}. * * @return value of instance variable {@link #emptyRow} */ public UIRow getEmptyRow() { return this.emptyRow; } /** * Add a filterlist to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _list lsi of value to filter * */ public void addFilterList(final UITableHeader _uitableHeader, final Set<?> _list) { final TableFilter filter = new TableFilter(_uitableHeader, _list); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a range to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _from from value * @throws EFapsException on error * */ public void addFilterTextLike(final UITableHeader _uitableHeader, final String _from) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _from); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a range to the filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _from from value * @param _to to value * @throws EFapsException on error * */ public void addFilterRange(final UITableHeader _uitableHeader, final String _from, final String _to) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _from, _to); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Add a classification based filters of this UiTable. * * @param _uitableHeader UitableHeader this filter belongs to * @param _uiClassification classification based filters * @throws EFapsException on error * */ public void addFilterClassifcation(final UITableHeader _uitableHeader, final UIClassification _uiClassification) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _uiClassification); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); } /** * Method to get a Filter from the list of filters belonging to this * UITable. * * @param _uitableHeader UitableHeader this filter belongs to * @return filter * @throws EFapsException on error */ public TableFilter getFilter(final UITableHeader _uitableHeader) throws EFapsException { TableFilter ret = this.filters.get(_uitableHeader.getFieldName()); if (ret != null && ret.getUiTableHeader() == null) { ret = new TableFilter(_uitableHeader); this.filters.put(_uitableHeader.getFieldName(), ret); } return ret; } /** * Get the List of values for a PICKERLIST. * * @param _uitableHeader UitableHeader this filter belongs to * @return List of Values */ public List<String> getFilterPickList(final UITableHeader _uitableHeader) { final List<String> ret = new ArrayList<String>(); for (final UIRow rowmodel : this.values) { final List<UITableCell> cells = rowmodel.getValues(); for (final UITableCell cell : cells) { if (cell.getFieldId() == _uitableHeader.getFieldId()) { final String value = cell.getCellTitle(); if (!ret.contains(value)) { ret.add(value); } break; } } } Collections.sort(ret); return ret; } /** * Store the Filter in the Session. */ private void storeFilters() { final Map<String, TableFilter> sessFilter = new HashMap<String, TableFilter>(); for (final Entry<String, TableFilter> entry : this.filters.entrySet()) { sessFilter.put(entry.getKey(), entry.getValue()); } try { Context.getThreadContext().setSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER), sessFilter); } catch (final EFapsException e) { UITable.LOG.error("Error storing Filtermap for Table called by Command with UUID: {}", getCommandUUID(), e); } } /** * This is the getter method for the instance variable {@link #values}. * * @return value of instance variable {@link #values} * @throws EFapsException * @see #values * @see #setValues */ public List<UIRow> getValues() { List<UIRow> ret = new ArrayList<UIRow>(); if (isFiltered()) { for (final UIRow row : this.values) { boolean filtered = false; for (final TableFilter filter : this.filters.values()) { filtered = filter.filterRow(row); if (filtered) { break; } } if (!filtered) { ret.add(row); } } } else { ret = this.values; } setSize(ret.size()); return ret; } /** * Are the values of the Rows filtered or not. * * @return true if filtered, else false */ @Override public boolean isFiltered() { return !this.filters.isEmpty(); } /** * Method to remove a filter from the filters. * * @param _uiTableHeader UITableHeader the filter is removed for */ public void removeFilter(final UITableHeader _uiTableHeader) { this.filters.remove(_uiTableHeader.getFieldName()); final UITableHeader orig = getHeader4Id(_uiTableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(false); } storeFilters(); } /** * {@inheritDoc} */ @Override public void resetModel() { super.setInitialized(false); this.values.clear(); getHeaders().clear(); getHiddenCells().clear(); } /** * Method to get the events that are related to this UITable. * * @param _eventType eventype to get * @return List of events * @throws CacheReloadException on error */ protected List<EventDefinition> getEvents(final EventType _eventType) throws CacheReloadException { return this.getCommand().getEvents(_eventType); } /** * The instance method sorts the table values depending on the sort key in * {@link #sortKey} and the sort direction in {@link #sortDirection}. * @throws EFapsException on error */ @Override public void sort() throws EFapsException { if (getSortKey() != null && getSortKey().length() > 0) { int sortKeyTmp = 0; final List<Field> fields = getUserSortedColumns(); for (int i = 0; i < fields.size(); i++) { final Field field = fields.get(i); if (field.hasAccess(getMode(), getInstance(), getCommand()) && !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) { if (field.getName().equals(getSortKey())) { break; } sortKeyTmp++; } } if (sortKeyTmp < getTable().getFields().size()) { final int index = sortKeyTmp; Collections.sort(this.values, new Comparator<UIRow>() { @Override public int compare(final UIRow _rowModel1, final UIRow _rowModel2) { FieldValue fValue1 = null; FieldValue fValue2 = null; try { final UITableCell cellModel1 = _rowModel1.getValues().get(index); fValue1 = new FieldValue(getTable().getFields().get(index), cellModel1 .getUiClass(), cellModel1.getCompareValue() != null ? cellModel1 .getCompareValue() : cellModel1.getCellValue()); final UITableCell cellModel2 = _rowModel2.getValues().get(index); fValue2 = new FieldValue(getTable().getFields().get(index), cellModel2 .getUiClass(), cellModel2.getCompareValue() != null ? cellModel2 .getCompareValue() : cellModel2.getCellValue()); } catch (final CacheReloadException e) { UITable.LOG.error("Error during sorting for table", e); } return fValue1.compareTo(fValue2); } }); if (getSortDirection() == SortDirection.DESCENDING) { Collections.reverse(this.values); } } } } /** * Class represents one filter applied to this UITable. */ public class TableFilter implements IClusterable { /** * Key to the value for "from" in the map for the esjp. */ public static final String FROM = "from"; /** * Key to the value for "to" in the map for the esjp. */ public static final String TO = "to"; /** * Key to the value for "to" in the map for the esjp. */ public static final String LIST = "list"; /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * Set of value for the filter. Only used for filter using a PICKERLIST or CLASSIFICATION. */ private Set<?> filterList; /** * Value of the from Field from the website. */ private String from; /** * Value of the to Field from the website. */ private String to; /** * DateTime value for {@link #from} in case that the filter is for a * date field. */ private DateTime dateFrom; /** * DateTime value for {@link #to} in case that the filter is for a date * field. */ private DateTime dateTo; /** * Id of the field this header belongs to. */ private long headerFieldId; /** * Type of the Filter. */ private final FilterType filterType; /** * Constructor is used for a database based filter in case that it is * required. */ public TableFilter() { this.headerFieldId = 0; this.filterType = null; } /** * Constructor is used in case that a filter is required, during loading * the date first time for a memory base filter. * * @param _uitableHeader UITableHeader this filter lies in * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); if (_uitableHeader.getFilter().getDefaultValue() != null) { if (_uitableHeader.getFilterType().equals(FilterType.DATE)) { final String filter = _uitableHeader.getFilter().getDefaultValue(); final String[] parts = filter.split(":"); final String range = parts[0]; final int sub = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; final FilterDefault def = FilterDefault.valueOf(range.toUpperCase()); DateMidnight tmp = DateTimeUtil.translateFromUI(new DateTime()).toDateMidnight(); switch (def) { case TODAY: this.dateFrom = tmp.toDateTime().minusDays(sub); this.dateTo = this.dateFrom.plusDays(1).plusSeconds(1); break; case WEEK: tmp = tmp.minusDays(tmp.getDayOfWeek() - 1); this.dateFrom = tmp.toDateTime().minusWeeks(sub); this.dateTo = tmp.toDateTime().plusWeeks(1); break; case MONTH: tmp = tmp.minusDays(tmp.getDayOfMonth() - 1); this.dateFrom = tmp.toDateTime().minusMonths(sub); this.dateTo = tmp.toDateTime().plusMonths(1); break; case YEAR: tmp = tmp.minusDays(tmp.getDayOfYear() - 1); this.dateFrom = tmp.toDateTime().minusYears(sub); this.dateTo = tmp.toDateTime().plusYears(1); break; default: break; } } } } /** * Standard Constructor for a Filter containing a range. * * @param _uitableHeader UITableHeader this filter lies in * @param _from value for from * @param _to value for to * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader, final String _from, final String _to) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.from = _from; this.to = _to; if (_uitableHeader.getFilterType().equals(FilterType.DATE)) { this.dateFrom = DateTimeUtil.translateFromUI(_from); this.dateTo = DateTimeUtil.translateFromUI(_to); this.dateTo = this.dateTo == null ? null : this.dateTo.plusDays(1); } } /** * Standard Constructor for a Filter containing a range. * * @param _uitableHeader UITableHeader this filter lies in * @param _from value for from * @param _to value for to * @throws EFapsException on error */ public TableFilter(final UITableHeader _uitableHeader, final String _from) throws EFapsException { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.from = _from; } /** * Standard Constructor for a Filter using a PICKLIST. * * @param _uitableHeader UITableHeader this filter lies in * @param _filterList set of values for the filter */ public TableFilter(final UITableHeader _uitableHeader, final Set<?> _filterList) { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); this.filterList = _filterList; } /** * Standard Constructor for a Filter using a CLASSICIATION. * * @param _uitableHeader UITableHeader this filter lies in * @param _uiClassification set of values for the filter */ public TableFilter(final UITableHeader _uitableHeader, final UIClassification _uiClassification) { this.headerFieldId = _uitableHeader.getFieldId(); this.filterType = _uitableHeader.getFilterType(); final Set<UUID> list = new HashSet<UUID>(); if (_uiClassification.isSelected()) { list.add(_uiClassification.getClassificationUUID()); } for (final UIClassification uiClass : _uiClassification.getDescendants()) { if (uiClass.isSelected()) { list.add(uiClass.getClassificationUUID()); } } this.filterList = list; } /** * Getter method for instance variable {@link #uiTableHeader}. * * @return value of instance variable {@link #uiTableHeader} */ public UITableHeader getUiTableHeader() { return getHeader4Id(this.headerFieldId); } /** * Method to get the map that must be passed for this filter to the * esjp. * * @return Map */ public Map<String, Object> getMap4esjp() { final Map<String, Object> ret = new HashMap<String, Object>(); if (this.filterList == null) { ret.put(UITable.TableFilter.FROM, this.from); ret.put(UITable.TableFilter.TO, this.to); } else { ret.put(UITable.TableFilter.LIST, this.filterList); } return ret; } /** * Method is used for memory based filters to filter one row. * * @param _uiRow UIRow to filter * @return false if the row must be shown to the user, true if the row * must be filtered */ public boolean filterRow(final UIRow _uiRow) { boolean ret = false; if (this.headerFieldId > 0 && Field.get(this.headerFieldId).getFilter().getBase().equals(Filter.Base.MEMORY)) { final List<UITableCell> cells = _uiRow.getValues(); for (final UITableCell cell : cells) { if (cell.getFieldId() == this.headerFieldId) { if (this.filterList != null) { final String value = cell.getCellTitle(); if (!this.filterList.contains(value)) { ret = true; } } else if (this.filterType.equals(FilterType.DATE)) { if (this.dateFrom == null || this.dateTo == null) { ret = true; } else { final Interval interval = new Interval(this.dateFrom, this.dateTo); final DateTime value = (DateTime) cell.getCompareValue(); if (!(interval.contains(value) || value.isEqual(this.dateFrom) || value.isEqual(this.dateTo))) { ret = true; } } } break; } } } return ret; } /** * Getter method for instance variable {@link #dateFrom}. * * @return value of instance variable {@link #dateFrom} */ public DateTime getDateFrom() { return this.dateFrom; } /** * Getter method for instance variable {@link #dateTo}. * * @return value of instance variable {@link #dateTo} */ public DateTime getDateTo() { return this.dateTo; } /** * Getter method for the instance variable {@link #from}. * * @return value of instance variable {@link #from} */ public String getFrom() { return this.from; } /** * Setter method for instance variable {@link #headerFieldId}. * * @param _headerFieldId value for instance variable {@link #headerFieldId} */ protected void setHeaderFieldId(final long _headerFieldId) { this.headerFieldId = _headerFieldId; } /** * Getter method for the instance variable {@link #filterList}. * * @return value of instance variable {@link #filterList} */ public Set<?> getFilterList() { return this.filterList; } } }
- webapp: correction of default filter git-svn-id: 6de479fac40b5ab7fd12e267df1fa0a7a72510c4@10045 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
src/main/java/org/efaps/ui/wicket/models/objects/UITable.java
- webapp: correction of default filter
Java
apache-2.0
2bd9d7afd727c8ca16e8e685baacfdf43db3ebcd
0
aaudiber/alluxio,EvilMcJerkface/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,maobaolong/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,bf8086/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,aaudiber/alluxio,jsimsa/alluxio,Reidddddd/alluxio,riversand963/alluxio,yuluo-ding/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,ChangerYoung/alluxio,Reidddddd/mo-alluxio,jswudi/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,Reidddddd/alluxio,calvinjia/tachyon,Reidddddd/alluxio,uronce-cc/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,ShailShah/alluxio,maboelhassan/alluxio,bf8086/alluxio,jsimsa/alluxio,Alluxio/alluxio,riversand963/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,Reidddddd/alluxio,calvinjia/tachyon,jsimsa/alluxio,maboelhassan/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,calvinjia/tachyon,maobaolong/alluxio,calvinjia/tachyon,madanadit/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,Alluxio/alluxio,riversand963/alluxio,ShailShah/alluxio,yuluo-ding/alluxio,yuluo-ding/alluxio,bf8086/alluxio,jswudi/alluxio,Reidddddd/alluxio,ShailShah/alluxio,Alluxio/alluxio,maboelhassan/alluxio,apc999/alluxio,Alluxio/alluxio,apc999/alluxio,apc999/alluxio,jswudi/alluxio,bf8086/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,ChangerYoung/alluxio,bf8086/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,maobaolong/alluxio,maobaolong/alluxio,maobaolong/alluxio,bf8086/alluxio,aaudiber/alluxio,apc999/alluxio,Alluxio/alluxio,madanadit/alluxio,madanadit/alluxio,riversand963/alluxio,ShailShah/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,aaudiber/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,apc999/alluxio,Reidddddd/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,apc999/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,Reidddddd/mo-alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,Alluxio/alluxio,PasaLab/tachyon,uronce-cc/alluxio,madanadit/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,jswudi/alluxio,jsimsa/alluxio,calvinjia/tachyon,jsimsa/alluxio,madanadit/alluxio,aaudiber/alluxio,uronce-cc/alluxio,calvinjia/tachyon,bf8086/alluxio,maboelhassan/alluxio,maobaolong/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,jswudi/alluxio,apc999/alluxio,madanadit/alluxio,madanadit/alluxio,ShailShah/alluxio,Alluxio/alluxio,riversand963/alluxio,bf8086/alluxio,Reidddddd/mo-alluxio,WilliamZapata/alluxio,madanadit/alluxio,PasaLab/tachyon,wwjiang007/alluxio,PasaLab/tachyon
/* * Licensed to the University of California, Berkeley 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 tachyon.master.block; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import org.apache.thrift.TProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import tachyon.Constants; import tachyon.StorageDirId; import tachyon.StorageLevelAlias; import tachyon.collections.IndexedSet; import tachyon.conf.TachyonConf; import tachyon.exception.BlockInfoException; import tachyon.exception.ExceptionMessage; import tachyon.exception.NoWorkerException; import tachyon.heartbeat.HeartbeatContext; import tachyon.heartbeat.HeartbeatExecutor; import tachyon.heartbeat.HeartbeatThread; import tachyon.master.MasterBase; import tachyon.master.MasterContext; import tachyon.master.block.journal.BlockContainerIdGeneratorEntry; import tachyon.master.block.journal.BlockInfoEntry; import tachyon.master.block.meta.MasterBlockInfo; import tachyon.master.block.meta.MasterBlockLocation; import tachyon.master.block.meta.MasterWorkerInfo; import tachyon.master.journal.Journal; import tachyon.master.journal.JournalEntry; import tachyon.master.journal.JournalInputStream; import tachyon.master.journal.JournalOutputStream; import tachyon.test.Testable; import tachyon.test.Tester; import tachyon.thrift.BlockInfo; import tachyon.thrift.BlockLocation; import tachyon.thrift.BlockMasterService; import tachyon.thrift.Command; import tachyon.thrift.CommandType; import tachyon.thrift.NetAddress; import tachyon.thrift.WorkerInfo; import tachyon.util.CommonUtils; import tachyon.util.FormatUtils; import tachyon.util.ThreadFactoryUtils; import tachyon.util.io.PathUtils; /** * This master manages the metadata for all the blocks and block workers in Tachyon. */ public final class BlockMaster extends MasterBase implements ContainerIdGenerable, Testable<BlockMaster> { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** Block metadata management. */ /** * Blocks on all workers, including active and lost blocks. This state must be journaled. Access * must be synchronized on mBlocks. If both block and worker metadata must be locked, mBlocks must * be locked first. */ private final Map<Long, MasterBlockInfo> mBlocks = new HashMap<Long, MasterBlockInfo>(); /** * Keeps track of block which are no longer in tachyon storage. Access must be synchronized on * mBlocks. */ private final Set<Long> mLostBlocks = new HashSet<Long>(); /** This state must be journaled. */ private final BlockContainerIdGenerator mBlockContainerIdGenerator = new BlockContainerIdGenerator(); /** Worker metadata management. */ private final IndexedSet.FieldIndex<MasterWorkerInfo> mIdIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getId(); } }; private final IndexedSet.FieldIndex<MasterWorkerInfo> mAddressIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getAddress(); } }; @SuppressWarnings("unchecked") /** * All worker information. Access must be synchronized on mWorkers. If both block and worker * metadata must be locked, mBlocks must be locked first. */ private final IndexedSet<MasterWorkerInfo> mWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** * Keeps track of workers which are no longer in communication with the master. Access must be * synchronized on mWorkers. */ private final IndexedSet<MasterWorkerInfo> mLostWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** The service that detects lost worker nodes, and tries to restart the failed workers. */ private Future<?> mLostWorkerDetectionService; /** The next worker id to use. This state must be journaled. */ private final AtomicLong mNextWorkerId = new AtomicLong(1); /** * @param baseDirectory the base journal directory * @return the journal directory for this master */ public static String getJournalDirectory(String baseDirectory) { return PathUtils.concatPath(baseDirectory, Constants.BLOCK_MASTER_SERVICE_NAME); } public BlockMaster(Journal journal) { super(journal, Executors.newFixedThreadPool(2, ThreadFactoryUtils.build("block-master-%d", true))); } @Override public TProcessor getProcessor() { return new BlockMasterService.Processor<BlockMasterServiceHandler>( new BlockMasterServiceHandler(this)); } @Override public String getServiceName() { return Constants.BLOCK_MASTER_SERVICE_NAME; } @Override public void processJournalCheckpoint(JournalInputStream inputStream) throws IOException { // clear state before processing checkpoint. mBlocks.clear(); super.processJournalCheckpoint(inputStream); } @Override public void processJournalEntry(JournalEntry entry) throws IOException { // TODO(gene): A better way to process entries besides a huge switch? if (entry instanceof BlockContainerIdGeneratorEntry) { mBlockContainerIdGenerator .setNextContainerId(((BlockContainerIdGeneratorEntry) entry).getNextContainerId()); } else if (entry instanceof BlockInfoEntry) { BlockInfoEntry blockInfoEntry = (BlockInfoEntry) entry; mBlocks.put(blockInfoEntry.getBlockId(), new MasterBlockInfo(blockInfoEntry.getBlockId(), blockInfoEntry.getLength())); } else { throw new IOException(ExceptionMessage.UNEXPECETD_JOURNAL_ENTRY.getMessage(entry)); } } @Override public void streamToJournalCheckpoint(JournalOutputStream outputStream) throws IOException { outputStream.writeEntry(mBlockContainerIdGenerator.toJournalEntry()); for (MasterBlockInfo blockInfo : mBlocks.values()) { outputStream.writeEntry(new BlockInfoEntry(blockInfo.getBlockId(), blockInfo.getLength())); } } @Override public void start(boolean isLeader) throws IOException { super.start(isLeader); if (isLeader) { mLostWorkerDetectionService = getExecutorService().submit( new HeartbeatThread(HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), MasterContext.getConf().getInt( Constants.MASTER_HEARTBEAT_INTERVAL_MS))); } } @Override public void stop() throws IOException { super.stop(); if (mLostWorkerDetectionService != null) { mLostWorkerDetectionService.cancel(true); } } /** * @return the number of workers */ public int getWorkerCount() { synchronized (mWorkers) { return mWorkers.size(); } } /** * @return a list of {@link WorkerInfo} objects representing the workers in Tachyon. Called via * RPC, and the internal web ui. */ public List<WorkerInfo> getWorkerInfoList() { synchronized (mWorkers) { List<WorkerInfo> workerInfoList = new ArrayList<WorkerInfo>(mWorkers.size()); for (MasterWorkerInfo masterWorkerInfo : mWorkers) { workerInfoList.add(masterWorkerInfo.generateClientWorkerInfo()); } return workerInfoList; } } /** * @return the total capacity (in bytes) on all tiers, on all workers of Tachyon. Called via RPC * and internal web ui. */ public long getCapacityBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { ret += worker.getCapacityBytes(); } } return ret; } /** * @return the total used bytes on all tiers, on all workers of Tachyon. Called via RPC and * internal web ui. */ public long getUsedBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { ret += worker.getUsedBytes(); } } return ret; } /** * Gets info about the lost workers. Called by the internal web ui. * * @return a list of worker info */ public List<WorkerInfo> getLostWorkersInfo() { synchronized (mWorkers) { List<WorkerInfo> ret = new ArrayList<WorkerInfo>(mLostWorkers.size()); for (MasterWorkerInfo worker : mLostWorkers) { ret.add(worker.generateClientWorkerInfo()); } return ret; } } /** * Removes blocks from workers. Called by internal masters. * * @param blockIds a list of block ids to remove from Tachyon space. */ public void removeBlocks(List<Long> blockIds) { synchronized (mBlocks) { synchronized (mWorkers) { for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { continue; } for (long workerId : new ArrayList<Long>(masterBlockInfo.getWorkers())) { masterBlockInfo.removeWorker(workerId); MasterWorkerInfo worker = mWorkers.getFirstByField(mIdIndex, workerId); if (worker != null) { worker.updateToRemovedBlock(true, blockId); } } mLostBlocks.remove(blockId); } } } } /** * @return a new block container id. Called by internal masters */ @Override public long getNewContainerId() { synchronized (mBlockContainerIdGenerator) { long containerId = mBlockContainerIdGenerator.getNewContainerId(); writeJournalEntry(mBlockContainerIdGenerator.toJournalEntry()); flushJournal(); return containerId; } } /** * Marks a block as committed on a specific worker. Called by workers via RPC. * * @param workerId the worker id committing the block * @param usedBytesOnTier the updated used bytes on the tier of the worker * @param tierAlias the tier alias where the worker is committing the block to * @param blockId the committing block id * @param length the length of the block */ public void commitBlock(long workerId, long usedBytesOnTier, int tierAlias, long blockId, long length) { LOG.debug("Commit block from worker: {}", FormatUtils.parametersToString(workerId, usedBytesOnTier, blockId, length)); synchronized (mBlocks) { synchronized (mWorkers) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); workerInfo.addBlock(blockId); workerInfo.updateUsedBytes(tierAlias, usedBytesOnTier); workerInfo.updateLastUpdatedTimeMs(); MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { masterBlockInfo = new MasterBlockInfo(blockId, length); mBlocks.put(blockId, masterBlockInfo); writeJournalEntry( new BlockInfoEntry(masterBlockInfo.getBlockId(), masterBlockInfo.getLength())); flushJournal(); } masterBlockInfo.addWorker(workerId, tierAlias); mLostBlocks.remove(blockId); } } } /** * Marks a block as committed, but without a worker location. This means the block is only in ufs. * Called by internal masters. * * @param blockId the id of the block to commit * @param length the length of the block */ public void commitBlockInUFS(long blockId, long length) { LOG.debug("Commit block to ufs: {}", FormatUtils.parametersToString(blockId, length)); synchronized (mBlocks) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { // The block has not been committed previously, so add the metadata to commit the block. masterBlockInfo = new MasterBlockInfo(blockId, length); mBlocks.put(blockId, masterBlockInfo); writeJournalEntry( new BlockInfoEntry(masterBlockInfo.getBlockId(), masterBlockInfo.getLength())); flushJournal(); } } } /** * @param blockId the block id to get information for * @return the {@link BlockInfo} for the given block id. Called via RPC * @throws BlockInfoException */ public BlockInfo getBlockInfo(long blockId) throws BlockInfoException { synchronized (mBlocks) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { throw new BlockInfoException("Block info not found for " + blockId); } // Construct the block info object to return. synchronized (mWorkers) { return generateBlockInfo(masterBlockInfo); } } } /** * Retrieves information for the given list of block ids. Called by internal masters. * * @param blockIds A list of block ids to retrieve the information for * @return A list of {@link BlockInfo} objects corresponding to the input list of block ids. The * list is in the same order as the input list */ public List<BlockInfo> getBlockInfoList(List<Long> blockIds) { List<BlockInfo> ret = new ArrayList<BlockInfo>(blockIds.size()); synchronized (mBlocks) { synchronized (mWorkers) { for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo != null) { // Construct the block info object to return. ret.add(generateBlockInfo(masterBlockInfo)); } } return ret; } } } /** * @return the total bytes on each storage tier. Called by internal web ui */ public List<Long> getTotalBytesOnTiers() { List<Long> ret = new ArrayList<Long>(Collections.nCopies(StorageLevelAlias.SIZE, 0L)); synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { for (int i = 0; i < worker.getTotalBytesOnTiers().size(); i ++) { ret.set(i, ret.get(i) + worker.getTotalBytesOnTiers().get(i)); } } } return ret; } /** * @return the used bytes on each storage tier. Called by internal web ui */ public List<Long> getUsedBytesOnTiers() { List<Long> ret = new ArrayList<Long>(Collections.nCopies(StorageLevelAlias.SIZE, 0L)); synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { for (int i = 0; i < worker.getUsedBytesOnTiers().size(); i ++) { ret.set(i, ret.get(i) + worker.getUsedBytesOnTiers().get(i)); } } } return ret; } /** * Returns a worker id for the given worker. Returns the existing worker id if it exists. Called * by workers, via RPC. * * @param workerNetAddress the worker {@link NetAddress} * @return the worker id for this worker */ public long getWorkerId(NetAddress workerNetAddress) { // TODO(gene): This NetAddress cloned in case thrift re-uses the object. Does thrift re-use it? NetAddress workerAddress = new NetAddress(workerNetAddress); synchronized (mWorkers) { if (mWorkers.contains(mAddressIndex, workerAddress)) { // This worker address is already mapped to a worker id. long oldWorkerId = mWorkers.getFirstByField(mAddressIndex, workerAddress).getId(); LOG.warn("The worker " + workerAddress + " already exists as id " + oldWorkerId + "."); return oldWorkerId; } if (mLostWorkers.contains(mAddressIndex, workerAddress)) { // this is one of the lost workers final MasterWorkerInfo lostWorkerInfo = mLostWorkers.getFirstByField(mAddressIndex, workerAddress); final long lostWorkerId = lostWorkerInfo.getId(); LOG.warn("A lost worker " + workerAddress + " has requested its old id " + lostWorkerId + "."); mWorkers.add(lostWorkerInfo); mLostWorkers.remove(lostWorkerInfo); return lostWorkerId; } // Generate a new worker id. long workerId = mNextWorkerId.getAndIncrement(); mWorkers.add(new MasterWorkerInfo(workerId, workerNetAddress)); LOG.info("getWorkerId(): WorkerNetAddress: " + workerAddress + " id: " + workerId); return workerId; } } /** * Updates metadata when a worker registers with the master. Called by workers via RPC. * * @param workerId the worker id of the worker registering * @param totalBytesOnTiers list of total bytes on each tier * @param usedBytesOnTiers list of the used byes on each tier * @param currentBlocksOnTiers a mapping of each storage dir, to all the blocks on that storage * @throws NoWorkerException if workerId cannot be found */ public void workerRegister(long workerId, List<Long> totalBytesOnTiers, List<Long> usedBytesOnTiers, Map<Long, List<Long>> currentBlocksOnTiers) throws NoWorkerException { synchronized (mBlocks) { synchronized (mWorkers) { if (!mWorkers.contains(mIdIndex, workerId)) { throw new NoWorkerException("Could not find worker id: " + workerId + " to register."); } MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); workerInfo.updateLastUpdatedTimeMs(); // Gather all blocks on this worker. HashSet<Long> blocks = new HashSet<Long>(); for (List<Long> blockIds : currentBlocksOnTiers.values()) { blocks.addAll(blockIds); } // Detect any lost blocks on this worker. Set<Long> removedBlocks = workerInfo.register(totalBytesOnTiers, usedBytesOnTiers, blocks); processWorkerRemovedBlocks(workerInfo, removedBlocks); processWorkerAddedBlocks(workerInfo, currentBlocksOnTiers); LOG.info("registerWorker(): " + workerInfo); } } } /** * Updates metadata when a worker periodically heartbeats with the master. Called by the worker * periodically, via RPC. * * @param workerId the worker id * @param usedBytesOnTiers a list of used bytes on each tier * @param removedBlockIds a list of block ids removed from this worker * @param addedBlocksOnTiers the added blocks for each storage dir. It maps storage dir id, to a * list of added block for that storage dir. * @return an optional command for the worker to execute */ public Command workerHeartbeat(long workerId, List<Long> usedBytesOnTiers, List<Long> removedBlockIds, Map<Long, List<Long>> addedBlocksOnTiers) { synchronized (mBlocks) { synchronized (mWorkers) { if (!mWorkers.contains(mIdIndex, workerId)) { LOG.warn("Could not find worker id: " + workerId + " for heartbeat."); return new Command(CommandType.Register, new ArrayList<Long>()); } MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); processWorkerRemovedBlocks(workerInfo, removedBlockIds); processWorkerAddedBlocks(workerInfo, addedBlocksOnTiers); workerInfo.updateUsedBytes(usedBytesOnTiers); workerInfo.updateLastUpdatedTimeMs(); List<Long> toRemoveBlocks = workerInfo.getToRemoveBlocks(); if (toRemoveBlocks.isEmpty()) { return new Command(CommandType.Nothing, new ArrayList<Long>()); } return new Command(CommandType.Free, toRemoveBlocks); } } } /** * Updates the worker and block metadata for blocks removed from a worker. * * mBlocks should already be locked before calling this method. * * @param workerInfo The worker metadata object * @param removedBlockIds A list of block ids removed from the worker */ private void processWorkerRemovedBlocks(MasterWorkerInfo workerInfo, Collection<Long> removedBlockIds) { for (long removedBlockId : removedBlockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(removedBlockId); if (masterBlockInfo == null) { LOG.warn("Worker " + workerInfo.getId() + " removed block " + removedBlockId + " but block does not exist."); // Continue to remove the remaining blocks. continue; } LOG.info("Block " + removedBlockId + " is removed on worker " + workerInfo.getId()); workerInfo.removeBlock(masterBlockInfo.getBlockId()); masterBlockInfo.removeWorker(workerInfo.getId()); if (masterBlockInfo.getNumLocations() == 0) { mLostBlocks.add(removedBlockId); } } } /** * Called by the heartbeat thread whenever a worker is lost. * @param latest the latest {@link MasterWorkerInfo} available at the time of worker loss */ private void processLostWorker(MasterWorkerInfo latest) { synchronized (mBlocks) { final Set<Long> lostBlocks = latest.getBlocks(); processWorkerRemovedBlocks(latest, lostBlocks); } } /** * Updates the worker and block metadata for blocks added to a worker. * * mBlocks should already be locked before calling this method. * * @param workerInfo The worker metadata object * @param addedBlockIds Mapping from StorageDirId to a list of block ids added to the directory. */ private void processWorkerAddedBlocks(MasterWorkerInfo workerInfo, Map<Long, List<Long>> addedBlockIds) { for (Entry<Long, List<Long>> blockIds : addedBlockIds.entrySet()) { long storageDirId = blockIds.getKey(); for (long blockId : blockIds.getValue()) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo != null) { workerInfo.addBlock(blockId); // TODO(gene): Change upper API so that this is tier level or type, not storage dir id. int tierAlias = StorageDirId.getStorageLevelAliasValue(storageDirId); masterBlockInfo.addWorker(workerInfo.getId(), tierAlias); mLostBlocks.remove(blockId); } else { LOG.warn( "failed to register workerId: " + workerInfo.getId() + " to blockId: " + blockId); } } } } /** * @return the lost blocks in Tachyon Storage */ public Set<Long> getLostBlocks() { synchronized (mLostBlocks) { return ImmutableSet.copyOf(mLostBlocks); } } /** * Creates a {@link BlockInfo} form a given {@link MasterBlockInfo}, by populating worker * locations. * * mWorkers should already be locked before calling this method. * * @param masterBlockInfo the {@link MasterBlockInfo} * @return a {@link BlockInfo} from a {@link MasterBlockInfo}. Populates worker locations */ private BlockInfo generateBlockInfo(MasterBlockInfo masterBlockInfo) { // "Join" to get all the addresses of the workers. List<BlockLocation> locations = new ArrayList<BlockLocation>(); for (MasterBlockLocation masterBlockLocation : masterBlockInfo.getBlockLocations()) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, masterBlockLocation.getWorkerId()); if (workerInfo != null) { locations.add(new BlockLocation(masterBlockLocation.getWorkerId(), workerInfo.getAddress(), masterBlockLocation.getTier())); } } return new BlockInfo(masterBlockInfo.getBlockId(), masterBlockInfo.getLength(), locations); } /** * Reports the ids of the blocks lost on workers. * * @param blockIds the ids of the lost blocks */ public void reportLostBlocks(List<Long> blockIds) { synchronized (mLostBlocks) { mLostBlocks.addAll(blockIds); } } /** * Lost worker periodic check. */ private final class LostWorkerDetectionHeartbeatExecutor implements HeartbeatExecutor { @Override public void heartbeat() { LOG.debug("System status checking."); TachyonConf conf = MasterContext.getConf(); int masterWorkerTimeoutMs = conf.getInt(Constants.MASTER_WORKER_TIMEOUT_MS); synchronized (mWorkers) { Iterator<MasterWorkerInfo> iter = mWorkers.iterator(); while (iter.hasNext()) { MasterWorkerInfo worker = iter.next(); if (CommonUtils.getCurrentMs() - worker.getLastUpdatedTimeMs() > masterWorkerTimeoutMs) { LOG.error("The worker " + worker + " got timed out!"); mLostWorkers.add(worker); iter.remove(); processLostWorker(worker); } } } } } class PrivateAccess { private PrivateAccess() {} /** * @param worker a {@link MasterWorkerInfo} to add to the list of lost workers */ public void addLostWorker(MasterWorkerInfo worker) { synchronized (mWorkers) { mLostWorkers.add(worker); } } /** * Looks up the {@link MasterWorkerInfo} for a given worker ID. * * @param workerId the worker ID to look up * @return the {@link MasterWorkerInfo} for the given workerId */ public MasterWorkerInfo getWorkerById(long workerId) { synchronized (mWorkers) { return mWorkers.getFirstByField(mIdIndex, workerId); } } /** * Looks up the {@link MasterBlockInfo} for the given block ID. * * @param blockId the block ID * @return the {@link MasterBlockInfo} */ public MasterBlockInfo getMasterBlockInfo(long blockId) { synchronized (mBlocks) { return mBlocks.get(blockId); } } } /** Grants access to private members to testers of this class. */ @Override public void grantAccess(Tester<BlockMaster> tester) { tester.receiveAccess(new PrivateAccess()); } }
servers/src/main/java/tachyon/master/block/BlockMaster.java
/* * Licensed to the University of California, Berkeley 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 tachyon.master.block; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import org.apache.thrift.TProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tachyon.Constants; import tachyon.StorageDirId; import tachyon.StorageLevelAlias; import tachyon.collections.IndexedSet; import tachyon.conf.TachyonConf; import tachyon.exception.BlockInfoException; import tachyon.exception.ExceptionMessage; import tachyon.exception.NoWorkerException; import tachyon.heartbeat.HeartbeatContext; import tachyon.heartbeat.HeartbeatExecutor; import tachyon.heartbeat.HeartbeatThread; import tachyon.master.MasterBase; import tachyon.master.MasterContext; import tachyon.master.block.journal.BlockContainerIdGeneratorEntry; import tachyon.master.block.journal.BlockInfoEntry; import tachyon.master.block.meta.MasterBlockInfo; import tachyon.master.block.meta.MasterBlockLocation; import tachyon.master.block.meta.MasterWorkerInfo; import tachyon.master.journal.Journal; import tachyon.master.journal.JournalEntry; import tachyon.master.journal.JournalInputStream; import tachyon.master.journal.JournalOutputStream; import tachyon.test.Testable; import tachyon.test.Tester; import tachyon.thrift.BlockInfo; import tachyon.thrift.BlockLocation; import tachyon.thrift.BlockMasterService; import tachyon.thrift.Command; import tachyon.thrift.CommandType; import tachyon.thrift.NetAddress; import tachyon.thrift.WorkerInfo; import tachyon.util.CommonUtils; import tachyon.util.FormatUtils; import tachyon.util.ThreadFactoryUtils; import tachyon.util.io.PathUtils; /** * This master manages the metadata for all the blocks and block workers in Tachyon. */ public final class BlockMaster extends MasterBase implements ContainerIdGenerable, Testable<BlockMaster> { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** Block metadata management. */ /** * Blocks on all workers, including active and lost blocks. This state must be journaled. Access * must be synchronized on mBlocks. If both block and worker metadata must be locked, mBlocks must * be locked first. */ private final Map<Long, MasterBlockInfo> mBlocks = new HashMap<Long, MasterBlockInfo>(); /** * Keeps track of block which are no longer in tachyon storage. Access must be synchronized on * mBlocks. */ private final Set<Long> mLostBlocks = new HashSet<Long>(); /** This state must be journaled. */ private final BlockContainerIdGenerator mBlockContainerIdGenerator = new BlockContainerIdGenerator(); /** Worker metadata management. */ private final IndexedSet.FieldIndex<MasterWorkerInfo> mIdIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getId(); } }; private final IndexedSet.FieldIndex<MasterWorkerInfo> mAddressIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getAddress(); } }; @SuppressWarnings("unchecked") /** * All worker information. Access must be synchronized on mWorkers. If both block and worker * metadata must be locked, mBlocks must be locked first. */ private final IndexedSet<MasterWorkerInfo> mWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** * Keeps track of workers which are no longer in communication with the master. Access must be * synchronized on mWorkers. */ private final IndexedSet<MasterWorkerInfo> mLostWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** The service that detects lost worker nodes, and tries to restart the failed workers. */ private Future<?> mLostWorkerDetectionService; /** The next worker id to use. This state must be journaled. */ private final AtomicLong mNextWorkerId = new AtomicLong(1); /** * @param baseDirectory the base journal directory * @return the journal directory for this master */ public static String getJournalDirectory(String baseDirectory) { return PathUtils.concatPath(baseDirectory, Constants.BLOCK_MASTER_SERVICE_NAME); } public BlockMaster(Journal journal) { super(journal, Executors.newFixedThreadPool(2, ThreadFactoryUtils.build("block-master-%d", true))); } @Override public TProcessor getProcessor() { return new BlockMasterService.Processor<BlockMasterServiceHandler>( new BlockMasterServiceHandler(this)); } @Override public String getServiceName() { return Constants.BLOCK_MASTER_SERVICE_NAME; } @Override public void processJournalCheckpoint(JournalInputStream inputStream) throws IOException { // clear state before processing checkpoint. mBlocks.clear(); super.processJournalCheckpoint(inputStream); } @Override public void processJournalEntry(JournalEntry entry) throws IOException { // TODO(gene): A better way to process entries besides a huge switch? if (entry instanceof BlockContainerIdGeneratorEntry) { mBlockContainerIdGenerator .setNextContainerId(((BlockContainerIdGeneratorEntry) entry).getNextContainerId()); } else if (entry instanceof BlockInfoEntry) { BlockInfoEntry blockInfoEntry = (BlockInfoEntry) entry; mBlocks.put(blockInfoEntry.getBlockId(), new MasterBlockInfo(blockInfoEntry.getBlockId(), blockInfoEntry.getLength())); } else { throw new IOException(ExceptionMessage.UNEXPECETD_JOURNAL_ENTRY.getMessage(entry)); } } @Override public void streamToJournalCheckpoint(JournalOutputStream outputStream) throws IOException { outputStream.writeEntry(mBlockContainerIdGenerator.toJournalEntry()); for (MasterBlockInfo blockInfo : mBlocks.values()) { outputStream.writeEntry(new BlockInfoEntry(blockInfo.getBlockId(), blockInfo.getLength())); } } @Override public void start(boolean isLeader) throws IOException { super.start(isLeader); if (isLeader) { mLostWorkerDetectionService = getExecutorService().submit( new HeartbeatThread(HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), MasterContext.getConf().getInt( Constants.MASTER_HEARTBEAT_INTERVAL_MS))); } } @Override public void stop() throws IOException { super.stop(); if (mLostWorkerDetectionService != null) { mLostWorkerDetectionService.cancel(true); } } /** * @return the number of workers */ public int getWorkerCount() { synchronized (mWorkers) { return mWorkers.size(); } } /** * @return a list of {@link WorkerInfo} objects representing the workers in Tachyon. Called via * RPC, and the internal web ui. */ public List<WorkerInfo> getWorkerInfoList() { synchronized (mWorkers) { List<WorkerInfo> workerInfoList = new ArrayList<WorkerInfo>(mWorkers.size()); for (MasterWorkerInfo masterWorkerInfo : mWorkers) { workerInfoList.add(masterWorkerInfo.generateClientWorkerInfo()); } return workerInfoList; } } /** * @return the total capacity (in bytes) on all tiers, on all workers of Tachyon. Called via RPC * and internal web ui. */ public long getCapacityBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { ret += worker.getCapacityBytes(); } } return ret; } /** * @return the total used bytes on all tiers, on all workers of Tachyon. Called via RPC and * internal web ui. */ public long getUsedBytes() { long ret = 0; synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { ret += worker.getUsedBytes(); } } return ret; } /** * Gets info about the lost workers. Called by the internal web ui. * * @return a list of worker info */ public List<WorkerInfo> getLostWorkersInfo() { synchronized (mWorkers) { List<WorkerInfo> ret = new ArrayList<WorkerInfo>(mLostWorkers.size()); for (MasterWorkerInfo worker : mLostWorkers) { ret.add(worker.generateClientWorkerInfo()); } return ret; } } /** * Removes blocks from workers. Called by internal masters. * * @param blockIds a list of block ids to remove from Tachyon space. */ public void removeBlocks(List<Long> blockIds) { synchronized (mBlocks) { synchronized (mWorkers) { for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { continue; } for (long workerId : new ArrayList<Long>(masterBlockInfo.getWorkers())) { masterBlockInfo.removeWorker(workerId); MasterWorkerInfo worker = mWorkers.getFirstByField(mIdIndex, workerId); if (worker != null) { worker.updateToRemovedBlock(true, blockId); } } mLostBlocks.remove(blockId); } } } } /** * @return a new block container id. Called by internal masters */ @Override public long getNewContainerId() { synchronized (mBlockContainerIdGenerator) { long containerId = mBlockContainerIdGenerator.getNewContainerId(); writeJournalEntry(mBlockContainerIdGenerator.toJournalEntry()); flushJournal(); return containerId; } } /** * Marks a block as committed on a specific worker. Called by workers via RPC. * * @param workerId the worker id committing the block * @param usedBytesOnTier the updated used bytes on the tier of the worker * @param tierAlias the tier alias where the worker is committing the block to * @param blockId the committing block id * @param length the length of the block */ public void commitBlock(long workerId, long usedBytesOnTier, int tierAlias, long blockId, long length) { LOG.debug("Commit block from worker: {}", FormatUtils.parametersToString(workerId, usedBytesOnTier, blockId, length)); synchronized (mBlocks) { synchronized (mWorkers) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); workerInfo.addBlock(blockId); workerInfo.updateUsedBytes(tierAlias, usedBytesOnTier); workerInfo.updateLastUpdatedTimeMs(); MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { masterBlockInfo = new MasterBlockInfo(blockId, length); mBlocks.put(blockId, masterBlockInfo); writeJournalEntry( new BlockInfoEntry(masterBlockInfo.getBlockId(), masterBlockInfo.getLength())); flushJournal(); } masterBlockInfo.addWorker(workerId, tierAlias); mLostBlocks.remove(blockId); } } } /** * Marks a block as committed, but without a worker location. This means the block is only in ufs. * Called by internal masters. * * @param blockId the id of the block to commit * @param length the length of the block */ public void commitBlockInUFS(long blockId, long length) { LOG.debug("Commit block to ufs: {}", FormatUtils.parametersToString(blockId, length)); synchronized (mBlocks) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { // The block has not been committed previously, so add the metadata to commit the block. masterBlockInfo = new MasterBlockInfo(blockId, length); mBlocks.put(blockId, masterBlockInfo); writeJournalEntry( new BlockInfoEntry(masterBlockInfo.getBlockId(), masterBlockInfo.getLength())); flushJournal(); } } } /** * @param blockId the block id to get information for * @return the {@link BlockInfo} for the given block id. Called via RPC * @throws BlockInfoException */ public BlockInfo getBlockInfo(long blockId) throws BlockInfoException { synchronized (mBlocks) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { throw new BlockInfoException("Block info not found for " + blockId); } // Construct the block info object to return. synchronized (mWorkers) { return generateBlockInfo(masterBlockInfo); } } } /** * Retrieves information for the given list of block ids. Called by internal masters. * * @param blockIds A list of block ids to retrieve the information for * @return A list of {@link BlockInfo} objects corresponding to the input list of block ids. The * list is in the same order as the input list */ public List<BlockInfo> getBlockInfoList(List<Long> blockIds) { List<BlockInfo> ret = new ArrayList<BlockInfo>(blockIds.size()); synchronized (mBlocks) { synchronized (mWorkers) { for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo != null) { // Construct the block info object to return. ret.add(generateBlockInfo(masterBlockInfo)); } } return ret; } } } /** * @return the total bytes on each storage tier. Called by internal web ui */ public List<Long> getTotalBytesOnTiers() { List<Long> ret = new ArrayList<Long>(Collections.nCopies(StorageLevelAlias.SIZE, 0L)); synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { for (int i = 0; i < worker.getTotalBytesOnTiers().size(); i ++) { ret.set(i, ret.get(i) + worker.getTotalBytesOnTiers().get(i)); } } } return ret; } /** * @return the used bytes on each storage tier. Called by internal web ui */ public List<Long> getUsedBytesOnTiers() { List<Long> ret = new ArrayList<Long>(Collections.nCopies(StorageLevelAlias.SIZE, 0L)); synchronized (mWorkers) { for (MasterWorkerInfo worker : mWorkers) { for (int i = 0; i < worker.getUsedBytesOnTiers().size(); i ++) { ret.set(i, ret.get(i) + worker.getUsedBytesOnTiers().get(i)); } } } return ret; } /** * Returns a worker id for the given worker. Returns the existing worker id if it exists. Called * by workers, via RPC. * * @param workerNetAddress the worker {@link NetAddress} * @return the worker id for this worker */ public long getWorkerId(NetAddress workerNetAddress) { // TODO(gene): This NetAddress cloned in case thrift re-uses the object. Does thrift re-use it? NetAddress workerAddress = new NetAddress(workerNetAddress); synchronized (mWorkers) { if (mWorkers.contains(mAddressIndex, workerAddress)) { // This worker address is already mapped to a worker id. long oldWorkerId = mWorkers.getFirstByField(mAddressIndex, workerAddress).getId(); LOG.warn("The worker " + workerAddress + " already exists as id " + oldWorkerId + "."); return oldWorkerId; } if (mLostWorkers.contains(mAddressIndex, workerAddress)) { // this is one of the lost workers final MasterWorkerInfo lostWorkerInfo = mLostWorkers.getFirstByField(mAddressIndex, workerAddress); final long lostWorkerId = lostWorkerInfo.getId(); LOG.warn("A lost worker " + workerAddress + " has requested its old id " + lostWorkerId + "."); mWorkers.add(lostWorkerInfo); mLostWorkers.remove(lostWorkerInfo); return lostWorkerId; } // Generate a new worker id. long workerId = mNextWorkerId.getAndIncrement(); mWorkers.add(new MasterWorkerInfo(workerId, workerNetAddress)); LOG.info("getWorkerId(): WorkerNetAddress: " + workerAddress + " id: " + workerId); return workerId; } } /** * Updates metadata when a worker registers with the master. Called by workers via RPC. * * @param workerId the worker id of the worker registering * @param totalBytesOnTiers list of total bytes on each tier * @param usedBytesOnTiers list of the used byes on each tier * @param currentBlocksOnTiers a mapping of each storage dir, to all the blocks on that storage * @throws NoWorkerException if workerId cannot be found */ public void workerRegister(long workerId, List<Long> totalBytesOnTiers, List<Long> usedBytesOnTiers, Map<Long, List<Long>> currentBlocksOnTiers) throws NoWorkerException { synchronized (mBlocks) { synchronized (mWorkers) { if (!mWorkers.contains(mIdIndex, workerId)) { throw new NoWorkerException("Could not find worker id: " + workerId + " to register."); } MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); workerInfo.updateLastUpdatedTimeMs(); // Gather all blocks on this worker. HashSet<Long> blocks = new HashSet<Long>(); for (List<Long> blockIds : currentBlocksOnTiers.values()) { blocks.addAll(blockIds); } // Detect any lost blocks on this worker. Set<Long> removedBlocks = workerInfo.register(totalBytesOnTiers, usedBytesOnTiers, blocks); processWorkerRemovedBlocks(workerInfo, removedBlocks); processWorkerAddedBlocks(workerInfo, currentBlocksOnTiers); LOG.info("registerWorker(): " + workerInfo); } } } /** * Updates metadata when a worker periodically heartbeats with the master. Called by the worker * periodically, via RPC. * * @param workerId the worker id * @param usedBytesOnTiers a list of used bytes on each tier * @param removedBlockIds a list of block ids removed from this worker * @param addedBlocksOnTiers the added blocks for each storage dir. It maps storage dir id, to a * list of added block for that storage dir. * @return an optional command for the worker to execute */ public Command workerHeartbeat(long workerId, List<Long> usedBytesOnTiers, List<Long> removedBlockIds, Map<Long, List<Long>> addedBlocksOnTiers) { synchronized (mBlocks) { synchronized (mWorkers) { if (!mWorkers.contains(mIdIndex, workerId)) { LOG.warn("Could not find worker id: " + workerId + " for heartbeat."); return new Command(CommandType.Register, new ArrayList<Long>()); } MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); processWorkerRemovedBlocks(workerInfo, removedBlockIds); processWorkerAddedBlocks(workerInfo, addedBlocksOnTiers); workerInfo.updateUsedBytes(usedBytesOnTiers); workerInfo.updateLastUpdatedTimeMs(); List<Long> toRemoveBlocks = workerInfo.getToRemoveBlocks(); if (toRemoveBlocks.isEmpty()) { return new Command(CommandType.Nothing, new ArrayList<Long>()); } return new Command(CommandType.Free, toRemoveBlocks); } } } /** * Updates the worker and block metadata for blocks removed from a worker. * * mBlocks should already be locked before calling this method. * * @param workerInfo The worker metadata object * @param removedBlockIds A list of block ids removed from the worker */ private void processWorkerRemovedBlocks(MasterWorkerInfo workerInfo, Collection<Long> removedBlockIds) { for (long removedBlockId : removedBlockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(removedBlockId); if (masterBlockInfo == null) { LOG.warn("Worker " + workerInfo.getId() + " removed block " + removedBlockId + " but block does not exist."); // Continue to remove the remaining blocks. continue; } LOG.info("Block " + removedBlockId + " is removed on worker " + workerInfo.getId()); workerInfo.removeBlock(masterBlockInfo.getBlockId()); masterBlockInfo.removeWorker(workerInfo.getId()); if (masterBlockInfo.getNumLocations() == 0) { mLostBlocks.add(removedBlockId); } } } /** * Updates the worker and block metadata for blocks added to a worker. * * mBlocks should already be locked before calling this method. * * @param workerInfo The worker metadata object * @param addedBlockIds Mapping from StorageDirId to a list of block ids added to the directory. */ private void processWorkerAddedBlocks(MasterWorkerInfo workerInfo, Map<Long, List<Long>> addedBlockIds) { for (Entry<Long, List<Long>> blockIds : addedBlockIds.entrySet()) { long storageDirId = blockIds.getKey(); for (long blockId : blockIds.getValue()) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo != null) { workerInfo.addBlock(blockId); // TODO(gene): Change upper API so that this is tier level or type, not storage dir id. int tierAlias = StorageDirId.getStorageLevelAliasValue(storageDirId); masterBlockInfo.addWorker(workerInfo.getId(), tierAlias); mLostBlocks.remove(blockId); } else { LOG.warn( "failed to register workerId: " + workerInfo.getId() + " to blockId: " + blockId); } } } } /** * @return the lost blocks in Tachyon Storage */ public Set<Long> getLostBlocks() { return Collections.unmodifiableSet(mLostBlocks); } /** * Creates a {@link BlockInfo} form a given {@link MasterBlockInfo}, by populating worker * locations. * * mWorkers should already be locked before calling this method. * * @param masterBlockInfo the {@link MasterBlockInfo} * @return a {@link BlockInfo} from a {@link MasterBlockInfo}. Populates worker locations */ private BlockInfo generateBlockInfo(MasterBlockInfo masterBlockInfo) { // "Join" to get all the addresses of the workers. List<BlockLocation> locations = new ArrayList<BlockLocation>(); for (MasterBlockLocation masterBlockLocation : masterBlockInfo.getBlockLocations()) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, masterBlockLocation.getWorkerId()); if (workerInfo != null) { locations.add(new BlockLocation(masterBlockLocation.getWorkerId(), workerInfo.getAddress(), masterBlockLocation.getTier())); } } return new BlockInfo(masterBlockInfo.getBlockId(), masterBlockInfo.getLength(), locations); } /** * Reports the ids of the blocks lost on workers. * * @param blockIds the ids of the lost blocks */ public void reportLostBlocks(List<Long> blockIds) { synchronized (mLostBlocks) { mLostBlocks.addAll(blockIds); } } /** * Lost worker periodic check. */ public final class LostWorkerDetectionHeartbeatExecutor implements HeartbeatExecutor { @Override public void heartbeat() { LOG.debug("System status checking."); TachyonConf conf = MasterContext.getConf(); int masterWorkerTimeoutMs = conf.getInt(Constants.MASTER_WORKER_TIMEOUT_MS); synchronized (mWorkers) { Iterator<MasterWorkerInfo> iter = mWorkers.iterator(); while (iter.hasNext()) { MasterWorkerInfo worker = iter.next(); if (CommonUtils.getCurrentMs() - worker.getLastUpdatedTimeMs() > masterWorkerTimeoutMs) { LOG.error("The worker " + worker + " got timed out!"); mLostWorkers.add(worker); iter.remove(); } } } } } class PrivateAccess { private PrivateAccess() {} /** * @param worker a {@link MasterWorkerInfo} to add to the list of lost workers */ public void addLostWorker(MasterWorkerInfo worker) { synchronized (mWorkers) { mLostWorkers.add(worker); } } /** * Looks up the {@link MasterWorkerInfo} for a given worker ID. * * @param workerId the worker ID to look up * @return the {@link MasterWorkerInfo} for the given workerId */ public MasterWorkerInfo getWorkerById(long workerId) { synchronized (mWorkers) { return mWorkers.getFirstByField(mIdIndex, workerId); } } /** * Looks up the {@link MasterBlockInfo} for the given block ID. * * @param blockId the block ID * @return the {@link MasterBlockInfo} */ public MasterBlockInfo getMasterBlockInfo(long blockId) { synchronized (mBlocks) { return mBlocks.get(blockId); } } } /** Grants access to private members to testers of this class. */ @Override public void grantAccess(Tester<BlockMaster> tester) { tester.receiveAccess(new PrivateAccess()); } }
Fixed lost worker blocks detection
servers/src/main/java/tachyon/master/block/BlockMaster.java
Fixed lost worker blocks detection
Java
apache-2.0
455f012172efe6d39bf395177edbe905c103a89c
0
googleinterns/step136-2020,googleinterns/step136-2020,googleinterns/step136-2020
package com.google.sps.servlets; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.sps.data.User; import com.google.sps.util.FormHelper; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet responsible for creating new recipes. */ @WebServlet("/new-recipe") public class NewRecipeServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // get responses from form String name = request.getParameter("name").trim(); String tagsResponse = request.getParameter("tags").trim(); String description = request.getParameter("description").trim(); String ingredientsResponse = request.getParameter("ingredients").trim(); String stepsResponse = request.getParameter("steps").trim(); String privacy = request.getParameter("privacy"); String idToken = request.getParameter("idToken"); // prevents empty responses as being saved in datastore and redirects user back to UserPage // TODO: inform the user that they're missing stuff if (name.equals("") || tagsResponse.equals("") || description.equals("") || ingredientsResponse.equals("") || stepsResponse.equals("")) { response.sendRedirect("/pages/UserPage.jsp"); return; } // splits the String responses from the form into lists List<String> tags = FormHelper.separateByCommas(tagsResponse); List<String> ingredients = FormHelper.separateByNewlines(ingredientsResponse); List<String> steps = FormHelper.separateByNewlines(stepsResponse); User user = new User(idToken); Entity recipeEntity = new Entity("Recipe"); recipeEntity.setProperty("name", name); recipeEntity.setProperty("tags", tags); recipeEntity.setProperty("description", description); recipeEntity.setProperty("ingredients", ingredients); recipeEntity.setProperty("steps", steps); recipeEntity.setProperty("authorID", user.getId()); recipeEntity.setProperty("popularity", 0); recipeEntity.setProperty("published", false); // user has chosen to publish their recipe if (privacy.equals("public")) { recipeEntity.setProperty("published", true); } // getUploads returns a set of blobs that have been uploaded // the Map object is a list that associates the names of the upload fields to the blobs they contained BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request); List<BlobKey> blobKeys = blobs.get("image"); // user submitted form without selecting a file, so we can't get a URL. (dev server) // redirects user back to UserPage if (blobKeys == null || blobKeys.isEmpty()) { response.sendRedirect("/pages/UserPage.jsp"); return; } else { BlobKey blobkey = blobKeys.get(0); BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobkey); // user submitted form without selecting a file, so we can't get a URL. (dev server) // redirects user back to UserPage if (blobInfo.getSize() == 0) { blobstoreService.delete(blobkey); response.sendRedirect("/pages/UserPage.jsp"); return; } else { recipeEntity.setProperty("imageBlobKey", blobkey.getKeyString()); } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(recipeEntity); response.sendRedirect("/pages/UserPage.jsp"); } }
src/main/java/com/google/sps/servlets/NewRecipeServlet.java
package com.google.sps.servlets; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.sps.data.User; import com.google.sps.util.FormHelper; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet responsible for creating new recipes. */ @WebServlet("/new-recipe") public class NewRecipeServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // get responses from form String name = request.getParameter("name").trim(); String tagsResponse = request.getParameter("tags").trim(); String description = request.getParameter("description").trim(); String ingredientsResponse = request.getParameter("ingredients").trim(); String stepsResponse = request.getParameter("steps").trim(); String privacy = request.getParameter("privacy"); String idToken = request.getParameter("idToken"); // prevents empty responses as being saved in datastore and redirects user back to UserPage // TODO: inform the user that they're missing stuff if (name.equals("") || tagsResponse.equals("") || description.equals("") || ingredientsResponse.equals("") || stepsResponse.equals("")) { response.sendRedirect("/pages/UserPage.jsp"); return; } // splits the String responses from the form into lists List<String> tags = FormHelper.separateByCommas(tagsResponse); List<String> ingredients = FormHelper.separateByNewlines(ingredientsResponse); List<String> steps = FormHelper.separateByNewlines(stepsResponse); User user = new User(idToken); Entity recipeEntity = new Entity("Recipe"); recipeEntity.setProperty("name", name); recipeEntity.setProperty("tags", tags); recipeEntity.setProperty("description", description); recipeEntity.setProperty("ingredients", ingredients); recipeEntity.setProperty("steps", steps); recipeEntity.setProperty("authorID", user.getId()); recipeEntity.setProperty("popularity", 0); recipeEntity.setProperty("published", false); recipeEntity.setProperty("popularity", 0); // user has chosen to publish their recipe if (privacy.equals("public")) { recipeEntity.setProperty("published", true); } // getUploads returns a set of blobs that have been uploaded // the Map object is a list that associates the names of the upload fields to the blobs they contained BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request); List<BlobKey> blobKeys = blobs.get("image"); // user submitted form without selecting a file, so we can't get a URL. (dev server) // redirects user back to UserPage if (blobKeys == null || blobKeys.isEmpty()) { response.sendRedirect("/pages/UserPage.jsp"); return; } else { BlobKey blobkey = blobKeys.get(0); BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobkey); // user submitted form without selecting a file, so we can't get a URL. (dev server) // redirects user back to UserPage if (blobInfo.getSize() == 0) { blobstoreService.delete(blobkey); response.sendRedirect("/pages/UserPage.jsp"); return; } else { recipeEntity.setProperty("imageBlobKey", blobkey.getKeyString()); } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(recipeEntity); response.sendRedirect("/pages/UserPage.jsp"); } }
Update NewRecipeServlet.java
src/main/java/com/google/sps/servlets/NewRecipeServlet.java
Update NewRecipeServlet.java
Java
apache-2.0
b876bd8cec3d6f403a577e0094e992b8ab0a9687
0
kiril-me/netty,bob329/netty,mubarak/netty,ejona86/netty,cnoldtree/netty,danbev/netty,qingsong-xu/netty,codevelop/netty,doom369/netty,mosoft521/netty,maliqq/netty,liuciuse/netty,shenguoquan/netty,Apache9/netty,moyiguket/netty,yipen9/netty,eincs/netty,Kingson4Wu/netty,mway08/netty,NiteshKant/netty,AchinthaReemal/netty,golovnin/netty,balaprasanna/netty,johnou/netty,ninja-/netty,nadeeshaan/netty,woshilaiceshide/netty,blucas/netty,yonglehou/netty-1,sverkera/netty,youprofit/netty,wangyikai/netty,mcobrien/netty,zhoffice/netty,jongyeol/netty,huuthang1993/netty,WangJunTYTL/netty,bob329/netty,chrisprobst/netty,sunbeansoft/netty,lukehutch/netty,louxiu/netty,tbrooks8/netty,maliqq/netty,Scottmitch/netty,joansmith/netty,Scottmitch/netty,satishsaley/netty,niuxinghua/netty,ifesdjeen/netty,KatsuraKKKK/netty,skyao/netty,duqiao/netty,nadeeshaan/netty,wuyinxian124/netty,purplefox/netty-4.0.2.8-hacked,jchambers/netty,Spikhalskiy/netty,brennangaunce/netty,zhujingling/netty,buchgr/netty,kyle-liu/netty4study,ngocdaothanh/netty,louiscryan/netty,KatsuraKKKK/netty,zer0se7en/netty,serioussam/netty,gerdriesselmann/netty,seetharamireddy540/netty,AchinthaReemal/netty,mcobrien/netty,duqiao/netty,NiteshKant/netty,afredlyj/learn-netty,carlbai/netty,menacher/netty,wangyikai/netty,louiscryan/netty,afredlyj/learn-netty,nayato/netty,ajaysarda/netty,xiexingguang/netty,zzcclp/netty,Kingson4Wu/netty,cnoldtree/netty,x1957/netty,yipen9/netty,mubarak/netty,normanmaurer/netty,gerdriesselmann/netty,xiongzheng/netty,liuciuse/netty,junjiemars/netty,lukehutch/netty,skyao/netty,DolphinZhao/netty,bob329/netty,lznhust/netty,liuciuse/netty,zxhfirefox/netty,ejona86/netty,blademainer/netty,jenskordowski/netty,mikkokar/netty,jroper/netty,danbev/netty,zhoffice/netty,gigold/netty,timboudreau/netty,dongjiaqiang/netty,danny200309/netty,afredlyj/learn-netty,skyao/netty,louiscryan/netty,ngocdaothanh/netty,mway08/netty,hgl888/netty,idelpivnitskiy/netty,imangry/netty-zh,nat2013/netty,fengjiachun/netty,jdivy/netty,LuminateWireless/netty,clebertsuconic/netty,DolphinZhao/netty,mx657649013/netty,eonezhang/netty,normanmaurer/netty,zer0se7en/netty,cnoldtree/netty,ninja-/netty,AnselQiao/netty,djchen/netty,caoyanwei/netty,x1957/netty,DavidAlphaFox/netty,zxhfirefox/netty,LuminateWireless/netty,nadeeshaan/netty,yrcourage/netty,MediumOne/netty,xingguang2013/netty,Alwayswithme/netty,alkemist/netty,normanmaurer/netty,MediumOne/netty,alkemist/netty,f7753/netty,fengjiachun/netty,hgl888/netty,ngocdaothanh/netty,lukw00/netty,lukehutch/netty,kiril-me/netty,jchambers/netty,NiteshKant/netty,carl-mastrangelo/netty,AnselQiao/netty,x1957/netty,fantayeneh/netty,djchen/netty,yawkat/netty,mikkokar/netty,kjniemi/netty,skyao/netty,chinayin/netty,idelpivnitskiy/netty,yawkat/netty,lznhust/netty,DolphinZhao/netty,timboudreau/netty,lukw00/netty,clebertsuconic/netty,sja/netty,nmittler/netty,sverkera/netty,fantayeneh/netty,Spikhalskiy/netty,woshilaiceshide/netty,f7753/netty,shism/netty,WangJunTYTL/netty,satishsaley/netty,fengshao0907/netty,hepin1989/netty,eonezhang/netty,CodingFabian/netty,andsel/netty,lukw00/netty,yonglehou/netty-1,JungMinu/netty,mway08/netty,xiongzheng/netty,eonezhang/netty,bigheary/netty,fengshao0907/netty,lznhust/netty,duqiao/netty,WangJunTYTL/netty,mx657649013/netty,olupotd/netty,ninja-/netty,yawkat/netty,ninja-/netty,johnou/netty,ifesdjeen/netty,BrunoColin/netty,lukehutch/netty,qingsong-xu/netty,clebertsuconic/netty,hyangtack/netty,huanyi0723/netty,xiongzheng/netty,niuxinghua/netty,Techcable/netty,blademainer/netty,nkhuyu/netty,blucas/netty,KeyNexus/netty,zhujingling/netty,unei66/netty,alkemist/netty,fengjiachun/netty,carlbai/netty,hgl888/netty,DolphinZhao/netty,ijuma/netty,brennangaunce/netty,firebase/netty,altihou/netty,lugt/netty,bryce-anderson/netty,lukw00/netty,chrisprobst/netty,chanakaudaya/netty,WangJunTYTL/netty,doom369/netty,Techcable/netty,clebertsuconic/netty,kvr000/netty,seetharamireddy540/netty,bryce-anderson/netty,fenik17/netty,seetharamireddy540/netty,woshilaiceshide/netty,x1957/netty,woshilaiceshide/netty,firebase/netty,mway08/netty,andsel/netty,woshilaiceshide/netty,joansmith/netty,altihou/netty,ichaki5748/netty,Kingson4Wu/netty,chinayin/netty,gigold/netty,yrcourage/netty,castomer/netty,zer0se7en/netty,sja/netty,liyang1025/netty,yrcourage/netty,mikkokar/netty,sunbeansoft/netty,codevelop/netty,mcobrien/netty,cnoldtree/netty,djchen/netty,f7753/netty,ijuma/netty,phlizik/netty,ejona86/netty,wangyikai/netty,imangry/netty-zh,johnou/netty,serioussam/netty,yawkat/netty,hepin1989/netty,ajaysarda/netty,Squarespace/netty,caoyanwei/netty,mx657649013/netty,zhoffice/netty,hepin1989/netty,moyiguket/netty,codevelop/netty,lznhust/netty,drowning/netty,ajaysarda/netty,orika/netty,BrunoColin/netty,mubarak/netty,Mounika-Chirukuri/netty,Kalvar/netty,mcanthony/netty,louiscryan/netty,ngocdaothanh/netty,NiteshKant/netty,satishsaley/netty,bigheary/netty,idelpivnitskiy/netty,Kalvar/netty,rovarga/netty,mikkokar/netty,seetharamireddy540/netty,yrcourage/netty,chinayin/netty,yipen9/netty,AchinthaReemal/netty,mosoft521/netty,menacher/netty,rovarga/netty,yrcourage/netty,hgl888/netty,shism/netty,zhujingling/netty,DavidAlphaFox/netty,phlizik/netty,jenskordowski/netty,exinguu/netty,jovezhougang/netty,Apache9/netty,rovarga/netty,serioussam/netty,KatsuraKKKK/netty,junjiemars/netty,MediumOne/netty,balaprasanna/netty,brennangaunce/netty,sameira/netty,johnou/netty,mcanthony/netty,timboudreau/netty,bob329/netty,ichaki5748/netty,sammychen105/netty,wuxiaowei907/netty,yonglehou/netty-1,fengjiachun/netty,ejona86/netty,nadeeshaan/netty,mcanthony/netty,kiril-me/netty,djchen/netty,kiril-me/netty,tbrooks8/netty,shelsonjava/netty,shenguoquan/netty,BrunoColin/netty,Techcable/netty,sja/netty,daschl/netty,brennangaunce/netty,shelsonjava/netty,maliqq/netty,mcobrien/netty,huuthang1993/netty,silvaran/netty,LuminateWireless/netty,MediumOne/netty,aperepel/netty,junjiemars/netty,zxhfirefox/netty,s-gheldd/netty,wuxiaowei907/netty,shuangqiuan/netty,ijuma/netty,CodingFabian/netty,LuminateWireless/netty,sunbeansoft/netty,orika/netty,lightsocks/netty,chrisprobst/netty,sameira/netty,kjniemi/netty,wuxiaowei907/netty,jchambers/netty,nayato/netty,sverkera/netty,nayato/netty,lightsocks/netty,eincs/netty,orika/netty,carlbai/netty,wuxiaowei907/netty,gerdriesselmann/netty,liuciuse/netty,carlbai/netty,SinaTadayon/netty,yonglehou/netty-1,dongjiaqiang/netty,ioanbsu/netty,jovezhougang/netty,louxiu/netty,nat2013/netty,gigold/netty,shuangqiuan/netty,BrunoColin/netty,unei66/netty,huanyi0723/netty,ajaysarda/netty,Mounika-Chirukuri/netty,caoyanwei/netty,xingguang2013/netty,luyiisme/netty,zxhfirefox/netty,IBYoung/netty,jdivy/netty,jovezhougang/netty,andsel/netty,huanyi0723/netty,maliqq/netty,yonglehou/netty-1,tbrooks8/netty,carl-mastrangelo/netty,liyang1025/netty,Techcable/netty,youprofit/netty,wangyikai/netty,drowning/netty,smayoorans/netty,xiexingguang/netty,Apache9/netty,zzcclp/netty,develar/netty,silvaran/netty,JungMinu/netty,silvaran/netty,doom369/netty,fengshao0907/netty,olupotd/netty,lightsocks/netty,nat2013/netty,kjniemi/netty,Squarespace/netty,jchambers/netty,firebase/netty,purplefox/netty-4.0.2.8-hacked,MediumOne/netty,tempbottle/netty,ngocdaothanh/netty,shelsonjava/netty,slandelle/netty,KatsuraKKKK/netty,CodingFabian/netty,drowning/netty,silvaran/netty,wuyinxian124/netty,slandelle/netty,lukw00/netty,johnou/netty,shenguoquan/netty,AnselQiao/netty,afds/netty,jovezhougang/netty,eincs/netty,Alwayswithme/netty,chrisprobst/netty,golovnin/netty,Alwayswithme/netty,smayoorans/netty,SinaTadayon/netty,netty/netty,tempbottle/netty,artgon/netty,skyao/netty,sverkera/netty,huuthang1993/netty,shism/netty,duqiao/netty,tempbottle/netty,buchgr/netty,chanakaudaya/netty,idelpivnitskiy/netty,Mounika-Chirukuri/netty,blucas/netty,afds/netty,yawkat/netty,kyle-liu/netty4study,unei66/netty,buchgr/netty,zhujingling/netty,Kalvar/netty,idelpivnitskiy/netty,altihou/netty,orika/netty,kiril-me/netty,sja/netty,gigold/netty,jenskordowski/netty,lugt/netty,pengzj/netty,ioanbsu/netty,jongyeol/netty,DavidAlphaFox/netty,wangyikai/netty,andsel/netty,eonezhang/netty,Alwayswithme/netty,mcanthony/netty,nkhuyu/netty,unei66/netty,windie/netty,imangry/netty-zh,zzcclp/netty,ajaysarda/netty,buchgr/netty,danbev/netty,danbev/netty,carlbai/netty,jdivy/netty,doom369/netty,fantayeneh/netty,blademainer/netty,Alwayswithme/netty,ijuma/netty,kjniemi/netty,AchinthaReemal/netty,ioanbsu/netty,danny200309/netty,exinguu/netty,luyiisme/netty,lugt/netty,Apache9/netty,eincs/netty,KeyNexus/netty,afds/netty,nkhuyu/netty,daschl/netty,ichaki5748/netty,unei66/netty,Squarespace/netty,codevelop/netty,bob329/netty,doom369/netty,hyangtack/netty,mcobrien/netty,xiongzheng/netty,liuciuse/netty,olupotd/netty,fengjiachun/netty,huanyi0723/netty,eincs/netty,zzcclp/netty,gerdriesselmann/netty,kvr000/netty,nayato/netty,CodingFabian/netty,zhoffice/netty,louxiu/netty,DavidAlphaFox/netty,youprofit/netty,castomer/netty,SinaTadayon/netty,exinguu/netty,gerdriesselmann/netty,s-gheldd/netty,zhoffice/netty,ichaki5748/netty,smayoorans/netty,huuthang1993/netty,jongyeol/netty,andsel/netty,djchen/netty,jenskordowski/netty,mosoft521/netty,jdivy/netty,xiexingguang/netty,orika/netty,nadeeshaan/netty,blucas/netty,blucas/netty,nkhuyu/netty,Apache9/netty,exinguu/netty,artgon/netty,fantayeneh/netty,cnoldtree/netty,netty/netty,mway08/netty,shuangqiuan/netty,windie/netty,netty/netty,castomer/netty,artgon/netty,bryce-anderson/netty,serioussam/netty,KatsuraKKKK/netty,phlizik/netty,fenik17/netty,zxhfirefox/netty,ioanbsu/netty,joansmith/netty,silvaran/netty,SinaTadayon/netty,castomer/netty,netty/netty,tbrooks8/netty,clebertsuconic/netty,LuminateWireless/netty,danny200309/netty,AnselQiao/netty,kvr000/netty,shelsonjava/netty,nmittler/netty,carl-mastrangelo/netty,DolphinZhao/netty,mcanthony/netty,balaprasanna/netty,shenguoquan/netty,artgon/netty,hepin1989/netty,pengzj/netty,Kingson4Wu/netty,alkemist/netty,qingsong-xu/netty,fenik17/netty,sammychen105/netty,carl-mastrangelo/netty,chrisprobst/netty,bigheary/netty,olupotd/netty,windie/netty,phlizik/netty,danbev/netty,bigheary/netty,lukehutch/netty,fenik17/netty,normanmaurer/netty,nmittler/netty,wuyinxian124/netty,slandelle/netty,liyang1025/netty,mx657649013/netty,sammychen105/netty,sunbeansoft/netty,lugt/netty,imangry/netty-zh,Techcable/netty,sja/netty,satishsaley/netty,moyiguket/netty,chanakaudaya/netty,zer0se7en/netty,dongjiaqiang/netty,f7753/netty,mosoft521/netty,smayoorans/netty,carl-mastrangelo/netty,s-gheldd/netty,hyangtack/netty,Scottmitch/netty,satishsaley/netty,Spikhalskiy/netty,Kalvar/netty,AchinthaReemal/netty,bigheary/netty,wuyinxian124/netty,luyiisme/netty,s-gheldd/netty,blademainer/netty,brennangaunce/netty,golovnin/netty,duqiao/netty,WangJunTYTL/netty,tempbottle/netty,ninja-/netty,imangry/netty-zh,liyang1025/netty,balaprasanna/netty,liyang1025/netty,IBYoung/netty,f7753/netty,Mounika-Chirukuri/netty,BrunoColin/netty,IBYoung/netty,qingsong-xu/netty,caoyanwei/netty,Spikhalskiy/netty,yipen9/netty,drowning/netty,ichaki5748/netty,mosoft521/netty,xingguang2013/netty,luyiisme/netty,afds/netty,lightsocks/netty,niuxinghua/netty,daschl/netty,xiongzheng/netty,louiscryan/netty,NiteshKant/netty,chinayin/netty,JungMinu/netty,s-gheldd/netty,rovarga/netty,blademainer/netty,jongyeol/netty,timboudreau/netty,smayoorans/netty,jchambers/netty,afds/netty,seetharamireddy540/netty,castomer/netty,jdivy/netty,Scottmitch/netty,wuxiaowei907/netty,CliffYuan/netty,xingguang2013/netty,hyangtack/netty,louxiu/netty,lznhust/netty,joansmith/netty,olupotd/netty,IBYoung/netty,niuxinghua/netty,kvr000/netty,joansmith/netty,normanmaurer/netty,moyiguket/netty,mx657649013/netty,shelsonjava/netty,balaprasanna/netty,artgon/netty,slandelle/netty,golovnin/netty,x1957/netty,chinayin/netty,junjiemars/netty,youprofit/netty,lugt/netty,chanakaudaya/netty,mubarak/netty,shuangqiuan/netty,ijuma/netty,sameira/netty,huuthang1993/netty,qingsong-xu/netty,Squarespace/netty,SinaTadayon/netty,CliffYuan/netty,netty/netty,exinguu/netty,eonezhang/netty,golovnin/netty,Scottmitch/netty,chanakaudaya/netty,zzcclp/netty,jenskordowski/netty,danny200309/netty,sunbeansoft/netty,ejona86/netty,youprofit/netty,caoyanwei/netty,altihou/netty,hgl888/netty,nkhuyu/netty,fantayeneh/netty,alkemist/netty,lightsocks/netty,louxiu/netty,IBYoung/netty,Mounika-Chirukuri/netty,Spikhalskiy/netty,zhujingling/netty,zer0se7en/netty,pengzj/netty,nayato/netty,ioanbsu/netty,mikkokar/netty,kvr000/netty,luyiisme/netty,AnselQiao/netty,Kalvar/netty,tbrooks8/netty,fenik17/netty,serioussam/netty,junjiemars/netty,niuxinghua/netty,Kingson4Wu/netty,shuangqiuan/netty,tempbottle/netty,JungMinu/netty,sameira/netty,xingguang2013/netty,shenguoquan/netty,dongjiaqiang/netty,dongjiaqiang/netty,sverkera/netty,windie/netty,firebase/netty,danny200309/netty,CodingFabian/netty,huanyi0723/netty,xiexingguang/netty,windie/netty,altihou/netty,kjniemi/netty,gigold/netty,timboudreau/netty,bryce-anderson/netty,shism/netty,jovezhougang/netty,mubarak/netty,moyiguket/netty,jongyeol/netty,xiexingguang/netty,Squarespace/netty,pengzj/netty,purplefox/netty-4.0.2.8-hacked,bryce-anderson/netty,maliqq/netty,sameira/netty,shism/netty,develar/netty,purplefox/netty-4.0.2.8-hacked
/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util; import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; /** * An unbounded {@linkplain BlockingQueue} based on linked nodes. * This queue orders elements FIFO (first-in-first-out) with respect * to any given producer. The <em>head</em> of the queue is that * element that has been on the queue the longest time for some * producer. The <em>tail</em> of the queue is that element that has * been on the queue the shortest time for some producer. * * <p>Beware that, unlike in most collections, the <tt>size</tt> * method is <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current number * of elements requires a traversal of the elements. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code LinkedTransferQueue} <i>happen-before</i> actions subsequent * to the access or removal of that element from the * {@code LinkedTransferQueue} in another thread. * * @author Doug Lea * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @param <E> the type of elements held in this collection * */ public class LinkedTransferQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { /* * This is still a work in progress... * * This class extends the approach used in FIFO-mode * SynchronousQueues. See the internal documentation, as well as * the PPoPP 2006 paper "Scalable Synchronous Queues" by Scherer, * Lea & Scott * (http://www.cs.rice.edu/~wns1/papers/2006-PPoPP-SQ.pdf) * * The main extension is to provide different Wait modes * for the main "xfer" method that puts or takes items. * These don't impact the basic dual-queue logic, but instead * control whether or how threads block upon insertion * of request or data nodes into the dual queue. */ // Wait modes for xfer method private static final int NOWAIT = 0; private static final int TIMEOUT = 1; private static final int WAIT = 2; /** The number of CPUs, for spin control */ private static final int NCPUS = Runtime.getRuntime().availableProcessors(); private static final QNode UNDEFINED = new QNode(null, false); /** * The number of times to spin before blocking in timed waits. * The value is empirically derived -- it works well across a * variety of processors and OSes. Empirically, the best value * seems not to vary with number of CPUs (beyond 2) so is just * a constant. */ private static final int maxTimedSpins = NCPUS < 2? 0 : 32; /** * The number of times to spin before blocking in untimed waits. * This is greater than timed value because untimed waits spin * faster since they don't need to check times on each spin. */ private static final int maxUntimedSpins = maxTimedSpins * 16; /** * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices. */ private static final long spinForTimeoutThreshold = 1000L; /** * Node class for LinkedTransferQueue. Opportunistically subclasses from * AtomicReference to represent item. Uses Object, not E, to allow * setting item to "this" after use, to avoid garbage * retention. Similarly, setting the next field to this is used as * sentinel that node is off list. */ private static final class QNode extends AtomicReference<Object> { private static final long serialVersionUID = 5925596372370723938L; volatile QNode next; transient volatile Thread waiter; // to control park/unpark final boolean isData; QNode(Object item, boolean isData) { super(item); this.isData = isData; } private static final AtomicReferenceFieldUpdater<QNode, QNode> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (QNode.class, QNode.class, "next"); boolean casNext(QNode cmp, QNode val) { return nextUpdater.compareAndSet(this, cmp, val); } } /** * Padded version of AtomicReference used for head, tail and * cleanMe, to alleviate contention across threads CASing one vs * the other. */ private static final class PaddedAtomicReference<T> extends AtomicReference<T> { private static final long serialVersionUID = 4684288940772921317L; // enough padding for 64bytes with 4byte refs Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe; PaddedAtomicReference(T r) { super(r); } } /** head of the queue */ private final PaddedAtomicReference<QNode> head; /** tail of the queue */ private final PaddedAtomicReference<QNode> tail; /** * Reference to a cancelled node that might not yet have been * unlinked from queue because it was the last inserted node * when it cancelled. */ private final PaddedAtomicReference<QNode> cleanMe; /** * Tries to cas nh as new head; if successful, unlink * old head's next node to avoid garbage retention. */ private boolean advanceHead(QNode h, QNode nh) { if (h == head.get() && head.compareAndSet(h, nh)) { h.next = h; // forget old next return true; } return false; } /** * Puts or takes an item. Used for most queue operations (except * poll() and tryTransfer()) * @param e the item or if null, signifies that this is a take * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT * @param nanos timeout in nanosecs, used only if mode is TIMEOUT * @return an item, or null on failure */ private Object xfer(Object e, int mode, long nanos) { boolean isData = e != null; QNode s = null; final AtomicReference<QNode> head = this.head; final AtomicReference<QNode> tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { if (s == null) { s = new QNode(e, isData); } QNode last = t.next; if (last != null) { if (t == tail.get()) { tail.compareAndSet(t, last); } } else if (t.casNext(null, s)) { tail.compareAndSet(t, s); return awaitFulfill(t, s, e, mode, nanos); } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Version of xfer for poll() and tryTransfer, which * simplifies control paths both here and in xfer */ private Object fulfill(Object e) { boolean isData = e != null; final AtomicReference<QNode> head = this.head; final AtomicReference<QNode> tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { QNode last = t.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else { return null; } } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Spins/blocks until node s is fulfilled or caller gives up, * depending on wait mode. * * @param pred the predecessor of waiting node * @param s the waiting node * @param e the comparison value for checking match * @param mode mode * @param nanos timeout value * @return matched item, or s if cancelled */ private Object awaitFulfill(QNode pred, QNode s, Object e, int mode, long nanos) { if (mode == NOWAIT) { return null; } long lastTime = mode == TIMEOUT? System.nanoTime() : 0; Thread w = Thread.currentThread(); int spins = -1; // set to desired spin count below for (;;) { if (w.isInterrupted()) { s.compareAndSet(e, s); } Object x = s.get(); if (x != e) { // Node was matched or cancelled advanceHead(pred, s); // unlink if head if (x == s) { return clean(pred, s); } else if (x != null) { s.set(s); // avoid garbage retention return x; } else { return e; } } if (mode == TIMEOUT) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.compareAndSet(e, s); // try to cancel continue; } } if (spins < 0) { QNode h = head.get(); // only spin if at head spins = h != null && h.next == s ? (mode == TIMEOUT? maxTimedSpins : maxUntimedSpins) : 0; } if (spins > 0) { --spins; } else if (s.waiter == null) { s.waiter = w; } else if (mode != TIMEOUT) { // LockSupport.park(this); LockSupport.park(); // allows run on java5 s.waiter = null; spins = -1; } else if (nanos > spinForTimeoutThreshold) { // LockSupport.parkNanos(this, nanos); LockSupport.parkNanos(nanos); s.waiter = null; spins = -1; } } } /** * Gets rid of cancelled node s with original predecessor pred. * @return null (to simplify use by callers) */ Object clean(final QNode pred, final QNode s) { Thread w = s.waiter; if (w != null) { // Wake up thread s.waiter = null; if (w != Thread.currentThread()) { LockSupport.unpark(w); } } QNode olddp = UNDEFINED; for (;;) { if (pred.next != s) { return null; } QNode h = head.get(); QNode hn = h.next; // Absorb cancelled first node as head if (hn != null && hn.next == hn) { advanceHead(h, hn); continue; } QNode t = tail.get(); // Ensure consistent read for tail if (t == h) { return null; } QNode tn = t.next; if (t != tail.get()) { continue; } if (tn != null) { // Help advance tail tail.compareAndSet(t, tn); continue; } if (s != t) { // If not tail, try to unsplice QNode sn = s.next; if (sn == s || pred.casNext(s, sn)) { return null; } } boolean stateUnchanged = true; QNode dp = cleanMe.get(); if (dp != null) { // Try unlinking previous cancelled node QNode d = dp.next; QNode dn; if (d == null || // d is gone or d == dp || // d is off list or d.get() != d || // d not cancelled or d != t && // d not tail and (dn = d.next) != null && // has successor dn != d && // that is on list dp.casNext(d, dn)) { cleanMe.compareAndSet(dp, null); stateUnchanged = false; } if (dp == pred) { return null; // s is already saved node } if (stateUnchanged && olddp == dp) { return null; // infinite loop expected - bail out } else { olddp = dp; } } else if (cleanMe.compareAndSet(null, pred)) { return null; // Postpone cleaning s } } } /** * Creates an initially empty <tt>LinkedTransferQueue</tt>. */ public LinkedTransferQueue() { QNode dummy = new QNode(null, false); head = new PaddedAtomicReference<QNode>(dummy); tail = new PaddedAtomicReference<QNode>(dummy); cleanMe = new PaddedAtomicReference<QNode>(null); } /** * Creates a <tt>LinkedTransferQueue</tt> * initially containing the elements of the given collection, * added in traversal order of the collection's iterator. * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedTransferQueue(Collection<? extends E> c) { this(); addAll(c); } public void put(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); } public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); return true; } public boolean offer(E e) { if (e == null) { throw new NullPointerException(); } xfer(e, NOWAIT, 0); return true; } public void transfer(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, WAIT, 0) == null) { Thread.interrupted(); throw new InterruptedException(); } } public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null) { return true; } if (!Thread.interrupted()) { return false; } throw new InterruptedException(); } public boolean tryTransfer(E e) { if (e == null) { throw new NullPointerException(); } return fulfill(e) != null; } public E take() throws InterruptedException { Object e = xfer(null, WAIT, 0); if (e != null) { return cast(e); } Thread.interrupted(); throw new InterruptedException(); } @SuppressWarnings("unchecked") E cast(Object e) { return (E) e; } public E poll(long timeout, TimeUnit unit) throws InterruptedException { Object e = xfer(null, TIMEOUT, unit.toNanos(timeout)); if (e != null || !Thread.interrupted()) { return cast(e); } throw new InterruptedException(); } public E poll() { return cast(fulfill(null)); } public int drainTo(Collection<? super E> c) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while ( (e = poll()) != null) { c.add(e); ++n; } return n; } public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while (n < maxElements && (e = poll()) != null) { c.add(e); ++n; } return n; } // Traversal-based methods /** * Return head after performing any outstanding helping steps */ QNode traversalHead() { for (;;) { QNode t = tail.get(); QNode h = head.get(); if (h != null && t != null) { QNode last = t.next; QNode first = h.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else if (first != null) { Object x = first.get(); if (x == first) { advanceHead(h, first); } else { return h; } } else { return h; } } } } } @Override public Iterator<E> iterator() { return new Itr(); } /** * Iterators. Basic strategy is to traverse list, treating * non-data (i.e., request) nodes as terminating list. * Once a valid data node is found, the item is cached * so that the next call to next() will return it even * if subsequently removed. */ private class Itr implements Iterator<E> { private QNode nextNode; // Next node to return next private QNode currentNode; // last returned node, for remove() private QNode prevNode; // predecessor of last returned node private E nextItem; // Cache of next item, once commited to in next Itr() { nextNode = traversalHead(); advance(); } private E advance() { prevNode = currentNode; currentNode = nextNode; E x = nextItem; QNode p = nextNode.next; for (;;) { if (p == null || !p.isData) { nextNode = null; nextItem = null; return x; } Object item = p.get(); if (item != p && item != null) { nextNode = p; nextItem = cast(item); return x; } prevNode = p; p = p.next; } } public boolean hasNext() { return nextNode != null; } public E next() { if (nextNode == null) { throw new NoSuchElementException(); } return advance(); } public void remove() { QNode p = currentNode; QNode prev = prevNode; if (prev == null || p == null) { throw new IllegalStateException(); } Object x = p.get(); if (x != null && x != p && p.compareAndSet(x, p)) { clean(prev, p); } } } public E peek() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return null; } Object x = p.get(); if (p != x) { if (!p.isData) { return null; } if (x != null) { return cast(x); } } } } @Override public boolean isEmpty() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return true; } Object x = p.get(); if (p != x) { if (!p.isData) { return true; } if (x != null) { return false; } } } } public boolean hasWaitingConsumer() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return false; } Object x = p.get(); if (p != x) { return !p.isData; } } } /** * Returns the number of elements in this queue. If this queue * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current * number of elements requires an O(n) traversal. * * @return the number of elements in this queue */ @Override public int size() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && p.isData; p = p.next) { Object x = p.get(); if (x != null && x != p) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int getWaitingConsumerCount() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && !p.isData; p = p.next) { if (p.get() == null) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int remainingCapacity() { return Integer.MAX_VALUE; } }
src/main/java/org/jboss/netty/util/LinkedTransferQueue.java
/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util; import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; /** * An unbounded {@linkplain BlockingQueue} based on linked nodes. * This queue orders elements FIFO (first-in-first-out) with respect * to any given producer. The <em>head</em> of the queue is that * element that has been on the queue the longest time for some * producer. The <em>tail</em> of the queue is that element that has * been on the queue the shortest time for some producer. * * <p>Beware that, unlike in most collections, the <tt>size</tt> * method is <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current number * of elements requires a traversal of the elements. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code LinkedTransferQueue} <i>happen-before</i> actions subsequent * to the access or removal of that element from the * {@code LinkedTransferQueue} in another thread. * * @author Doug Lea * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @param <E> the type of elements held in this collection * */ public class LinkedTransferQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { /* * This is still a work in progress... * * This class extends the approach used in FIFO-mode * SynchronousQueues. See the internal documentation, as well as * the PPoPP 2006 paper "Scalable Synchronous Queues" by Scherer, * Lea & Scott * (http://www.cs.rice.edu/~wns1/papers/2006-PPoPP-SQ.pdf) * * The main extension is to provide different Wait modes * for the main "xfer" method that puts or takes items. * These don't impact the basic dual-queue logic, but instead * control whether or how threads block upon insertion * of request or data nodes into the dual queue. */ // Wait modes for xfer method private static final int NOWAIT = 0; private static final int TIMEOUT = 1; private static final int WAIT = 2; /** The number of CPUs, for spin control */ private static final int NCPUS = Runtime.getRuntime().availableProcessors(); /** * The number of times to spin before blocking in timed waits. * The value is empirically derived -- it works well across a * variety of processors and OSes. Empirically, the best value * seems not to vary with number of CPUs (beyond 2) so is just * a constant. */ private static final int maxTimedSpins = NCPUS < 2? 0 : 32; /** * The number of times to spin before blocking in untimed waits. * This is greater than timed value because untimed waits spin * faster since they don't need to check times on each spin. */ private static final int maxUntimedSpins = maxTimedSpins * 16; /** * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices. */ private static final long spinForTimeoutThreshold = 1000L; /** * Node class for LinkedTransferQueue. Opportunistically subclasses from * AtomicReference to represent item. Uses Object, not E, to allow * setting item to "this" after use, to avoid garbage * retention. Similarly, setting the next field to this is used as * sentinel that node is off list. */ private static final class QNode extends AtomicReference<Object> { private static final long serialVersionUID = 5925596372370723938L; volatile QNode next; transient volatile Thread waiter; // to control park/unpark final boolean isData; QNode(Object item, boolean isData) { super(item); this.isData = isData; } private static final AtomicReferenceFieldUpdater<QNode, QNode> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (QNode.class, QNode.class, "next"); boolean casNext(QNode cmp, QNode val) { return nextUpdater.compareAndSet(this, cmp, val); } } /** * Padded version of AtomicReference used for head, tail and * cleanMe, to alleviate contention across threads CASing one vs * the other. */ private static final class PaddedAtomicReference<T> extends AtomicReference<T> { private static final long serialVersionUID = 4684288940772921317L; // enough padding for 64bytes with 4byte refs Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe; PaddedAtomicReference(T r) { super(r); } } /** head of the queue */ private final PaddedAtomicReference<QNode> head; /** tail of the queue */ private final PaddedAtomicReference<QNode> tail; /** * Reference to a cancelled node that might not yet have been * unlinked from queue because it was the last inserted node * when it cancelled. */ private final PaddedAtomicReference<QNode> cleanMe; /** * Tries to cas nh as new head; if successful, unlink * old head's next node to avoid garbage retention. */ private boolean advanceHead(QNode h, QNode nh) { if (h == head.get() && head.compareAndSet(h, nh)) { h.next = h; // forget old next return true; } return false; } /** * Puts or takes an item. Used for most queue operations (except * poll() and tryTransfer()) * @param e the item or if null, signifies that this is a take * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT * @param nanos timeout in nanosecs, used only if mode is TIMEOUT * @return an item, or null on failure */ private Object xfer(Object e, int mode, long nanos) { boolean isData = e != null; QNode s = null; final AtomicReference<QNode> head = this.head; final AtomicReference<QNode> tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { if (s == null) { s = new QNode(e, isData); } QNode last = t.next; if (last != null) { if (t == tail.get()) { tail.compareAndSet(t, last); } } else if (t.casNext(null, s)) { tail.compareAndSet(t, s); return awaitFulfill(t, s, e, mode, nanos); } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Version of xfer for poll() and tryTransfer, which * simplifies control paths both here and in xfer */ private Object fulfill(Object e) { boolean isData = e != null; final AtomicReference<QNode> head = this.head; final AtomicReference<QNode> tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { QNode last = t.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else { return null; } } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Spins/blocks until node s is fulfilled or caller gives up, * depending on wait mode. * * @param pred the predecessor of waiting node * @param s the waiting node * @param e the comparison value for checking match * @param mode mode * @param nanos timeout value * @return matched item, or s if cancelled */ private Object awaitFulfill(QNode pred, QNode s, Object e, int mode, long nanos) { if (mode == NOWAIT) { return null; } long lastTime = mode == TIMEOUT? System.nanoTime() : 0; Thread w = Thread.currentThread(); int spins = -1; // set to desired spin count below for (;;) { if (w.isInterrupted()) { s.compareAndSet(e, s); } Object x = s.get(); if (x != e) { // Node was matched or cancelled advanceHead(pred, s); // unlink if head if (x == s) { return clean(pred, s); } else if (x != null) { s.set(s); // avoid garbage retention return x; } else { return e; } } if (mode == TIMEOUT) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.compareAndSet(e, s); // try to cancel continue; } } if (spins < 0) { QNode h = head.get(); // only spin if at head spins = h != null && h.next == s ? (mode == TIMEOUT? maxTimedSpins : maxUntimedSpins) : 0; } if (spins > 0) { --spins; } else if (s.waiter == null) { s.waiter = w; } else if (mode != TIMEOUT) { // LockSupport.park(this); LockSupport.park(); // allows run on java5 s.waiter = null; spins = -1; } else if (nanos > spinForTimeoutThreshold) { // LockSupport.parkNanos(this, nanos); LockSupport.parkNanos(nanos); s.waiter = null; spins = -1; } } } /** * Gets rid of cancelled node s with original predecessor pred. * @return null (to simplify use by callers) */ Object clean(QNode pred, QNode s) { Thread w = s.waiter; if (w != null) { // Wake up thread s.waiter = null; if (w != Thread.currentThread()) { LockSupport.unpark(w); } } for (;;) { if (pred.next != s) { return null; } QNode h = head.get(); QNode hn = h.next; // Absorb cancelled first node as head if (hn != null && hn.next == hn) { advanceHead(h, hn); continue; } QNode t = tail.get(); // Ensure consistent read for tail if (t == h) { return null; } QNode tn = t.next; if (t != tail.get()) { continue; } if (tn != null) { // Help advance tail tail.compareAndSet(t, tn); continue; } if (s != t) { // If not tail, try to unsplice QNode sn = s.next; if (sn == s || pred.casNext(s, sn)) { return null; } } QNode dp = cleanMe.get(); if (dp != null) { // Try unlinking previous cancelled node QNode d = dp.next; QNode dn; if (d == null || // d is gone or d == dp || // d is off list or d.get() != d || // d not cancelled or d != t && // d not tail and (dn = d.next) != null && // has successor dn != d && // that is on list dp.casNext(d, dn)) { cleanMe.compareAndSet(dp, null); } if (dp == pred) { return null; // s is already saved node } } else if (cleanMe.compareAndSet(null, pred)) { return null; // Postpone cleaning s } } } /** * Creates an initially empty <tt>LinkedTransferQueue</tt>. */ public LinkedTransferQueue() { QNode dummy = new QNode(null, false); head = new PaddedAtomicReference<QNode>(dummy); tail = new PaddedAtomicReference<QNode>(dummy); cleanMe = new PaddedAtomicReference<QNode>(null); } /** * Creates a <tt>LinkedTransferQueue</tt> * initially containing the elements of the given collection, * added in traversal order of the collection's iterator. * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedTransferQueue(Collection<? extends E> c) { this(); addAll(c); } public void put(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); } public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); return true; } public boolean offer(E e) { if (e == null) { throw new NullPointerException(); } xfer(e, NOWAIT, 0); return true; } public void transfer(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, WAIT, 0) == null) { Thread.interrupted(); throw new InterruptedException(); } } public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null) { return true; } if (!Thread.interrupted()) { return false; } throw new InterruptedException(); } public boolean tryTransfer(E e) { if (e == null) { throw new NullPointerException(); } return fulfill(e) != null; } public E take() throws InterruptedException { Object e = xfer(null, WAIT, 0); if (e != null) { return cast(e); } Thread.interrupted(); throw new InterruptedException(); } @SuppressWarnings("unchecked") E cast(Object e) { return (E) e; } public E poll(long timeout, TimeUnit unit) throws InterruptedException { Object e = xfer(null, TIMEOUT, unit.toNanos(timeout)); if (e != null || !Thread.interrupted()) { return cast(e); } throw new InterruptedException(); } public E poll() { return cast(fulfill(null)); } public int drainTo(Collection<? super E> c) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while ( (e = poll()) != null) { c.add(e); ++n; } return n; } public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while (n < maxElements && (e = poll()) != null) { c.add(e); ++n; } return n; } // Traversal-based methods /** * Return head after performing any outstanding helping steps */ QNode traversalHead() { for (;;) { QNode t = tail.get(); QNode h = head.get(); if (h != null && t != null) { QNode last = t.next; QNode first = h.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else if (first != null) { Object x = first.get(); if (x == first) { advanceHead(h, first); } else { return h; } } else { return h; } } } } } @Override public Iterator<E> iterator() { return new Itr(); } /** * Iterators. Basic strategy is to traverse list, treating * non-data (i.e., request) nodes as terminating list. * Once a valid data node is found, the item is cached * so that the next call to next() will return it even * if subsequently removed. */ private class Itr implements Iterator<E> { private QNode nextNode; // Next node to return next private QNode currentNode; // last returned node, for remove() private QNode prevNode; // predecessor of last returned node private E nextItem; // Cache of next item, once commited to in next Itr() { nextNode = traversalHead(); advance(); } private E advance() { prevNode = currentNode; currentNode = nextNode; E x = nextItem; QNode p = nextNode.next; for (;;) { if (p == null || !p.isData) { nextNode = null; nextItem = null; return x; } Object item = p.get(); if (item != p && item != null) { nextNode = p; nextItem = cast(item); return x; } prevNode = p; p = p.next; } } public boolean hasNext() { return nextNode != null; } public E next() { if (nextNode == null) { throw new NoSuchElementException(); } return advance(); } public void remove() { QNode p = currentNode; QNode prev = prevNode; if (prev == null || p == null) { throw new IllegalStateException(); } Object x = p.get(); if (x != null && x != p && p.compareAndSet(x, p)) { clean(prev, p); } } } public E peek() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return null; } Object x = p.get(); if (p != x) { if (!p.isData) { return null; } if (x != null) { return cast(x); } } } } @Override public boolean isEmpty() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return true; } Object x = p.get(); if (p != x) { if (!p.isData) { return true; } if (x != null) { return false; } } } } public boolean hasWaitingConsumer() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return false; } Object x = p.get(); if (p != x) { return !p.isData; } } } /** * Returns the number of elements in this queue. If this queue * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current * number of elements requires an O(n) traversal. * * @return the number of elements in this queue */ @Override public int size() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && p.isData; p = p.next) { Object x = p.get(); if (x != null && x != p) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int getWaitingConsumerCount() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && !p.isData; p = p.next) { if (p.get() == null) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int remainingCapacity() { return Integer.MAX_VALUE; } }
Added a potential fix for infinite loop in LinkedTransferQueue.clean()
src/main/java/org/jboss/netty/util/LinkedTransferQueue.java
Added a potential fix for infinite loop in LinkedTransferQueue.clean()
Java
apache-2.0
30856635f2ec1a6e4ddce62aed5ef9ccfd1e19e5
0
kef/hieos,kef/hieos,kef/hieos
/* * This code is subject to the HIEOS License, Version 1.0 * * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved. * * 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.vangent.hieos.xutil.atna; import com.vangent.hieos.xutil.xconfig.XConfig; import com.vangent.hieos.xutil.exception.MetadataException; import com.vangent.hieos.xutil.exception.MetadataValidationException; import com.vangent.hieos.xutil.exception.XdsInternalException; import com.vangent.hieos.xutil.metadata.structure.Metadata; import com.vangent.hieos.xutil.metadata.structure.MetadataSupport; import com.vangent.hieos.xutil.metadata.structure.ParamParser; //import com.vangent.hieos.xutil.base64.Base64Coder; // Third-party. import com.vangent.hieos.xutil.metadata.structure.SqParams; import com.vangent.hieos.xutil.xua.client.XServiceProvider; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.net.URL; import org.apache.axiom.om.OMElement; import org.apache.axis2.context.MessageContext; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; /** * * @author Vincent Lewis (original) * @author Sastry Dhara (clean up,, refactor) * @author Ravi Nistala (clean up, refactor) * @author Bernie Thuman (rewrite). */ public class XATNALogger { private final static Logger logger = Logger.getLogger(XATNALogger.class); // Public accessible parameters. public static final String TXN_ITI8 = "ITI-8"; public static final String TXN_ITI18 = "ITI-18"; public static final String TXN_ITI38 = "ITI-38"; public static final String TXN_ITI39 = "ITI-39"; public static final String TXN_ITI41 = "ITI-41"; public static final String TXN_ITI42 = "ITI-42"; public static final String TXN_ITI43 = "ITI-43"; public static final String TXN_ITI44 = "ITI-44"; public static final String TXN_ITI55 = "ITI-55"; public static final String TXN_START = "START"; public static final String TXN_STOP = "STOP"; // BHT: Deals with OutcomeIndicator as defined by DICOM Supplement 95 public enum OutcomeIndicator { SUCCESS(0), MINOR_FAILURE(4), SERIOUS_FAILURE(8), MAJOR_FAILURE(12); private final int value; OutcomeIndicator(int value) { this.value = value; } @Override public String toString() { return Integer.toString(value); } } public enum ActorType { REGISTRY, REPOSITORY, DOCCONSUMER, INITIATING_GATEWAY, RESPONDING_GATEWAY, UNKNOWN, DOCRECIPIENT } private static final String REG_STOR_QRY = "Registry Stored Query"; private static final String REG_DOC_SET = "Register Document Set-b"; private static final String CRS_GTWY_QRY = "Cross Gateway Query"; private static final String CRS_GTWY_PATIENT_DISCOVERY = "Cross Gateway Patient Discovery"; private static final String IHE_TX = "IHE Transactions"; //private static final String RTV_DOC = "Retrieve Document"; private static final String RTV_DOC_SET = "Retrieve Document Set"; private static final String CRS_GTWY_RTV = "Cross Gateway Retrieve"; private static final String PROVD_N_REG_DOC_SET_B = "Provide and Register Document Set b"; private static final String PATIENT_IDENTITY_FEED = "Patient Identity Feed"; private static final String IHE_XDS_MDT = "IHE XDS Metadata"; private static final String DCM = "DCM"; private static final String APL_STRT = "Application Start"; private static final String APL_ACTV = "Application Activity"; private static final String APL_STP = "Application Stop"; //private static final String UNDEF = "UNKNOWN"; private static final String AUDIT_SRC_SUFFIX = "VANGENT_HIEOS"; private ActorType actorType = ActorType.UNKNOWN; private String transactionId; private boolean performAudit = false; private AuditMessageBuilder amb = null; private OutcomeIndicator outcome = OutcomeIndicator.SUCCESS; //private String sourceId = "UNKNOWN"; // Context variables. //private String hostName = ""; private String hostAddress = ""; private String pid = ""; private String endpoint = ""; private String fromAddress = ""; private String replyTo = ""; private String targetEndpoint = ""; private String userName = ""; /** * * @param transactionId * @throws java.lang.Exception */ public XATNALogger(String transactionId, ActorType actorType) throws Exception { this.transactionId = transactionId; this.actorType = actorType; this.performAudit = XConfig.getInstance().getHomeCommunityConfigPropertyAsBoolean("ATNAperformAudit"); } /** * * @param rootNode * @param targetEndpoint * @param successFlag * @throws java.lang.Exception */ public void performAudit(OMElement rootNode, String targetEndpoint, OutcomeIndicator outcome) throws Exception { if (!this.performAudit) { return; // Early exit. } // Prep for audit. this.outcome = outcome; this.setContextVariables(targetEndpoint); // Audit ProvideAndRegisterDocumentSetb if (TXN_ITI41.equals(this.transactionId)) { this.auditProvideAndRegisterDocumentSetbToRepository(rootNode); } else if (TXN_ITI42.equals(this.transactionId) && this.actorType == ActorType.REPOSITORY) { this.auditRegisterDocumentSetbFromRepository(rootNode); } else if (TXN_ITI42.equals(this.transactionId) && this.actorType == ActorType.REGISTRY) { this.auditRegisterDocumentSetbToRegistry(rootNode); } else if ((TXN_ITI43.equals(this.transactionId) || (TXN_ITI39.equals(this.transactionId))) && this.actorType == ActorType.REPOSITORY) { this.auditRetrieveDocumentSetToRepository(rootNode); } else if ((TXN_ITI43.equals(this.transactionId) || (TXN_ITI39.equals(this.transactionId))) && this.actorType == ActorType.DOCCONSUMER) { this.auditRetrieveDocumentSetFromConsumer(rootNode); } else if ((TXN_ITI18.equals(this.transactionId) || (TXN_ITI38.equals(this.transactionId))) && this.actorType == ActorType.REGISTRY) { this.auditRegistryStoredQueryToRegistry(rootNode); } else if ((TXN_ITI18.equals(this.transactionId) || (TXN_ITI38.equals(this.transactionId))) && this.actorType == ActorType.DOCCONSUMER) { this.auditRegistryStoredQueryFromConsumer(rootNode); } else if (transactionId.equals(TXN_START)) { this.auditStart(); } else if (transactionId.equals(TXN_STOP)) { this.auditStop(); } // Persist the message. if (amb != null) { amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } } /** * * @return */ private String getAuditSourceId() { return this.hostAddress + "@" + this.actorType + "_" + AUDIT_SRC_SUFFIX; } /** * */ private void auditStart() { CodedValueType eventId = this.getCodedValueType("110100", DCM, APL_ACTV); CodedValueType eventType = this.getCodedValueType("110120", DCM, APL_STRT); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", "0"); CodedValueType roleIdCode = this.getCodedValueType("110150", "DCM", "Application"); amb.setActiveParticipant( "root", /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ } /** * */ private void auditStop() { CodedValueType eventId = this.getCodedValueType("110100", DCM, APL_ACTV); CodedValueType eventType = this.getCodedValueType("110121", DCM, APL_STP); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", "0"); CodedValueType roleIdCode = this.getCodedValueType("110150", "DCM", "Application"); amb.setActiveParticipant( "root", /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ } /** * * @param patientId * @param homeCommunityId * @param queryId * @param queryByParameter * @param targetEndpoint * @param outcome * @throws Exception */ public void performAuditCrossGatewayPatientDiscovery( String patientId, String homeCommunityId, String queryId, String queryByParameter, String targetEndpoint, OutcomeIndicator outcome) throws Exception { if (!this.performAudit) { return; // Early exit. } // Prep for audit. this.outcome = outcome; this.setContextVariables(targetEndpoint); if (this.actorType == ActorType.INITIATING_GATEWAY) { this.performAuditCGPD_InitiatingGatewaySend(patientId, homeCommunityId, queryId, queryByParameter); } else { this.performAuditCGPD_RespondingGatewayReceive(patientId, homeCommunityId, queryId, queryByParameter); } // Persist the message. if (amb != null) { amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.XdsInternalException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void performAuditCGPD_RespondingGatewayReceive( String patientId, String homeCommunityId, String queryId, String queryByParameter) throws UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, CRS_GTWY_PATIENT_DISCOVERY); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Initiating Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Responding Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ byte[] queryBase64Bytes = Base64.encodeBase64(queryByParameter.getBytes()); // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, CRS_GTWY_PATIENT_DISCOVERY); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ queryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param patientId * @param homeCommunityId * @param queryId * @param queryByParameter * @throws UnsupportedEncodingException * @throws MalformedURLException */ private void performAuditCGPD_InitiatingGatewaySend( String patientId, String homeCommunityId, String queryId, String queryByParameter) throws UnsupportedEncodingException, MalformedURLException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName = CRS_GTWY_PATIENT_DISCOVERY; CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer / Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ byte[] queryBase64Bytes = Base64.encodeBase64(queryByParameter.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ queryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditProvideAndRegisterDocumentSetbToRepository(OMElement rootNode) throws MetadataValidationException, MetadataException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); CodedValueType eventType = this.getCodedValueType(this.transactionId, IHE_TX, PROVD_N_REG_DOC_SET_B); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Document Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Repository): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * * @param rootNode * @param successFlag * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditRegisterDocumentSetbFromRepository(OMElement rootNode) throws MetadataValidationException, MetadataException, MalformedURLException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110106", "DCM", "Export"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, REG_DOC_SET); amb = new AuditMessageBuilder(null, null, eventId, eventType, "R", this.outcome.toString()); // Source (Repository): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void auditRegisterDocumentSetbToRegistry(OMElement rootNode) throws MetadataException, MetadataValidationException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, REG_DOC_SET); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Repository / Document Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * This transaction is from the perspective of the Repository. The repository is the source * for the document and exports the doc to the consumer (destination) * @param rootNode */ private void auditRetrieveDocumentSetToRepository(OMElement rootNode) { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110106", "DCM", "Export"); String displayName; if (TXN_ITI43.equals(transactionId)) { displayName = RTV_DOC_SET; } else { displayName = CRS_GTWY_RTV; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "R", this.outcome.toString()); // Source (Document Repository): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Document Consumer): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Document URIs: CodedValueType participantObjectIdentifier = this.getCodedValueType("9", "RFC-3881", "Report Number"); for (OMElement doc_request : MetadataSupport.childrenWithLocalName(rootNode, "DocumentRequest")) { String homeCommunityId = null; String repositoryId; String documentId; repositoryId = MetadataSupport.firstChildWithLocalName(doc_request, "RepositoryUniqueId").getText(); byte[] podval = repositoryId.getBytes(); documentId = MetadataSupport.firstChildWithLocalName(doc_request, "DocumentUniqueId").getText(); OMElement homeNode = MetadataSupport.firstChildWithLocalName(doc_request, "HomeCommunityId"); if (homeNode != null) { homeCommunityId = homeNode.getText(); } // Document URI: amb.setParticipantObject( "2", /* participantObjectTypeCode */ "3", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ documentId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ null, /* participantObjectQuery */ "Repository Unique Id", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ } } /** * This transaction is from the perspective of the Consumer. The consumer is the destination of the * document and will import the doc from the repository which is the source. * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditRetrieveDocumentSetFromConsumer(OMElement rootNode) throws MetadataValidationException, MetadataException, MalformedURLException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); String displayName; if (TXN_ITI43.equals(transactionId)) { displayName = RTV_DOC_SET; } else { displayName = CRS_GTWY_RTV; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Document Repository) CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Destination (Document Consumer): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Document URIs: CodedValueType participantObjectIdentifier = this.getCodedValueType("9", "RFC-3881", "Report Number"); for (OMElement doc_request : MetadataSupport.childrenWithLocalName(rootNode, "DocumentRequest")) { String homeCommunityId = null; String repositoryId; String documentId; repositoryId = MetadataSupport.firstChildWithLocalName(doc_request, "RepositoryUniqueId").getText(); byte[] podval = repositoryId.getBytes(); documentId = MetadataSupport.firstChildWithLocalName(doc_request, "DocumentUniqueId").getText(); OMElement homeNode = MetadataSupport.firstChildWithLocalName(doc_request, "HomeCommunityId"); if (homeNode != null) { homeCommunityId = homeNode.getText(); } // Document URI: amb.setParticipantObject( "2", /* participantObjectTypeCode */ "3", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ documentId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ null, /* participantObjectQuery */ "Repository Unique Id", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ } } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.XdsInternalException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void auditRegistryStoredQueryToRegistry(OMElement rootNode) throws XdsInternalException, MetadataValidationException, UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName; if (TXN_ITI18.equals(transactionId)) { displayName = REG_STOR_QRY; } else { displayName = CRS_GTWY_QRY; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Pull values from metadata. String patientId; String storedQueryId; OMElement adhocQuery = MetadataSupport.firstChildWithLocalName(rootNode, "AdhocQuery"); storedQueryId = adhocQuery.getAttributeValue(MetadataSupport.id_qname); patientId = this.getQueryPatientID(rootNode, storedQueryId); String query = rootNode.toString(); /* BHT: Removed and replaced with line below. String queryBase64String = Base64Coder.encodeString(query); // Convert to base64. byte[] queryBase64Bytes = queryBase64String.getBytes(); */ byte[] queryBase64Bytes = Base64.encodeBase64(query.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); String homeCommunityId = this.getHomeCommunityId(adhocQuery); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ storedQueryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.XdsInternalException */ private void auditRegistryStoredQueryFromConsumer(OMElement rootNode) throws MetadataValidationException, XdsInternalException, MalformedURLException, UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName; if (TXN_ITI18.equals(transactionId)) { displayName = REG_STOR_QRY; } else { displayName = CRS_GTWY_QRY; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer / Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Pull values from metadata. String patientId; String storedQueryId; OMElement adhocQuery = MetadataSupport.firstChildWithLocalName(rootNode, "AdhocQuery"); storedQueryId = adhocQuery.getAttributeValue(MetadataSupport.id_qname); patientId = this.getQueryPatientID(rootNode, storedQueryId); String query = rootNode.toString(); /* BHT: Removed and replaced with line below. String queryBase64String = Base64Coder.encodeString(query); // Convert to base64. byte[] queryBase64Bytes = queryBase64String.getBytes(); */ byte[] queryBase64Bytes = Base64.encodeBase64(query.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); String homeCommunityId = this.getHomeCommunityId(adhocQuery); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ storedQueryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * This is public and does not follow the main audit pattern due to the complexity of the * HL7v3 message structure. * * @param patientId * @param messageId * @param updateMode * @param successFlag * @param sourceIdentity * @param sourceIP */ public void auditPatientIdentityFeedToRegistry(String patientId, String messageId, boolean updateMode, OutcomeIndicator outcome, String sourceIdentity, String sourceIP) { if (!this.performAudit) { return; // Early exit. } // Prep for audit: this.outcome = outcome; this.setContextVariables(null); // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110110", "DCM", "Patient Record"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, PATIENT_IDENTITY_FEED); String eventAction = updateMode ? "U" : "C"; amb = new AuditMessageBuilder(null, null, eventId, eventType, eventAction, this.outcome.toString()); // Source (Patient Identity Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( sourceIdentity != null ? sourceIdentity : this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ sourceIP != null ? sourceIP : this.fromAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Patient ID: byte[] podval = messageId.getBytes(); CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ "Message Identifier", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ // Now, persist the audit message. amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } /** * * @param queryRequest * @return */ private String getHomeCommunityId(OMElement queryRequest) { String homeCommunityId = queryRequest.getAttributeValue(MetadataSupport.home_qname); if (homeCommunityId == null || homeCommunityId.equals("")) { homeCommunityId = null; } if (homeCommunityId == null) { homeCommunityId = "HomeCommunityId not present in request"; } return homeCommunityId; } /** * * @param code * @param codeSystem * @param displayName * @return */ private CodedValueType getCodedValueType(String code, String codeSystem, String displayName) { CodedValueType codeValueType = new CodedValueType(); codeValueType.setCode(code); codeValueType.setCodeSystem(codeSystem); codeValueType.setCodeSystemName(codeSystem); codeValueType.setDisplayName(displayName); return codeValueType; } /** * * @param request * @param queryRequest * @return * @throws com.vangent.hieos.xutil.exception.XdsInternalException */ private String getQueryPatientID(OMElement request, String queryId) { if (queryId == null) { return "QueryId not known"; // Early exit (FIXME). } // Parse the query parameters. ParamParser parser = new ParamParser(); SqParams params = null; try { params = parser.parse(request); } catch (MetadataValidationException ex) { logger.error("Could not parse stored query in ATNA", ex); } catch (XdsInternalException ex) { logger.error("Could not parse stored query in ATNA", ex); } if (params == null) { return "Query Parameters could not be parsed"; // Early exit. } String patientId = null; if (queryId.equals(MetadataSupport.SQ_FindDocuments)) { // $XDSDocumentEntryPatientId patientId = params.getStringParm("$XDSDocumentEntryPatientId"); } else if (queryId.equals(MetadataSupport.SQ_FindFolders)) { // $XDSFolderPatientId patientId = params.getStringParm("$XDSFolderPatientId"); } else if (queryId.equals(MetadataSupport.SQ_FindSubmissionSets)) { // $XDSSubmissionSetPatientId patientId = params.getStringParm("$XDSSubmissionSetPatientId"); } else if (queryId.equals(MetadataSupport.SQ_GetAll)) { // FIXME: NOT IMPLEMENTED [NEED TO FIGURE OUT WHAT TO PULL OUT HERE. return "SQ_GetAll not implemented"; } if (patientId == null) { return "PatientId not present on request"; } return patientId; } /** * * @return */ private MessageContext getCurrentMessageContext() { return MessageContext.getCurrentMessageContext(); } /** * */ private void setContextVariables(String targetEndpoint) { // Set host address: try { InetAddress addr; addr = InetAddress.getLocalHost(); this.hostAddress = addr.getHostAddress(); } catch (UnknownHostException e) { this.hostAddress = null; logger.error("Exception in XATNALogger", e); } // Set target endpoint and process id: this.targetEndpoint = targetEndpoint; this.pid = ManagementFactory.getRuntimeMXBean().getName(); MessageContext messageContext = this.getCurrentMessageContext(); if (messageContext != null) { // Set current endpoint: try { this.endpoint = messageContext.getTo().toString(); } catch (Exception e) { this.endpoint = null; logger.error("Exception in XATNALogger", e); } // Set from address: try { this.fromAddress = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR); } catch (Exception e) { this.fromAddress = null; logger.error("Exception in XATNALogger", e); } // Set replyTo address: try { org.apache.axis2.addressing.EndpointReference replyToEndpointRef = messageContext.getReplyTo(); this.replyTo = replyToEndpointRef != null ? replyToEndpointRef.toString() : null; } catch (Exception e) { this.replyTo = null; logger.error("Exception in XATNALogger", e); } // Set userName on request (if available): this.userName = this.getUserNameFromRequest(); } else { this.endpoint = null; this.fromAddress = null; this.replyTo = null; } /* // The endpoint for the current web service running. AxisEndpoint axisEndPoint = (AxisEndpoint) messageContext.getProperty("endpoint"); this.endpoint = axisEndPoint.getEndpointURL(); // IP Address from the caller. this.fromAddress = (String) messageContext.getProperty("REMOTE_ADDR"); */ // DEBUG: /* System.out.println("--- AUDIT VARIABLES ---"); System.out.println("hostname: " + this.hostname); System.out.println("pid:" + this.pid); System.out.println("endpoint: " + this.endpoint); System.out.println("fromAddress: " + this.fromAddress); System.out.println("getFrom().getAddress(): " + messageContext.getFrom().getAddress().toString()); System.out.println("replyTo:" + messageContext.getReplyTo().toString()); System.out.println("replyToAddress: " + messageContext.getReplyTo().getAddress().toString()); System.out.println("-----------------------"); */ //logger.error("Exception in XATNALogger", e); } /** * * @return */ private String getUserNameFromRequest() { XServiceProvider xServiceProvider = new XServiceProvider(null); return xServiceProvider.getUserNameFromRequest(this.getCurrentMessageContext()); } }
src/xutil/src/com/vangent/hieos/xutil/atna/XATNALogger.java
/* * This code is subject to the HIEOS License, Version 1.0 * * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved. * * 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.vangent.hieos.xutil.atna; import com.vangent.hieos.xutil.xconfig.XConfig; import com.vangent.hieos.xutil.exception.MetadataException; import com.vangent.hieos.xutil.exception.MetadataValidationException; import com.vangent.hieos.xutil.exception.XdsInternalException; import com.vangent.hieos.xutil.metadata.structure.Metadata; import com.vangent.hieos.xutil.metadata.structure.MetadataSupport; import com.vangent.hieos.xutil.metadata.structure.ParamParser; //import com.vangent.hieos.xutil.base64.Base64Coder; // Third-party. import com.vangent.hieos.xutil.metadata.structure.SqParams; import com.vangent.hieos.xutil.xua.client.XServiceProvider; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.net.URL; import org.apache.axiom.om.OMElement; import org.apache.axis2.context.MessageContext; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; /** * * @author Vincent Lewis (original) * @author Sastry Dhara (clean up,, refactor) * @author Ravi Nistala (clean up, refactor) * @author Bernie Thuman (rewrite). */ public class XATNALogger { private final static Logger logger = Logger.getLogger(XATNALogger.class); // Public accessible parameters. public static final String TXN_ITI8 = "ITI-8"; public static final String TXN_ITI18 = "ITI-18"; public static final String TXN_ITI38 = "ITI-38"; public static final String TXN_ITI39 = "ITI-39"; public static final String TXN_ITI41 = "ITI-41"; public static final String TXN_ITI42 = "ITI-42"; public static final String TXN_ITI43 = "ITI-43"; public static final String TXN_ITI44 = "ITI-44"; public static final String TXN_ITI55 = "ITI-55"; public static final String TXN_START = "START"; public static final String TXN_STOP = "STOP"; // BHT: Deals with OutcomeIndicator as defined by DICOM Supplement 95 public enum OutcomeIndicator { SUCCESS(0), MINOR_FAILURE(4), SERIOUS_FAILURE(8), MAJOR_FAILURE(12); private final int value; OutcomeIndicator(int value) { this.value = value; } @Override public String toString() { return Integer.toString(value); } } public enum ActorType { REGISTRY, REPOSITORY, DOCCONSUMER, INITIATING_GATEWAY, RESPONDING_GATEWAY, UNKNOWN, DOCRECIPIENT } private static final String REG_STOR_QRY = "Registry Stored Query"; private static final String REG_DOC_SET = "Register Document Set-b"; private static final String CRS_GTWY_QRY = "Cross Gateway Query"; private static final String CRS_GTWY_PATIENT_DISCOVERY = "Cross Gateway Patient Discovery"; private static final String IHE_TX = "IHE Transactions"; //private static final String RTV_DOC = "Retrieve Document"; private static final String RTV_DOC_SET = "Retrieve Document Set"; private static final String CRS_GTWY_RTV = "Cross Gateway Retrieve"; private static final String PROVD_N_REG_DOC_SET_B = "Provide and Register Document Set b"; private static final String PATIENT_IDENTITY_FEED = "Patient Identity Feed"; private static final String IHE_XDS_MDT = "IHE XDS Metadata"; private static final String DCM = "DCM"; private static final String APL_STRT = "Application Start"; private static final String APL_ACTV = "Application Activity"; private static final String APL_STP = "Application Stop"; //private static final String UNDEF = "UNKNOWN"; private static final String AUDIT_SRC_SUFFIX = "VANGENT_HIEOS"; private ActorType actorType = ActorType.UNKNOWN; private String transactionId; private boolean performAudit = false; private AuditMessageBuilder amb = null; private OutcomeIndicator outcome = OutcomeIndicator.SUCCESS; //private String sourceId = "UNKNOWN"; // Context variables. //private String hostName = ""; private String hostAddress = ""; private String pid = ""; private String endpoint = ""; private String fromAddress = ""; private String replyTo = ""; private String targetEndpoint = ""; private String userName = ""; /** * * @param transactionId * @throws java.lang.Exception */ public XATNALogger(String transactionId, ActorType actorType) throws Exception { this.transactionId = transactionId; this.actorType = actorType; this.performAudit = XConfig.getInstance().getHomeCommunityConfigPropertyAsBoolean("ATNAperformAudit"); } /** * * @param rootNode * @param targetEndpoint * @param successFlag * @throws java.lang.Exception */ public void performAudit(OMElement rootNode, String targetEndpoint, OutcomeIndicator outcome) throws Exception { if (!this.performAudit) { return; // Early exit. } // Prep for audit. this.outcome = outcome; this.setContextVariables(targetEndpoint); // Audit ProvideAndRegisterDocumentSetb if (TXN_ITI41.equals(this.transactionId)) { this.auditProvideAndRegisterDocumentSetbToRepository(rootNode); } else if (TXN_ITI42.equals(this.transactionId) && this.actorType == ActorType.REPOSITORY) { this.auditRegisterDocumentSetbFromRepository(rootNode); } else if (TXN_ITI42.equals(this.transactionId) && this.actorType == ActorType.REGISTRY) { this.auditRegisterDocumentSetbToRegistry(rootNode); } else if ((TXN_ITI43.equals(this.transactionId) || (TXN_ITI39.equals(this.transactionId))) && this.actorType == ActorType.REPOSITORY) { this.auditRetrieveDocumentSetToRepository(rootNode); } else if ((TXN_ITI43.equals(this.transactionId) || (TXN_ITI39.equals(this.transactionId))) && this.actorType == ActorType.DOCCONSUMER) { this.auditRetrieveDocumentSetFromConsumer(rootNode); } else if ((TXN_ITI18.equals(this.transactionId) || (TXN_ITI38.equals(this.transactionId))) && this.actorType == ActorType.REGISTRY) { this.auditRegistryStoredQueryToRegistry(rootNode); } else if ((TXN_ITI18.equals(this.transactionId) || (TXN_ITI38.equals(this.transactionId))) && this.actorType == ActorType.DOCCONSUMER) { this.auditRegistryStoredQueryFromConsumer(rootNode); } else if (transactionId.equals(TXN_START)) { this.auditStart(); } else if (transactionId.equals(TXN_STOP)) { this.auditStop(); } // Persist the message. if (amb != null) { amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } } /** * * @return */ private String getAuditSourceId() { return this.hostAddress + "@" + this.actorType + "_" + AUDIT_SRC_SUFFIX; } /** * */ private void auditStart() { CodedValueType eventId = this.getCodedValueType("110100", DCM, APL_ACTV); CodedValueType eventType = this.getCodedValueType("110120", DCM, APL_STRT); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", "0"); CodedValueType roleIdCode = this.getCodedValueType("110150", "DCM", "Application"); amb.setActiveParticipant( "root", /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ } /** * */ private void auditStop() { CodedValueType eventId = this.getCodedValueType("110100", DCM, APL_ACTV); CodedValueType eventType = this.getCodedValueType("110121", DCM, APL_STP); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", "0"); CodedValueType roleIdCode = this.getCodedValueType("110150", "DCM", "Application"); amb.setActiveParticipant( "root", /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ } /** * * @param patientId * @param homeCommunityId * @param queryId * @param queryByParameter * @param targetEndpoint * @param outcome * @throws Exception */ public void performAuditCrossGatewayPatientDiscovery( String patientId, String homeCommunityId, String queryId, String queryByParameter, String targetEndpoint, OutcomeIndicator outcome) throws Exception { if (!this.performAudit) { return; // Early exit. } // Prep for audit. this.outcome = outcome; this.setContextVariables(targetEndpoint); if (this.actorType == ActorType.INITIATING_GATEWAY) { this.performAuditCGPD_InitiatingGatewaySend(patientId, homeCommunityId, queryId, queryByParameter); } else { this.performAuditCGPD_RespondingGatewayReceive(patientId, homeCommunityId, queryId, queryByParameter); } // Persist the message. if (amb != null) { amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.XdsInternalException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void performAuditCGPD_RespondingGatewayReceive( String patientId, String homeCommunityId, String queryId, String queryByParameter) throws UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, CRS_GTWY_PATIENT_DISCOVERY); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Initiating Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Responding Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ byte[] queryBase64Bytes = Base64.encodeBase64(queryByParameter.getBytes()); // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, CRS_GTWY_PATIENT_DISCOVERY); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ queryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param patientId * @param homeCommunityId * @param queryId * @param queryByParameter * @throws UnsupportedEncodingException * @throws MalformedURLException */ private void performAuditCGPD_InitiatingGatewaySend( String patientId, String homeCommunityId, String queryId, String queryByParameter) throws UnsupportedEncodingException, MalformedURLException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName = CRS_GTWY_PATIENT_DISCOVERY; CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer / Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ byte[] queryBase64Bytes = Base64.encodeBase64(queryByParameter.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ queryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditProvideAndRegisterDocumentSetbToRepository(OMElement rootNode) throws MetadataValidationException, MetadataException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); CodedValueType eventType = this.getCodedValueType(this.transactionId, IHE_TX, PROVD_N_REG_DOC_SET_B); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Document Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Repository): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* altnerateuserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * * @param rootNode * @param successFlag * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditRegisterDocumentSetbFromRepository(OMElement rootNode) throws MetadataValidationException, MetadataException, MalformedURLException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110106", "DCM", "Export"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, REG_DOC_SET); amb = new AuditMessageBuilder(null, null, eventId, eventType, "R", this.outcome.toString()); // Source (Repository): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void auditRegisterDocumentSetbToRegistry(OMElement rootNode) throws MetadataException, MetadataValidationException { // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, REG_DOC_SET); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Repository / Document Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Metadata variables: Metadata m = new Metadata(rootNode); String patientId = m.getSubmissionSetPatientId(); String submissionSetId = m.getSubmissionSetUniqueId(); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ // Submission Set: participantObjectIdentifier = this.getCodedValueType(MetadataSupport.XDSSubmissionSet_classification_uuid, IHE_XDS_MDT, "submission set classificationNode"); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "20", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ submissionSetId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjecxtDetailValue */ } /** * This transaction is from the perspective of the Repository. The repository is the source * for the document and exports the doc to the consumer (destination) * @param rootNode */ private void auditRetrieveDocumentSetToRepository(OMElement rootNode) { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110106", "DCM", "Export"); String displayName; if (TXN_ITI43.equals(transactionId)) { displayName = RTV_DOC_SET; } else { displayName = CRS_GTWY_RTV; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "R", this.outcome.toString()); // Source (Document Repository): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Document Consumer): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Document URIs: CodedValueType participantObjectIdentifier = this.getCodedValueType("9", "RFC-3881", "Report Number"); for (OMElement doc_request : MetadataSupport.childrenWithLocalName(rootNode, "DocumentRequest")) { String homeCommunityId = null; String repositoryId; String documentId; repositoryId = MetadataSupport.firstChildWithLocalName(doc_request, "RepositoryUniqueId").getText(); byte[] podval = repositoryId.getBytes(); documentId = MetadataSupport.firstChildWithLocalName(doc_request, "DocumentUniqueId").getText(); OMElement homeNode = MetadataSupport.firstChildWithLocalName(doc_request, "HomeCommunityId"); if (homeNode != null) { homeCommunityId = homeNode.getText(); } // Document URI: amb.setParticipantObject( "2", /* participantObjectTypeCode */ "3", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ documentId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ null, /* participantObjectQuery */ "Repository Unique Id", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ } } /** * This transaction is from the perspective of the Consumer. The consumer is the destination of the * document and will import the doc from the repository which is the source. * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.MetadataException */ private void auditRetrieveDocumentSetFromConsumer(OMElement rootNode) throws MetadataValidationException, MetadataException, MalformedURLException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110107", "DCM", "Import"); String displayName; if (TXN_ITI43.equals(transactionId)) { displayName = RTV_DOC_SET; } else { displayName = CRS_GTWY_RTV; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "C", this.outcome.toString()); // Source (Document Repository) CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Destination (Document Consumer): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Document URIs: CodedValueType participantObjectIdentifier = this.getCodedValueType("9", "RFC-3881", "Report Number"); for (OMElement doc_request : MetadataSupport.childrenWithLocalName(rootNode, "DocumentRequest")) { String homeCommunityId = null; String repositoryId; String documentId; repositoryId = MetadataSupport.firstChildWithLocalName(doc_request, "RepositoryUniqueId").getText(); byte[] podval = repositoryId.getBytes(); documentId = MetadataSupport.firstChildWithLocalName(doc_request, "DocumentUniqueId").getText(); OMElement homeNode = MetadataSupport.firstChildWithLocalName(doc_request, "HomeCommunityId"); if (homeNode != null) { homeCommunityId = homeNode.getText(); } // Document URI: amb.setParticipantObject( "2", /* participantObjectTypeCode */ "3", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ documentId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ null, /* participantObjectQuery */ "Repository Unique Id", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ } } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.XdsInternalException * @throws com.vangent.hieos.xutil.exception.MetadataValidationException */ private void auditRegistryStoredQueryToRegistry(OMElement rootNode) throws XdsInternalException, MetadataValidationException, UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName; if (TXN_ITI18.equals(transactionId)) { displayName = REG_STOR_QRY; } else { displayName = CRS_GTWY_QRY; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.fromAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Pull values from metadata. String patientId; String storedQueryId; OMElement adhocQuery = MetadataSupport.firstChildWithLocalName(rootNode, "AdhocQuery"); storedQueryId = adhocQuery.getAttributeValue(MetadataSupport.id_qname); patientId = this.getQueryPatientID(rootNode, storedQueryId); String query = rootNode.toString(); /* BHT: Removed and replaced with line below. String queryBase64String = Base64Coder.encodeString(query); // Convert to base64. byte[] queryBase64Bytes = queryBase64String.getBytes(); */ byte[] queryBase64Bytes = Base64.encodeBase64(query.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); String homeCommunityId = this.getHomeCommunityId(adhocQuery); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ storedQueryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * * @param rootNode * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.XdsInternalException */ private void auditRegistryStoredQueryFromConsumer(OMElement rootNode) throws MetadataValidationException, XdsInternalException, MalformedURLException, UnsupportedEncodingException { // Event ID and Event Type: CodedValueType eventId = this.getCodedValueType("110112", "DCM", "Query"); String displayName; if (TXN_ITI18.equals(transactionId)) { displayName = REG_STOR_QRY; } else { displayName = CRS_GTWY_QRY; } CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, displayName); amb = new AuditMessageBuilder(null, null, eventId, eventType, "E", this.outcome.toString()); // Source (Document Consumer / Gateway): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Destination (Registry / Gateway): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); URL url = new URL(this.targetEndpoint); amb.setActiveParticipant( this.targetEndpoint, /* userId */ null, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ url.getHost()); /* networkAccessPointId */ // Pull values from metadata. String patientId; String storedQueryId; OMElement adhocQuery = MetadataSupport.firstChildWithLocalName(rootNode, "AdhocQuery"); storedQueryId = adhocQuery.getAttributeValue(MetadataSupport.id_qname); patientId = this.getQueryPatientID(rootNode, storedQueryId); String query = rootNode.toString(); /* BHT: Removed and replaced with line below. String queryBase64String = Base64Coder.encodeString(query); // Convert to base64. byte[] queryBase64Bytes = queryBase64String.getBytes(); */ byte[] queryBase64Bytes = Base64.encodeBase64(query.getBytes()); // Patient ID: CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ // Stored Query ID: participantObjectIdentifier = this.getCodedValueType(transactionId, IHE_TX, displayName); String homeCommunityId = this.getHomeCommunityId(adhocQuery); amb.setParticipantObject( "2", /* participantObjectTypeCode */ "24", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ storedQueryId, /* participantObjectId */ homeCommunityId, /* participantObjectName */ queryBase64Bytes, /* participantObjectQuery */ null, /* participantObjectDetailName */ null); /* participantObjectDetailValue */ } /** * This is public and does not follow the main audit pattern due to the complexity of the * HL7v3 message structure. * * @param patientId * @param messageId * @param updateMode * @param successFlag * @param sourceIdentity * @param sourceIP */ public void auditPatientIdentityFeedToRegistry(String patientId, String messageId, boolean updateMode, OutcomeIndicator outcome, String sourceIdentity, String sourceIP) { if (!this.performAudit) { return; // Early exit. } // Prep for audit: this.outcome = outcome; this.setContextVariables(null); // Event ID and Type: CodedValueType eventId = this.getCodedValueType("110110", "DCM", "Patient Record"); CodedValueType eventType = this.getCodedValueType(transactionId, IHE_TX, PATIENT_IDENTITY_FEED); String eventAction = updateMode ? "U" : "C"; amb = new AuditMessageBuilder(null, null, eventId, eventType, eventAction, this.outcome.toString()); // Source (Patient Identity Source): CodedValueType roleIdCode = this.getCodedValueType("110153", "DCM", "Source"); amb.setActiveParticipant( sourceIdentity != null ? sourceIdentity : this.replyTo, /* userId */ null, /* alternateUserId */ this.userName, /* userName */ "true", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ sourceIP != null ? sourceIP : this.fromAddress); /* networkAccessPointId */ // Destination (Registry): roleIdCode = this.getCodedValueType("110152", "DCM", "Destination"); amb.setActiveParticipant( this.endpoint, /* userId */ this.pid, /* alternateUserId */ null, /* userName */ "false", /* userIsRequestor */ roleIdCode, /* roleIdCode */ "2", /* networkAccessPointTypeCode (1 = hostname, 2 = IP Address) */ this.hostAddress); /* networkAccessPointId */ // Patient ID: byte[] podval = messageId.getBytes(); CodedValueType participantObjectIdentifier = this.getCodedValueType("2", "RFC-3881", "Patient Number"); amb.setParticipantObject( "1", /* participantObjectTypeCode */ "1", /* participantObjectTypeCodeRole */ null, /* participantObjectDataLifeCycle */ participantObjectIdentifier, /* participantIDTypeCode */ null, /* participantObjectSensitivity */ patientId, /* participantObjectId */ null, /* participantObjectName */ null, /* participantObjectQuery */ "Message Identifier", /* participantObjectDetailName */ podval); /* participantObjectDetailValue */ // Now, persist the audit message. amb.setAuditSource(this.getAuditSourceId(), null, null); amb.persistMessage(); } /** * * @param queryRequest * @return */ private String getHomeCommunityId(OMElement queryRequest) { String homeCommunityId = queryRequest.getAttributeValue(MetadataSupport.home_qname); if (homeCommunityId == null || homeCommunityId.equals("")) { homeCommunityId = null; } if (homeCommunityId == null) { homeCommunityId = "HomeCommunityId not present in request"; } return homeCommunityId; } /** * * @param code * @param codeSystem * @param displayName * @return */ private CodedValueType getCodedValueType(String code, String codeSystem, String displayName) { CodedValueType codeValueType = new CodedValueType(); codeValueType.setCode(code); codeValueType.setCodeSystem(codeSystem); codeValueType.setCodeSystemName(codeSystem); codeValueType.setDisplayName(displayName); return codeValueType; } /** * * @param request * @param queryRequest * @return * @throws com.vangent.hieos.xutil.exception.XdsInternalException */ private String getQueryPatientID(OMElement request, String queryId) { if (queryId == null) { return "QueryId not known"; // Early exit (FIXME). } // Parse the query parameters. ParamParser parser = new ParamParser(); SqParams params = null; try { params = parser.parse(request); } catch (MetadataValidationException ex) { logger.error("Could not parse stored query in ATNA", ex); } catch (XdsInternalException ex) { logger.error("Could not parse stored query in ATNA", ex); } if (params == null) { return "Query Parameters could not be parsed"; // Early exit. } String patientId = null; if (queryId.equals(MetadataSupport.SQ_FindDocuments)) { // $XDSDocumentEntryPatientId patientId = params.getStringParm("$XDSDocumentEntryPatientId"); } else if (queryId.equals(MetadataSupport.SQ_FindFolders)) { // $XDSFolderPatientId patientId = params.getStringParm("$XDSFolderPatientId"); } else if (queryId.equals(MetadataSupport.SQ_FindSubmissionSets)) { // $XDSSubmissionSetPatientId patientId = params.getStringParm("$XDSSubmissionSetPatientId"); } else if (queryId.equals(MetadataSupport.SQ_GetAll)) { // FIXME: NOT IMPLEMENTED [NEED TO FIGURE OUT WHAT TO PULL OUT HERE. return "SQ_GetAll not implemented"; } if (patientId == null) { return "PatientId not present on request"; } return patientId; } /** * * @return */ private MessageContext getCurrentMessageContext() { return MessageContext.getCurrentMessageContext(); } /** * */ private void setContextVariables(String targetEndpoint) { // Set host address: try { InetAddress addr; addr = InetAddress.getLocalHost(); this.hostAddress = addr.getHostAddress(); } catch (UnknownHostException e) { this.hostAddress = null; logger.error("Exception in XATNALogger", e); } // Set target endpoint and process id: this.targetEndpoint = targetEndpoint; this.pid = ManagementFactory.getRuntimeMXBean().getName(); MessageContext messageContext = this.getCurrentMessageContext(); if (messageContext != null) { // Set current endpoint: try { this.endpoint = messageContext.getTo().toString(); } catch (Exception e) { this.endpoint = null; logger.error("Exception in XATNALogger", e); } // Set from address: try { this.fromAddress = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR); } catch (Exception e) { this.fromAddress = null; logger.error("Exception in XATNALogger", e); } // Set replyTo address: try { org.apache.axis2.addressing.EndpointReference replyToEndpointRef = messageContext.getReplyTo(); this.replyTo = replyToEndpointRef != null ? replyToEndpointRef.toString() : null; } catch (Exception e) { this.replyTo = null; logger.error("Exception in XATNALogger", e); } // Set userName on request (if available): this.userName = this.getUserNameFromRequest(); System.out.println("+++ userName=" + this.userName); } else { this.endpoint = null; this.fromAddress = null; this.replyTo = null; } /* // The endpoint for the current web service running. AxisEndpoint axisEndPoint = (AxisEndpoint) messageContext.getProperty("endpoint"); this.endpoint = axisEndPoint.getEndpointURL(); // IP Address from the caller. this.fromAddress = (String) messageContext.getProperty("REMOTE_ADDR"); */ // DEBUG: /* System.out.println("--- AUDIT VARIABLES ---"); System.out.println("hostname: " + this.hostname); System.out.println("pid:" + this.pid); System.out.println("endpoint: " + this.endpoint); System.out.println("fromAddress: " + this.fromAddress); System.out.println("getFrom().getAddress(): " + messageContext.getFrom().getAddress().toString()); System.out.println("replyTo:" + messageContext.getReplyTo().toString()); System.out.println("replyToAddress: " + messageContext.getReplyTo().getAddress().toString()); System.out.println("-----------------------"); */ //logger.error("Exception in XATNALogger", e); } /** * * @return */ private String getUserNameFromRequest() { XServiceProvider xServiceProvider = new XServiceProvider(null); return xServiceProvider.getUserNameFromRequest(this.getCurrentMessageContext()); } }
Reverted accidental commit.
src/xutil/src/com/vangent/hieos/xutil/atna/XATNALogger.java
Reverted accidental commit.