answer
stringlengths
17
10.2M
package org.modmine.web; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.tiles.ComponentContext; import org.apache.struts.tiles.actions.TilesAction; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.query.PathQueryExecutor; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.session.SessionMethods; import org.modmine.web.logic.ModMineUtil; /** * Class that generates heatMap data for a list of genes or exons. * * @author Sergio * @author Fengyuan Hu * */ public class HeatMapController extends TilesAction { protected static final Logger LOG = Logger.getLogger(HeatMapController.class); private static final String[] EXPRESSION_ORDERED_CONDITION = {"CME L1", "Sg4", "ML-DmD11", "ML-DmD20-c2", "ML-DmD20-c5", "Kc167", "GM2", "S2-DRSC", "S2R+", "S1", "1182-4H", "ML-DmD16-c3", "ML-DmD32", "ML-DmD17-c3", "ML-DmD8", "CME W1 Cl.8+", "ML-DmD9", "ML-DmBG1-c1", "ML-DmD21", "ML-DmD4-c1", "ML-DmBG3-c2", "S3", "CME W2", "mbn2", "ML-DmBG2-c2", "Embryo 0-2 h", "Embryo 2-4 h", "Embryo 4-6 h", "Embryo 6-8 h", "emb 8-10h", "emb 10-12h", "emb 12-14h", "emb 14-16h", "emb 16-18h", "emb 18-20h", "emb 20-22h", "emb 22-24h", "L1 stage larvae", "L2 stage larvae", "L3 stage larvae 12hr", "L3 stage larvae dark blue", "L3 stage larvae light blue", "L3 stage larvae clear", "White prepupae (WPP)", "White prepupae (WPP) 12 h", "White prepupae (WPP) 24 h", "White prepupae (WPP) 2days", "White prepupae (WPP) 3days", "White prepupae (WPP) 4days", "Adult F Ecl 1day", "Adult M Ecl 1day", "Adult F Ecl 5day", "Adult M Ecl 5day", "Adult F Ecl 30day", "Adult M Ecl 30day"}; private static String geneExpressionScoreTitle = "Drosophila Gene Expression Scores"; private static String expressionScoreSummary = "These expression levels are derived " + "from RNA-seq data from "; private static String geneExpressionScoreDescription = "This heatmap shows estimated " + "expression levels for annotated genes, using signals from Affymetrix " + "Drosophila tiling arrays. The arrays were hybridized with total RNAs " + "extracted from 25 cell lines and 30 developmental stages. The original gene " + "scores table provides expression scores for all genes listed in the FlyBase " + "version 5.12 annotation. Each gene was assigned a score equal to the maximum" + " exon score for all the exons associated with the gene in the annotation. " + "That is, we made no effort to derive distinct scores for known isoforms. " + "[Note: Some exons are annotated as components of more than one genes. Such " + "exons are represented in more than one row, with different values for " + "geneID, geneName and FBgn.] IMPORTANT: Hybridization efficiencies vary " + "significantly from probe to probe and exon to exon. Consequently, the data " + "in these tables are useful for comparing a single gene in multiple RNA " + "samples (i.e. you may compare scores within a row). But they are NOT useful" + " for comparing different genes or exons from a single RNA sample (i.e. do " + "NOT try to compare scores within a column). We have taken log2 of each " + "expression score to create the heatmap. "; private static String exonExpressionScoreTitle = "Drosophila Exon Expression Score"; private static String exonExpressionScoreDescription = "This heatmap shows estimated " + "expression levels for annotated exons, using signals from Affymetrix " + "Drosophila tiling arrays. The arrays were hybridized with total RNAs " + "extracted from 25 cell lines and 30 developmental stages. * IMPORTANT: " + "Hybridization efficiencies vary significantly from probe to probe and exon " + "to exon. Consequently, the data in these tables are useful for comparing a " + "single exon in multiple RNA samples (i.e. you may compare scores within a " + "row). But they are NOT useful for comparing different genes or exons from a" + " single RNA sample (i.e. do NOT try to compare scores within a column). * " + "The original exons scores table provides scores for all exons annotated in " + "either FlyBase (v5.12) or in the unpublished annotation MB6 from the WUSL " + "sub-group led by Michael Brent. * The primary data were Affymetrix signal " + "graph files. Each signal graph incorporates data from three (biologically " + "independent) replicate arrays. * For each exon, all probes contained within" + " the annotated coordinates were scored as follows: 1. A preliminary score is" + " the median intensity for all probes completely contained within the exon. " + "2. Scores less than zero were converted to zero. (Negative scores occur in " + "the signal graph files as a consequence of background correction.) 3. All " + "scores from a single sample (i.e. cell line or developmental stage) were " + "normalized by median-centering to a value of 100. That is, we divided each " + "score in a sample by the grand median of all scores in that sample, and " + "multiplied by 100, thereby setting the median of each sample to 100. We have" + " taken log2 of each expression score to create the heatmap. "; /** * {@inheritDoc} */ @Override public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); ObjectStore os = im.getObjectStore(); InterMineBag bag = (InterMineBag) request.getAttribute("bag"); DecimalFormat df = new DecimalFormat(" Model model = im.getModel(); PathQuery query = new PathQuery(model); if ("Gene".equals(bag.getType())) { // for Gene expression query = queryGeneExpressionScore(bag.getName(), query); Profile profile = SessionMethods.getProfile(session); PathQueryExecutor executor = im.getPathQueryExecutor(profile); ExportResultsIterator result = executor.execute(query); Map<String, List<ExpressionScore>> geneExpressionScoreMap = new LinkedHashMap<String, List<ExpressionScore>>(); String dCCid = null; // 3305 String prevGene = null; List<String> expressionConditionsInOrder = Arrays.asList(EXPRESSION_ORDERED_CONDITION); List<ExpressionScore> expressionScoreList = new ArrayList<ExpressionScore>( Collections.nCopies(expressionConditionsInOrder.size(), new ExpressionScore())); while (result.hasNext()) { List<ResultElement> row = result.next(); String condition = null; // parse returned data String geneId = (String) row.get(0).getField(); String geneSymbol = (String) row.get(1).getField(); Double score = (Double) row.get(2).getField(); String cellLine = (String) row.get(3).getField(); String developmentalStage = (String) row.get(4).getField(); String dccId = (String) row.get(5).getField(); dCCid = dccId; if (geneSymbol == null) { geneSymbol = geneId; } ExpressionScore aScore = null; if (prevGene != null && !geneSymbol.equalsIgnoreCase(prevGene)) { geneExpressionScoreMap.put(prevGene, expressionScoreList); expressionScoreList = new ArrayList<ExpressionScore>( Collections.nCopies(expressionConditionsInOrder.size(), new ExpressionScore())); } if (cellLine == null && developmentalStage != null) { aScore = new ExpressionScore(developmentalStage, score, geneId, geneSymbol); condition = developmentalStage; } else if (developmentalStage == null && cellLine != null) { aScore = new ExpressionScore(cellLine, score, geneId, geneSymbol); condition = cellLine; } else { String msg = "CellLine and DevelopmentalStage must be mutually exclusive and " + "can not be NULL at the same time..."; throw new RuntimeException(msg); } expressionScoreList.set(expressionConditionsInOrder.indexOf(condition), aScore); prevGene = geneSymbol; } geneExpressionScoreMap.put(prevGene, expressionScoreList); request.setAttribute("expressionScoreMap", geneExpressionScoreMap); // To make a legend for the heat map Double logGeneExpressionScoreMin = Math.log(ModMineUtil.getMinGeneExpressionScore(os) + 1) / Math.log(2); Double logGeneExpressionScoreMax = Math.log(ModMineUtil.getMaxGeneExpressionScore(os) + 1) / Math.log(2); request.setAttribute("minExpressionScore", df.format(logGeneExpressionScoreMin)); request.setAttribute("maxExpressionScore", df.format(logGeneExpressionScoreMax)); request.setAttribute("maxExpressionScoreCeiling", Math.ceil(logGeneExpressionScoreMax)); request.setAttribute("expressionScoreDCCid", dCCid); request.setAttribute("ExpressionScoreTitle", geneExpressionScoreTitle); request.setAttribute("ExpressionScoreSummary", expressionScoreSummary); request.setAttribute("ExpressionScoreDescription", geneExpressionScoreDescription); } else if ("Exon".equals(bag.getType())) { // for Exon expression query = queryExonExpressionScore(bag.getName(), query); Profile profile = SessionMethods.getProfile(session); PathQueryExecutor executor = im.getPathQueryExecutor(profile); ExportResultsIterator result = executor.execute(query); Map<String, List<ExpressionScore>> exonExpressionScoreMap = new LinkedHashMap<String, List<ExpressionScore>>(); String dCCid = null; // 3305 String prevExon = null; List<String> expressionConditionsInOrder = Arrays.asList(EXPRESSION_ORDERED_CONDITION); List<ExpressionScore> expressionScoreList = new ArrayList<ExpressionScore>( Collections.nCopies(expressionConditionsInOrder.size(), new ExpressionScore())); while (result.hasNext()) { List<ResultElement> row = result.next(); String condition = null; // parse returned data String exonId = (String) row.get(0).getField(); String exonSymbol = (String) row.get(1).getField(); Double score = (Double) row.get(2).getField(); String cellLine = (String) row.get(3).getField(); String developmentalStage = (String) row.get(4).getField(); String dccId = (String) row.get(5).getField(); dCCid = dccId; if (exonSymbol == null) { exonSymbol = exonId; } ExpressionScore aScore = null; if (prevExon != null && !exonSymbol.equalsIgnoreCase(prevExon)) { exonExpressionScoreMap.put(prevExon, expressionScoreList); expressionScoreList = new ArrayList<ExpressionScore>( Collections.nCopies(expressionConditionsInOrder.size(), new ExpressionScore())); } if (cellLine == null && developmentalStage != null) { aScore = new ExpressionScore(developmentalStage, score, exonId, exonSymbol); condition = developmentalStage; } else if (developmentalStage == null && cellLine != null) { aScore = new ExpressionScore(cellLine, score, exonId, exonSymbol); condition = cellLine; } else { String msg = "CellLine and DevelopmentalStage must be mutually exclusive and " + "can not be NULL at the same time..."; throw new RuntimeException(msg); } expressionScoreList.set(expressionConditionsInOrder.indexOf(condition), aScore); prevExon = exonSymbol; } exonExpressionScoreMap.put(prevExon, expressionScoreList); request.setAttribute("expressionScoreMap", exonExpressionScoreMap); // To make a legend for the heat map, take log2 of the original scores Double logExonExpressionScoreMin = Math.log(ModMineUtil.getMinExonExpressionScore(os) + 1) / Math.log(2); Double logExonExpressionScoreMax = Math.log(ModMineUtil.getMaxExonExpressionScore(os) + 1) / Math.log(2); request.setAttribute("minExpressionScore", df.format(logExonExpressionScoreMin)); request.setAttribute("maxExpressionScore", df.format(logExonExpressionScoreMax)); request.setAttribute("maxExpressionScoreCeiling", Math.ceil(logExonExpressionScoreMax)); request.setAttribute("expressionScoreDCCid", dCCid); request.setAttribute("ExpressionScoreTitle", exonExpressionScoreTitle); request.setAttribute("ExpressionScoreSummary", expressionScoreSummary); request.setAttribute("ExpressionScoreDescription", exonExpressionScoreDescription); } else { return null; } return null; } /** * Create a path query to retrieve gene expression score. * * @param bagName the bag includes the query genes * @param query a pathquery * @return the pathquery */ private PathQuery queryGeneExpressionScore(String bagName, PathQuery query) { // Add views query.addViews( "GeneExpressionScore.gene.primaryIdentifier", "GeneExpressionScore.gene.symbol", "GeneExpressionScore.score", "GeneExpressionScore.cellLine.name", "GeneExpressionScore.developmentalStage.name", "GeneExpressionScore.submission.DCCid" ); // Add orderby query.addOrderBy("GeneExpressionScore.gene.primaryIdentifier", OrderDirection.ASC); // Add constraints and you can edit the constraint values below query.addConstraint(Constraints.in("GeneExpressionScore.gene", bagName)); // Add join status query.setOuterJoinStatus("GeneExpressionScore.cellLine", OuterJoinStatus.OUTER); query.setOuterJoinStatus("GeneExpressionScore.developmentalStage", OuterJoinStatus.OUTER); return query; } /** * Create a path query to retrieve exon expression score. * * @param bagName the bag includes the query exons * @param query a pathquery * @return the pathquery */ private PathQuery queryExonExpressionScore(String bagName, PathQuery query) { // Add views query.addViews( "ExonExpressionScore.exon.primaryIdentifier", "ExonExpressionScore.exon.symbol", "ExonExpressionScore.score", "ExonExpressionScore.cellLine.name", "ExonExpressionScore.developmentalStage.name", "ExonExpressionScore.submission.DCCid" ); // Add orderby query.addOrderBy("ExonExpressionScore.exon.primaryIdentifier", OrderDirection.ASC); // Add constraints and you can edit the constraint values below query.addConstraint(Constraints.in("ExonExpressionScore.exon", bagName)); // Add join status query.setOuterJoinStatus("ExonExpressionScore.cellLine", OuterJoinStatus.OUTER); query.setOuterJoinStatus("ExonExpressionScore.developmentalStage", OuterJoinStatus.OUTER); return query; } }
package com.lopei.collageview; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.v7.widget.CardView; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollageView extends LinearLayout { private List<String> urls; private int[] resIds; private int color = Color.TRANSPARENT; private int photoPadding = 0; private int photoMargin = 0; private int placeHolderResId = 0; private int photoFrameColor = Color.TRANSPARENT; private boolean useCards = false; private boolean useFirstAsHeader = true; private int defaultPhotosForLine = 3; private ImageForm photosForm = ImageForm.IMAGE_FORM_SQUARE; private ImageForm headerForm = ImageForm.IMAGE_FORM_SQUARE; private OnPhotoClickListener onPhotoClickListener; public CollageView(Context context) { super(context); } public CollageView(Context context, AttributeSet attrs) { super(context, attrs); } public CollageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public CollageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public CollageView backgroundColor(int color) { this.color = color; return this; } public CollageView photoPadding(int photoPadding) { this.photoPadding = photoPadding; return this; } public CollageView photoMargin(int photoMargin) { this.photoMargin = photoMargin; return this; } public CollageView photoFrameColor(int photoFrameColor) { this.photoFrameColor = photoFrameColor; return this; } public CollageView placeHolder(int resId) { this.placeHolderResId = resId; return this; } public CollageView useCards(boolean useCards) { this.useCards = useCards; return this; } public void loadPhotos(String[] urls) { this.urls = new ArrayList<>(Arrays.asList(urls)); init(); } public void loadPhotos(int[] resIds) { this.resIds = resIds; init(); } public void loadPhotos(List<String> urls) { this.urls = urls; init(); } public CollageView useFirstAsHeader(boolean useFirstAsHeader) { this.useFirstAsHeader = useFirstAsHeader; return this; } public CollageView defaultPhotosForLine(int defaultPhotosForLine) { this.defaultPhotosForLine = defaultPhotosForLine; return this; } public CollageView photosForm(ImageForm photosForm) { this.photosForm = photosForm; return this; } public CollageView headerForm(ImageForm headerForm) { this.headerForm = headerForm; return this; } private void init() { boolean fromResources = resIds != null && urls == null; setOrientation(VERTICAL); setBackgroundColor(color); removeAllViews(); ArrayList<String> addUrls = new ArrayList<>(); ArrayList<Integer> addRes = new ArrayList<>(); ArrayList<Integer> photosCount = buildPhotosCounts(); if (urls != null || resIds != null) { int size = getPhotosSize(); if (size > 0) { int number = 0; int i = 0; while (i < size) { int photosInLine = photosCount.get(getChildCount()); if (fromResources) { addRes.add(resIds[i]); } else { addUrls.add(urls.get(i)); } number++; if (number == photosInLine || size == i + 1) { final LinearLayout photosLine = new LinearLayout(getContext()); photosLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); photosLine.setOrientation(LinearLayout.HORIZONTAL); photosLine.setWeightSum(photosInLine * 1f); for (int j = 0; j < photosInLine; j++) { ViewGroup photoFrame; if (useCards) { photoFrame = new CardView(getContext()); } else { photoFrame = new FrameLayout(getContext()); } LayoutParams layoutParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f); layoutParams.setMargins(photoMargin, photoMargin, photoMargin, photoMargin); photoFrame.setLayoutParams(layoutParams); ImageForm imageForm = useFirstAsHeader && i == 0 ? headerForm : photosForm; ImageView imageView = new RectangleImageView(getContext(), imageForm); imageView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); imageView.setAdjustViewBounds(true); imageView.setBackgroundColor(photoFrameColor); imageView.setPadding(photoPadding, photoPadding, photoPadding, photoPadding); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); photoFrame.addView(imageView); String url = null; int resId = 0; if (fromResources) { resId = addRes.get(j); } else { url = addUrls.get(j); } try { Picasso picasso = Picasso .with(getContext()); RequestCreator requestCreator = null; if (fromResources) { if (resId != 0) { requestCreator = picasso.load(resId); } } else { if (url != null) { requestCreator = picasso.load(url); } } if (requestCreator != null) { if (placeHolderResId != 0) { requestCreator.placeholder(placeHolderResId); } requestCreator.into(imageView); } } catch (NullPointerException e) { e.printStackTrace(); } final int finalI = i; photoFrame.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (onPhotoClickListener != null) { onPhotoClickListener.onPhotoClick(finalI); } } }); photosLine.addView(photoFrame); } addView(photosLine); addUrls.clear(); addRes.clear(); number = 0; } i++; } } } } private int getPhotosSize() { int size = 0; if (urls != null) { size = urls.size(); } else if (resIds != null) { size = resIds.length; } return size; } private ArrayList<Integer> buildPhotosCounts() { int headerDecreaser = useFirstAsHeader ? 1 : 0; int photosSize = getPhotosSize() - headerDecreaser; int remainder = photosSize % defaultPhotosForLine; int lineCount = photosSize / defaultPhotosForLine; ArrayList<Integer> photosCounts = new ArrayList<>(); if (useFirstAsHeader) { photosCounts.add(1); lineCount++; } for (int i = 0; i < lineCount; i++) { photosCounts.add(defaultPhotosForLine); } if (remainder >= lineCount) { photosCounts.add(headerDecreaser, remainder); } else { for (int i = lineCount - 1; i > lineCount - remainder - 1; i photosCounts.set(i, photosCounts.get(i) + 1); } } return photosCounts; } public void setOnPhotoClickListener(OnPhotoClickListener onPhotoClickListener) { this.onPhotoClickListener = onPhotoClickListener; } public interface OnPhotoClickListener { void onPhotoClick(int position); } public enum ImageForm { IMAGE_FORM_SQUARE(1), IMAGE_FORM_HALF_HEIGHT(2); private int divider = 1; ImageForm(int divider) { this.divider = divider; } public int getDivider() { return divider; } } }
package org.apache.cloudstack.storage.resource; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.exception.CloudRuntimeException; import javax.naming.ConfigurationException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.Map; import java.util.Properties; import junit.framework.Assert; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NfsSecondaryStorageResourceTest extends TestCase { private static final Logger s_logger = LoggerFactory.getLogger(NfsSecondaryStorageResourceTest.class.getName()); private static Map<String, Object> testParams; NfsSecondaryStorageResource resource; @Before @Override public void setUp() throws ConfigurationException { resource = new NfsSecondaryStorageResource(); resource.setInSystemVM(true); testParams = PropertiesUtil.toMap(loadProperties()); resource.configureStorageLayerClass(testParams); final Object testLocalRoot = testParams.get("testLocalRoot"); if (testLocalRoot != null) { resource.setParentPath((String) testLocalRoot); } } public static Properties loadProperties() throws ConfigurationException { final Properties properties = new Properties(); final File file = PropertiesUtil.findConfigFile("agent.properties"); if (file == null) { throw new ConfigurationException("Unable to find agent.properties."); } s_logger.info("agent.properties found at " + file.getAbsolutePath()); try (FileInputStream fs = new FileInputStream(file)) { properties.load(fs); } catch (final FileNotFoundException ex) { throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex); } catch (final IOException ex) { throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex); } return properties; } @Test public void testMount() throws Exception { final String sampleUriStr = "cifs://192.168.1.128/CSHV3?user=administrator&password=1pass%40word1&foo=bar"; final URI sampleUri = new URI(sampleUriStr); s_logger.info("Check HostIp parsing"); final String hostIpStr = resource.getUriHostIp(sampleUri); Assert.assertEquals("Expected host IP " + sampleUri.getHost() + " and actual host IP " + hostIpStr + " differ.", sampleUri.getHost(), hostIpStr); s_logger.info("Check option parsing"); final String expected = "user=administrator,password=1pass@word1,foo=bar,"; final String actualOpts = resource.parseCifsMountOptions(sampleUri); Assert.assertEquals("Options should be " + expected + " and not " + actualOpts, expected, actualOpts); // attempt a configured mount final Map<String, Object> params = PropertiesUtil.toMap(loadProperties()); final String sampleMount = (String) params.get("testCifsMount"); if (!sampleMount.isEmpty()) { s_logger.info("functional test, mount " + sampleMount); final URI realMntUri = new URI(sampleMount); final String mntSubDir = resource.mountUri(realMntUri); s_logger.info("functional test, umount " + mntSubDir); resource.umount(resource.getMountingRoot() + mntSubDir, realMntUri); } else { s_logger.info("no entry for testCifsMount in " + "./conf/agent.properties - skip functional test"); } } }
package org.deeplearning4j.iterativereduce.actor.multilayer; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.deeplearning4j.datasets.DataSet; import org.deeplearning4j.iterativereduce.actor.core.Ack; import org.deeplearning4j.iterativereduce.actor.core.ClearWorker; import org.deeplearning4j.iterativereduce.actor.core.ClusterListener; import org.deeplearning4j.iterativereduce.actor.core.Job; import org.deeplearning4j.iterativereduce.actor.core.NoJobFound; import org.deeplearning4j.iterativereduce.actor.core.actor.MasterActor; import org.deeplearning4j.iterativereduce.actor.util.ActorRefUtils; import org.deeplearning4j.iterativereduce.tracker.statetracker.StateTracker; import org.deeplearning4j.iterativereduce.tracker.statetracker.hazelcast.HazelCastStateTracker; import org.deeplearning4j.nn.BaseMultiLayerNetwork; import org.deeplearning4j.scaleout.conf.Conf; import org.deeplearning4j.scaleout.iterativereduce.Updateable; import org.deeplearning4j.scaleout.iterativereduce.multi.UpdateableImpl; import org.jblas.DoubleMatrix; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.Props; import akka.contrib.pattern.DistributedPubSubExtension; import akka.contrib.pattern.DistributedPubSubMediator; import akka.contrib.pattern.DistributedPubSubMediator.Put; import akka.dispatch.Futures; /** * Iterative reduce actor for handling batch sizes * @author Adam Gibson * */ public class WorkerActor extends org.deeplearning4j.iterativereduce.actor.core.actor.WorkerActor<UpdateableImpl> { protected BaseMultiLayerNetwork network; protected DoubleMatrix combinedInput; protected UpdateableImpl workerUpdateable; protected ActorRef mediator = DistributedPubSubExtension.get(getContext().system()).mediator(); protected Cancellable heartbeat; protected static Logger log = LoggerFactory.getLogger(WorkerActor.class); public final static String SYSTEM_NAME = "Workers"; protected int numTimesReceivedNullJob = 0; public WorkerActor(Conf conf,StateTracker<UpdateableImpl> tracker) { super(conf,tracker); setup(conf); //subscribe to broadcasts from workers (location agnostic) mediator.tell(new Put(getSelf()), getSelf()); //subscribe to broadcasts from master (location agnostic) mediator.tell(new DistributedPubSubMediator.Subscribe(MasterActor.BROADCAST, getSelf()), getSelf()); //subscribe to broadcasts from master (location agnostic) mediator.tell(new DistributedPubSubMediator.Subscribe(id, getSelf()), getSelf()); heartbeat(); } public WorkerActor(ActorRef clusterClient,Conf conf,StateTracker<UpdateableImpl> tracker) { super(conf,clusterClient,tracker); setup(conf); //subscribe to broadcasts from workers (location agnostic) mediator.tell(new Put(getSelf()), getSelf()); //subscribe to broadcasts from master (location agnostic) mediator.tell(new DistributedPubSubMediator.Subscribe(MasterActor.BROADCAST, getSelf()), getSelf()); tracker.addWorker(id); //subscribe to broadcasts from master (location agnostic) mediator.tell(new DistributedPubSubMediator.Subscribe(id, getSelf()), getSelf()); heartbeat(); } public static Props propsFor(ActorRef actor,Conf conf,StateTracker<UpdateableImpl> tracker) { return Props.create(WorkerActor.class,actor,conf,tracker); } public static Props propsFor(Conf conf,HazelCastStateTracker stateTracker) { return Props.create(WorkerActor.class,conf,stateTracker); } protected void confirmWorking() { Job j = tracker.jobFor(id); //reply if(j != null) mediator.tell(new DistributedPubSubMediator.Publish(MasterActor.MASTER, j), getSelf()); else log.warn("Not confirming work when none to be found"); } protected void heartbeat() { heartbeat = context().system().scheduler().schedule(Duration.apply(10, TimeUnit.SECONDS), Duration.apply(10, TimeUnit.SECONDS), new Runnable() { @Override public void run() { log.info("Sending heartbeat to master"); mediator.tell(new DistributedPubSubMediator.Publish(MasterActor.MASTER, register()), getSelf()); tracker.addWorker(id); } }, context().dispatcher()); } @SuppressWarnings("unchecked") @Override public void onReceive(Object message) throws Exception { if (message instanceof DistributedPubSubMediator.SubscribeAck || message instanceof DistributedPubSubMediator.UnsubscribeAck) { DistributedPubSubMediator.SubscribeAck ack = (DistributedPubSubMediator.SubscribeAck) message; //reply mediator.tell(new DistributedPubSubMediator.Publish(ClusterListener.TOPICS, message), getSelf()); log.info("Subscribed to " + ack.toString()); } else if(message instanceof Job) { Job j = (Job) message; Job trackerJob = tracker.jobFor(id); if(trackerJob == null) { tracker.addJobToCurrent(j); log.info("Confirmation from " + j.getWorkerId() + " on work"); List<DataSet> input = (List<DataSet>) j.getWork(); confirmWorking(); updateTraining(input); } else { //block till there's an available worker Job j2 = null; boolean redist = false; while(!redist) { List<String> ids = tracker.jobIds(); for(String s : ids) { if(tracker.jobFor(s) == null) { //wrap in a job for additional metadata j2 = j; j2.setWorkerId(s); //replicate the network mediator.tell(new DistributedPubSubMediator.Publish(s, j2), getSelf()); log.info("Delegated work to worker " + s); redist = true; break; } } } } } else if(message instanceof BaseMultiLayerNetwork) { setNetwork((BaseMultiLayerNetwork) message); log.info("Set network"); } else if(message instanceof Ack) { log.info("Ack from master on worker " + id); } else if(message instanceof Updateable) { final UpdateableImpl m = (UpdateableImpl) message; Future<Void> f = Futures.future(new Callable<Void>() { @Override public Void call() throws Exception { if(m.get() == null) { setNetwork(tracker.getCurrent().get()); } else { setWorkerUpdateable(m.clone()); setNetwork(m.get()); } return null; } },context().dispatcher()); ActorRefUtils.throwExceptionIfExists(f, context().dispatcher()); } else unhandled(message); } protected void updateTraining(List<DataSet> list) { DoubleMatrix newInput = new DoubleMatrix(list.size(),list.get(0).getFirst().columns); DoubleMatrix newOutput = new DoubleMatrix(list.size(),list.get(0).getSecond().columns); for(int i = 0; i < list.size(); i++) { newInput.putRow(i,list.get(i).getFirst()); newOutput.putRow(i,list.get(i).getSecond()); } setCombinedInput(newInput); setOutcomes(newOutput); Future<UpdateableImpl> f = Futures.future(new Callable<UpdateableImpl>() { @Override public UpdateableImpl call() throws Exception { UpdateableImpl work = compute(); if(work != null) { log.info("Updating parent actor..."); //update parameters in master param server mediator.tell(new DistributedPubSubMediator.Publish(MasterActor.MASTER, work), getSelf()); } else { //ensure next iteration happens by decrementing number of required batches mediator.tell(new DistributedPubSubMediator.Publish(MasterActor.MASTER, NoJobFound.getInstance()), getSelf()); log.info("No job found; unlocking worker " + id); } return work; } }, getContext().dispatcher()); ActorRefUtils.throwExceptionIfExists(f, context().dispatcher()); } @Override public UpdateableImpl compute(List<UpdateableImpl> records) { return compute(); } @Override public UpdateableImpl compute() { log.info("Training network"); BaseMultiLayerNetwork network = this.getNetwork(); while(network == null) { try { network = tracker.getCurrent().get(); this.network = network; } catch (Exception e) { throw new RuntimeException(e); } } DataSet d = null; Job j = tracker.jobFor(id); if(j != null) { log.info("Found job for worker " + id); if(j.getWork() instanceof List) { List<DataSet> l = (List<DataSet>) j.getWork(); d = DataSet.merge(l); } else d = (DataSet) j.getWork(); combinedInput = d.getFirst(); outcomes = d.getSecond(); } if(j == null) return null; if(d == null) { throw new IllegalStateException("No job found for worker " + id); } if(tracker.isPretrain()) { log.info("Worker " + id + " pretraining"); network.pretrain(d.getFirst(), extraParams); } else { network.setInput(d.getFirst()); log.info("Worker " + id + " finetuning"); network.finetune(d.getSecond(), learningRate, fineTuneEpochs); } try { if(j != null) tracker.clearJob(j); } catch (Exception e) { throw new RuntimeException(e); } return new UpdateableImpl(network); } @Override public boolean incrementIteration() { return false; } @Override public void setup(Conf conf) { super.setup(conf); } @Override public void aroundPostStop() { super.aroundPostStop(); //replicate the network mediator.tell(new DistributedPubSubMediator.Publish(MasterActor.MASTER, new ClearWorker(id)), getSelf()); heartbeat.cancel(); } @Override public UpdateableImpl getResults() { return workerUpdateable; } @Override public void update(UpdateableImpl t) { this.workerUpdateable = t; } public synchronized BaseMultiLayerNetwork getNetwork() { return network; } public void setNetwork(BaseMultiLayerNetwork network) { this.network = network; } public DoubleMatrix getCombinedInput() { return combinedInput; } public void setCombinedInput(DoubleMatrix combinedInput) { this.combinedInput = combinedInput; } public UpdateableImpl getWorkerUpdateable() { return workerUpdateable; } public void setWorkerUpdateable(UpdateableImpl workerUpdateable) { this.workerUpdateable = workerUpdateable; } }
package org.neo4j.server.logging; import java.util.Properties; import org.apache.log4j.PropertyConfigurator; import org.junit.Test; public class LoggerTest { @Test public void testParsingLog() { Properties props = new Properties(); props.put( "log4j.rootLogger", "DEBUG, R" ); props.put( "log4j.appender.R", "org.apache.log4j.RollingFileAppender" ); props.put( "log4j.appender.R.File","target/neo4j.log" ); props.put( "log4j.appender.R.layout","org.apache.log4j.PatternLayout" ); props.put( "log4j.appender.R.layout.ConversionPattern","%p %t %c - %m%n" ); PropertyConfigurator.configure(props); Logger log = Logger.getLogger( getClass()); org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger( getClass() ); String message = String.format("No configuration file at [%s]", "%N"); log4jLogger.error( String.format( "%%N") ); log.error( message ); } }
package br.ufba.ia.copsandrobbers.search; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import java.util.Vector; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; public class AStar { //Declare constants public static final int larguraTela = 80, alturaTela = 60, tamanhoPixel = 20, qtdeAgentes = 3; // Constantes relacionadas ao caminho public static final int naoTerminou = 0 ; public static final int naoComecou = 0; public static final int encontrado = 1, naoExiste = 2; public static final int caminhoPassavel = 0, caminhoBloqueado = 1; // constantes referente a habilidade de andar. public int naListaFechada = 10; //Create needed arrays public char[][] espacoDeCaminhada = new char[larguraTela][alturaTela]; public int[] listaAberta = new int[larguraTela*alturaTela+2]; public int[][] whichList = new int[larguraTela+1][alturaTela+1]; public int[] openX = new int[larguraTela*alturaTela+2]; public int[] openY = new int[larguraTela*alturaTela+2]; public int[][] parentX = new int[larguraTela+1][alturaTela+1]; public int[][] parentY = new int[larguraTela+1][alturaTela+1]; public int[] Fcost = new int[larguraTela*alturaTela+2]; public int[][] Gcost = new int[larguraTela+1][alturaTela+1]; public int[] Hcost = new int[larguraTela*alturaTela+2]; public int[] pathLength = new int[qtdeAgentes+1]; //armazena o tamanho do caminho encontrado para a criatura public int[] pathLocation = new int[qtdeAgentes+1]; //int* pathBank [qtdeAgentes+1]; public List<Integer> pathBank[] = new List[qtdeAgentes+1]; public List<Integer[]> pathBank2 = new ArrayList<Integer[]>(); //Path reading variables public int[] pathStatus = new int[qtdeAgentes+1]; public int[] xPath = new int[qtdeAgentes+1]; public int[] yPath = new int[qtdeAgentes+1]; public void InitializePathfinder () { for (int x = 0; x < qtdeAgentes+1; x++){ pathBank[x] = new Vector<Integer>(); pathBank2.add(new Integer[4]); } } public void EndPathfinder () { for (int x = 0; x < qtdeAgentes+1; x++){ pathBank[x].clear(); pathBank2.set(x, null); } } public int FindPath (int pathfinderID, int startingX, int startingY, int targetX, int targetY) { int naListaAberta=0, parentXval=0, parentYval=0, a=0, b=0, m=0, u=0, v=0, temp=0, corner=0, numItemsListaAberta=0, addedGCost=0, tempGcost = 0, path = 0, tempx, pathX, pathY, cellPosition, novoIDItemListaAberta=0; int startX = startingX/tamanhoPixel; int startY = startingY/tamanhoPixel; targetX = targetX/tamanhoPixel; targetY = targetY/tamanhoPixel; if (startX == targetX && startY == targetY && pathLocation[pathfinderID] > 0) return encontrado; if (startX == targetX && startY == targetY && pathLocation[pathfinderID] == 0) return naoExiste; if (espacoDeCaminhada[targetX][targetY] == caminhoBloqueado) { xPath[pathfinderID] = startingX; yPath[pathfinderID] = startingY; return naoExiste; } if (naListaFechada > 1000000) //Resetando whichList ocasionalmente { for (int x = 0; x < larguraTela; x++) { for (int y = 0; y < alturaTela; y++) whichList [x][y] = 0; } naListaFechada = 10; } naListaFechada = naListaFechada+2; //alterando os valores da listaAberta(lista aberta) e onClosed list eh mais rapida do que redimensionar whichList() array; naListaAberta = naListaFechada-1; pathLength [pathfinderID] = naoComecou;//i.e, = 0 pathLocation [pathfinderID] = naoComecou;//i.e, = 0 Gcost[startX][startY] = 0; //resetando o quadrado inicial com o valor de G para 0 //4. Adicionando a posicao inicial listaAberta de quadrados para serem verificados. numItemsListaAberta = 1; listaAberta[1] = 1; //colocando este como o item do topo(e atualmente somente) da listaAberta, que eh mantida como uma heap binaria. openX[1] = startX; openY[1] = startY; //5. Faca o seguinte ate que um caminho eh encontrador ou ele nao exista. do { if (numItemsListaAberta != 0) { //7. Remova o primeiro item da listaAberta. parentXval = openX[listaAberta[1]]; parentYval = openY[listaAberta[1]]; //Grave as coordenadas da celula do item whichList[parentXval][parentYval] = naListaFechada;//adicione o item para a closedList numItemsListaAberta = numItemsListaAberta - 1;//reduzindo o numero de items da listaAberta em 1 listaAberta[1] = listaAberta[numItemsListaAberta+1];//mova o ultimo item na heap a cima para o slot v = 1; do { u = v; if (2*u+1 <= numItemsListaAberta) //Se ambos os filhos existirem { //Selecione o menor dos dois filhos. if (Fcost[listaAberta[u]] >= Fcost[listaAberta[2*u]]) v = 2*u; if (Fcost[listaAberta[v]] >= Fcost[listaAberta[2*u+1]]) v = 2*u+1; } else { if (2*u <= numItemsListaAberta) //Se somente o filho 1 existe { if (Fcost[listaAberta[u]] >= Fcost[listaAberta[2*u]]) v = 2*u; } } if (u != v) { temp = listaAberta[u]; listaAberta[u] = listaAberta[v]; listaAberta[v] = temp; } else break; //de outro modo, saia do loop } while (!(Gdx.input.isKeyPressed(Keys.ESCAPE))); //Tentei isso, mas no sei como criar a varivel actualkey. for (b = parentYval-1; b <= parentYval+1; b++){ for (a = parentXval-1; a <= parentXval+1; a++){ if (a != -1 && b != -1 && a != larguraTela && b != alturaTela){ if (whichList[a][b] != naListaFechada) { if (espacoDeCaminhada [a][b] != caminhoBloqueado) { corner = caminhoPassavel; if (a == parentXval-1) { if (b == parentYval-1) { if (espacoDeCaminhada[parentXval-1][parentYval] == caminhoBloqueado || espacoDeCaminhada[parentXval][parentYval-1] == caminhoBloqueado) corner = caminhoBloqueado; } else if (b == parentYval+1) { if (espacoDeCaminhada[parentXval][parentYval+1] == caminhoBloqueado || espacoDeCaminhada[parentXval-1][parentYval] == caminhoBloqueado) corner = caminhoBloqueado; } } else if (a == parentXval+1) { if (b == parentYval-1) { if (espacoDeCaminhada[parentXval][parentYval-1] == caminhoBloqueado || espacoDeCaminhada[parentXval+1][parentYval] == caminhoBloqueado) corner = caminhoBloqueado; } else if (b == parentYval+1) { if (espacoDeCaminhada[parentXval+1][parentYval] == caminhoBloqueado || espacoDeCaminhada[parentXval][parentYval+1] == caminhoBloqueado) corner = caminhoBloqueado; } } if (corner == caminhoPassavel) { if (whichList[a][b] != naListaAberta) { //Cria um item novo na listaAberta na heap binaria. novoIDItemListaAberta = novoIDItemListaAberta + 1; //Cada novo item tem um ID unico. m = numItemsListaAberta+1; listaAberta[m] = novoIDItemListaAberta;// Coloque o novo item da listaAberta(atualmente ID#) na base da heap. openX[novoIDItemListaAberta] = a; openY[novoIDItemListaAberta] = b;//grave suas coordenadas x e y do novo item //Calculando o custo de G if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//custo de ir pelas diagonais dos quadrados; else addedGCost = 10; Gcost[a][b] = Gcost[parentXval][parentYval] + addedGCost; //Calcular os custos H e F e o pai Hcost[listaAberta[m]] = AStar.tamanhoPixel*(Math.abs(a - targetX) + Math.abs(b - targetY)); Fcost[listaAberta[m]] = Gcost[a][b] + Hcost[listaAberta[m]]; parentX[a][b] = parentXval ; parentY[a][b] = parentYval; //Iniciando da base, sucessivamente comparar items pais, //ou borbulhando todos os caminhos para o topo (se este tem o menor custo de F). while (m != 1) { if (Fcost[listaAberta[m]] <= Fcost[listaAberta[m/2]]) { temp = listaAberta[m/2]; listaAberta[m/2] = listaAberta[m]; listaAberta[m] = temp; m = m/2; } else break; } numItemsListaAberta = numItemsListaAberta+1; whichList[a][b] = naListaAberta; } //8.If adjacent cell is already on the open list, check to see if this else //Se whichList(a,b) = naListaAberta { if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//Custo de ir pelas diagonais else addedGCost = 10; tempGcost = Gcost[parentXval][parentYval] + addedGCost; if (tempGcost < Gcost[a][b]) { parentX[a][b] = parentXval; //troque o quadrado pai parentY[a][b] = parentYval; Gcost[a][b] = tempGcost;//troque o custo de G for (int x = 1; x <= numItemsListaAberta; x++) //olho para o item na listaAberta { if (openX[listaAberta[x]] == a && openY[listaAberta[x]] == b) //item encontrado { Fcost[listaAberta[x]] = Gcost[a][b] + Hcost[listaAberta[x]];//troque o custo F m = x; while (m != 1) { if (Fcost[listaAberta[m]] < Fcost[listaAberta[m/2]]) { temp = listaAberta[m/2]; listaAberta[m/2] = listaAberta[m]; listaAberta[m] = temp; m = m/2; } else break; } break; //saia para x = loop } //Se openX(listaAberta(x)) = a } //For x = 1 To numItemsListaAberta }//If tempGcost < Gcost(a,b) }//else If whichList(a,b) = naListaAberta } } } } }//for (a = parentXval-1; a <= parentXval+1; a++){ }//for (b = parentYval-1; b <= parentYval+1; b++){ }//if (numItemsListaAberta != 0) else { path = naoExiste; break; } if (whichList[targetX][targetY] == naListaAberta) { path = encontrado; break; } } while (true); if (path == encontrado) { pathX = targetX; pathY = targetY; do { tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; //Calcular o tamanho do caminho. pathLength[pathfinderID] = pathLength[pathfinderID] + 1; } while (pathX != startX || pathY != startY); //b.Redimensione o dataBank para o correto tamanho em bytes. Integer[] arr = pathBank2.get(pathfinderID); pathBank2.set(pathfinderID, Arrays.copyOf(arr, pathLength[pathfinderID]*8)); // um conjunto corretamente ordenado de dados do caminho, para o primeiro passo pathX = targetX ; pathY = targetY; cellPosition = pathLength[pathfinderID]*2;//Inicie do final do { cellPosition = cellPosition - 2; pathBank2.get(pathfinderID)[cellPosition] = pathX; pathBank2.get(pathfinderID)[cellPosition+1] = pathY; tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; } while (pathX != startX || pathY != startY); //11. Leia o primeiro passo dentro dos arrays xPath/yPath. ReadPath(pathfinderID,startingX,startingY,1); } return path; } public void ReadPath (int pathfinderID,int currentX,int currentY, int pixelsPerFrame) { int ID = pathfinderID; //Se um caminho tem sido encontrado para o pathfinder ... if (pathStatus[ID] == encontrado) { if (pathLocation[ID] < pathLength[ID]) { if (pathLocation[ID] == 0 || (Math.abs(currentX - xPath[ID]) < pixelsPerFrame && Math.abs(currentY - yPath[ID]) < pixelsPerFrame)) pathLocation[ID] = pathLocation[ID] + 1; } //Leia o dado do caminho. xPath[ID] = ReadPathX(ID,pathLocation[ID]); yPath[ID] = ReadPathY(ID,pathLocation[ID]); if (pathLocation[ID] == pathLength[ID]) { if (Math.abs(currentX - xPath[ID]) < pixelsPerFrame && Math.abs(currentY - yPath[ID]) < pixelsPerFrame) //Se perto o suficiente do quadrado do centro pathStatus[ID] = naoComecou; } } else { xPath[ID] = currentX; yPath[ID] = currentY; } } //The following two functions read the raw path data from the pathBank. //You can call these functions directly and skip the readPath function //above if you want. Make sure you know what your current pathLocation //atual. // Name: ReadPathX int ReadPathX(int pathfinderID,int pathLocation) { int x = 0; if (pathLocation <= pathLength[pathfinderID]) { //Le a coordenada X do pathPathBank x = pathBank2.get(pathfinderID)[pathLocation*2-2]; //Ajusta a coordenada para ela ficar alinhada ao inicio do quadrado. x = (int) (tamanhoPixel*x); } return x; } // Name: ReadPathY int ReadPathY(int pathfinderID,int pathLocation) { int y = 0; if (pathLocation <= pathLength[pathfinderID]) { //Le as coordenadas do pathBank. // y = pathBank[pathfinderID].get(pathLocation*2-1); y = pathBank2.get(pathfinderID)[pathLocation*2-1]; //Ajusta a coordenada para ela ficar alinhada ao inicio do quadrado. y = (int) ( tamanhoPixel*y); } return y; } public int FindPathBuscaCega (int pathfinderID, int startingX, int startingY, int targetX, int targetY) { int naListaAberta=0, parentXval=0, parentYval=0, a=0, b=0, m=0, u=0, v=0, temp=0, corner=0, numItemsListaAberta=0, addedGCost=0, tempGcost = 0, path = 0, tempx, pathX, pathY, cellPosition, novoIDItemListaAberta=0; int startX = startingX/tamanhoPixel; int startY = startingY/tamanhoPixel; targetX = targetX/tamanhoPixel; targetY = targetY/tamanhoPixel; if (startX == targetX && startY == targetY && pathLocation[pathfinderID] > 0) return encontrado; if (startX == targetX && startY == targetY && pathLocation[pathfinderID] == 0) return naoExiste; if (espacoDeCaminhada[targetX][targetY] == caminhoBloqueado) { xPath[pathfinderID] = startingX; yPath[pathfinderID] = startingY; return naoExiste; } if (naListaFechada > 1000000) //Resetando whichList ocasionalmente { for (int x = 0; x < larguraTela; x++) { for (int y = 0; y < alturaTela; y++) whichList [x][y] = 0; } naListaFechada = 10; } naListaFechada = naListaFechada+2; naListaAberta = naListaFechada-1; pathLength [pathfinderID] = naoComecou;//i.e, = 0 pathLocation [pathfinderID] = naoComecou;//i.e, = 0 Gcost[startX][startY] = 0; //resetando o quadrado inicial com o valor de G para 0 pilha.push(1); openX[1] = startX; openY[1] = startY; do { if (!pilha.isEmpty()) { //7. Remova o primeiro item da openList. parentXval = openX[pilha.peek()]; parentYval = openY[pilha.peek()]; //Grave as coordenadas da celula do item numItemsListaAberta = numItemsListaAberta - 1;//reduzindo o numero de items da listaAberta em 1 listaAberta[1] = listaAberta[numItemsListaAberta+1];//mova o ultimo item na heap a cima para o slot v = 1; do { u = v; if (2*u+1 <= numItemsListaAberta) //Se ambos os filhos existirem { //Selecione o menor dos dois filhos. if (Fcost[listaAberta[u]] >= Fcost[listaAberta[2*u]]) v = 2*u; if (Fcost[listaAberta[v]] >= Fcost[listaAberta[2*u+1]]) v = 2*u+1; } else { if (2*u <= numItemsListaAberta) //Se somente o filho 1 existe { if (Fcost[listaAberta[u]] >= Fcost[listaAberta[2*u]]) v = 2*u; } } if (u != v) { temp = listaAberta[u]; listaAberta[u] = listaAberta[v]; listaAberta[v] = temp; } else break; //de outro modo, saia do loop } while (!(Gdx.input.isKeyPressed(Keys.ESCAPE))); //Tentei isso, mas no sei como criar a varivel actualkey. for (b = parentYval-1; b <= parentYval+1; b++){ for (a = parentXval-1; a <= parentXval+1; a++){ if (a != -1 && b != -1 && a != larguraTela && b != alturaTela){ if (whichList[a][b] != naListaFechada) { if (espacoDeCaminhada [a][b] != caminhoBloqueado) { corner = caminhoPassavel; if (a == parentXval-1) { if (b == parentYval-1) { if (espacoDeCaminhada[parentXval-1][parentYval] == caminhoBloqueado || espacoDeCaminhada[parentXval][parentYval-1] == caminhoBloqueado) corner = caminhoBloqueado; } else if (b == parentYval+1) { if (espacoDeCaminhada[parentXval][parentYval+1] == caminhoBloqueado || espacoDeCaminhada[parentXval-1][parentYval] == caminhoBloqueado) corner = caminhoBloqueado; } } else if (a == parentXval+1) { if (b == parentYval-1) { if (espacoDeCaminhada[parentXval][parentYval-1] == caminhoBloqueado || espacoDeCaminhada[parentXval+1][parentYval] == caminhoBloqueado) corner = caminhoBloqueado; } else if (b == parentYval+1) { if (espacoDeCaminhada[parentXval+1][parentYval] == caminhoBloqueado || espacoDeCaminhada[parentXval][parentYval+1] == caminhoBloqueado) corner = caminhoBloqueado; } } if (corner == caminhoPassavel) { if (whichList[a][b] != naListaAberta) { //Cria um item novo na listaAberta na heap binaria. novoIDItemListaAberta = novoIDItemListaAberta + 1; //Cada novo item tem um ID unico. m = numItemsListaAberta+1; listaAberta[m] = novoIDItemListaAberta;// Coloque o novo item da listaAberta(atualmente ID#) na base da heap. openX[novoIDItemListaAberta] = a; openY[novoIDItemListaAberta] = b;//grave suas coordenadas x e y do novo item //Calculando o custo de G if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//custo de ir pelas diagonais dos quadrados; else addedGCost = 10; Gcost[a][b] = 1; //Calcular os custos H e F e o pai Hcost[listaAberta[m]] = 1; Fcost[listaAberta[m]] = Gcost[a][b] + Hcost[listaAberta[m]]; parentX[a][b] = parentXval ; parentY[a][b] = parentYval; //Iniciando da base, sucessivamente comparar items pais, //ou borbulhando todos os caminhos para o topo (se este tem o menor custo de F). while (m != 1) { if (Fcost[listaAberta[m]] <= Fcost[listaAberta[m/2]]) { temp = listaAberta[m/2]; listaAberta[m/2] = listaAberta[m]; listaAberta[m] = temp; m = m/2; } else break; } numItemsListaAberta = numItemsListaAberta+1; whichList[a][b] = naListaAberta; } //8.If adjacent cell is already on the open list, check to see if this else //Se whichList(a,b) = naListaAberta { if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//Custo de ir pelas diagonais else addedGCost = 10; tempGcost = Gcost[parentXval][parentYval]; if (tempGcost < Gcost[a][b]) { parentX[a][b] = parentXval; //troque o quadrado pai parentY[a][b] = parentYval; Gcost[a][b] = tempGcost;//troque o custo de G for (int x = 1; x <= numItemsListaAberta; x++) //olho para o item na listaAberta { if (openX[listaAberta[x]] == a && openY[listaAberta[x]] == b) //item encontrado { Fcost[listaAberta[x]] = Gcost[a][b] + Hcost[listaAberta[x]];//troque o custo F m = x; while (m != 1) { if (Fcost[listaAberta[m]] < Fcost[listaAberta[m/2]]) { temp = listaAberta[m/2]; listaAberta[m/2] = listaAberta[m]; listaAberta[m] = temp; m = m/2; } else break; } break; //saia para x = loop } //Se openX(listaAberta(x)) = a } //For x = 1 To numItemsListaAberta }//If tempGcost < Gcost(a,b) }//else If whichList(a,b) = naListaAberta } } } } }//for (a = parentXval-1; a <= parentXval+1; a++){ }//for (b = parentYval-1; b <= parentYval+1; b++){ }//if (numItemsListaAberta != 0) else { path = naoExiste; break; } if (whichList[targetX][targetY] == naListaAberta) { path = encontrado; break; } } while (true); if (path == encontrado) { pathX = targetX; pathY = targetY; do { tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; //Calcular o tamanho do caminho. pathLength[pathfinderID] = pathLength[pathfinderID] + 1; } while (pathX != startX || pathY != startY); //b.Redimensione o dataBank para o correto tamanho em bytes. Integer[] arr = pathBank2.get(pathfinderID); pathBank2.set(pathfinderID, Arrays.copyOf(arr, pathLength[pathfinderID]*8)); // um conjunto corretamente ordenado de dados do caminho, para o primeiro passo pathX = targetX ; pathY = targetY; cellPosition = pathLength[pathfinderID]*2;//Inicie do final do { cellPosition = cellPosition - 2; pathBank2.get(pathfinderID)[cellPosition] = pathX; pathBank2.get(pathfinderID)[cellPosition+1] = pathY; tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; } while (pathX != startX || pathY != startY); //11. Leia o primeiro passo dentro dos arrays xPath/yPath. ReadPath(pathfinderID,startingX,startingY,1); } return path; } }
package br.ufba.ia.copsandrobbers.search; import java.util.ArrayList; import java.util.List; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class AStar { //Declare constants public static final int mapWidth = 80, mapHeight = 60, tileSize = 10, numberPeople = 3; public static final int notfinished = 0, notStarted = 0; // path-related constants public static final int found = 1, nonexistent = 2; public static final int walkable = 0, unwalkable = 1; // walkability array constants public int onClosedList = 10; //Create needed arrays public char[][] walkability = new char[mapWidth][mapHeight]; public int[] openList = new int[mapWidth*mapHeight+2]; //1 dimensional array holding ID# of open list items public int[][] whichList = new int[mapWidth+1][mapHeight+1]; //2 dimensional array used to record // whether a cell is on the open list or on the closed list. public int[] openX = new int[mapWidth*mapHeight+2]; //1d array stores the x location of an item on the open list public int[] openY = new int[mapWidth*mapHeight+2]; //1d array stores the y location of an item on the open list public int[][] parentX = new int[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (x) public int[][] parentY = new int[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (y) public int[] Fcost = new int[mapWidth*mapHeight+2]; //1d array to store F cost of a cell on the open list public int[][] Gcost = new int[mapWidth+1][mapHeight+1]; //2d array to store G cost for each cell. public int[] Hcost = new int[mapWidth*mapHeight+2]; //1d array to store H cost of a cell on the open list public int[] pathLength = new int[numberPeople+1]; //stores length of the found path for critter public int[] pathLocation = new int[numberPeople+1]; //stores current position along the chosen path for critter //int* pathBank [numberPeople+1]; public List<Integer> pathBank[] = new List[numberPeople+1]; //Path reading variables public int[] pathStatus = new int[numberPeople+1]; public int[] xPath = new int[numberPeople+1]; public int[] yPath = new int[numberPeople+1]; public void InitializePathfinder () { for (int x = 0; x < numberPeople+1; x++) pathBank[x] = new ArrayList<Integer>(); } public void EndPathfinder () { for (int x = 0; x < numberPeople+1; x++) pathBank[x].clear(); } public int FindPath (int pathfinderID, int startingX, int startingY, int targetX, int targetY) { int onOpenList=0, parentXval=0, parentYval=0, a=0, b=0, m=0, u=0, v=0, temp=0, corner=0, numberOfOpenListItems=0, addedGCost=0, tempGcost = 0, path = 0, tempx, pathX, pathY, cellPosition, newOpenListItemID=0; //1. Convert location data (in pixels) to coordinates in the walkability array. int startX = startingX/tileSize; int startY = startingY/tileSize; targetX = targetX/tileSize; targetY = targetY/tileSize; //2.Quick Path Checks: Under the some circumstances no path needs to //be generated ... //If starting location and target are in the same location... if (startX == targetX && startY == targetY && pathLocation[pathfinderID] > 0) return found; if (startX == targetX && startY == targetY && pathLocation[pathfinderID] == 0) return nonexistent; //If target square is unwalkable, return that it's a nonexistent path. if (walkability[targetX][targetY] == unwalkable) { xPath[pathfinderID] = startingX; yPath[pathfinderID] = startingY; return nonexistent; } //3.Reset some variables that need to be cleared if (onClosedList > 1000000) //reset whichList occasionally { for (int x = 0; x < mapWidth; x++) { for (int y = 0; y < mapHeight; y++) whichList [x][y] = 0; } onClosedList = 10; } onClosedList = onClosedList+2; //changing the values of onOpenList and onClosed list is faster than redimming whichList() array onOpenList = onClosedList-1; pathLength [pathfinderID] = notStarted;//i.e, = 0 pathLocation [pathfinderID] = notStarted;//i.e, = 0 Gcost[startX][startY] = 0; //reset starting square's G value to 0 //4.Add the starting location to the open list of squares to be checked. numberOfOpenListItems = 1; openList[1] = 1;//assign it as the top (and currently only) item in the open list, which is maintained as a binary heap (explained below) openX[1] = startX; openY[1] = startY; //5.Do the following until a path is found or deemed nonexistent. do { //6.If the open list is not empty, take the first cell off of the list. // This is the lowest F cost cell on the open list. if (numberOfOpenListItems != 0) { //7. Pop the first item off the open list. parentXval = openX[openList[1]]; parentYval = openY[openList[1]]; //record cell coordinates of the item whichList[parentXval][parentYval] = onClosedList;//add the item to the closed list // Open List = Binary Heap: Delete this item from the open list, which // is maintained as a binary heap. For more information on binary heaps, see: numberOfOpenListItems = numberOfOpenListItems - 1;//reduce number of open list items by 1 // Delete the top item in binary heap and reorder the heap, with the lowest F cost item rising to the top. openList[1] = openList[numberOfOpenListItems+1];//move the last item in the heap up to slot v = 1; // Repeat the following until the new item in slot #1 sinks to its proper spot in the heap. do { u = v; if (2*u+1 <= numberOfOpenListItems) //if both children exist { //Check if the F cost of the parent is greater than each child. //Select the lowest of the two children. if (Fcost[openList[u]] >= Fcost[openList[2*u]]) v = 2*u; if (Fcost[openList[v]] >= Fcost[openList[2*u+1]]) v = 2*u+1; } else { if (2*u <= numberOfOpenListItems) //if only child #1 exists { //Check if the F cost of the parent is greater than child if (Fcost[openList[u]] >= Fcost[openList[2*u]]) v = 2*u; } } if (u != v) //if parent's F is > one of its children, swap them { temp = openList[u]; openList[u] = openList[v]; openList[v] = temp; } else break; //otherwise, exit loop } // while (!KeyDown(27)); -> O que estava no C++... 27 = Codigo do boto: ESC while (actualkey.getKeyCode() != KeyEvent.VK_ESCAPE); //Tentei isso, mas no sei como criar a varivel actualkey. //7. Check the adjacent squares. (Its "children" -- these path children // are similar, conceptually, to the binary heap children mentioned // above, but don't confuse them. They are different. Path children // are portrayed in Demo 1 with grey pointers pointing toward // their parents.) Add these adjacent child squares to the open list // for later consideration if appropriate (see various if statements // below). for (b = parentYval-1; b <= parentYval+1; b++){ for (a = parentXval-1; a <= parentXval+1; a++){ // If not off the map (do this first to avoid array out-of-bounds errors) if (a != -1 && b != -1 && a != mapWidth && b != mapHeight){ // If not already on the closed list (items on the closed list have // already been considered and can now be ignored). if (whichList[a][b] != onClosedList) { // If not a wall/obstacle square. if (walkability [a][b] != unwalkable) { // Don't cut across corners corner = walkable; if (a == parentXval-1) { if (b == parentYval-1) { if (walkability[parentXval-1][parentYval] == unwalkable || walkability[parentXval][parentYval-1] == unwalkable) \ corner = unwalkable; } else if (b == parentYval+1) { if (walkability[parentXval][parentYval+1] == unwalkable || walkability[parentXval-1][parentYval] == unwalkable) corner = unwalkable; } } else if (a == parentXval+1) { if (b == parentYval-1) { if (walkability[parentXval][parentYval-1] == unwalkable || walkability[parentXval+1][parentYval] == unwalkable) corner = unwalkable; } else if (b == parentYval+1) { if (walkability[parentXval+1][parentYval] == unwalkable || walkability[parentXval][parentYval+1] == unwalkable) corner = unwalkable; } } if (corner == walkable) { // If not already on the open list, add it to the open list. if (whichList[a][b] != onOpenList) { //Create a new open list item in the binary heap. newOpenListItemID = newOpenListItemID + 1; //each new item has a unique ID m = numberOfOpenListItems+1; openList[m] = newOpenListItemID;//place the new open list item (actually, its ID#) at the bottom of the heap openX[newOpenListItemID] = a; openY[newOpenListItemID] = b;//record the x and y coordinates of the new item //Figure out its G cost if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//cost of going to diagonal squares else addedGCost = 10;//cost of going to non-diagonal squares Gcost[a][b] = Gcost[parentXval][parentYval] + addedGCost; //Figure out its H and F costs and parent Hcost[openList[m]] = 10*(Math.abs(a - targetX) + Math.abs(b - targetY)); Fcost[openList[m]] = Gcost[a][b] + Hcost[openList[m]]; parentX[a][b] = parentXval ; parentY[a][b] = parentYval; //Move the new open list item to the proper place in the binary heap. //Starting at the bottom, successively compare to parent items, //swapping as needed until the item finds its place in the heap //or bubbles all the way to the top (if it has the lowest F cost). while (m != 1) //While item hasn't bubbled to the top (m=1) { //Check if child's F cost is < parent's F cost. If so, swap them. if (Fcost[openList[m]] <= Fcost[openList[m/2]]) { temp = openList[m/2]; openList[m/2] = openList[m]; openList[m] = temp; m = m/2; } else break; } numberOfOpenListItems = numberOfOpenListItems+1;//add one to the number of items in the heap //Change whichList to show that the new item is on the open list. whichList[a][b] = onOpenList; } //8.If adjacent cell is already on the open list, check to see if this // path to that cell from the starting location is a better one. // If so, change the parent of the cell and its G and F costs. else //If whichList(a,b) = onOpenList { //Figure out the G cost of this possible new path if (Math.abs(a-parentXval) == 1 && Math.abs(b-parentYval) == 1) addedGCost = 14;//cost of going to diagonal tiles else addedGCost = 10;//cost of going to non-diagonal tiles tempGcost = Gcost[parentXval][parentYval] + addedGCost; //If this path is shorter (G cost is lower) then change //the parent cell, G cost and F cost. if (tempGcost < Gcost[a][b]) //if G cost is less, { parentX[a][b] = parentXval; //change the square's parent parentY[a][b] = parentYval; Gcost[a][b] = tempGcost;//change the G cost //Because changing the G cost also changes the F cost, if //the item is on the open list we need to change the item's //recorded F cost and its position on the open list to make //sure that we maintain a properly ordered open list. for (int x = 1; x <= numberOfOpenListItems; x++) //look for the item in the heap { if (openX[openList[x]] == a && openY[openList[x]] == b) //item found { Fcost[openList[x]] = Gcost[a][b] + Hcost[openList[x]];//change the F cost //See if changing the F score bubbles the item up from it's current location in the heap m = x; while (m != 1) //While item hasn't bubbled to the top (m=1) { //Check if child is < parent. If so, swap them. if (Fcost[openList[m]] < Fcost[openList[m/2]]) { temp = openList[m/2]; openList[m/2] = openList[m]; openList[m] = temp; m = m/2; } else break; } break; //exit for x = loop } //If openX(openList(x)) = a } //For x = 1 To numberOfOpenListItems }//If tempGcost < Gcost(a,b) }//else If whichList(a,b) = onOpenList }//If not cutting a corner }//If not a wall/obstacle square. }//If not already on the closed list }//If not off the map }//for (a = parentXval-1; a <= parentXval+1; a++){ }//for (b = parentYval-1; b <= parentYval+1; b++){ }//if (numberOfOpenListItems != 0) //9.If open list is empty then there is no path. else { path = nonexistent; break; } //If target is added to open list then path has been found. if (whichList[targetX][targetY] == onOpenList) { path = found; break; } } while (true);//Do until path is found or deemed nonexistent //10.Save the path if it exists. if (path == found) { //a.Working backwards from the target to the starting location by checking // each cell's parent, figure out the length of the path. pathX = targetX; pathY = targetY; do { //Look up the parent of the current cell. tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; //Figure out the path length pathLength[pathfinderID] = pathLength[pathfinderID] + 1; } while (pathX != startX || pathY != startY); //b.Resize the data bank to the right size in bytes // pathBank[pathfinderID] = (int*) realloc (pathBank[pathfinderID], pathLength[pathfinderID]*8); //c. Now copy the path information over to the databank. Since we are // working backwards from the target to the start location, we copy // the information to the data bank in reverse order. The result is // a properly ordered set of path data, from the first step to the // last. pathX = targetX ; pathY = targetY; cellPosition = pathLength[pathfinderID]*2;//start at the end do { cellPosition = cellPosition - 2;//work backwards 2 integers pathBank[pathfinderID].set(cellPosition, pathX); pathBank[pathfinderID].set(cellPosition+1, pathY); //d.Look up the parent of the current cell. tempx = parentX[pathX][pathY]; pathY = parentY[pathX][pathY]; pathX = tempx; //e.If we have reached the starting square, exit the loop. } while (pathX != startX || pathY != startY); //11.Read the first path step into xPath/yPath arrays ReadPath(pathfinderID,startingX,startingY,1); } return path; } public void ReadPath (int pathfinderID,int currentX,int currentY, int pixelsPerFrame) { int ID = pathfinderID; //redundant, but makes the following easier to read //If a path has been found for the pathfinder ... if (pathStatus[ID] == found) { //If path finder is just starting a new path or has reached the //center of the current path square (and the end of the path //hasn't been reached), look up the next path square. if (pathLocation[ID] < pathLength[ID]) { //if just starting or if close enough to center of square if (pathLocation[ID] == 0 || (Math.abs(currentX - xPath[ID]) < pixelsPerFrame && Math.abs(currentY - yPath[ID]) < pixelsPerFrame)) pathLocation[ID] = pathLocation[ID] + 1; } //Read the path data. xPath[ID] = ReadPathX(ID,pathLocation[ID]); yPath[ID] = ReadPathY(ID,pathLocation[ID]); //If the center of the last path square on the path has been //reached then reset. if (pathLocation[ID] == pathLength[ID]) { if (Math.abs(currentX - xPath[ID]) < pixelsPerFrame && Math.abs(currentY - yPath[ID]) < pixelsPerFrame) //if close enough to center of square pathStatus[ID] = notStarted; } } //If there is no path for this pathfinder, simply stay in the current //location. else { xPath[ID] = currentX; yPath[ID] = currentY; } } //The following two functions read the raw path data from the pathBank. //You can call these functions directly and skip the readPath function //above if you want. Make sure you know what your current pathLocation // Name: ReadPathX // Desc: Reads the x coordinate of the next path step int ReadPathX(int pathfinderID,int pathLocation) { int x; if (pathLocation <= pathLength[pathfinderID]) { //Read coordinate from bank // x = pathBank[pathfinderID] [pathLocation*2-2]; x = pathBank[pathfinderID].get(pathLocation*2-2); //Adjust the coordinates so they align with the center //of the path square (optional). This assumes that you are using //sprites that are centered -- i.e., with the midHandle command. //Otherwise you will want to adjust this. x = tileSize*x + .5*tileSize; } return x; } // Name: ReadPathY // Desc: Reads the y coordinate of the next path step int ReadPathY(int pathfinderID,int pathLocation) { int y; if (pathLocation <= pathLength[pathfinderID]) { //Read coordinate from bank y = pathBank[pathfinderID].get(pathLocation*2-1); //Adjust the coordinates so they align with the center //of the path square (optional). This assumes that you are using //sprites that are centered -- i.e., with the midHandle command. //Otherwise you will want to adjust this. y = tileSize*y + .5*tileSize; } return y; } }
package imagej.legacy; import ij.ImagePlus; import java.util.HashSet; import java.util.Set; /** * The legacy output tracker is responsible for tracking important changes to * the IJ1 environment as a result of running a plugin. Important changes * include newly created {@link ImagePlus}es and {@link ImagePlus}es whose * window has closed. * * @author Curtis Rueden * @author Barry DeZonia */ public class LegacyOutputTracker { // -- instance variables -- /** Used to provide one list of {@link ImagePlus} per calling thread. */ private static ThreadLocal<Set<ImagePlus>> outputImps = new ThreadLocal<Set<ImagePlus>>() { @Override protected synchronized Set<ImagePlus> initialValue() { return new HashSet<ImagePlus>(); } }; /** Used to provide one list of {@link ImagePlus} per calling thread. */ private static ThreadLocal<Set<ImagePlus>> closedImps = new ThreadLocal<Set<ImagePlus>>() { @Override protected synchronized Set<ImagePlus> initialValue() { return new HashSet<ImagePlus>(); } }; /** Tracks which ImagePluses have their close() method initiated by IJ2 */ private static ThreadLocal<Set<ImagePlus>> beingClosedByIJ2 = new ThreadLocal<Set<ImagePlus>>() { @Override protected synchronized Set<ImagePlus> initialValue() { return new HashSet<ImagePlus>(); } }; // -- public interface -- /** * Gets a list for storing the ImagePluses generated by a plugin. This method * is (??) thread-safe, because it uses a separate set per thread. */ public static Set<ImagePlus> getOutputImps() { return outputImps.get(); } /** * Gets a list for storing the ImagePluses closed by a plugin. This method is * (??) thread-safe, because it uses a separate set per thread. */ public static Set<ImagePlus> getClosedImps() { return closedImps.get(); } /** Informs tracker that IJ2 has initiated the close() of an ImagePlus */ public static void closeInitiatedByIJ2(final ImagePlus imp) { beingClosedByIJ2.get().add(imp); } /** Informs tracker that IJ2 has finished the close() of an ImagePlus */ public static void closeCompletedByIJ2(final ImagePlus imp) { beingClosedByIJ2.get().remove(imp); } /** Informs API user whether a given ImagePlus is currently being closed by * ImageJ2. */ public static boolean isBeingClosedbyIJ2(final ImagePlus imp) { return beingClosedByIJ2.get().contains(imp); } }
package org.zstack.core.workflow; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.Platform; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.utils.CollectionUtils; import org.zstack.utils.DebugUtils; import org.zstack.utils.FieldUtils; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.logging.CLogger; import java.lang.reflect.Field; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; /** * Created with IntelliJ IDEA. * User: frank * Time: 2:38 PM * To change this template use File | Settings | File Templates. */ @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class SimpleFlowChain implements FlowTrigger, FlowRollback, FlowChain, FlowChainMutable { private static final CLogger logger = Utils.getLogger(SimpleFlowChain.class); private String id; private List<Flow> flows = new ArrayList<>(); private Stack<Flow> rollBackFlows = new Stack<>(); private Map data = new HashMap(); private Iterator<Flow> it; private boolean isStart = false; private boolean isRollbackStart = false; private Flow currentFlow; private Flow currentRollbackFlow; private ErrorCode errorCode; private FlowErrorHandler errorHandler; private FlowDoneHandler doneHandler; private FlowFinallyHandler finallyHandler; private String name; private boolean skipRestRollbacks; private boolean allowEmptyFlow; private FlowMarshaller flowMarshaller; private List<FlowChainProcessor> processors; private List<List<Runnable>> afterDone = new ArrayList<>(); private List<List<Runnable>> afterError = new ArrayList<>(); private List<List<Runnable>> afterFinal = new ArrayList<>(); private boolean isFailCalled; private static final Map<String, WorkFlowStatistic> statistics = new ConcurrentHashMap<>(); private class FlowStopWatch { Map<String, Long> beginTime = new HashMap<>(); void start(Flow flow) { long btime = System.currentTimeMillis(); if (currentFlow != null) { String cname = getFlowName(currentFlow); long stime = beginTime.get(cname); WorkFlowStatistic stat = statistics.get(cname); stat.addStatistic(btime - stime); logger.debug(String.format("[FlowChain(%s):%s, flow:%s] takes %sms to complete", id, name, cname, stat.getTotalTime())); } String fname = getFlowName(flow); beginTime.put(fname, btime); WorkFlowStatistic stat = statistics.get(fname); if (stat == null) { stat = new WorkFlowStatistic(); stat.setName(fname); statistics.put(fname, stat); } } void stop() { long etime = System.currentTimeMillis(); if (currentFlow != null) { String fname = getFlowName(currentFlow); long stime = beginTime.get(fname); WorkFlowStatistic stat = statistics.get(fname); stat.addStatistic(etime - stime); } } } private FlowStopWatch stopWatch; { if (CoreGlobalProperty.PROFILER_WORKFLOW) { stopWatch = new FlowStopWatch(); } } @Autowired private ErrorFacade errf; public SimpleFlowChain() { id = "FCID_" + Platform.getUuid().substring(0, 8); } public SimpleFlowChain(Map<String, Object> data) { id = "FCID_" + Platform.getUuid().substring(0, 8); this.data.putAll(data); } @Override public List<Flow> getFlows() { return flows; } @Override public void setFlows(List<Flow> flows) { this.flows = flows; } @Override public FlowDoneHandler getFlowDoneHandler() { return doneHandler; } @Override public void setFlowDoneHandler(FlowDoneHandler handler) { done(handler); } @Override public FlowErrorHandler getFlowErrorHandler() { return errorHandler; } @Override public void setFlowErrorHandler(FlowErrorHandler handler) { error(handler); } @Override public FlowFinallyHandler getFlowFinallyHandler() { return finallyHandler; } @Override public void setFlowFinallyHandler(FlowFinallyHandler handler) { Finally(handler); } @Override public String getChainName() { return name; } @Override public void setChainName(String name) { setName(name); } @Override public Map getChainData() { return data; } @Override public void setChainData(Map data) { setData(data); } @Override public FlowChain insert(Flow flow) { flows.add(0, flow); return this; } @Override public FlowChain insert(int pos, Flow flow) { flows.add(pos, flow); return this; } @Override public FlowChain setFlowMarshaller(FlowMarshaller marshaller) { flowMarshaller = marshaller; return this; } public SimpleFlowChain then(Flow flow) { flows.add(flow); return this; } public SimpleFlowChain error(FlowErrorHandler handler) { DebugUtils.Assert(errorHandler==null, "there has been an FlowErrorHandler installed"); errorHandler = handler; return this; } @Override public FlowChain Finally(FlowFinallyHandler handler) { finallyHandler = handler; return this; } @Override public FlowChain setData(Map data) { this.data.putAll(data); return this; } @Override public FlowChain putData(Entry...es) { for (Map.Entry e : es) { data.put(e.getKey(), e.getValue()); } return this; } @Override public FlowChain setName(String name) { this.name = name; return this; } @Override public void setProcessors(List<FlowChainProcessor> processors) { this.processors = processors; } @Override public Map getData() { return this.data; } @Override public SimpleFlowChain done(FlowDoneHandler handler) { DebugUtils.Assert(doneHandler==null, "there has been a FlowDoneHandler installed"); doneHandler = handler; return this; } private void collectAfterRunnable(Flow flow) { List<Field> ad = FieldUtils.getAnnotatedFieldsOnThisClass(AfterDone.class, flow.getClass()); for (Field f : ad) { List lst = FieldUtils.getFieldValue(f.getName(), flow); if (lst != null) { afterDone.add(lst); } } ad = FieldUtils.getAnnotatedFieldsOnThisClass(AfterError.class, flow.getClass()); for (Field f : ad) { List lst = FieldUtils.getFieldValue(f.getName(), flow); if (lst != null) { afterError.add(lst); } } ad = FieldUtils.getAnnotatedFieldsOnThisClass(AfterFinal.class, flow.getClass()); for (Field f : ad) { List lst = FieldUtils.getFieldValue(f.getName(), flow); if (lst != null) { afterFinal.add(lst); } } } private void runFlow(Flow flow) { try { Flow toRun = null; if (flowMarshaller != null) { toRun = flowMarshaller.marshalTheNextFlow(currentFlow == null ? null : currentFlow.getClass().getName(), flow.getClass().getName(), this, data); if (toRun != null) { logger.debug(String.format("[FlowChain(%s): %s] FlowMarshaller[%s] replaces the next flow[%s] to the flow[%s]", id, name, flowMarshaller.getClass(), flow.getClass(), toRun.getClass())); } } if (toRun == null) { toRun = flow; } if (CoreGlobalProperty.PROFILER_WORKFLOW) { stopWatch.start(toRun); } currentFlow = toRun; String flowName = getFlowName(currentFlow); String info = String.format("[FlowChain(%s): %s] start executing flow[%s]", id, name, flowName); logger.debug(info); collectAfterRunnable(toRun); toRun.run(this, data); } catch (OperationFailureException oe) { String errInfo = oe.getErrorCode() != null ? oe.getErrorCode().toString() : ""; logger.warn(errInfo, oe); fail(oe.getErrorCode()); } catch (FlowException fe) { String errInfo = fe.getErrorCode() != null ? fe.getErrorCode().toString() : ""; logger.warn(errInfo, fe); fail(fe.getErrorCode()); } catch (Throwable t) { logger.warn(String.format("[FlowChain(%s): %s] unhandled exception when executing flow[%s], start to rollback", id, name, flow.getClass().getName()), t); fail(errf.throwableToInternalError(t)); } } private void rollbackFlow(Flow flow) { try { logger.debug(String.format("[FlowChain(%s): %s] start to rollback flow[%s]", id, name, getFlowName(flow))); flow.rollback(this, data); } catch (Throwable t) { logger.warn(String.format("[FlowChain(%s): %s] unhandled exception when rollback flow[%s]," + " continue to next rollback", id, name, flow.getClass().getSimpleName()), t); rollback(); } } private void callErrorHandler(boolean info) { if (info) { logger.debug(String.format("[FlowChain(%s): %s] rolled back all flows because error%s", id, name, errorCode)); } if (errorHandler != null) { try { errorHandler.handle(errorCode, this.data); } catch (Throwable t) { logger.warn(String.format("unhandled exception when calling %s", errorHandler.getClass()), t); } } if (!afterError.isEmpty()) { Collections.reverse(afterError); for (List errors : afterError) { CollectionUtils.safeForEach(errors, new ForEachFunction<Runnable>() { @Override public void run(Runnable arg) { if (logger.isTraceEnabled()) { logger.trace(String.format("call after error handler %s", arg.getClass())); } arg.run(); } }); } } callFinallyHandler(); } private String getFlowName(Flow flow) { String name = FieldUtils.getFieldValue("__name__", flow); if (name == null) { name = flow.getClass().getSimpleName(); if (name.equals("")) { name = flow.getClass().getName(); } } if (logger.isTraceEnabled()) { String className = flow.getClass().getName(); String[] ff = className.split("\\."); String filename = ff[ff.length-1]; if (filename.contains("$")) { int index = filename.indexOf("$"); filename = filename.substring(0, index); } name = String.format("%s.java:%s", filename, name); } return name; } @Override public void rollback() { if (!isFailCalled) { throw new CloudRuntimeException("rollback() cannot be called before fail() is called"); } isRollbackStart = true; if (rollBackFlows.empty()) { callErrorHandler(true); return; } if (skipRestRollbacks) { List<String> restRollbackNames = CollectionUtils.transformToList(rollBackFlows, new Function<String, Flow>() { @Override public String call(Flow arg) { return arg.getClass().getSimpleName(); } }); logger.debug(String.format("[FlowChain(%s): %s] we are instructed to skip rollbacks for remaining flows%s", id, name, restRollbackNames)); callErrorHandler(true); return; } if (currentRollbackFlow != null) { logger.debug(String.format("[FlowChain(%s): %s] successfully rolled back flow[%s]", id, name, getFlowName(currentRollbackFlow))); } else { logger.debug(String.format("[FlowChain(%s): %s] start to rollback", id, name)); } Flow flow = rollBackFlows.pop(); currentRollbackFlow = flow; rollbackFlow(flow); } @Override public void skipRestRollbacks() { skipRestRollbacks = true; } @Override public void setError(ErrorCode error) { setErrorCode(error); } private void callFinallyHandler() { if (finallyHandler != null) { try { finallyHandler.Finally(); } catch (Throwable t) { logger.warn(String.format("unhandled exception when calling %s", finallyHandler.getClass()), t); } } if (!afterFinal.isEmpty()) { Collections.reverse(afterFinal); for (List finals : afterFinal) { CollectionUtils.safeForEach(finals, new ForEachFunction<Runnable>() { @Override public void run(Runnable arg) { if (logger.isTraceEnabled()) { logger.trace(String.format("call after final handler %s", arg.getClass())); } arg.run(); } }); } } } private void callDoneHandler() { if (CoreGlobalProperty.PROFILER_WORKFLOW) { stopWatch.stop(); } if (doneHandler != null) { try { doneHandler.handle(this.data); } catch (Throwable t) { logger.warn(String.format("unhandled exception when calling %s", doneHandler.getClass()), t); } } logger.debug(String.format("[FlowChain(%s): %s] successfully completed", id, name)); if (!afterDone.isEmpty()) { Collections.reverse(afterDone); for (List dones : afterDone) { CollectionUtils.safeForEach(dones, new ForEachFunction<Runnable>() { @Override public void run(Runnable arg) { if (logger.isTraceEnabled()) { logger.trace(String.format("call after done handler %s", arg.getClass())); } arg.run(); } }); } } callFinallyHandler(); } @Override public void fail(ErrorCode errorCode) { isFailCalled = true; setErrorCode(errorCode); rollBackFlows.push(currentFlow); rollback(); } @Override public void next() { if (!isStart) { throw new CloudRuntimeException( String.format("[FlowChain(%s): %s] you must call start() first, and only call next() in Flow.run()", id, name)); } if (isRollbackStart) { throw new CloudRuntimeException( String.format("[FlowChain(%s): %s] rollback has started, you can't call next()", id, name)); } rollBackFlows.push(currentFlow); logger.debug(String.format("[FlowChain(%s): %s] successfully executed flow[%s]", id, name, getFlowName(currentFlow))); if (!it.hasNext()) { if (errorCode == null) { callDoneHandler(); } else { callErrorHandler(false); } return; } Flow flow = it.next(); runFlow(flow); } @Override public void start() { if (processors != null) { for (FlowChainProcessor p : processors) { p.processFlowChain(this); } } if (flows.isEmpty() && allowEmptyFlow) { callDoneHandler(); return; } if (flows.isEmpty()) { throw new CloudRuntimeException("you must call then() to add flow before calling start() or allowEmptyFlow() to run empty flow chain on purpose"); } if (data == null) { data = new HashMap<String, Object>(); } isStart = true; if (name == null) { name = "anonymous-chain"; } logger.debug(String.format("[FlowChain(%s): %s] starts", id, name)); if (logger.isTraceEnabled()) { List<String> names = CollectionUtils.transformToList(flows, new Function<String, Flow>() { @Override public String call(Flow arg) { return String.format("%s[%s]", arg.getClass(), getFlowName(arg)); } }); logger.trace(String.format("execution path:\n%s", StringUtils.join(names, " } it = flows.iterator(); Flow flow = it.next(); runFlow(flow); } @Override public FlowChain noRollback(boolean no) { skipRestRollbacks = no; return this; } @Override public FlowChain allowEmptyFlow() { allowEmptyFlow = true; return this; } private void setErrorCode(ErrorCode errorCode) { this.errorCode = errorCode; } public static Map<String, WorkFlowStatistic> getStatistics() { return statistics; } }
package tk.mybatis.mapper.mapperhelper; import tk.mybatis.mapper.annotation.Version; import tk.mybatis.mapper.entity.EntityColumn; import tk.mybatis.mapper.entity.IDynamicTableName; import tk.mybatis.mapper.util.StringUtil; import tk.mybatis.mapper.version.VersionException; import java.util.Set; /** * SQL * * @author liuzh * @since 2015-11-03 22:40 */ public class SqlHelper { /** * - * * @param entityClass * @param tableName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(_parameter) and dynamicTableName != null and dynamicTableName != ''\">"); sql.append("${dynamicTableName}\n"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return tableName; } } /** * - parameterName@Param * * @param entityClass * @param tableName * @param parameterName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName, String parameterName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { if (StringUtil.isNotEmpty(parameterName)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(" + parameterName + ") and " + parameterName + ".dynamicTableName != null and " + parameterName + ".dynamicTableName != ''\">"); sql.append("${" + parameterName + ".dynamicTableName}"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return getDynamicTableName(entityClass, tableName); } } else { return tableName; } } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindCache(EntityColumn column) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_cache\" "); sql.append("value=\"").append(column.getProperty()).append("\"/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindValue(EntityColumn column, String value) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_bind\" "); sql.append("value='").append(value).append("'/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getIfCacheNotNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * _cache == null * * @param column * @return */ public static String getIfCacheIsNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache == null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * !=null * * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(EntityColumn column, String contents, boolean empty) { return getIfNotNull(null, column, contents, empty); } /** * ==null * * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(EntityColumn column, String contents, boolean empty) { return getIfIsNull(null, column, contents, empty); } /** * !=null * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" and "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * ==null * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" or "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * id,name,code... * * @param entityClass * @return */ public static String getAllColumns(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); StringBuilder sql = new StringBuilder(); for (EntityColumn entityColumn : columnSet) { sql.append(entityColumn.getColumn()).append(","); } return sql.substring(0, sql.length() - 1); } /** * select xxx,xxx... * * @param entityClass * @return */ public static String selectAllColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); sql.append(getAllColumns(entityClass)); sql.append(" "); return sql.toString(); } /** * select count(x) * * @param entityClass * @return */ public static String selectCount(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } return sql.toString(); } /** * select case when count(x) > 0 then 1 else 0 end * * @param entityClass * @return */ public static String selectCountExists(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT CASE WHEN "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } sql.append(" > 0 THEN 1 ELSE 0 END AS result "); return sql.toString(); } /** * from tableName - * * @param entityClass * @param defaultTableName * @return */ public static String fromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append(" FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * update tableName - * * @param entityClass * @param defaultTableName * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName) { return updateTable(entityClass, defaultTableName, null); } /** * update tableName - * * @param entityClass * @param defaultTableName * @param entityName * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(getDynamicTableName(entityClass, defaultTableName, entityName)); sql.append(" "); return sql.toString(); } /** * delete tableName - * * @param entityClass * @param defaultTableName * @return */ public static String deleteFromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert into tableName - * * @param entityClass * @param defaultTableName * @return */ public static String insertIntoTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert table() * * @param entityClass * @param skipId id * @param notNull !=null * @param notEmpty String!='' * @return */ public static String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, column.getColumn() + ",", notEmpty)); } else { sql.append(column.getColumn() + ","); } } sql.append("</trim>"); return sql.toString(); } /** * insert-values() * * @param entityClass * @param skipId id * @param notNull !=null * @param notEmpty String!='' * @return */ public static String insertValuesColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder() + ",", notEmpty)); } else { sql.append(column.getColumnHolder() + ","); } } sql.append("</trim>"); return sql.toString(); } /** * update set * * @param entityClass * @param entityName * @param notNull !=null * @param notEmpty String!='' * @return */ public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<set>"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); EntityColumn versionColumn = null; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (versionColumn != null) { throw new VersionException(entityClass.getCanonicalName() + " @Version @Version !"); } versionColumn = column; } if (!column.isId() && column.isUpdatable()) { if (column == versionColumn) { Version version = versionColumn.getEntityField().getAnnotation(Version.class); String versionClass = version.nextVersion().getCanonicalName(); //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)} sql.append(column.getColumn()) .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(\"") .append(versionClass).append("\", ") .append(column.getProperty()).append(")},"); } else if (notNull) { sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty)); } else { sql.append(column.getColumnEqualsHolder(entityName) + ","); } } else if(column.isId() && column.isUpdatable()){ //set id = id, sql.append(column.getColumn()).append(" = ").append(column.getColumn()).append(","); } } sql.append("</set>"); return sql.toString(); } /** * null * * @param parameterName * @param columnSet * @return */ public static String notAllNullParameterCheck(String parameterName, Set<EntityColumn> columnSet) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"notAllNullParameterCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notAllNullParameterCheck("); sql.append(parameterName).append(", '"); StringBuilder fields = new StringBuilder(); for (EntityColumn column : columnSet) { if(fields.length() > 0){ fields.append(","); } fields.append(column.getProperty()); } sql.append(fields); sql.append("')\"/>"); return sql.toString(); } /** * Example 1 * * @param parameterName * @return */ public static String exampleHasAtLeastOneCriteriaCheck(String parameterName) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"exampleHasAtLeastOneCriteriaCheck\" value=\"@tk.mybatis.mapper.util.OGNL@exampleHasAtLeastOneCriteriaCheck("); sql.append(parameterName).append(")\"/>"); return sql.toString(); } /** * where * * @param entityClass * @return */ public static String wherePKColumns(Class<?> entityClass) { return wherePKColumns(entityClass, false); } /** * where * * @param entityClass * @return */ public static String wherePKColumns(Class<?> entityClass, boolean useVersion) { StringBuilder sql = new StringBuilder(); sql.append("<where>"); Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass); for (EntityColumn column : columnSet) { sql.append(" AND " + column.getColumnEqualsHolder()); } if (useVersion) { sql.append(whereVersion(entityClass)); } sql.append("</where>"); return sql.toString(); } /** * where!=null * * @param entityClass * @param empty * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty) { return whereAllIfColumns(entityClass, empty, false); } /** * where!=null * * @param entityClass * @param empty * @param useVersion * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty, boolean useVersion) { StringBuilder sql = new StringBuilder(); sql.append("<where>"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnSet) { if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) { sql.append(getIfNotNull(column, " AND " + column.getColumnEqualsHolder(), empty)); } } if (useVersion) { sql.append(whereVersion(entityClass)); } sql.append("</where>"); return sql.toString(); } /** * * * @param entityClass * @return */ public static String whereVersion(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); boolean hasVersion = false; String result = ""; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (hasVersion) { throw new VersionException(entityClass.getCanonicalName() + " @Version @Version !"); } hasVersion = true; result = " AND " + column.getColumnEqualsHolder(); } } return result; } /** * orderBy * * @param entityClass * @return */ public static String orderByDefault(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append(" ORDER BY "); sql.append(orderByClause); } return sql.toString(); } /** * example * * @return */ public static String exampleSelectColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">"); sql.append("<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">"); sql.append("${selectColumn}"); sql.append("</foreach>"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(getAllColumns(entityClass)); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } /** * example * * @return */ public static String exampleCountColumn(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasCountColumn(_parameter)\">"); sql.append("COUNT(${countColumn})"); sql.append("</when>"); sql.append("<otherwise>"); sql.append("COUNT(0)"); sql.append("</otherwise>"); sql.append("</choose>"); sql.append("<if test=\"@tk.mybatis.mapper.util.OGNL@hasNoSelectColumns(_parameter)\">"); sql.append(getAllColumns(entityClass)); sql.append("</if>"); return sql.toString(); } /** * exampleorderByorderBy * * @return */ public static String exampleOrderBy(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"orderByClause != null\">"); sql.append("order by ${orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * exampleorderByorderBy * * @return */ public static String exampleOrderBy(String entityName, Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(entityName).append(".orderByClause != null\">"); sql.append("order by ${").append(entityName).append(".orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"").append(entityName).append(".orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * example for update * * @return */ public static String exampleForUpdate() { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"@tk.mybatis.mapper.util.OGNL@hasForUpdate(_parameter)\">"); sql.append("FOR UPDATE"); sql.append("</if>"); return sql.toString(); } /** * example for update * * @return */ public static String exampleCheck(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"checkExampleEntityClass\" value=\"@tk.mybatis.mapper.util.OGNL@checkExampleEntityClass(_parameter, '"); sql.append(entityClass.getCanonicalName()); sql.append("')\"/>"); return sql.toString(); } /** * ExamplewhereExample * * @return */ public static String exampleWhereClause() { return "<if test=\"_parameter != null\">" + "<where>\n" + " <foreach collection=\"oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + "</where>" + "</if>"; } /** * Example-UpdatewhereExample@Param("example") * * @return */ public static String updateByExampleWhereClause() { return "<where>\n" + " <foreach collection=\"example.oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + "</where>"; } }
package acr.browser.lightning; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class HistoryDatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name public static final String DATABASE_NAME = "historyManager"; // HistoryItems table name public static final String TABLE_HISTORY = "history"; // HistoryItems Table Columns names public static final String KEY_ID = "id"; public static final String KEY_URL = "url"; public static final String KEY_TITLE = "title"; public static SQLiteDatabase mDatabase; public HistoryDatabaseHandler(Context context) { super(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION); mDatabase = this.getWritableDatabase(); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_URL + " TEXT," + KEY_TITLE + " TEXT" + ")"; db.execSQL(CREATE_HISTORY_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY); // Create tables again onCreate(db); } public boolean isOpen() { if (mDatabase != null) { return mDatabase.isOpen(); } else { return false; } } @Override public synchronized void close() { if (mDatabase != null) { mDatabase.close(); } super.close(); } /** * All CRUD(Create, Read, Update, Delete) Operations */ public synchronized void deleteHistoryItem(String url) { mDatabase.delete(TABLE_HISTORY, KEY_URL + " = ?", new String[] { url }); } public synchronized void visitHistoryItem(String url, String title) { mDatabase.delete(TABLE_HISTORY, KEY_URL + " = ?", new String[] { url }); ContentValues values = new ContentValues(); values.put(KEY_URL, url); values.put(KEY_TITLE, title); mDatabase.insert(TABLE_HISTORY, null, values); } // Adding new item public synchronized void addHistoryItem(HistoryItem item) { ContentValues values = new ContentValues(); values.put(KEY_URL, item.getUrl()); values.put(KEY_TITLE, item.getTitle()); mDatabase.insert(TABLE_HISTORY, null, values); } // Getting single item String getHistoryItem(String url) { Cursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE }, KEY_URL + "=?", new String[] { url }, null, null, null, null); String m = null; if (cursor != null) { cursor.moveToFirst(); m = cursor.getString(0); cursor.close(); } // return item return m; } public List<HistoryItem> findItemsContaining(String search) { List<HistoryItem> itemList = new ArrayList<HistoryItem>(); // select query String selectQuery = "SELECT * FROM " + TABLE_HISTORY + " WHERE " + KEY_TITLE + " LIKE '%" + search + "%' OR " + KEY_URL + " LIKE '%" + search + "%' LIMIT 5"; Cursor cursor = mDatabase.rawQuery(selectQuery, null); // looping through all rows and adding to list int n = 0; if (cursor.moveToLast()) { do { HistoryItem item = new HistoryItem(); item.setID(Integer.parseInt(cursor.getString(0))); item.setUrl(cursor.getString(1)); item.setTitle(cursor.getString(2)); item.setImageId(R.drawable.ic_history); // Adding item to list itemList.add(item); n++; } while (cursor.moveToPrevious() && n < 5); } cursor.close(); // return item list return itemList; } public List<HistoryItem> getLastHundredItems() { List<HistoryItem> itemList = new ArrayList<HistoryItem>(); String selectQuery = "SELECT * FROM " + TABLE_HISTORY; Cursor cursor = mDatabase.rawQuery(selectQuery, null); int counter = 0; if (cursor.moveToLast()) { do { HistoryItem item = new HistoryItem(); item.setID(Integer.parseInt(cursor.getString(0))); item.setUrl(cursor.getString(1)); item.setTitle(cursor.getString(2)); item.setImageId(R.drawable.ic_history); itemList.add(item); counter++; } while (cursor.moveToPrevious() && counter < 100); } cursor.close(); return itemList; } public List<HistoryItem> getAllHistoryItems() { List<HistoryItem> itemList = new ArrayList<HistoryItem>(); String selectQuery = "SELECT * FROM " + TABLE_HISTORY; Cursor cursor = mDatabase.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { HistoryItem item = new HistoryItem(); item.setID(Integer.parseInt(cursor.getString(0))); item.setUrl(cursor.getString(1)); item.setTitle(cursor.getString(2)); item.setImageId(R.drawable.ic_history); itemList.add(item); } while (cursor.moveToNext()); } cursor.close(); return itemList; } // Updating single item public synchronized int updateHistoryItem(HistoryItem item) { ContentValues values = new ContentValues(); values.put(KEY_URL, item.getUrl()); values.put(KEY_TITLE, item.getTitle()); int n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + " = ?", new String[] { String.valueOf(item.getId()) }); // updating row return n; } // Getting items Count public int getHistoryItemsCount() { String countQuery = "SELECT * FROM " + TABLE_HISTORY; Cursor cursor = mDatabase.rawQuery(countQuery, null); cursor.close(); // return count return cursor.getCount(); } }
package sx.lambda.voxel.client.render.meshing; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import sx.lambda.voxel.api.VoxelGameAPI; import sx.lambda.voxel.block.Block; import sx.lambda.voxel.block.IBlockRenderer; import sx.lambda.voxel.block.Side; import sx.lambda.voxel.world.chunk.IChunk; import java.util.ArrayList; import java.util.List; // TODO not meshing the chunk sides causes holes after the neighbor chunk is added. public class GreedyMesher implements Mesher { private final IChunk chunk; private boolean useAlpha; /** * @param chunk Chunk to mesh */ public GreedyMesher(IChunk chunk) { this.chunk = chunk; } @Override public Mesh meshVoxels(MeshBuilder builder, Block[][][] voxels, short[][][] metadata, float[][][] lightLevels) { List<Face> faces = getFaces(voxels, metadata, lightLevels); return meshFaces(faces, builder); } public List<Face> getFaces(Block[][][] voxels, short[][][] metadata, float[][][] lightLevels, OccludeCondition ocCond) { List<Face> faces = new ArrayList<>(); // Top, bottom for (int y = 0; y < voxels[0].length; y++) { int[][] topBlocks = new int[voxels.length][voxels[0][0].length]; short[][] topMeta = new short[voxels.length][voxels[0][0].length]; float[][] topLightLevels = new float[voxels.length][voxels[0][0].length]; int[][] btmBlocks = new int[voxels.length][voxels[0][0].length]; short[][] btmMeta = new short[voxels.length][voxels[0][0].length]; float[][] btmLightLevels = new float[voxels.length][voxels[0][0].length]; for (int x = 0; x < voxels.length; x++) { for (int z = 0; z < voxels[0][0].length; z++) { Block curBlock = voxels[x][y][z]; if (curBlock == null) continue; if (y < voxels[0].length - 1) { if (!ocCond.shouldOcclude(curBlock, voxels[x][y + 1][z])) { topBlocks[x][z] = curBlock.getID(); topMeta[x][z] = metadata[x][y][z]; topLightLevels[x][z] = lightLevels[x][y + 1][z]; } } else { topBlocks[x][z] = curBlock.getID(); topLightLevels[x][z] = 1; } if (y > 0) { if(!ocCond.shouldOcclude(curBlock, voxels[x][y - 1][z])) { btmBlocks[x][z] = curBlock.getID(); btmMeta[x][z] = metadata[x][y][z]; btmLightLevels[x][z] = lightLevels[x][y - 1][z]; } } else { btmLightLevels[x][z] = 1; continue; } } } greedy(faces, Side.TOP, topBlocks, topMeta, topLightLevels, y + chunk.getStartPosition().y, chunk.getStartPosition().x, chunk.getStartPosition().z); greedy(faces, Side.BOTTOM, btmBlocks, btmMeta, btmLightLevels, y + chunk.getStartPosition().y, chunk.getStartPosition().x, chunk.getStartPosition().z); } // East, west for (int x = 0; x < voxels.length; x++) { int[][] westBlocks = new int[voxels[0][0].length][voxels[0].length]; short[][] westMeta = new short[voxels[0][0].length][voxels[0].length]; float[][] westLightLevels = new float[voxels[0][0].length][voxels[0].length]; int[][] eastBlocks = new int[voxels[0][0].length][voxels[0].length]; short[][] eastMeta = new short[voxels[0][0].length][voxels[0].length]; float[][] eastLightLevels = new float[voxels[0][0].length][voxels[0].length]; for (int z = 0; z < voxels[0][0].length; z++) { for (int y = 0; y < voxels[0].length; y++) { Block curBlock = voxels[x][y][z]; if (curBlock == null) continue; int westNeighborX = chunk.getStartPosition().x + x - 1; IChunk westNeighborChunk = chunk.getWorld().getChunkAtPosition(westNeighborX, chunk.getStartPosition().z + z); if (westNeighborChunk != null) { Block westNeighborBlk = VoxelGameAPI.instance.getBlockByID( westNeighborChunk.getBlockIdAtPosition(westNeighborX, y, z)); if (!ocCond.shouldOcclude(curBlock, westNeighborBlk)) { westBlocks[z][y] = curBlock.getID(); westMeta[z][y] = metadata[x][y][z]; westLightLevels[z][y] = westNeighborChunk.getLightLevel(westNeighborX, y, z); } } else { westLightLevels[z][y] = 1; continue; } int eastNeighborX = chunk.getStartPosition().x + x + 1; IChunk eastNeighborChunk = chunk.getWorld().getChunkAtPosition(eastNeighborX, chunk.getStartPosition().z + z); if (eastNeighborChunk != null) { Block eastNeighborBlk = VoxelGameAPI.instance.getBlockByID( eastNeighborChunk.getBlockIdAtPosition(eastNeighborX, y, z)); if (!ocCond.shouldOcclude(curBlock, eastNeighborBlk)) { eastBlocks[z][y] = curBlock.getID(); eastMeta[z][y] = metadata[x][y][z]; eastLightLevels[z][y] = eastNeighborChunk.getLightLevel(eastNeighborX, y, z); } } else { eastLightLevels[z][y] = 1; continue; } } } greedy(faces, Side.EAST, eastBlocks, eastMeta, eastLightLevels, x + chunk.getStartPosition().x, chunk.getStartPosition().z, chunk.getStartPosition().y); greedy(faces, Side.WEST, westBlocks, westMeta, westLightLevels, x + chunk.getStartPosition().x, chunk.getStartPosition().z, chunk.getStartPosition().y); } // North, south for (int z = 0; z < voxels[0][0].length; z++) { int[][] northBlocks = new int[voxels.length][voxels[0].length]; short[][] northMeta = new short[voxels.length][voxels[0].length]; float[][] northLightLevels = new float[voxels.length][voxels[0].length]; int[][] southBlocks = new int[voxels.length][voxels[0].length]; short[][] southMeta = new short[voxels.length][voxels[0].length]; float[][] southLightLevels = new float[voxels.length][voxels[0].length]; for (int x = 0; x < voxels.length; x++) { for (int y = 0; y < voxels[0].length; y++) { Block curBlock = voxels[x][y][z]; if (curBlock == null) continue; int northNeighborZ = chunk.getStartPosition().z + z + 1; int southNeighborZ = chunk.getStartPosition().z + z - 1; IChunk northNeighborChunk = chunk.getWorld().getChunkAtPosition(chunk.getStartPosition().x + x, northNeighborZ); IChunk southNeighborChunk = chunk.getWorld().getChunkAtPosition(chunk.getStartPosition().x + x, southNeighborZ); if (northNeighborChunk != null) { Block northNeighborBlock = VoxelGameAPI.instance.getBlockByID( northNeighborChunk.getBlockIdAtPosition(x, y, northNeighborZ)); if (!ocCond.shouldOcclude(curBlock, northNeighborBlock)) { northBlocks[x][y] = curBlock.getID(); northMeta[x][y] = metadata[x][y][z]; northLightLevels[x][y] = northNeighborChunk.getLightLevel(x, y, northNeighborZ); } } else { northLightLevels[x][y] = 1; continue; } if (southNeighborChunk != null) { Block southNeighborBlock = VoxelGameAPI.instance.getBlockByID( southNeighborChunk.getBlockIdAtPosition(x, y, southNeighborZ)); if (!ocCond.shouldOcclude(curBlock, southNeighborBlock)) { southBlocks[x][y] = curBlock.getID(); southMeta[x][y] = metadata[x][y][z]; southLightLevels[x][y] = southNeighborChunk.getLightLevel(x, y, southNeighborZ); } } else { southLightLevels[x][y] = 1; continue; } } } greedy(faces, Side.NORTH, northBlocks, northMeta, northLightLevels, z + chunk.getStartPosition().z, chunk.getStartPosition().x, chunk.getStartPosition().y); greedy(faces, Side.SOUTH, southBlocks, southMeta, southLightLevels, z + chunk.getStartPosition().z, chunk.getStartPosition().x, chunk.getStartPosition().y); } return faces; } public List<Face> getFaces(Block[][][] voxels, short[][][] metadata, float[][][] lightLevels) { return getFaces(voxels, metadata, lightLevels, new OccludeCondition() { @Override public boolean shouldOcclude(Block curBlock, Block blockToSide) { return !(blockToSide == null || (blockToSide.isTranslucent() && !curBlock.isTranslucent())) && (curBlock.occludeCovered() && blockToSide.occludeCovered()); } }); } /** * @param outputList List to put faces in * @param side Side being meshed * @param blks Blocks on the plane * @param lls Light levels of the blocks * @param z Depth on the plane */ private void greedy(List<Face> outputList, Side side, int[][] blks, short metadata[][], float lls[][], int z, int offsetX, int offsetY) { int width = blks.length; int height = blks[0].length; boolean[][] used = new boolean[blks.length][blks[0].length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int blk = blks[x][y]; if(blk == 0) continue; float ll = lls[x][y]; short meta = metadata[x][y]; if (!used[x][y] && blk > 0) { used[x][y] = true; int endX = x + 1; int endY = y + 1; while (true) { int newX = endX; if (newX == blks.length) { break; } int newBlk = blks[newX][y]; float newll = lls[newX][y]; short newMeta = metadata[newX][y]; if (((newBlk == blk && newMeta == meta) || (newll == 0 && newBlk != 0)) && newll == ll && !used[newX][y]) { endX++; used[newX][y] = true; } else { while (true) { if (endY == height) break; boolean allPassed = true; for (int lx = x; lx < endX; lx++) { if (blks[lx][endY] != blk || metadata[lx][endY] != meta || lls[lx][endY] != ll || used[lx][endY]) { allPassed = false; } } if (allPassed) { for (int lx = x; lx < endX; lx++) { used[lx][endY] = true; } } else { break; } endY++; } break; } } outputList.add(new Face(side, blk, ll, x + offsetX, y + offsetY, endX + offsetX, endY + offsetY, z)); } } } } public Mesh meshFaces(List<Face> faces, MeshBuilder builder) { builder.begin(VertexAttributes.Usage.Position | VertexAttributes.Usage.TextureCoordinates | VertexAttributes.Usage.ColorPacked | VertexAttributes.Usage.Normal, GL20.GL_TRIANGLES); for (Face f : faces) { f.render(builder); } return builder.end(); } @Override public void enableAlpha() { this.useAlpha = true; } @Override public void disableAlpha() { this.useAlpha = false; } public static class Face { private final Side side; private final int x1, y1, x2, y2, z; private final Block block; private final float lightLevel; public Face(Side side, int block, float lightLevel, int startX, int startY, int endX, int endY, int z) { this.block = VoxelGameAPI.instance.getBlockByID(block); this.lightLevel = lightLevel; this.x1 = startX; this.y1 = startY; this.x2 = endX; this.y2 = endY; this.z = z; this.side = side; } public void render(MeshBuilder builder) { IBlockRenderer renderer = block.getRenderer(); switch (side) { case TOP: renderer.renderTop(block.getTextureIndex(), x1, y1, x2, y2, z + 1, lightLevel, builder); break; case BOTTOM: renderer.renderBottom(block.getTextureIndex(), x1, y1, x2, y2, z, lightLevel, builder); break; case NORTH: renderer.renderNorth(block.getTextureIndex(), x1, y1, x2, y2, z + 1, lightLevel, builder); break; case SOUTH: renderer.renderSouth(block.getTextureIndex(), x1, y1, x2, y2, z, lightLevel, builder); break; case EAST: renderer.renderEast(block.getTextureIndex(), x1, y1, x2, y2, z + 1, lightLevel, builder); break; case WEST: renderer.renderWest(block.getTextureIndex(), x1, y1, x2, y2, z, lightLevel, builder); break; } } } public interface OccludeCondition { /** * @param curBlock Current block being checked * @param blockToSide Block the the side of the current block * @return True if the side of the curBlock should be occluded */ boolean shouldOcclude(Block curBlock, Block blockToSide); } }
package spelling; import java.util.TreeSet; /** * @author UC San Diego Intermediate MOOC team * */ public class DictionaryBST implements Dictionary { private TreeSet<String> dict; // TODO: Implement the dictionary interface using a TreeSet. // You'll need a constructor here /** Add this word to the dictionary. Convert it to lowercase first * for the assignment requirements. * @param word The word to add * @return true if the word was added to the dictionary * (it wasn't already there). */ public boolean addWord(String word) { return dict.add(word); } /** Return the number of words in the dictionary */ public int size() { return dict.size(); } /** Is this a word according to this dictionary? */ public boolean isWord(String s) { //TODO: Implement this method return false; } }
package sx.lambda.voxel.client.render.meshing; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder; import sx.lambda.voxel.api.VoxelGameAPI; import sx.lambda.voxel.block.Block; import sx.lambda.voxel.block.IBlockRenderer; import sx.lambda.voxel.block.Side; import sx.lambda.voxel.world.chunk.IChunk; import java.util.ArrayList; import java.util.List; // TODO not meshing the chunk sides causes holes after the neighbor chunk is added. public class GreedyMesher implements Mesher { private final IChunk chunk; private boolean useAlpha; /** * @param chunk Chunk to mesh */ public GreedyMesher(IChunk chunk) { this.chunk = chunk; } @Override public Mesh meshVoxels(MeshBuilder builder, Block[][][] voxels, float[][][] lightLevels) { List<Face> faces = new ArrayList<>(); // Top, bottom for (int y = 0; y < voxels[0].length; y++) { Block[][] topBlocks = new Block[voxels.length][voxels[0][0].length]; float[][] topLightLevels = new float[voxels.length][voxels[0][0].length]; Block[][] btmBlocks = new Block[voxels.length][voxels[0][0].length]; float[][] btmLightLevels = new float[voxels.length][voxels[0][0].length]; for (int x = 0; x < voxels.length; x++) { for (int z = 0; z < voxels[0][0].length; z++) { if (voxels[x][y][z] == null) continue; if (y < voxels[0].length - 1) { if (voxels[x][y + 1][z] == null) { topBlocks[x][z] = voxels[x][y][z]; topLightLevels[x][z] = lightLevels[x][y + 1][z]; } else if (voxels[x][y + 1][z].isTransparent() && !voxels[x][y][z].isTransparent()) { topBlocks[x][z] = voxels[x][y][z]; topLightLevels[x][z] = lightLevels[x][y + 1][z]; } } else { topBlocks[x][z] = voxels[x][y][z]; topLightLevels[x][z] = 1; } if (y > 0) { if (voxels[x][y - 1][z] == null) { btmBlocks[x][z] = voxels[x][y][z]; btmLightLevels[x][z] = lightLevels[x][y - 1][z]; } else if (voxels[x][y - 1][z].isTransparent() && !voxels[x][y][z].isTransparent()) { btmBlocks[x][z] = voxels[x][y][z]; btmLightLevels[x][z] = lightLevels[x][y - 1][z]; } } else { btmLightLevels[x][z] = 1; continue; } } } greedy(faces, Side.TOP, topBlocks, topLightLevels, y + chunk.getStartPosition().y, chunk.getStartPosition().x, chunk.getStartPosition().z); greedy(faces, Side.BOTTOM, btmBlocks, btmLightLevels, y + chunk.getStartPosition().y, chunk.getStartPosition().x, chunk.getStartPosition().z); } // East, west for (int x = 0; x < voxels.length; x++) { Block[][] westBlocks = new Block[voxels[0][0].length][voxels[0].length]; float[][] westLightLevels = new float[voxels[0][0].length][voxels[0].length]; Block[][] eastBlocks = new Block[voxels[0][0].length][voxels[0].length]; float[][] eastLightLevels = new float[voxels[0][0].length][voxels[0].length]; for (int z = 0; z < voxels[0][0].length; z++) { for (int y = 0; y < voxels[0].length; y++) { if (voxels[x][y][z] == null) continue; int westNeighborX = chunk.getStartPosition().x + x - 1; IChunk westNeighborChunk = chunk.getWorld().getChunkAtPosition(westNeighborX, chunk.getStartPosition().z + z); if (westNeighborChunk != null) { Block westNeighborBlk = VoxelGameAPI.instance.getBlockByID( westNeighborChunk.getBlockIdAtPosition(westNeighborX, y, z)); if (westNeighborBlk == null) { westBlocks[z][y] = voxels[x][y][z]; westLightLevels[z][y] = westNeighborChunk.getLightLevel(westNeighborX, y, z); } else if (westNeighborBlk.isTransparent() && !voxels[x][y][z].isTransparent()) { westBlocks[z][y] = voxels[x][y][z]; westLightLevels[z][y] = westNeighborChunk.getLightLevel(westNeighborX, y, z); } } else { westLightLevels[z][y] = 1; continue; } int eastNeighborX = chunk.getStartPosition().x + x + 1; IChunk eastNeighborChunk = chunk.getWorld().getChunkAtPosition(eastNeighborX, chunk.getStartPosition().z + z); if (eastNeighborChunk != null) { Block eastNeighborBlk = VoxelGameAPI.instance.getBlockByID( eastNeighborChunk.getBlockIdAtPosition(eastNeighborX, y, z)); if (eastNeighborBlk == null) { eastBlocks[z][y] = voxels[x][y][z]; eastLightLevels[z][y] = eastNeighborChunk.getLightLevel(eastNeighborX, y, z); } else if (eastNeighborBlk.isTransparent() && !voxels[x][y][z].isTransparent()) { eastBlocks[z][y] = voxels[x][y][z]; eastLightLevels[z][y] = eastNeighborChunk.getLightLevel(eastNeighborX, y, z); } } else { eastLightLevels[z][y] = 1; continue; } } } greedy(faces, Side.EAST, eastBlocks, eastLightLevels, x + chunk.getStartPosition().x, chunk.getStartPosition().z, chunk.getStartPosition().y); greedy(faces, Side.WEST, westBlocks, westLightLevels, x + chunk.getStartPosition().x, chunk.getStartPosition().z, chunk.getStartPosition().y); } // North, south for (int z = 0; z < voxels[0][0].length; z++) { Block[][] northBlocks = new Block[voxels.length][voxels[0].length]; float[][] northLightLevels = new float[voxels.length][voxels[0].length]; Block[][] southBlocks = new Block[voxels.length][voxels[0].length]; float[][] southLightLevels = new float[voxels.length][voxels[0].length]; for (int x = 0; x < voxels.length; x++) { for (int y = 0; y < voxels[0].length; y++) { if (voxels[x][y][z] == null) continue; int northNeighborZ = chunk.getStartPosition().z + z + 1; int southNeighborZ = chunk.getStartPosition().z + z - 1; IChunk northNeighborChunk = chunk.getWorld().getChunkAtPosition(chunk.getStartPosition().x + x, northNeighborZ); IChunk southNeighborChunk = chunk.getWorld().getChunkAtPosition(chunk.getStartPosition().x + x, southNeighborZ); if (northNeighborChunk != null) { Block northNeighborBlock = VoxelGameAPI.instance.getBlockByID( northNeighborChunk.getBlockIdAtPosition(x, y, northNeighborZ)); if (northNeighborBlock == null) { northBlocks[x][y] = voxels[x][y][z]; northLightLevels[x][y] = northNeighborChunk.getLightLevel(x, y, northNeighborZ); } else if (northNeighborBlock.isTransparent() && !voxels[x][y][z].isTransparent()) { northBlocks[x][y] = voxels[x][y][z]; northLightLevels[x][y] = northNeighborChunk.getLightLevel(x, y, northNeighborZ); } } else { northBlocks[x][y] = voxels[x][y][z]; northLightLevels[x][y] = 1; } if (southNeighborChunk != null) { Block southNeighborBlock = VoxelGameAPI.instance.getBlockByID( southNeighborChunk.getBlockIdAtPosition(x, y, southNeighborZ)); if (southNeighborBlock == null) { southBlocks[x][y] = voxels[x][y][z]; southLightLevels[x][y] = southNeighborChunk.getLightLevel(x, y, southNeighborZ); } else if (southNeighborBlock.isTransparent() && !voxels[x][y][z].isTransparent()) { southBlocks[x][y] = voxels[x][y][z]; southLightLevels[x][y] = southNeighborChunk.getLightLevel(x, y, southNeighborZ); } } else { southLightLevels[x][y] = 1; continue; } } } greedy(faces, Side.NORTH, northBlocks, northLightLevels, z + chunk.getStartPosition().z, chunk.getStartPosition().x, chunk.getStartPosition().y); greedy(faces, Side.SOUTH, southBlocks, southLightLevels, z + chunk.getStartPosition().z, chunk.getStartPosition().x, chunk.getStartPosition().y); } builder.begin(VertexAttributes.Usage.Position | VertexAttributes.Usage.TextureCoordinates | VertexAttributes.Usage.ColorPacked | VertexAttributes.Usage.Normal, GL20.GL_TRIANGLES); for (Face f : faces) { f.render(builder); } return builder.end(); } /** * @param outputList List to put faces in * @param side Side being meshed * @param blks Blocks on the plane * @param lls Light levels of the blocks * @param z Depth on the plane */ private void greedy(List<Face> outputList, Side side, Block[][] blks, float lls[][], int z, int offsetX, int offsetY) { int width = blks.length; int height = blks[0].length; boolean[][] used = new boolean[blks.length][blks[0].length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Block blk = blks[x][y]; float ll = lls[x][y]; if (!used[x][y] && blk != null) { used[x][y] = true; int endX = x + 1; int endY = y + 1; while (true) { int newX = endX; if (newX == blks.length) { break; } Block newBlk = blks[newX][y]; float newll = lls[newX][y]; if (newBlk == blk && newll == ll && !used[newX][y]) { endX++; used[newX][y] = true; } else { while (true) { if (endY == height) break; boolean allPassed = true; for (int lx = x; lx < endX; lx++) { if (blks[lx][endY] != blk || lls[lx][endY] != ll || used[lx][endY]) { allPassed = false; } } if (allPassed) { for (int lx = x; lx < endX; lx++) { used[lx][endY] = true; } } else { break; } endY++; } break; } } outputList.add(new Face(side, blk, ll, x + offsetX, y + offsetY, endX + offsetX, endY + offsetY, z)); } } } } @Override public void enableAlpha() { this.useAlpha = true; } @Override public void disableAlpha() { this.useAlpha = false; } private static class Face { private final Side side; private final int x1, y1, x2, y2, z; private final Block block; private final float lightLevel; public Face(Side side, Block block, float lightLevel, int startX, int startY, int endX, int endY, int z) { this.block = block; this.lightLevel = lightLevel; this.x1 = startX; this.y1 = startY; this.x2 = endX; this.y2 = endY; this.z = z; this.side = side; } public void render(MeshBuilder builder) { IBlockRenderer renderer = block.getRenderer(); switch (side) { case TOP: renderer.renderTop(x1, y1, x2, y2, z + 1, lightLevel, builder); break; case BOTTOM: renderer.renderBottom(x1, y1, x2, y2, z, lightLevel, builder); break; case NORTH: renderer.renderNorth(x1, y1, x2, y2, z + 1, lightLevel, builder); break; case SOUTH: renderer.renderSouth(x1, y1, x2, y2, z, lightLevel, builder); break; case EAST: renderer.renderEast(x1, y1, x2, y2, z + 1, lightLevel, builder); break; case WEST: renderer.renderWest(x1, y1, x2, y2, z, lightLevel, builder); break; } } } }
// ZeissLSMReader.java package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveInteger; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.MDBService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffCompression; import loci.formats.tiff.TiffConstants; import loci.formats.tiff.TiffParser; public class ZeissLSMReader extends FormatReader { // -- Constants -- public static final String[] MDB_SUFFIX = {"mdb"}; /** Tag identifying a Zeiss LSM file. */ private static final int ZEISS_ID = 34412; /** Data types. */ private static final int TYPE_SUBBLOCK = 0; private static final int TYPE_ASCII = 2; private static final int TYPE_LONG = 4; private static final int TYPE_RATIONAL = 5; /** Subblock types. */ private static final int SUBBLOCK_RECORDING = 0x10000000; private static final int SUBBLOCK_LASER = 0x50000000; private static final int SUBBLOCK_TRACK = 0x40000000; private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000; private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000; private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000; private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000; private static final int SUBBLOCK_TIMER = 0x12000000; private static final int SUBBLOCK_MARKER = 0x14000000; private static final int SUBBLOCK_END = (int) 0xffffffff; /** Data types. */ private static final int RECORDING_NAME = 0x10000001; private static final int RECORDING_DESCRIPTION = 0x10000002; private static final int RECORDING_OBJECTIVE = 0x10000004; private static final int RECORDING_ZOOM = 0x10000016; private static final int RECORDING_SAMPLE_0TIME = 0x10000036; private static final int RECORDING_CAMERA_BINNING = 0x10000052; private static final int TRACK_ACQUIRE = 0x40000006; private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b; private static final int LASER_NAME = 0x50000001; private static final int LASER_ACQUIRE = 0x50000002; private static final int LASER_POWER = 0x50000003; private static final int CHANNEL_DETECTOR_GAIN = 0x70000003; private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009; private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005; private static final int CHANNEL_FILTER_SET = 0x7000000f; private static final int CHANNEL_FILTER = 0x70000010; private static final int CHANNEL_ACQUIRE = 0x7000000b; private static final int CHANNEL_NAME = 0x70000014; private static final int ILLUM_CHANNEL_NAME = 0x90000001; private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002; private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003; private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004; private static final int START_TIME = 0x10000036; private static final int DATA_CHANNEL_NAME = 0xd0000001; private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017; private static final int BEAM_SPLITTER_FILTER = 0xb0000002; private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003; /** Drawing element types. */ private static final int TEXT = 13; private static final int LINE = 14; private static final int SCALE_BAR = 15; private static final int OPEN_ARROW = 16; private static final int CLOSED_ARROW = 17; private static final int RECTANGLE = 18; private static final int ELLIPSE = 19; private static final int CLOSED_POLYLINE = 20; private static final int OPEN_POLYLINE = 21; private static final int CLOSED_BEZIER = 22; private static final int OPEN_BEZIER = 23; private static final int CIRCLE = 24; private static final int PALETTE = 25; private static final int POLYLINE_ARROW = 26; private static final int BEZIER_WITH_ARROW = 27; private static final int ANGLE = 28; private static final int CIRCLE_3POINT = 29; // -- Static fields -- private static final Hashtable<Integer, String> METADATA_KEYS = createKeys(); // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private byte[][][] lut = null; private Vector<Double> timestamps; private int validChannels; private String[] lsmFilenames; private Vector<IFDList> ifdsList; private TiffParser tiffParser; private int nextLaser = 0, nextDetector = 0; private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0; private int nextDataChannel = 0, nextIllumChannel = 0, nextDetectChannel = 0; private boolean splitPlanes = false; private double zoom; private Vector<String> imageNames; private String binning; private Vector<Double> xCoordinates, yCoordinates, zCoordinates; private int dimensionM, dimensionP; private Hashtable<String, Integer> seriesCounts; private String userName; private double originX, originY, originZ; private int totalROIs = 0; private int prevPlane = -1; private int prevChannel = 0; private byte[] prevBuf = null; private Region prevRegion = null; // -- Constructor -- /** Constructs a new Zeiss LSM reader. */ public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getOptimalTileWidth() */ public int getOptimalWidth() { FormatTools.assertId(currentId, true, 1); try { return (int) ifdsList.get(getSeries()).get(0).getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); } /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); try { return (int) ifdsList.get(getSeries()).get(0).getTileLength(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile height", e); } return super.getOptimalTileHeight(); } /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { if (checkSuffix(id, MDB_SUFFIX)) return false; return isGroupFiles() ? getMDBFile(id) != null : true; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { pixelSizeX = pixelSizeY = pixelSizeZ = 0; lut = null; timestamps = null; validChannels = 0; lsmFilenames = null; ifdsList = null; tiffParser = null; nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextIllumChannel = nextDetectChannel = 0; splitPlanes = false; zoom = 0; imageNames = null; binning = null; totalROIs = 0; prevPlane = -1; prevChannel = 0; prevBuf = null; prevRegion = null; xCoordinates = null; yCoordinates = null; zCoordinates = null; dimensionM = 0; dimensionP = 0; seriesCounts = null; originX = originY = originZ = 0d; userName = null; } } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 4; if (!FormatTools.validStream(stream, blockLen, false)) return false; TiffParser parser = new TiffParser(stream); return parser.isValidHeader() || stream.readShort() == 0x5374; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) { if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId}; return null; } if (lsmFilenames == null) return new String[] {currentId}; if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) { return lsmFilenames; } return new String[] {currentId, getLSMFileFromSeries(getSeries())}; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT8) { return null; } byte[][] b = new byte[3][]; b[0] = lut[getSeries()][prevChannel * 3]; b[1] = lut[getSeries()][prevChannel * 3 + 1]; b[2] = lut[getSeries()][prevChannel * 3 + 2]; return b; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT16) { return null; } short[][] s = new short[3][65536]; for (int i=2; i>=3-validChannels; i for (int j=0; j<s[i].length; j++) { s[i][j] = (short) j; } } return s; } /* @see loci.formats.IFormatReader#setSeries(int) */ public void setSeries(int series) { if (series != getSeries()) { prevBuf = null; } super.setSeries(series); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (getSeriesCount() > 1) { in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries())); in.order(!isLittleEndian()); tiffParser = new TiffParser(in); } IFDList ifds = ifdsList.get(getSeries()); if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT()) { int bpp = FormatTools.getBytesPerPixel(getPixelType()); int plane = no / getSizeC(); int c = no % getSizeC(); Region region = new Region(x, y, w, h); if (prevPlane != plane || prevBuf == null || prevBuf.length < w * h * bpp * getSizeC() || !region.equals(prevRegion)) { prevBuf = new byte[w * h * bpp * getSizeC()]; tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h); prevPlane = plane; prevRegion = region; } ImageTools.splitChannels( prevBuf, buf, c, getSizeC(), bpp, false, false, w * h * bpp); prevChannel = c; } else { tiffParser.getSamples(ifds.get(no), buf, x, y, w, h); prevChannel = getZCTCoords(no)[1]; } if (getSeriesCount() > 1) in.close(); return buf; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); if (!checkSuffix(id, MDB_SUFFIX) && isGroupFiles()) { String mdb = getMDBFile(id); if (mdb != null) { setId(mdb); return; } lsmFilenames = new String[] {id}; } else if (checkSuffix(id, MDB_SUFFIX)) { lsmFilenames = parseMDB(id); } else lsmFilenames = new String[] {id}; if (lsmFilenames == null || lsmFilenames.length == 0) { throw new FormatException("LSM files were not found."); } timestamps = new Vector<Double>(); imageNames = new Vector<String>(); xCoordinates = new Vector<Double>(); yCoordinates = new Vector<Double>(); zCoordinates = new Vector<Double>(); seriesCounts = new Hashtable<String, Integer>(); int seriesCount = 0; Vector<String> validFiles = new Vector<String>(); for (String filename : lsmFilenames) { try { int extraSeries = getExtraSeries(filename); seriesCounts.put(filename, extraSeries); seriesCount += extraSeries; validFiles.add(filename); } catch (IOException e) { LOGGER.debug("Failed to parse " + filename, e); } } lsmFilenames = validFiles.toArray(new String[validFiles.size()]); core = new CoreMetadata[seriesCount]; ifdsList = new Vector<IFDList>(); ifdsList.setSize(core.length); int realSeries = 0; for (int i=0; i<lsmFilenames.length; i++) { RandomAccessInputStream stream = new RandomAccessInputStream(lsmFilenames[i]); int count = seriesCounts.get(lsmFilenames[i]); TiffParser tp = new TiffParser(stream); Boolean littleEndian = tp.checkHeader(); long[] ifdOffsets = tp.getIFDOffsets(); int ifdsPerSeries = (ifdOffsets.length / 2) / count; int offset = 0; Object zeissTag = null; for (int s=0; s<count; s++, realSeries++) { core[realSeries] = new CoreMetadata(); core[realSeries].littleEndian = littleEndian; IFDList ifds = new IFDList(); while (ifds.size() < ifdsPerSeries) { tp.setDoCaching(offset == 0); IFD ifd = tp.getIFD(ifdOffsets[offset]); if (offset == 0) zeissTag = ifd.get(ZEISS_ID); if (offset > 0 && ifds.size() == 0) { ifd.putIFDValue(ZEISS_ID, zeissTag); } ifds.add(ifd); if (zeissTag != null) offset += 2; else offset++; } for (IFD ifd : ifds) { tp.fillInIFD(ifd); } ifdsList.set(realSeries, ifds); } stream.close(); } MetadataStore store = makeFilterMetadata(); lut = new byte[ifdsList.size()][][]; for (int series=0; series<ifdsList.size(); series++) { IFDList ifds = ifdsList.get(series); for (IFD ifd : ifds) { // check that predictor is set to 1 if anything other // than LZW compression is used if (ifd.getCompression() != TiffCompression.LZW) { ifd.putIFDValue(IFD.PREDICTOR, 1); } } // fix the offsets for > 4 GB files RandomAccessInputStream s = new RandomAccessInputStream(getLSMFileFromSeries(series)); for (int i=1; i<ifds.size(); i++) { long[] stripOffsets = ifds.get(i).getStripOffsets(); long[] previousStripOffsets = ifds.get(i - 1).getStripOffsets(); if (stripOffsets == null || previousStripOffsets == null) { throw new FormatException( "Strip offsets are missing; this is an invalid file."); } boolean neededAdjustment = false; for (int j=0; j<stripOffsets.length; j++) { if (j >= previousStripOffsets.length) break; if (stripOffsets[j] < previousStripOffsets[j]) { stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) | (stripOffsets[j] & 0xffffffffL); if (stripOffsets[j] < previousStripOffsets[j]) { stripOffsets[j] += 0x100000000L; } neededAdjustment = true; } if (neededAdjustment) { ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets); } } } s.close(); initMetadata(series); } for (int i=0; i<getSeriesCount(); i++) { core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT; } MetadataTools.populatePixels(store, this, true); for (int series=0; series<ifdsList.size(); series++) { setSeries(series); if (series < imageNames.size()) { store.setImageName(imageNames.get(series), series); } store.setPixelsBinDataBigEndian(!isLittleEndian(), series, 0); } setSeries(0); } // -- Helper methods -- private String getMDBFile(String id) throws FormatException, IOException { Location parentFile = new Location(id).getAbsoluteFile().getParentFile(); String[] fileList = parentFile.list(); for (int i=0; i<fileList.length; i++) { if (fileList[i].startsWith(".")) continue; if (checkSuffix(fileList[i], MDB_SUFFIX)) { Location file = new Location(parentFile, fileList[i]).getAbsoluteFile(); if (file.isDirectory()) continue; // make sure that the .mdb references this .lsm String[] lsms = parseMDB(file.getAbsolutePath()); if (lsms == null) return null; for (String lsm : lsms) { if (id.endsWith(lsm) || lsm.endsWith(id)) { return file.getAbsolutePath(); } } } } return null; } private int getEffectiveSeries(int currentSeries) { int seriesCount = 0; for (int i=0; i<lsmFilenames.length; i++) { Integer count = seriesCounts.get(lsmFilenames[i]); if (count == null) count = 1; seriesCount += count; if (seriesCount > currentSeries) return i; } return -1; } private String getLSMFileFromSeries(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries]; } private int getExtraSeries(String file) throws FormatException, IOException { if (in != null) in.close(); in = new RandomAccessInputStream(file); boolean littleEndian = in.read() == TiffConstants.LITTLE; in.order(littleEndian); tiffParser = new TiffParser(in); IFD ifd = tiffParser.getFirstIFD(); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) return 1; ras.order(littleEndian); ras.seek(264); dimensionP = ras.readInt(); dimensionM = ras.readInt(); ras.close(); int nSeries = dimensionM * dimensionP; return nSeries <= 0 ? 1 : nSeries; } private int getPosition(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); int firstPosition = 0; for (int i=0; i<effectiveSeries; i++) { firstPosition += seriesCounts.get(lsmFilenames[i]); } return currentSeries - firstPosition; } private RandomAccessInputStream getCZTag(IFD ifd) throws FormatException, IOException { // get TIF_CZ_LSMINFO structure short[] s = ifd.getIFDShortArray(ZEISS_ID); if (s == null) { LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID); TiffReader reader = new TiffReader(); reader.setId(getLSMFileFromSeries(series)); core[getSeries()] = reader.getCoreMetadata()[0]; reader.close(); return null; } byte[] cz = new byte[s.length]; for (int i=0; i<s.length; i++) { cz[i] = (byte) s[i]; } RandomAccessInputStream ras = new RandomAccessInputStream(cz); ras.order(isLittleEndian()); return ras; } protected void initMetadata(int series) throws FormatException, IOException { setSeries(series); IFDList ifds = ifdsList.get(series); IFD ifd = ifds.get(0); in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(series)); in.order(isLittleEndian()); tiffParser = new TiffParser(in); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[series].sizeX = (int) ifd.getImageWidth(); core[series].sizeY = (int) ifd.getImageLength(); core[series].rgb = samples > 1 || photo == PhotoInterp.RGB; core[series].interleaved = false; core[series].sizeC = isRGB() ? samples : 1; core[series].pixelType = ifd.getPixelType(); core[series].imageCount = ifds.size(); core[series].sizeZ = getImageCount(); core[series].sizeT = 1; LOGGER.info("Reading LSM metadata for series #{}", series); MetadataStore store = makeFilterMetadata(); int instrument = getEffectiveSeries(series); String imageName = getLSMFileFromSeries(series); if (imageName.indexOf(".") != -1) { imageName = imageName.substring(0, imageName.lastIndexOf(".")); } if (imageName.indexOf(File.separator) != -1) { imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); } if (lsmFilenames.length != getSeriesCount()) { imageName += " #" + (getPosition(series) + 1); } // link Instrument and Image store.setImageID(MetadataTools.createLSID("Image", series), series); String instrumentID = MetadataTools.createLSID("Instrument", instrument); store.setInstrumentID(instrumentID, instrument); store.setImageInstrumentRef(instrumentID, series); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) { imageNames.add(imageName); return; } ras.seek(16); core[series].sizeZ = ras.readInt(); ras.skipBytes(4); core[series].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: addSeriesMeta("DataType", "12 bit unsigned integer"); break; case 5: addSeriesMeta("DataType", "32 bit float"); break; case 0: addSeriesMeta("DataType", "varying data types"); break; default: addSeriesMeta("DataType", "8 bit unsigned integer"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { ras.seek(0); addSeriesMeta("MagicNumber ", ras.readInt()); addSeriesMeta("StructureSize", ras.readInt()); addSeriesMeta("DimensionX", ras.readInt()); addSeriesMeta("DimensionY", ras.readInt()); ras.seek(32); addSeriesMeta("ThumbnailX", ras.readInt()); addSeriesMeta("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; addSeriesMeta("VoxelSizeX", new Double(pixelSizeX)); addSeriesMeta("VoxelSizeY", new Double(pixelSizeY)); addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ)); originX = ras.readDouble() * 1000000; originY = ras.readDouble() * 1000000; originZ = ras.readDouble() * 1000000; addSeriesMeta("OriginX", originX); addSeriesMeta("OriginY", originY); addSeriesMeta("OriginZ", originZ); } else ras.seek(88); int scanType = ras.readShort(); switch (scanType) { case 0: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; break; case 1: addSeriesMeta("ScanType", "z scan (x-z plane)"); core[series].dimensionOrder = "XYZCT"; break; case 2: addSeriesMeta("ScanType", "line scan"); core[series].dimensionOrder = "XYZCT"; break; case 3: addSeriesMeta("ScanType", "time series x-y"); core[series].dimensionOrder = "XYTCZ"; break; case 4: addSeriesMeta("ScanType", "time series x-z"); core[series].dimensionOrder = "XYZTC"; break; case 5: addSeriesMeta("ScanType", "time series 'Mean of ROIs'"); core[series].dimensionOrder = "XYTCZ"; break; case 6: addSeriesMeta("ScanType", "time series x-y-z"); core[series].dimensionOrder = "XYZTC"; break; case 7: addSeriesMeta("ScanType", "spline scan"); core[series].dimensionOrder = "XYCTZ"; break; case 8: addSeriesMeta("ScanType", "spline scan x-z"); core[series].dimensionOrder = "XYCZT"; break; case 9: addSeriesMeta("ScanType", "time series spline plane x-z"); core[series].dimensionOrder = "XYTCZ"; break; case 10: addSeriesMeta("ScanType", "point mode"); core[series].dimensionOrder = "XYZCT"; break; default: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; } core[series].indexed = lut != null && lut[series] != null; if (isIndexed()) { core[series].rgb = false; } if (getSizeC() == 0) core[series].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[series].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } if (getEffectiveSizeC() == 0) { core[series].imageCount = getSizeZ() * getSizeT(); } else { core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); } if (getImageCount() != ifds.size()) { int diff = getImageCount() - ifds.size(); core[series].imageCount = ifds.size(); if (diff % getSizeZ() == 0) { core[series].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[series].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[series].sizeZ = ifds.size(); core[series].sizeT = 1; } else if (getSizeT() > 1) { core[series].sizeT = ifds.size(); core[series].sizeZ = 1; } } if (getSizeZ() == 0) core[series].sizeZ = getImageCount(); if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ(); long channelColorsOffset = 0; long timeStampOffset = 0; long eventListOffset = 0; long scanInformationOffset = 0; long channelWavelengthOffset = 0; if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { int spectralScan = ras.readShort(); if (spectralScan != 1) { addSeriesMeta("SpectralScan", "no spectral scan"); } else addSeriesMeta("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: addSeriesMeta("DataType2", "calculated data"); break; case 2: addSeriesMeta("DataType2", "animation"); break; default: addSeriesMeta("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); channelColorsOffset = ras.readInt(); addSeriesMeta("TimeInterval", ras.readDouble()); ras.skipBytes(4); scanInformationOffset = ras.readInt(); ras.skipBytes(4); timeStampOffset = ras.readInt(); eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); addSeriesMeta("DisplayAspectX", ras.readDouble()); addSeriesMeta("DisplayAspectY", ras.readDouble()); addSeriesMeta("DisplayAspectZ", ras.readDouble()); addSeriesMeta("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(series, overlayOffsets[i], overlayKeys[i], store); } } totalROIs = 0; addSeriesMeta("ToolbarFlags", ras.readInt()); channelWavelengthOffset = ras.readInt(); ras.skipBytes(64); } else ras.skipBytes(182); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series); if (getSizeC() > 1) { if (!splitPlanes) splitPlanes = isRGB(); core[series].rgb = false; if (splitPlanes) core[series].imageCount *= getSizeC(); } for (int c=0; c<getEffectiveSizeC(); c++) { String lsid = MetadataTools.createLSID("Channel", series, c); store.setChannelID(lsid, series, c); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // NB: the Zeiss LSM 5.5 specification indicates that there should be // 15 32-bit integers here; however, there are actually 16 32-bit // integers before the tile position offset. // We have confirmed with Zeiss that this is correct, and the 6.0 // specification was updated to contain the correct information. ras.skipBytes(64); int tilePositionOffset = ras.readInt(); ras.skipBytes(36); int positionOffset = ras.readInt(); // read referenced structures addSeriesMeta("DimensionZ", getSizeZ()); addSeriesMeta("DimensionChannels", getSizeC()); addSeriesMeta("DimensionM", dimensionM); addSeriesMeta("DimensionP", dimensionP); if (lsmFilenames.length == 1) { xCoordinates.clear(); yCoordinates.clear(); zCoordinates.clear(); } if (positionOffset != 0) { in.seek(positionOffset); int nPositions = in.readInt(); for (int i=0; i<nPositions; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; xCoordinates.add(xPos); yCoordinates.add(yPos); zCoordinates.add(zPos); addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (tilePositionOffset != 0) { in.seek(tilePositionOffset); int nTiles = in.readInt(); for (int i=0; i<nTiles; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; if (xCoordinates.size() > i) { xPos += xCoordinates.get(i); xCoordinates.setElementAt(xPos, i); } else if (xCoordinates.size() == i) { xCoordinates.add(xPos); } if (yCoordinates.size() > i) { yPos += yCoordinates.get(i); yCoordinates.setElementAt(yPos, i); } else if (yCoordinates.size() == i) { yCoordinates.add(yPos); } if (zCoordinates.size() > i) { zPos += zCoordinates.get(i); zCoordinates.setElementAt(zPos, i); } else if (zCoordinates.size() == i) { zCoordinates.add(zPos); } addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 12); int colorsOffset = in.readInt(); int namesOffset = in.readInt(); // read the color of each channel if (colorsOffset > 0) { in.seek(channelColorsOffset + colorsOffset); lut[getSeries()] = new byte[getSizeC() * 3][256]; core[getSeries()].indexed = true; for (int i=0; i<getSizeC(); i++) { int color = in.readInt(); int red = color & 0xff; int green = (color & 0xff00) >> 8; int blue = (color & 0xff0000) >> 16; for (int j=0; j<256; j++) { lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j); lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j); lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j); } } } // read the name of each channel if (namesOffset > 0) { in.seek(channelColorsOffset + namesOffset + 4); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) { addSeriesMeta("ChannelName" + i, name); } } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); addSeriesMeta("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); addSeriesMeta("Event" + i + " Time", eventTime); addSeriesMeta("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; addSeriesMeta("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextDetectChannel = nextIllumChannel = 0; Vector<SubBlock> blocks = new Vector<SubBlock>(); while (in.getFilePointer() < in.length() - 12) { if (in.getFilePointer() < 0) break; int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); if (blockType == TYPE_SUBBLOCK) { SubBlock block = null; switch (entry) { case SUBBLOCK_RECORDING: block = new Recording(); break; case SUBBLOCK_LASER: block = new Laser(); break; case SUBBLOCK_TRACK: block = new Track(); break; case SUBBLOCK_DETECTION_CHANNEL: block = new DetectionChannel(); break; case SUBBLOCK_ILLUMINATION_CHANNEL: block = new IlluminationChannel(); break; case SUBBLOCK_BEAM_SPLITTER: block = new BeamSplitter(); break; case SUBBLOCK_DATA_CHANNEL: block = new DataChannel(); break; case SUBBLOCK_TIMER: block = new Timer(); break; case SUBBLOCK_MARKER: block = new Marker(); break; } if (block != null) { blocks.add(block); } } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) { in.skipBytes(dataSize); } else break; } Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>(); SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]); for (SubBlock block : metadataBlocks) { block.addToHashtable(); if (!block.acquire) { nonAcquiredBlocks.add(block); blocks.remove(block); } } for (int i=0; i<blocks.size(); i++) { SubBlock block = blocks.get(i); // every valid IlluminationChannel must be immediately followed by // a valid DataChannel or IlluminationChannel if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) { SubBlock nextBlock = blocks.get(i + 1); if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) { ((IlluminationChannel) block).wavelength = null; } } // every valid DetectionChannel must be immediately preceded by // a valid Track or DetectionChannel else if ((block instanceof DetectionChannel) && i > 0) { SubBlock prevBlock = blocks.get(i - 1); if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) { block.acquire = false; nonAcquiredBlocks.add(block); } } if (block.acquire) populateMetadataStore(block, store, series); } for (SubBlock block : nonAcquiredBlocks) { populateMetadataStore(block, store, series); } } } imageNames.add(imageName); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (userName != null) { String experimenterID = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenterID, 0); store.setExperimenterUserName(userName, 0); store.setExperimenterDisplayName(userName, 0); } Double pixX = new Double(pixelSizeX); Double pixY = new Double(pixelSizeY); Double pixZ = new Double(pixelSizeZ); store.setPixelsPhysicalSizeX(pixX, series); store.setPixelsPhysicalSizeY(pixY, series); store.setPixelsPhysicalSizeZ(pixZ, series); double firstStamp = 0; if (timestamps.size() > 0) { firstStamp = timestamps.get(0).doubleValue(); } for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { double thisStamp = timestamps.get(zct[2]).doubleValue(); store.setPlaneDeltaT(thisStamp - firstStamp, series, i); int index = zct[2] + 1; double nextStamp = index < timestamps.size() ? timestamps.get(index).doubleValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = timestamps.get(zct[2] - 1).doubleValue(); } store.setPlaneExposureTime(nextStamp - thisStamp, series, i); } if (xCoordinates.size() > series) { store.setPlanePositionX(xCoordinates.get(series), series, i); store.setPlanePositionY(yCoordinates.get(series), series, i); store.setPlanePositionZ(zCoordinates.get(series), series, i); } } } ras.close(); } protected void populateMetadataStore(SubBlock block, MetadataStore store, int series) throws FormatException { if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { return; } int instrument = getEffectiveSeries(series); // NB: block.acquire can be false. If that is the case, Instrument data // is the only thing that should be populated. if (block instanceof Recording) { Recording recording = (Recording) block; String objectiveID = MetadataTools.createLSID("Objective", instrument, 0); if (recording.acquire) { store.setImageDescription(recording.description, series); store.setImageAcquiredDate(recording.startTime, series); store.setImageObjectiveSettingsID(objectiveID, series); binning = recording.binning; } store.setObjectiveCorrection( getCorrection(recording.correction), instrument, 0); store.setObjectiveImmersion( getImmersion(recording.immersion), instrument, 0); if (recording.magnification != null && recording.magnification > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(recording.magnification), instrument, 0); } store.setObjectiveLensNA(recording.lensNA, instrument, 0); store.setObjectiveIris(recording.iris, instrument, 0); store.setObjectiveID(objectiveID, instrument, 0); } else if (block instanceof Laser) { Laser laser = (Laser) block; if (laser.medium != null) { store.setLaserLaserMedium(getLaserMedium(laser.medium), instrument, nextLaser); } if (laser.type != null) { store.setLaserType(getLaserType(laser.type), instrument, nextLaser); } if (laser.model != null) { store.setLaserModel(laser.model, instrument, nextLaser); } String lightSourceID = MetadataTools.createLSID("LightSource", instrument, nextLaser); store.setLaserID(lightSourceID, instrument, nextLaser); nextLaser++; } else if (block instanceof Track) { Track track = (Track) block; if (track.acquire) { store.setPixelsTimeIncrement(track.timeIncrement, series); } } else if (block instanceof DataChannel) { DataChannel channel = (DataChannel) block; if (channel.name != null && nextDataChannel < getSizeC() && channel.acquire) { store.setChannelName(channel.name, series, nextDataChannel++); } } else if (block instanceof DetectionChannel) { DetectionChannel channel = (DetectionChannel) block; if (channel.pinhole != null && channel.pinhole.doubleValue() != 0f && nextDetectChannel < getSizeC() && channel.acquire) { store.setChannelPinholeSize(channel.pinhole, series, nextDetectChannel); } if (channel.filter != null) { String id = MetadataTools.createLSID("Filter", instrument, nextFilter); if (channel.acquire && nextDetectChannel < getSizeC()) { store.setLightPathEmissionFilterRef( id, instrument, nextDetectChannel, 0); } store.setFilterID(id, instrument, nextFilter); store.setFilterModel(channel.filter, instrument, nextFilter); int space = channel.filter.indexOf(" "); if (space != -1) { String type = channel.filter.substring(0, space).trim(); if (type.equals("BP")) type = "BandPass"; else if (type.equals("LP")) type = "LongPass"; store.setFilterType(getFilterType(type), instrument, nextFilter); String transmittance = channel.filter.substring(space + 1).trim(); String[] v = transmittance.split("-"); try { store.setTransmittanceRangeCutIn( PositiveInteger.valueOf(v[0].trim()), instrument, nextFilter); } catch (NumberFormatException e) { } if (v.length > 1) { try { store.setTransmittanceRangeCutOut( PositiveInteger.valueOf(v[1].trim()), instrument, nextFilter); } catch (NumberFormatException e) { } } } nextFilter++; } if (channel.channelName != null) { String detectorID = MetadataTools.createLSID("Detector", instrument, nextDetector); store.setDetectorID(detectorID, instrument, nextDetector); if (channel.acquire && nextDetector < getSizeC()) { store.setDetectorSettingsID(detectorID, series, nextDetector); store.setDetectorSettingsBinning( getBinning(binning), series, nextDetector); } } if (channel.amplificationGain != null) { store.setDetectorAmplificationGain( channel.amplificationGain, instrument, nextDetector); } if (channel.gain != null) { store.setDetectorGain(channel.gain, instrument, nextDetector); } store.setDetectorType(getDetectorType("PMT"), instrument, nextDetector); store.setDetectorZoom(zoom, instrument, nextDetector); nextDetectChannel++; nextDetector++; } else if (block instanceof BeamSplitter) { BeamSplitter beamSplitter = (BeamSplitter) block; if (beamSplitter.filterSet != null) { if (beamSplitter.filter != null) { String id = MetadataTools.createLSID( "Dichroic", instrument, nextDichroic); store.setDichroicID(id, instrument, nextDichroic); store.setDichroicModel(beamSplitter.filter, instrument, nextDichroic); if (nextDichroicChannel < getEffectiveSizeC()) { store.setLightPathDichroicRef(id, series, nextDichroicChannel); } nextDichroic++; } nextDichroicChannel++; } } else if (block instanceof IlluminationChannel) { IlluminationChannel channel = (IlluminationChannel) block; if (channel.acquire && channel.wavelength != null) { store.setChannelEmissionWavelength( new PositiveInteger(channel.wavelength), series, nextIllumChannel++); } } } /** Parses overlay-related fields. */ protected void parseOverlays(int series, long data, String suffix, MetadataStore store) throws IOException { if (data == 0) return; String prefix = "Series " + series + " "; in.seek(data); int numberOfShapes = in.readInt(); int size = in.readInt(); if (size <= 194) return; in.skipBytes(20); boolean valid = in.readInt() == 1; in.skipBytes(164); for (int i=totalROIs; i<totalROIs+numberOfShapes; i++) { long offset = in.getFilePointer(); int type = in.readInt(); int blockLength = in.readInt(); double lineWidth = in.readInt(); int measurements = in.readInt(); double textOffsetX = in.readDouble(); double textOffsetY = in.readDouble(); int color = in.readInt(); boolean validShape = in.readInt() != 0; int knotWidth = in.readInt(); int catchArea = in.readInt(); int fontHeight = in.readInt(); int fontWidth = in.readInt(); int fontEscapement = in.readInt(); int fontOrientation = in.readInt(); int fontWeight = in.readInt(); boolean fontItalic = in.readInt() != 0; boolean fontUnderlined = in.readInt() != 0; boolean fontStrikeout = in.readInt() != 0; int fontCharSet = in.readInt(); int fontOutputPrecision = in.readInt(); int fontClipPrecision = in.readInt(); int fontQuality = in.readInt(); int fontPitchAndFamily = in.readInt(); String fontName = DataTools.stripString(in.readString(64)); boolean enabled = in.readShort() == 0; boolean moveable = in.readInt() == 0; in.skipBytes(34); String roiID = MetadataTools.createLSID("ROI", i); String shapeID = MetadataTools.createLSID("Shape", i, 0); switch (type) { case TEXT: double x = in.readDouble(); double y = in.readDouble(); String text = DataTools.stripString(in.readCString()); store.setTextValue(text, i, 0); store.setTextFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setTextStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setTextID(shapeID, i, 0); break; case LINE: in.skipBytes(4); double startX = in.readDouble(); double startY = in.readDouble(); double endX = in.readDouble(); double endY = in.readDouble(); store.setLineX1(startX, i, 0); store.setLineY1(startY, i, 0); store.setLineX2(endX, i, 0); store.setLineY2(endY, i, 0); store.setLineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setLineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setLineID(shapeID, i, 0); break; case SCALE_BAR: case OPEN_ARROW: case CLOSED_ARROW: case PALETTE: in.skipBytes(36); break; case RECTANGLE: in.skipBytes(4); double topX = in.readDouble(); double topY = in.readDouble(); double bottomX = in.readDouble(); double bottomY = in.readDouble(); double width = Math.abs(bottomX - topX); double height = Math.abs(bottomY - topY); topX = Math.min(topX, bottomX); topY = Math.min(topY, bottomY); store.setRectangleX(topX, i, 0); store.setRectangleY(topY, i, 0); store.setRectangleWidth(width, i, 0); store.setRectangleHeight(height, i, 0); store.setRectangleFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setRectangleStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setRectangleID(shapeID, i, 0); break; case ELLIPSE: int knots = in.readInt(); double[] xs = new double[knots]; double[] ys = new double[knots]; for (int j=0; j<xs.length; j++) { xs[j] = in.readDouble(); ys[j] = in.readDouble(); } double rx = 0, ry = 0, centerX = 0, centerY = 0; if (knots == 4) { double r1x = Math.abs(xs[2] - xs[0]) / 2; double r1y = Math.abs(ys[2] - ys[0]) / 2; double r2x = Math.abs(xs[3] - xs[1]) / 2; double r2y = Math.abs(ys[3] - ys[1]) / 2; if (r1x > r2x) { ry = r1y; rx = r2x; centerX = Math.min(xs[3], xs[1]) + rx; centerY = Math.min(ys[2], ys[0]) + ry; } else { ry = r2y; rx = r1x; centerX = Math.min(xs[2], xs[0]) + rx; centerY = Math.min(ys[3], ys[1]) + ry; } } else if (knots == 3) { // we are given the center point and one cut point for each axis centerX = xs[0]; centerY = ys[0]; rx = Math.sqrt(Math.pow(xs[1] - xs[0], 2) + Math.pow(ys[1] - ys[0], 2)); ry = Math.sqrt(Math.pow(xs[2] - xs[0], 2) + Math.pow(ys[2] - ys[0], 2)); // calculate rotation angle double slope = (ys[2] - centerY) / (xs[2] - centerX); double theta = Math.toDegrees(Math.atan(slope)); store.setEllipseTransform("rotate(" + theta + " " + centerX + " " + centerY + ")", i, 0); } store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(rx, i, 0); store.setEllipseRadiusY(ry, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE: in.skipBytes(4); centerX = in.readDouble(); centerY = in.readDouble(); double curveX = in.readDouble(); double curveY = in.readDouble(); double radius = Math.sqrt(Math.pow(curveX - centerX, 2) + Math.pow(curveY - centerY, 2)); store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(radius, i, 0); store.setEllipseRadiusY(radius, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE_3POINT: in.skipBytes(4); // given 3 points on the perimeter of the circle, we need to // calculate the center and radius double[][] points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } double s = 0.5 * ((points[1][0] - points[2][0]) * (points[0][0] - points[2][0]) - (points[1][1] - points[2][1]) * (points[2][1] - points[0][1])); double div = (points[0][0] - points[1][0]) * (points[2][1] - points[0][1]) - (points[1][1] - points[0][1]) * (points[0][0] - points[2][0]); s /= div; double cx = 0.5 * (points[0][0] + points[1][0]) + s * (points[1][1] - points[0][1]); double cy = 0.5 * (points[0][1] + points[1][1]) + s * (points[0][0] - points[1][0]); double r = Math.sqrt(Math.pow(points[0][0] - cx, 2) + Math.pow(points[0][1] - cy, 2)); store.setEllipseX(cx, i, 0); store.setEllipseY(cy, i, 0); store.setEllipseRadiusX(r, i, 0); store.setEllipseRadiusY(r, i, 0); store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setEllipseID(shapeID, i, 0); break; case ANGLE: in.skipBytes(4); points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } StringBuffer p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; case CLOSED_POLYLINE: case OPEN_POLYLINE: case POLYLINE_ARROW: int nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineClosed(type == CLOSED_POLYLINE, i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; case CLOSED_BEZIER: case OPEN_BEZIER: case BEZIER_WITH_ARROW: nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); store.setPolylineClosed(type != OPEN_BEZIER, i, 0); store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setPolylineID(shapeID, i, 0); break; default: i numberOfShapes continue; } // populate shape attributes in.seek(offset + blockLength); } totalROIs += numberOfShapes; } /** Parse a .mdb file and return a list of referenced .lsm files. */ private String[] parseMDB(String mdbFile) throws FormatException, IOException { Location mdb = new Location(mdbFile).getAbsoluteFile(); Location parent = mdb.getParentFile(); MDBService mdbService = null; try { ServiceFactory factory = new ServiceFactory(); mdbService = factory.getInstance(MDBService.class); } catch (DependencyException de) { throw new FormatException("MDB Tools Java library not found", de); } try { mdbService.initialize(mdbFile); } catch (Exception e) { return null; } Vector<Vector<String[]>> tables = mdbService.parseDatabase(); Vector<String> referencedLSMs = new Vector<String>(); int referenceCount = 0; for (Vector<String[]> table : tables) { String[] columnNames = table.get(0); String tableName = columnNames[0]; for (int row=1; row<table.size(); row++) { String[] tableRow = table.get(row); for (int col=0; col<tableRow.length; col++) { String key = tableName + " " + columnNames[col + 1] + " " + row; if (currentId != null) { addGlobalMeta(key, tableRow[col]); } if (tableName.equals("Recordings") && columnNames[col + 1] != null && columnNames[col + 1].equals("SampleData")) { String filename = tableRow[col].trim(); filename = filename.replace('\\', File.separatorChar); filename = filename.replace('/', File.separatorChar); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); if (filename.length() > 0) { Location file = new Location(parent, filename); if (file.exists()) { referencedLSMs.add(file.getAbsolutePath()); } } referenceCount++; } } } } if (referencedLSMs.size() == referenceCount) { return referencedLSMs.toArray(new String[0]); } referencedLSMs.clear(); String[] fileList = parent.list(true); for (int i=0; i<fileList.length; i++) { String absolutePath = new Location(parent, fileList[i]).getAbsolutePath(); if (checkSuffix(fileList[i], new String[] {"lsm"})) { referencedLSMs.add(absolutePath); } else if (checkSuffix(fileList[i], "mdb") && (!absolutePath.equals(mdbFile) && !fileList[i].equals(mdbFile))) { referencedLSMs.clear(); break; } } return referencedLSMs.toArray(new String[0]); } private static Hashtable<Integer, String> createKeys() { Hashtable<Integer, String> h = new Hashtable<Integer, String>(); h.put(new Integer(0x10000001), "Name"); h.put(new Integer(0x4000000c), "Name"); h.put(new Integer(0x50000001), "Name"); h.put(new Integer(0x90000001), "Name"); h.put(new Integer(0x90000005), "Detection Channel Name"); h.put(new Integer(0xb0000003), "Name"); h.put(new Integer(0xd0000001), "Name"); h.put(new Integer(0x12000001), "Name"); h.put(new Integer(0x14000001), "Name"); h.put(new Integer(0x10000002), "Description"); h.put(new Integer(0x14000002), "Description"); h.put(new Integer(0x10000003), "Notes"); h.put(new Integer(0x10000004), "Objective"); h.put(new Integer(0x10000005), "Processing Summary"); h.put(new Integer(0x10000006), "Special Scan Mode"); h.put(new Integer(0x10000007), "Scan Type"); h.put(new Integer(0x10000008), "Scan Mode"); h.put(new Integer(0x10000009), "Number of Stacks"); h.put(new Integer(0x1000000a), "Lines Per Plane"); h.put(new Integer(0x1000000b), "Samples Per Line"); h.put(new Integer(0x1000000c), "Planes Per Volume"); h.put(new Integer(0x1000000d), "Images Width"); h.put(new Integer(0x1000000e), "Images Height"); h.put(new Integer(0x1000000f), "Number of Planes"); h.put(new Integer(0x10000010), "Number of Stacks"); h.put(new Integer(0x10000011), "Number of Channels"); h.put(new Integer(0x10000012), "Linescan XY Size"); h.put(new Integer(0x10000013), "Scan Direction"); h.put(new Integer(0x10000014), "Time Series"); h.put(new Integer(0x10000015), "Original Scan Data"); h.put(new Integer(0x10000016), "Zoom X"); h.put(new Integer(0x10000017), "Zoom Y"); h.put(new Integer(0x10000018), "Zoom Z"); h.put(new Integer(0x10000019), "Sample 0X"); h.put(new Integer(0x1000001a), "Sample 0Y"); h.put(new Integer(0x1000001b), "Sample 0Z"); h.put(new Integer(0x1000001c), "Sample Spacing"); h.put(new Integer(0x1000001d), "Line Spacing"); h.put(new Integer(0x1000001e), "Plane Spacing"); h.put(new Integer(0x1000001f), "Plane Width"); h.put(new Integer(0x10000020), "Plane Height"); h.put(new Integer(0x10000021), "Volume Depth"); h.put(new Integer(0x10000034), "Rotation"); h.put(new Integer(0x10000035), "Precession"); h.put(new Integer(0x10000036), "Sample 0Time"); h.put(new Integer(0x10000037), "Start Scan Trigger In"); h.put(new Integer(0x10000038), "Start Scan Trigger Out"); h.put(new Integer(0x10000039), "Start Scan Event"); h.put(new Integer(0x10000040), "Start Scan Time"); h.put(new Integer(0x10000041), "Stop Scan Trigger In"); h.put(new Integer(0x10000042), "Stop Scan Trigger Out"); h.put(new Integer(0x10000043), "Stop Scan Event"); h.put(new Integer(0x10000044), "Stop Scan Time"); h.put(new Integer(0x10000045), "Use ROIs"); h.put(new Integer(0x10000046), "Use Reduced Memory ROIs"); h.put(new Integer(0x10000047), "User"); h.put(new Integer(0x10000048), "Use B/C Correction"); h.put(new Integer(0x10000049), "Position B/C Contrast 1"); h.put(new Integer(0x10000050), "Position B/C Contrast 2"); h.put(new Integer(0x10000051), "Interpolation Y"); h.put(new Integer(0x10000052), "Camera Binning"); h.put(new Integer(0x10000053), "Camera Supersampling"); h.put(new Integer(0x10000054), "Camera Frame Width"); h.put(new Integer(0x10000055), "Camera Frame Height"); h.put(new Integer(0x10000056), "Camera Offset X"); h.put(new Integer(0x10000057), "Camera Offset Y"); h.put(new Integer(0x40000001), "Multiplex Type"); h.put(new Integer(0x40000002), "Multiplex Order"); h.put(new Integer(0x40000003), "Sampling Mode"); h.put(new Integer(0x40000004), "Sampling Method"); h.put(new Integer(0x40000005), "Sampling Number"); h.put(new Integer(0x40000006), "Acquire"); h.put(new Integer(0x50000002), "Acquire"); h.put(new Integer(0x7000000b), "Acquire"); h.put(new Integer(0x90000004), "Acquire"); h.put(new Integer(0xd0000017), "Acquire"); h.put(new Integer(0x40000007), "Sample Observation Time"); h.put(new Integer(0x40000008), "Time Between Stacks"); h.put(new Integer(0x4000000d), "Collimator 1 Name"); h.put(new Integer(0x4000000e), "Collimator 1 Position"); h.put(new Integer(0x4000000f), "Collimator 2 Name"); h.put(new Integer(0x40000010), "Collimator 2 Position"); h.put(new Integer(0x40000011), "Is Bleach Track"); h.put(new Integer(0x40000012), "Bleach After Scan Number"); h.put(new Integer(0x40000013), "Bleach Scan Number"); h.put(new Integer(0x40000014), "Trigger In"); h.put(new Integer(0x12000004), "Trigger In"); h.put(new Integer(0x14000003), "Trigger In"); h.put(new Integer(0x40000015), "Trigger Out"); h.put(new Integer(0x12000005), "Trigger Out"); h.put(new Integer(0x14000004), "Trigger Out"); h.put(new Integer(0x40000016), "Is Ratio Track"); h.put(new Integer(0x40000017), "Bleach Count"); h.put(new Integer(0x40000018), "SPI Center Wavelength"); h.put(new Integer(0x40000019), "Pixel Time"); h.put(new Integer(0x40000020), "ID Condensor Frontlens"); h.put(new Integer(0x40000021), "Condensor Frontlens"); h.put(new Integer(0x40000022), "ID Field Stop"); h.put(new Integer(0x40000023), "Field Stop Value"); h.put(new Integer(0x40000024), "ID Condensor Aperture"); h.put(new Integer(0x40000025), "Condensor Aperture"); h.put(new Integer(0x40000026), "ID Condensor Revolver"); h.put(new Integer(0x40000027), "Condensor Revolver"); h.put(new Integer(0x40000028), "ID Transmission Filter 1"); h.put(new Integer(0x40000029), "ID Transmission 1"); h.put(new Integer(0x40000030), "ID Transmission Filter 2"); h.put(new Integer(0x40000031), "ID Transmission 2"); h.put(new Integer(0x40000032), "Repeat Bleach"); h.put(new Integer(0x40000033), "Enable Spot Bleach Pos"); h.put(new Integer(0x40000034), "Spot Bleach Position X"); h.put(new Integer(0x40000035), "Spot Bleach Position Y"); h.put(new Integer(0x40000036), "Bleach Position Z"); h.put(new Integer(0x50000003), "Power"); h.put(new Integer(0x90000002), "Power"); h.put(new Integer(0x70000003), "Detector Gain"); h.put(new Integer(0x70000005), "Amplifier Gain"); h.put(new Integer(0x70000007), "Amplifier Offset"); h.put(new Integer(0x70000009), "Pinhole Diameter"); h.put(new Integer(0x7000000c), "Detector Name"); h.put(new Integer(0x7000000d), "Amplifier Name"); h.put(new Integer(0x7000000e), "Pinhole Name"); h.put(new Integer(0x7000000f), "Filter Set Name"); h.put(new Integer(0x70000010), "Filter Name"); h.put(new Integer(0x70000013), "Integrator Name"); h.put(new Integer(0x70000014), "Detection Channel Name"); h.put(new Integer(0x70000015), "Detector Gain B/C 1"); h.put(new Integer(0x70000016), "Detector Gain B/C 2"); h.put(new Integer(0x70000017), "Amplifier Gain B/C 1"); h.put(new Integer(0x70000018), "Amplifier Gain B/C 2"); h.put(new Integer(0x70000019), "Amplifier Offset B/C 1"); h.put(new Integer(0x70000020), "Amplifier Offset B/C 2"); h.put(new Integer(0x70000021), "Spectral Scan Channels"); h.put(new Integer(0x70000022), "SPI Wavelength Start"); h.put(new Integer(0x70000023), "SPI Wavelength End"); h.put(new Integer(0x70000026), "Dye Name"); h.put(new Integer(0xd0000014), "Dye Name"); h.put(new Integer(0x70000027), "Dye Folder"); h.put(new Integer(0xd0000015), "Dye Folder"); h.put(new Integer(0x90000003), "Wavelength"); h.put(new Integer(0x90000006), "Power B/C 1"); h.put(new Integer(0x90000007), "Power B/C 2"); h.put(new Integer(0xb0000001), "Filter Set"); h.put(new Integer(0xb0000002), "Filter"); h.put(new Integer(0xd0000004), "Color"); h.put(new Integer(0xd0000005), "Sample Type"); h.put(new Integer(0xd0000006), "Bits Per Sample"); h.put(new Integer(0xd0000007), "Ratio Type"); h.put(new Integer(0xd0000008), "Ratio Track 1"); h.put(new Integer(0xd0000009), "Ratio Track 2"); h.put(new Integer(0xd000000a), "Ratio Channel 1"); h.put(new Integer(0xd000000b), "Ratio Channel 2"); h.put(new Integer(0xd000000c), "Ratio Const. 1"); h.put(new Integer(0xd000000d), "Ratio Const. 2"); h.put(new Integer(0xd000000e), "Ratio Const. 3"); h.put(new Integer(0xd000000f), "Ratio Const. 4"); h.put(new Integer(0xd0000010), "Ratio Const. 5"); h.put(new Integer(0xd0000011), "Ratio Const. 6"); h.put(new Integer(0xd0000012), "Ratio First Images 1"); h.put(new Integer(0xd0000013), "Ratio First Images 2"); h.put(new Integer(0xd0000016), "Spectrum"); h.put(new Integer(0x12000003), "Interval"); return h; } private Integer readEntry() throws IOException { return new Integer(in.readInt()); } private Object readValue() throws IOException { int blockType = in.readInt(); int dataSize = in.readInt(); switch (blockType) { case TYPE_LONG: return new Long(in.readInt()); case TYPE_RATIONAL: return new Double(in.readDouble()); case TYPE_ASCII: String s = in.readString(dataSize).trim(); StringBuffer sb = new StringBuffer(); for (int i=0; i<s.length(); i++) { if (s.charAt(i) >= 10) sb.append(s.charAt(i)); else break; } return sb.toString(); case TYPE_SUBBLOCK: return null; } in.skipBytes(dataSize); return ""; } // -- Helper classes -- class SubBlock { public Hashtable<Integer, Object> blockData; public boolean acquire = true; public SubBlock() { try { read(); } catch (IOException e) { LOGGER.debug("Failed to read sub-block data", e); } } protected int getIntValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1; return !(o instanceof Number) ? -1 : ((Number) o).intValue(); } protected float getFloatValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1f; return !(o instanceof Number) ? -1f : ((Number) o).floatValue(); } protected double getDoubleValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1d; return !(o instanceof Number) ? -1d : ((Number) o).doubleValue(); } protected String getStringValue(int key) { Object o = blockData.get(new Integer(key)); return o == null ? null : o.toString(); } protected void read() throws IOException { blockData = new Hashtable<Integer, Object>(); Integer entry = readEntry(); Object value = readValue(); while (value != null) { if (!blockData.containsKey(entry)) blockData.put(entry, value); entry = readEntry(); value = readValue(); } } public void addToHashtable() { String prefix = this.getClass().getSimpleName() + " int index = 1; while (getSeriesMeta(prefix + index + " Acquire") != null) index++; prefix += index; Integer[] keys = blockData.keySet().toArray(new Integer[0]); for (Integer key : keys) { if (METADATA_KEYS.get(key) != null) { addSeriesMeta(prefix + " " + METADATA_KEYS.get(key), blockData.get(key)); if (METADATA_KEYS.get(key).equals("Bits Per Sample")) { core[getSeries()].bitsPerPixel = Integer.parseInt(blockData.get(key).toString()); } else if (METADATA_KEYS.get(key).equals("User")) { userName = blockData.get(key).toString(); } } } addGlobalMeta(prefix + " Acquire", new Boolean(acquire)); } } class Recording extends SubBlock { public String description; public String name; public String binning; public String startTime; // Objective data public String correction, immersion; public Integer magnification; public Double lensNA; public Boolean iris; protected void read() throws IOException { super.read(); description = getStringValue(RECORDING_DESCRIPTION); name = getStringValue(RECORDING_NAME); binning = getStringValue(RECORDING_CAMERA_BINNING); if (binning != null && binning.indexOf("x") == -1) { if (binning.equals("0")) binning = null; else binning += "x" + binning; } // start time in days since Dec 30 1899 long stamp = (long) (getDoubleValue(RECORDING_SAMPLE_0TIME) * 86400000); if (stamp > 0) { startTime = DateTools.convertDate(stamp, DateTools.MICROSOFT); } zoom = getDoubleValue(RECORDING_ZOOM); String objective = getStringValue(RECORDING_OBJECTIVE); correction = ""; if (objective == null) objective = ""; String[] tokens = objective.split(" "); int next = 0; for (; next<tokens.length; next++) { if (tokens[next].indexOf("/") != -1) break; correction += tokens[next]; } if (next < tokens.length) { String p = tokens[next++]; try { magnification = new Integer(p.substring(0, p.indexOf("/") - 1)); } catch (NumberFormatException e) { } try { lensNA = new Double(p.substring(p.indexOf("/") + 1)); } catch (NumberFormatException e) { } } immersion = next < tokens.length ? tokens[next++] : "Unknown"; iris = Boolean.FALSE; if (next < tokens.length) { iris = new Boolean(tokens[next++].trim().equalsIgnoreCase("iris")); } } } class Laser extends SubBlock { public String medium, type, model; public Double power; protected void read() throws IOException { super.read(); model = getStringValue(LASER_NAME); type = getStringValue(LASER_NAME); if (type == null) type = ""; medium = ""; if (type.startsWith("HeNe")) { medium = "HeNe"; type = "Gas"; } else if (type.startsWith("Argon")) { medium = "Ar"; type = "Gas"; } else if (type.equals("Titanium:Sapphire") || type.equals("Mai Tai")) { medium = "TiSapphire"; type = "SolidState"; } else if (type.equals("YAG")) { medium = ""; type = "SolidState"; } else if (type.equals("Ar/Kr")) { medium = ""; type = "Gas"; } acquire = getIntValue(LASER_ACQUIRE) != 0; power = getDoubleValue(LASER_POWER); } } class Track extends SubBlock { public Double timeIncrement; protected void read() throws IOException { super.read(); timeIncrement = getDoubleValue(TRACK_TIME_BETWEEN_STACKS); acquire = getIntValue(TRACK_ACQUIRE) != 0; } } class DetectionChannel extends SubBlock { public Double pinhole; public Double gain, amplificationGain; public String filter, filterSet; public String channelName; protected void read() throws IOException { super.read(); pinhole = new Double(getDoubleValue(CHANNEL_PINHOLE_DIAMETER)); gain = new Double(getDoubleValue(CHANNEL_DETECTOR_GAIN)); amplificationGain = new Double(getDoubleValue(CHANNEL_AMPLIFIER_GAIN)); filter = getStringValue(CHANNEL_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(CHANNEL_FILTER_SET); channelName = getStringValue(CHANNEL_NAME); acquire = getIntValue(CHANNEL_ACQUIRE) != 0; } } class IlluminationChannel extends SubBlock { public Integer wavelength; public Double attenuation; public String name; protected void read() throws IOException { super.read(); wavelength = new Integer(getIntValue(ILLUM_CHANNEL_WAVELENGTH)); attenuation = new Double(getDoubleValue(ILLUM_CHANNEL_ATTENUATION)); acquire = getIntValue(ILLUM_CHANNEL_ACQUIRE) != 0; name = getStringValue(ILLUM_CHANNEL_NAME); try { wavelength = new Integer(name); } catch (NumberFormatException e) { } } } class DataChannel extends SubBlock { public String name; protected void read() throws IOException { super.read(); name = getStringValue(DATA_CHANNEL_NAME); for (int i=0; i<name.length(); i++) { if (name.charAt(i) < 10) { name = name.substring(0, i); break; } } acquire = getIntValue(DATA_CHANNEL_ACQUIRE) != 0; } } class BeamSplitter extends SubBlock { public String filter, filterSet; protected void read() throws IOException { super.read(); filter = getStringValue(BEAM_SPLITTER_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(BEAM_SPLITTER_FILTER_SET); } } class Timer extends SubBlock { } class Marker extends SubBlock { } }
package jadx.core.xmlgen; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.core.codegen.CodeWriter; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.RootNode; import jadx.core.xmlgen.entry.EntryConfig; import jadx.core.xmlgen.entry.RawNamedValue; import jadx.core.xmlgen.entry.RawValue; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.core.xmlgen.entry.ValuesParser; public class ResTableParser extends CommonBinaryParser { private static final Logger LOG = LoggerFactory.getLogger(ResTableParser.class); private static final class PackageChunk { private final int id; private final String name; private final String[] typeStrings; private final String[] keyStrings; private PackageChunk(int id, String name, String[] typeStrings, String[] keyStrings) { this.id = id; this.name = name; this.typeStrings = typeStrings; this.keyStrings = keyStrings; } public int getId() { return id; } public String getName() { return name; } public String[] getTypeStrings() { return typeStrings; } public String[] getKeyStrings() { return keyStrings; } } private final RootNode root; private final ResourceStorage resStorage = new ResourceStorage(); private String[] strings; public ResTableParser(RootNode root) { this.root = root; } public void decode(InputStream inputStream) throws IOException { is = new ParserStream(inputStream); decodeTableChunk(); resStorage.finish(); } public ResContainer decodeFiles(InputStream inputStream) throws IOException { decode(inputStream); ValuesParser vp = new ValuesParser(root, strings, resStorage.getResourcesNames()); ResXmlGen resGen = new ResXmlGen(resStorage, vp); ICodeInfo content = makeXmlDump(); List<ResContainer> xmlFiles = resGen.makeResourcesXml(); return ResContainer.resourceTable("res", xmlFiles, content); } public ICodeInfo makeXmlDump() { CodeWriter writer = new CodeWriter(); writer.startLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writer.startLine("<resources>"); writer.incIndent(); Set<String> addedValues = new HashSet<>(); for (ResourceEntry ri : resStorage.getResources()) { if (addedValues.add(ri.getTypeName() + '.' + ri.getKeyName())) { String format = String.format("<public type=\"%s\" name=\"%s\" id=\"%s\" />", ri.getTypeName(), ri.getKeyName(), ri.getId()); writer.startLine(format); } } writer.decIndent(); writer.startLine("</resources>"); return writer.finish(); } public ResourceStorage getResStorage() { return resStorage; } public String[] getStrings() { return strings; } void decodeTableChunk() throws IOException { is.checkInt16(RES_TABLE_TYPE, "Not a table chunk"); is.checkInt16(0x000c, "Unexpected table header size"); /* int size = */ is.readInt32(); int pkgCount = is.readInt32(); strings = parseStringPool(); for (int i = 0; i < pkgCount; i++) { parsePackage(); } } private PackageChunk parsePackage() throws IOException { long start = is.getPos(); is.checkInt16(RES_TABLE_PACKAGE_TYPE, "Not a table chunk"); int headerSize = is.readInt16(); if (headerSize != 0x011c && headerSize != 0x0120) { die("Unexpected package header size"); } long size = is.readUInt32(); long endPos = start + size; int id = is.readInt32(); String name = is.readString16Fixed(128); long typeStringsOffset = start + is.readInt32(); /* int lastPublicType = */ is.readInt32(); long keyStringsOffset = start + is.readInt32(); /* int lastPublicKey = */ is.readInt32(); if (headerSize == 0x0120) { /* int typeIdOffset = */ is.readInt32(); } String[] typeStrings = null; if (typeStringsOffset != 0) { is.skipToPos(typeStringsOffset, "Expected typeStrings string pool"); typeStrings = parseStringPool(); } String[] keyStrings = null; if (keyStringsOffset != 0) { is.skipToPos(keyStringsOffset, "Expected keyStrings string pool"); keyStrings = parseStringPool(); deobfKeyStrings(keyStrings); } PackageChunk pkg = new PackageChunk(id, name, typeStrings, keyStrings); resStorage.setAppPackage(name); while (is.getPos() < endPos) { long chunkStart = is.getPos(); int type = is.readInt16(); if (type == RES_NULL_TYPE) { continue; } if (type == RES_TABLE_TYPE_SPEC_TYPE) { parseTypeSpecChunk(); } else if (type == RES_TABLE_TYPE_TYPE) { parseTypeChunk(chunkStart, pkg); } } return pkg; } private void deobfKeyStrings(String[] keyStrings) { int keysCount = keyStrings.length; if (root.getArgs().isRenamePrintable()) { for (int i = 0; i < keysCount; i++) { String keyString = keyStrings[i]; if (!NameMapper.isAllCharsPrintable(keyString)) { keyStrings[i] = makeNewKeyName(i); } } } if (root.getArgs().isRenameValid()) { Set<String> keySet = new HashSet<>(keysCount); for (int i = 0; i < keysCount; i++) { String keyString = keyStrings[i]; boolean isNew = keySet.add(keyString); if (!isNew) { keyStrings[i] = makeNewKeyName(i); } } } } private String makeNewKeyName(int idx) { return "JADX_DEOBF_" + idx; } @SuppressWarnings("unused") private void parseTypeSpecChunk() throws IOException { is.checkInt16(0x0010, "Unexpected type spec header size"); /* int size = */ is.readInt32(); int id = is.readInt8(); is.skip(3); int entryCount = is.readInt32(); for (int i = 0; i < entryCount; i++) { int entryFlag = is.readInt32(); } } private void parseTypeChunk(long start, PackageChunk pkg) throws IOException { /* int headerSize = */ is.readInt16(); /* int size = */ is.readInt32(); int id = is.readInt8(); is.checkInt8(0, "type chunk, res0"); is.checkInt16(0, "type chunk, res1"); int entryCount = is.readInt32(); long entriesStart = start + is.readInt32(); EntryConfig config = parseConfig(); if (config.isInvalid) { String typeName = pkg.getTypeStrings()[id - 1]; LOG.warn("Invalid config flags detected: {}{}", typeName, config.getQualifiers()); } int[] entryIndexes = new int[entryCount]; for (int i = 0; i < entryCount; i++) { entryIndexes[i] = is.readInt32(); } is.checkPos(entriesStart, "Expected entry start"); for (int i = 0; i < entryCount; i++) { if (entryIndexes[i] != NO_ENTRY) { parseEntry(pkg, id, i, config); } } } private void parseEntry(PackageChunk pkg, int typeId, int entryId, EntryConfig config) throws IOException { int size = is.readInt16(); int flags = is.readInt16(); int key = is.readInt32(); if (key == -1) { return; } int resRef = pkg.getId() << 24 | typeId << 16 | entryId; String typeName = pkg.getTypeStrings()[typeId - 1]; String keyName = pkg.getKeyStrings()[key]; if (keyName.isEmpty()) { FieldNode constField = root.getConstValues().getGlobalConstFields().get(resRef); if (constField != null) { keyName = constField.getName(); constField.add(AFlag.DONT_RENAME); } else { keyName = "RES_" + resRef; // autogenerate key name } } ResourceEntry ri = new ResourceEntry(resRef, pkg.getName(), typeName, keyName); ri.setConfig(config); if ((flags & FLAG_COMPLEX) != 0 || size == 16) { int parentRef = is.readInt32(); int count = is.readInt32(); ri.setParentRef(parentRef); List<RawNamedValue> values = new ArrayList<>(count); for (int i = 0; i < count; i++) { values.add(parseValueMap()); } ri.setNamedValues(values); } else { ri.setSimpleValue(parseValue()); } resStorage.add(ri); } private RawNamedValue parseValueMap() throws IOException { int nameRef = is.readInt32(); return new RawNamedValue(nameRef, parseValue()); } private RawValue parseValue() throws IOException { is.checkInt16(8, "value size"); is.checkInt8(0, "value res0 not 0"); int dataType = is.readInt8(); int data = is.readInt32(); return new RawValue(dataType, data); } private EntryConfig parseConfig() throws IOException { long start = is.getPos(); int size = is.readInt32(); if (size < 28) { throw new IOException("Config size < 28"); } short mcc = (short) is.readInt16(); short mnc = (short) is.readInt16(); char[] language = unpackLocaleOrRegion((byte) is.readInt8(), (byte) is.readInt8(), 'a'); char[] country = unpackLocaleOrRegion((byte) is.readInt8(), (byte) is.readInt8(), '0'); byte orientation = (byte) is.readInt8(); byte touchscreen = (byte) is.readInt8(); int density = is.readInt16(); byte keyboard = (byte) is.readInt8(); byte navigation = (byte) is.readInt8(); byte inputFlags = (byte) is.readInt8(); is.readInt8(); // inputPad0 short screenWidth = (short) is.readInt16(); short screenHeight = (short) is.readInt16(); short sdkVersion = (short) is.readInt16(); is.readInt16(); // minorVersion must always be 0 byte screenLayout = 0; byte uiMode = 0; short smallestScreenWidthDp = 0; if (size >= 32) { screenLayout = (byte) is.readInt8(); uiMode = (byte) is.readInt8(); smallestScreenWidthDp = (short) is.readInt16(); } short screenWidthDp = 0; short screenHeightDp = 0; if (size >= 36) { screenWidthDp = (short) is.readInt16(); screenHeightDp = (short) is.readInt16(); } char[] localeScript = null; char[] localeVariant = null; if (size >= 48) { localeScript = readScriptOrVariantChar(4).toCharArray(); localeVariant = readScriptOrVariantChar(8).toCharArray(); } byte screenLayout2 = 0; byte colorMode = 0; if (size >= 52) { screenLayout2 = (byte) is.readInt8(); colorMode = (byte) is.readInt8(); is.readInt16(); // reserved padding } is.skipToPos(start + size, "Config skip trailing bytes"); return new EntryConfig(mcc, mnc, language, country, orientation, touchscreen, density, keyboard, navigation, inputFlags, screenWidth, screenHeight, sdkVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp, screenHeightDp, localeScript, localeVariant, screenLayout2, colorMode, false, size); } private char[] unpackLocaleOrRegion(byte in0, byte in1, char base) { // check high bit, if so we have a packed 3 letter code if (((in0 >> 7) & 1) == 1) { int first = in1 & 0x1F; int second = ((in1 & 0xE0) >> 5) + ((in0 & 0x03) << 3); int third = (in0 & 0x7C) >> 2; // since this function handles languages & regions, we add the value(s) to the base char // which is usually 'a' or '0' depending on language or region. return new char[] { (char) (first + base), (char) (second + base), (char) (third + base) }; } return new char[] { (char) in0, (char) in1 }; } private String readScriptOrVariantChar(int length) throws IOException { long start = is.getPos(); StringBuilder sb = new StringBuilder(16); for (int i = 0; i < length; i++) { short ch = (short) is.readInt8(); if (ch == 0) { break; } sb.append((char) ch); } is.skipToPos(start + length, "readScriptOrVariantChar"); return sb.toString(); } }
package org.lwjgl.demo.stb; import org.lwjgl.glfw.*; import org.lwjgl.openal.*; import org.lwjgl.opengl.*; import org.lwjgl.stb.*; import org.lwjgl.system.*; import org.lwjgl.system.windows.*; import java.io.*; import java.nio.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static java.lang.Math.*; import static org.lwjgl.demo.util.IOUtil.*; import static org.lwjgl.glfw.Callbacks.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.glfw.GLFWNativeWin32.*; import static org.lwjgl.openal.AL10.*; import static org.lwjgl.openal.AL11.*; import static org.lwjgl.openal.ALC10.*; import static org.lwjgl.openal.EXTThreadLocalContext.*; import static org.lwjgl.openal.SOFTDirectChannels.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.stb.STBEasyFont.*; import static org.lwjgl.stb.STBVorbis.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.windows.User32.*; /** stb_vorbis demo */ public final class Vorbis implements AutoCloseable { /* Vorbis : UI state and event loop (GLFW) VorbisTrack : Vorbis decoding state (stb_vorbis) AudioRenderer : Stream decoding and audio playback (OpenAL) GraphicsRenderer : UI rendering (OpenGL) There are 3 threads: - Main/UI thread : loads the Vorbis file and runs the UI event loop (with blocking glfwWaitEvents) - Audio thread : stream decoding/playback (ticks at 30Hz) - Graphics thread : renders the current UI state (vsync) ProgressUpdater : Used to query the audio playback progress from the rendering thread (at 60fps) */ private final AtomicBoolean paused = new AtomicBoolean(); private final AtomicInteger sampleIndex = new AtomicInteger(); private final VorbisTrack track; private ProgressUpdater progressUpdater; private final long window; private final Callback windowProc; private int clientW = 640, clientH = 320; private int framebufferW, framebufferH; private float scaleX, scaleY; private double cursorX, cursorY; private boolean buttonPressed; private Vorbis(String filePath) { track = new VorbisTrack(filePath, sampleIndex); if (Platform.get() == Platform.WINDOWS) { // DPI changes work perfectly on Java 9, which is PER_MONITOR_AWARE. // Java 8 is only SYSTEM_AWARE. The call below will work and // dpi-aware functions will return the correct values for each // monitor, but the OpenGL framebuffer will be scaled automatically // by the system on monitors that do not match the system DPI. This // causes rendering problems. // Workaround: Build a custom executable and launch the JVM using JNI // after calling SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE) if (User32.Functions.SetThreadDpiAwarenessContext != NULL) { SetThreadDpiAwarenessContext(IsValidDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 : DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); } } GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); } glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); long monitor = glfwGetPrimaryMonitor(); if (Platform.get() == Platform.MACOSX) { glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE); framebufferW = clientW; framebufferH = clientH; scaleX = 1.0f; scaleY = 1.0f; } else { // Emulating GLFW_COCOA_RETINA_FRAMEBUFFER == GLFW_FALSE: // * Client coordinates are the same, regardless of window dpi. // * Normally we'd render to an FBO and upscale to the window framebuffer. We simply use a scaled glOrtho in this demo. try (MemoryStack s = stackPush()) { FloatBuffer px = s.mallocFloat(1); FloatBuffer py = s.mallocFloat(1); glfwGetMonitorContentScale(monitor, px, py); scaleX = px.get(0); scaleY = py.get(0); framebufferW = round(clientW * scaleX); framebufferH = round(clientH * scaleY); } } window = glfwCreateWindow(framebufferW, framebufferH, "stb_vorbis demo", NULL, NULL); if (window == NULL) { throw new RuntimeException("Failed to create the GLFW window"); } // Center window GLFWVidMode vidmode = glfwGetVideoMode(monitor); glfwSetWindowPos( window, (vidmode.width() - framebufferW) / 2, (vidmode.height() - framebufferH) / 2 ); // TODO: Remove if GLFW#1115 is merged if (Platform.get() == Platform.WINDOWS) { long hwnd = glfwGetWin32Window(window); long glfwProc = GetWindowLongPtr(hwnd, GWL_WNDPROC); windowProc = new WindowProc() { @Override public long invoke(long hwnd, int uMsg, long wParam, long lParam) { switch (uMsg) { case 0x02E0: // WM_DPICHANGED RECT rect = RECT.create(lParam); SetWindowPos(hwnd, NULL, rect.left(), rect.top(), rect.right() - rect.left(), rect.bottom() - rect.top(), SWP_NOZORDER | SWP_NOACTIVATE ); return 0; } return nCallWindowProc(glfwProc, hwnd, uMsg, wParam, lParam); } }; SetWindowLongPtr(hwnd, GWL_WNDPROC, windowProc.address()); } else { windowProc = null; } glfwSetFramebufferSizeCallback(window, (window, width, height) -> { this.framebufferW = width; this.framebufferH = height; try (MemoryStack s = stackPush()) { FloatBuffer px = s.mallocFloat(1); FloatBuffer py = s.mallocFloat(1); glfwGetWindowContentScale(window, px, py); if (scaleX != px.get(0) || scaleY != py.get(0)) { scaleX = px.get(0); scaleY = py.get(0); System.out.println("New content scale: " + scaleX + " x " + scaleY); } } this.clientW = round(width / scaleX); this.clientH = round(height / scaleY); }); glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { if (action == GLFW_RELEASE) { return; } switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); break; case GLFW_KEY_HOME: track.rewind(); break; case GLFW_KEY_LEFT: track.skip(-1); break; case GLFW_KEY_RIGHT: track.skip(1); break; case GLFW_KEY_SPACE: paused.set(!paused.get()); break; } }); glfwSetMouseButtonCallback(window, (window, button, action, mods) -> { if (button != GLFW_MOUSE_BUTTON_LEFT) { return; } buttonPressed = action == GLFW_PRESS; if (!buttonPressed) { return; } seek(track, cursorX, cursorY); }); glfwSetCursorPosCallback(window, (window, xpos, ypos) -> { cursorX = (xpos / scaleX - clientW * 0.5); cursorY = (ypos / scaleY - clientH * 0.5); if (buttonPressed) { seek(track, cursorX, cursorY); } }); } @Override public void close() { glfwFreeCallbacks(window); glfwDestroyWindow(window); if (windowProc != null) { windowProc.free(); } glfwTerminate(); glfwSetErrorCallback(null).free(); } public static void main(String[] args) { String filePath; if (args.length == 0) { System.out.println("Use 'ant demo -Dclass=org.lwjgl.demo.stb.Vorbis -Dargs=<path>' to load a different Ogg Vorbis file.\n"); filePath = "demo/phero.ogg"; } else { filePath = args[0]; } try (Vorbis vorbis = new Vorbis(filePath)) { vorbis.runEventLoop(); } } private void runEventLoop() { AtomicBoolean hasError = new AtomicBoolean(); CountDownLatch audioLatch = new CountDownLatch(1); Thread audioThread = new Thread(() -> { try (AudioRenderer audioRenderer = new AudioRenderer(track)) { progressUpdater = audioRenderer.getProgressUpdater(); if (!audioRenderer.play()) { System.err.println("Playback failed."); glfwSetWindowShouldClose(window, true); } audioLatch.countDown(); while (!glfwWindowShouldClose(window)) { if (!paused.get()) { if (!audioRenderer.update(true)) { System.err.println("Playback failed."); glfwSetWindowShouldClose(window, true); } } sleep(1000 / 30); } } catch (Throwable t) { t.printStackTrace(); hasError.set(true); audioLatch.countDown(); } }); audioThread.start(); CountDownLatch graphicsLatch = new CountDownLatch(1); Thread graphicsThread = new Thread(new Runnable() { int sampleIndexLast = -1; @Override public void run() { glfwMakeContextCurrent(window); try (GraphicsRenderer graphicsRenderer = new GraphicsRenderer()) { try { audioLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } glfwSetWindowRefreshCallback(window, window -> { if (clientW != 0 && clientH != 0) { // This is called on the UI thread, but rendering happens asynchronously in // the rendering thread. The UI thread blocks here, until the next v-sync // has completed. This effectively eliminates all rendering artifacts when // the window is resized. graphicsRenderer.awaitVSync(); } }); graphicsLatch.countDown(); progressUpdater.makeCurrent(true); while (!glfwWindowShouldClose(window)) { progressUpdater.updateProgress(); int sampleIndexCurr = sampleIndex.get(); if (sampleIndexCurr == sampleIndexLast || clientW == 0 || clientH == 0) { sleep(1000 / 60); continue; } sampleIndexLast = sampleIndexCurr; float progress = sampleIndex.get() / (float)(track.samplesLength); graphicsRenderer.render( framebufferW, framebufferH, clientW, clientH, progress, progress * track.samplesSec ); glfwSwapBuffers(window); graphicsRenderer.signalVSync(); } progressUpdater.makeCurrent(false); } catch (Throwable t) { t.printStackTrace(); hasError.set(true); graphicsLatch.countDown(); } } }); graphicsThread.start(); try { graphicsLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } glfwShowWindow(window); while (!glfwWindowShouldClose(window) && !hasError.get()) { glfwWaitEvents(); } try { graphicsThread.join(); audioThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } private static void seek(VorbisTrack track, double cursorX, double cursorY) { if (cursorX < -254.0 || 254.0 < cursorX) { return; } if (cursorY < -30.0 || 30.0 < cursorY) { return; } track.skipTo((float)((cursorX + 254.0) / 508.0)); } private static class VorbisTrack implements AutoCloseable { private final ByteBuffer encodedAudio; private final long handle; private final int channels; private final int sampleRate; final int samplesLength; final float samplesSec; private final AtomicInteger sampleIndex; VorbisTrack(String filePath, AtomicInteger sampleIndex) { try { encodedAudio = ioResourceToByteBuffer(filePath, 256 * 1024); } catch (IOException e) { throw new RuntimeException(e); } try (MemoryStack stack = stackPush()) { IntBuffer error = stack.mallocInt(1); handle = stb_vorbis_open_memory(encodedAudio, error, null); if (handle == NULL) { throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + error.get(0)); } STBVorbisInfo info = STBVorbisInfo.mallocStack(stack); print(info); this.channels = info.channels(); this.sampleRate = info.sample_rate(); } this.samplesLength = stb_vorbis_stream_length_in_samples(handle); this.samplesSec = stb_vorbis_stream_length_in_seconds(handle); this.sampleIndex = sampleIndex; sampleIndex.set(0); } @Override public void close() { stb_vorbis_close(handle); } void progressBy(int samples) { sampleIndex.set(sampleIndex.get() + samples); } void setSampleIndex(int sampleIndex) { this.sampleIndex.set(sampleIndex); } void rewind() { seek(0); } void skip(int direction) { seek(min(max(0, stb_vorbis_get_sample_offset(handle) + direction * sampleRate), samplesLength)); } void skipTo(float offset0to1) { seek(round(samplesLength * offset0to1)); } // called from audio thread synchronized int getSamples(ShortBuffer pcm) { return stb_vorbis_get_samples_short_interleaved(handle, channels, pcm); } // called from UI thread private synchronized void seek(int sampleIndex) { stb_vorbis_seek(handle, sampleIndex); setSampleIndex(sampleIndex); } private void print(STBVorbisInfo info) { System.out.println("stream length, samples: " + stb_vorbis_stream_length_in_samples(handle)); System.out.println("stream length, seconds: " + stb_vorbis_stream_length_in_seconds(handle)); System.out.println(); stb_vorbis_get_info(handle, info); System.out.println("channels = " + info.channels()); System.out.println("sampleRate = " + info.sample_rate()); System.out.println("maxFrameSize = " + info.max_frame_size()); System.out.println("setupMemoryRequired = " + info.setup_memory_required()); System.out.println("setupTempMemoryRequired() = " + info.setup_temp_memory_required()); System.out.println("tempMemoryRequired = " + info.temp_memory_required()); } } interface ProgressUpdater { void makeCurrent(boolean current); void updateProgress(); } private static class AudioRenderer implements AutoCloseable { private static final int BUFFER_SIZE = 1024 * 8; private final VorbisTrack track; private final int format; private final long device; private final long context; private final int source; private final IntBuffer buffers; private final ShortBuffer pcm; long bufferOffset; // offset of last processed buffer long offset; // bufferOffset + offset of current buffer long lastOffset; // last offset update AudioRenderer(VorbisTrack track) { this.track = track; switch (track.channels) { case 1: this.format = AL_FORMAT_MONO16; break; case 2: this.format = AL_FORMAT_STEREO16; break; default: throw new UnsupportedOperationException("Unsupported number of channels: " + track.channels); } device = alcOpenDevice((ByteBuffer)null); if (device == NULL) { throw new IllegalStateException("Failed to open the default device."); } context = alcCreateContext(device, (IntBuffer)null); if (context == NULL) { throw new IllegalStateException("Failed to create an OpenAL context."); } this.pcm = memAllocShort(BUFFER_SIZE); alcSetThreadContext(context); ALCCapabilities deviceCaps = ALC.createCapabilities(device); AL.createCapabilities(deviceCaps); source = alGenSources(); alSourcei(source, AL_DIRECT_CHANNELS_SOFT, AL_TRUE); buffers = memAllocInt(2); alGenBuffers(buffers); } @Override public void close() { alDeleteBuffers(buffers); alDeleteSources(source); memFree(buffers); memFree(pcm); alcSetThreadContext(NULL); alcDestroyContext(context); alcCloseDevice(device); } private int stream(int buffer) { int samples = 0; while (samples < BUFFER_SIZE) { pcm.position(samples); int samplesPerChannel = track.getSamples(pcm); if (samplesPerChannel == 0) { break; } samples += samplesPerChannel * track.channels; } if (samples != 0) { pcm.position(0); pcm.limit(samples); alBufferData(buffer, format, pcm, track.sampleRate); pcm.limit(BUFFER_SIZE); } return samples; } boolean play() { for (int i = 0; i < buffers.limit(); i++) { if (stream(buffers.get(i)) == 0) { return false; } } alSourceQueueBuffers(source, buffers); alSourcePlay(source); return true; } boolean update(boolean loop) { int processed = alGetSourcei(source, AL_BUFFERS_PROCESSED); for (int i = 0; i < processed; i++) { bufferOffset += BUFFER_SIZE / track.channels; int buffer = alSourceUnqueueBuffers(source); if (stream(buffer) == 0) { boolean shouldExit = true; if (loop) { track.rewind(); lastOffset = offset = bufferOffset = 0; shouldExit = stream(buffer) == 0; } if (shouldExit) { return false; } } alSourceQueueBuffers(source, buffer); } if (processed == 2) { alSourcePlay(source); } return true; } public ProgressUpdater getProgressUpdater() { return new ProgressUpdater() { @Override public void makeCurrent(boolean current) { alcSetThreadContext(current ? context : NULL); } @Override public void updateProgress() { offset = bufferOffset + alGetSourcei(source, AL_SAMPLE_OFFSET); track.progressBy((int)(offset - lastOffset)); lastOffset = offset; } }; } } private static class GraphicsRenderer implements AutoCloseable { private final Callback debugProc; private final ByteBuffer charBuffer; private final Phaser waitForVSync; GraphicsRenderer() { // Create context GL.createCapabilities(); debugProc = GLUtil.setupDebugMessageCallback(); glfwSwapInterval(1); charBuffer = memAlloc(256 * 270); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 16, charBuffer); glClearColor(43f / 255f, 43f / 255f, 43f / 255f, 0f); // BG color waitForVSync = new Phaser() { @Override protected boolean onAdvance(int phase, int registeredParties) { return false; // never terminate } }; } @Override public void close() { memFree(charBuffer); if (debugProc != null) { debugProc.free(); } } void render( int framebufferW, int framebufferH, int clientW, int clientH, float progress, float progressTime ) { glViewport(0, 0, framebufferW, framebufferH); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, clientW, clientH, 0.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); // Progress bar glPushMatrix(); glTranslatef(clientW * 0.5f, clientH * 0.5f, 0.0f); glBegin(GL_QUADS); { glColor3f(0.5f * 43f / 255f, 0.5f * 43f / 255f, 0.5f * 43f / 255f); glVertex2f(-256.0f, -32.0f); glVertex2f(256.0f, -32.0f); glVertex2f(256.0f, 32.0f); glVertex2f(-256.0f, 32.0f); glColor3f(0.5f, 0.5f, 0.0f); glVertex2f(-254.0f, -30.0f); glVertex2f(-254.0f + progress * 508.0f, -30.0f); glVertex2f(-254.0f + progress * 508.0f, 30.0f); glVertex2f(-254.0f, 30.0f); } glEnd(); glPopMatrix(); glColor3f(169f / 255f, 183f / 255f, 198f / 255f); // Text color // Progress text int minutes = (int)floor(progressTime / 60.0); int seconds = (int)floor(progressTime - minutes * 60.0); int millis = (int)floor((progressTime - minutes * 60.0 - seconds) * 100.0); int quads = stb_easy_font_print(clientW * 0.5f - 21, clientH * 0.5f - 4, String.format("%02d:%02d.%02d", minutes, seconds, millis), null, charBuffer); glDrawArrays(GL_QUADS, 0, quads * 4); // HUD quads = stb_easy_font_print(4, 4, "Press HOME to rewind", null, charBuffer); glDrawArrays(GL_QUADS, 0, quads * 4); quads = stb_easy_font_print(4, 20, "Press LEFT/RIGHT or LMB to seek", null, charBuffer); glDrawArrays(GL_QUADS, 0, quads * 4); quads = stb_easy_font_print(4, 36, "Press SPACE to pause/resume", null, charBuffer); glDrawArrays(GL_QUADS, 0, quads * 4); } // Called from the UI thread void awaitVSync() { // 2. wait for the rendering thread to signal that the v-sync is complete waitForVSync.awaitAdvance( // 1. signal the rendering thread to wait for v-sync waitForVSync.register() ); } // Called from the rendering thread void signalVSync() { if (waitForVSync.getRegisteredParties() != 0) { // wait for the v-sync to finish glFinish(); waitForVSync.arriveAndDeregister(); } } } }
package com.example.dylan.taxtimewithfriends; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class manualAddTrip extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manual_add_trip); } public void mainMenuActivity (View v){ startActivity(new Intent(manualAddTrip.this, MainActivity.class)); } public void clickFunction(View view){ EditText manOdoStart = (EditText)findViewById(getResources(R.id.manualOdoStart)); EditText manOdoEnd = (EditText)findViewById(getResources(R.id.manualOdoEnd)); EditText manDate = (EditText)findViewById(getResources(R.id.manualDatgetResources(e)); EditText manReason = (EditText)findViewById(getResources(R.id.manualReason)); Log.i("Manual Trip added", manOdoStart.getText().toString(), manOdoEnd.getText().toString(), manDate.getText().toString(), manReason.getText().toString()); } }
package com.pubnub.examples; import com.pubnub.api.*; import org.json.JSONArray; import org.json.JSONObject; import java.util.Hashtable; import java.util.Scanner; import static java.lang.System.out; public class PubnubDemoConsole { Pubnub pubnub; String publish_key = "demo"; String subscribe_key = "demo"; String secret_key = ""; String cipher_key = ""; boolean SSL; Scanner reader; public PubnubDemoConsole(String publish_key, String subscribe_key, String secret_key, String cipher_key) { this.publish_key = publish_key; this.subscribe_key = subscribe_key; this.secret_key = secret_key; this.cipher_key = cipher_key; } public PubnubDemoConsole() { } private void notifyUser(Object message) { out.println(message.toString()); } private void publish(String channel) { notifyUser("Enter the message for publish. To exit loop enter QUIT"); String message = ""; Callback cb = new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("PUBLISH : " + message); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("PUBLISH : " + error); } }; while (true) { Hashtable args = new Hashtable(2); message = reader.nextLine(); if (message.equalsIgnoreCase("QUIT")) { break; } try { Integer i = Integer.parseInt(message); pubnub.publish(channel, i, cb); continue; } catch (Exception e) { } try { Double d = Double.parseDouble(message); pubnub.publish(channel, d, cb); continue; } catch (Exception e) { } try { JSONArray js = new JSONArray(message); pubnub.publish(channel, js, cb); continue; } catch (Exception e) { } try { JSONObject js = new JSONObject(message); pubnub.publish(channel, js, cb); continue; } catch (Exception e) { } pubnub.publish(channel, message, cb); } } private void subscribe(final String channel) { Hashtable args = new Hashtable(6); args.put("channel", channel); try { pubnub.subscribe(args, new Callback() { @Override public void connectCallback(String channel, Object message) { notifyUser("SUBSCRIBE : CONNECT on channel:" + channel + " : " + message.getClass() + " : " + message.toString()); } @Override public void disconnectCallback(String channel, Object message) { notifyUser("SUBSCRIBE : DISCONNECT on channel:" + channel + " : " + message.getClass() + " : " + message.toString()); } public void reconnectCallback(String channel, Object message) { notifyUser("SUBSCRIBE : RECONNECT on channel:" + channel + " : " + message.getClass() + " : " + message.toString()); } @Override public void successCallback(String channel, Object message) { notifyUser("SUBSCRIBE : " + channel + " : " + message.getClass() + " : " + message.toString()); } @Override public void errorCallback(String channel, PubnubError error) { /* # Switch on error code, see PubnubError.java if (error.errorCode == 112) { # Bad Auth Key! unsubscribe, get a new auth key, subscribe, etc... } else if (error.errorCode == 113) { # Need to set Auth Key ! unsubscribe, set auth, resubscribe } */ notifyUser("SUBSCRIBE : ERROR on channel " + channel + " : " + error.toString()); } }); } catch (Exception e) { } } private void presence(String channel) { try { pubnub.presence(channel, new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("PRESENCE : " + message); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("PRESENCE : " + error); } }); } catch (PubnubException e) { } } private void detailedHistory(String channel) { pubnub.detailedHistory(channel, 2, new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("DETAILED HISTORY : " + message); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("DETAILED HISTORY : " + error); } }); } private void hereNow(String channel) { pubnub.hereNow(channel, new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("HERE NOW : " + message); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("HERE NOW : " + error); } }); } private void unsubscribe(String channel) { pubnub.unsubscribe(channel); } private void unsubscribePresence(String channel) { pubnub.unsubscribePresence(channel); } private void time() { pubnub.time(new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("TIME : " + message); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("TIME : " + error); } }); } private void disconnectAndResubscribe() { pubnub.disconnectAndResubscribe(); } private void disconnectAndResubscribeWithTimetoken(String timetoken) { pubnub.disconnectAndResubscribeWithTimetoken(timetoken); } public void startDemo() { reader = new Scanner(System.in); notifyUser("HINT:\tTo test Re-connect and catch-up"); notifyUser("\tDisconnect your machine from network/internet and"); notifyUser("\tre-connect your machine after sometime"); this.SSL = getBooleanFromConsole("SSL"); if (this.publish_key.length() == 0) this.publish_key = getStringFromConsole("Publish Key"); if (this.subscribe_key.length() == 0) this.subscribe_key = getStringFromConsole("Subscribe Key"); if (this.secret_key.length() == 0) this.secret_key = getStringFromConsole("Secret Key", true); if (this.cipher_key.length() == 0) this.cipher_key = getStringFromConsole("Cipher Key", true); pubnub = new Pubnub(this.publish_key, this.subscribe_key, this.secret_key, this.cipher_key, this.SSL); displayMenuOptions(); String channelName = null; int command = 0; while ((command = reader.nextInt()) != 9) { reader.nextLine(); switch (command) { case 0: displayMenuOptions(); break; case 1: channelName = getStringFromConsole("Subscribe: Enter Channel name"); subscribe(channelName); notifyUser("Subscribed to following channels: "); notifyUser(PubnubUtil.joinString( pubnub.getSubscribedChannelsArray(), " : ")); break; case 2: channelName = getStringFromConsole("Channel Name"); publish(channelName); break; case 3: channelName = getStringFromConsole("Channel Name"); presence(channelName); break; case 4: channelName = getStringFromConsole("Channel Name"); detailedHistory(channelName); break; case 5: channelName = getStringFromConsole("Channel Name"); hereNow(channelName); break; case 6: channelName = getStringFromConsole("Channel Name"); unsubscribe(channelName); break; case 7: channelName = getStringFromConsole("Channel Name"); unsubscribePresence(channelName); break; case 8: time(); break; case 10: disconnectAndResubscribe(); break; case 11: notifyUser("Disconnect and Resubscribe with timetoken : Enter timetoken"); String timetoken = getStringFromConsole("Timetoken"); disconnectAndResubscribeWithTimetoken(timetoken); break; case 12: pubnub.setResumeOnReconnect(pubnub.isResumeOnReconnect() ? false : true); notifyUser("RESUME ON RECONNECT : " + pubnub.isResumeOnReconnect()); break; case 13: int maxRetries = getIntFromConsole("Max Retries"); setMaxRetries(maxRetries); break; case 14: int retryInterval = getIntFromConsole("Retry Interval"); setRetryInterval(retryInterval); break; case 15: int subscribeTimeout = getIntFromConsole("Subscribe Timeout ( in milliseconds) "); setSubscribeTimeout(subscribeTimeout); break; case 16: int nonSubscribeTimeout = getIntFromConsole("Non Subscribe Timeout ( in milliseconds) "); setNonSubscribeTimeout(nonSubscribeTimeout); break; case 17: notifyUser("Set/Unset Auth Key: Enter blank for unsetting key"); String authKey = getStringFromConsole("Auth Key"); pubnub.setAuthKey(authKey); break; case 18: pamGrant(); break; case 19: pamRevoke(); break; case 20: pamAudit(); break; case 21: pubnub.setOrigin(getStringFromConsole("Origin")); break; case 22: pubnub.setDomain(getStringFromConsole("Domain")); break; case 23: pubnub.setCacheBusting(true); break; case 24: pubnub.setCacheBusting(false); break; default: notifyUser("Invalid Input"); } displayMenuOptions(); } notifyUser("Exiting"); pubnub.shutdown(); } private String getStringFromConsole(String message, boolean optional) { int attempt_count = 0; String input = null; do { if (attempt_count > 0) System.out.print("Invalid input. "); String message1 = "Enter " + message ; message1 = (optional)?message1+" ( Optional input. You can skip by pressing enter )":message1; notifyUser(message1); input = reader.nextLine(); attempt_count++; } while ((input == null || input.length() == 0) && !optional); notifyUser(message + " : " + input); return input; } private String getStringFromConsole(String message) { return getStringFromConsole(message, false); } private int getIntFromConsole(String message, boolean optional) { int attempt_count = 0; String input = null; int returnVal = -1; do { if (attempt_count > 0) notifyUser("Invalid input. "); String message1 = "Enter " + message; message1 = (optional)?message1+" ( Optional input. You can skip by pressing enter ) ":message1; notifyUser(message1); input = reader.nextLine(); attempt_count++; returnVal = Integer.parseInt(input); } while ((input == null || input.length() == 0 || returnVal == -1) && !optional); notifyUser(message + " : " + returnVal); return returnVal; } private int getIntFromConsole(String message) { return getIntFromConsole(message, false); } private boolean getBooleanFromConsole(String message, boolean optional) { int attempt_count = 0; String input = null; boolean returnVal = false; do { if (attempt_count > 0) notifyUser("Invalid input. "); String message1 = message + " ? ( Enter Yes/No or Y/N )"; message1 = (optional)?message1+" ( Optional input. You can skip by pressing enter ) ":message1; notifyUser(message1); input = reader.nextLine(); attempt_count++; } while ((input == null || input.length() == 0 || ( !input.equalsIgnoreCase("yes") && !input.equalsIgnoreCase("no") && !input.equalsIgnoreCase("y") && !input.equalsIgnoreCase("n"))) && !optional); returnVal = (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes"))?true:false; notifyUser(message + " : " + returnVal); return returnVal; } private boolean getBooleanFromConsole(String message) { return getBooleanFromConsole(message, false); } private void pamGrant() { String channel = getStringFromConsole("Channel"); String auth_key = getStringFromConsole("Auth Key"); boolean read = getBooleanFromConsole("Read"); boolean write = getBooleanFromConsole("Write"); int ttl = getIntFromConsole("TTL"); pubnub.pamGrant(channel, auth_key, read, write, ttl, new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("CHANNEL : " + channel + " , " + message.toString()); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("CHANNEL : " + channel + " , " + error.toString()); } }); } private void pamAudit() { String channel = getStringFromConsole("Channel", true); String auth_key = getStringFromConsole("Auth Key", true); Callback cb = new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("CHANNEL : " + channel + " , " + message.toString()); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("CHANNEL : " + channel + " , " + error.toString()); } }; if (channel != null && channel.length() > 0) { if (auth_key != null && auth_key.length() != 0) { pubnub.pamAudit(channel, auth_key, cb); } else { pubnub.pamAudit(channel, cb); } } else { pubnub.pamAudit(cb); } } private void pamRevoke() { String channel = getStringFromConsole("Enter Channel"); String auth_key = getStringFromConsole("Auth Key"); pubnub.pamRevoke(channel, auth_key, new Callback() { @Override public void successCallback(String channel, Object message) { notifyUser("CHANNEL : " + channel + " , " + message.toString()); } @Override public void errorCallback(String channel, PubnubError error) { notifyUser("CHANNEL : " + channel + " , " + error.toString()); } }); } private void setMaxRetries(int maxRetries) { pubnub.setMaxRetries(maxRetries); } private void setRetryInterval(int retryInterval) { pubnub.setRetryInterval(retryInterval); } private void setSubscribeTimeout(int subscribeTimeout) { pubnub.setSubscribeTimeout(subscribeTimeout); } private void setNonSubscribeTimeout(int nonSubscribeTimeout) { pubnub.setNonSubscribeTimeout(nonSubscribeTimeout); } private void displayMenuOptions() { notifyUser("ENTER 1 FOR Subscribe " + "(Currently subscribed to " + this.pubnub.getCurrentlySubscribedChannelNames() + ")"); notifyUser("ENTER 2 FOR Publish"); notifyUser("ENTER 3 FOR Presence"); notifyUser("ENTER 4 FOR Detailed History"); notifyUser("ENTER 5 FOR Here_Now"); notifyUser("ENTER 6 FOR Unsubscribe"); notifyUser("ENTER 7 FOR Presence-Unsubscribe"); notifyUser("ENTER 8 FOR Time"); notifyUser("ENTER 9 FOR EXIT OR QUIT"); notifyUser("ENTER 10 FOR Disconnect-And-Resubscribe"); notifyUser("ENTER 11 FOR Disconnect-And-Resubscribe with timetoken"); notifyUser("ENTER 12 FOR Toggle Resume On Reconnect ( current: " + pubnub.getResumeOnReconnect() + " )"); notifyUser("ENTER 13 FOR Setting MAX Retries ( current: " + pubnub.getMaxRetries() + " )"); notifyUser("ENTER 14 FOR Setting Retry Interval ( current: " + pubnub.getRetryInterval() + " milliseconds )"); notifyUser("ENTER 15 FOR Setting Subscribe Timeout ( current: " + pubnub.getSubscribeTimeout() + " milliseconds )"); notifyUser("ENTER 16 FOR Setting Non Subscribe Timeout ( current: " + pubnub.getNonSubscribeTimeout() + " milliseconds )"); notifyUser("ENTER 17 FOR Setting/Unsetting auth key ( current: " + pubnub.getAuthKey() + " )"); notifyUser("ENTER 18 FOR PAM grant"); notifyUser("ENTER 19 FOR PAM revoke"); notifyUser("ENTER 20 FOR PAM Audit"); notifyUser("ENTER 21 FOR Setting Origin ( current: " + pubnub.getOrigin() + " )"); notifyUser("ENTER 22 FOR Setting Domain ( current: "+ pubnub.getDomain() + " )"); notifyUser("ENTER 23 FOR Enabling Cache Busting ( current: " + pubnub.getCacheBusting() + " )"); notifyUser("ENTER 24 FOR Disabling Cache Busting ( current: " + pubnub.getCacheBusting() + " )"); notifyUser("\nENTER 0 to display this menu"); } /** * @param args */ public static void main(String[] args) { PubnubDemoConsole pdc; if (args.length == 4) { pdc = new PubnubDemoConsole(args[0], args[1], args[2], args[3]); } else pdc = new PubnubDemoConsole(); pdc.startDemo(); } }
package controllers; import com.avaje.ebean.Junction; import com.avaje.ebean.Page; import com.avaje.ebean.ExpressionList; import models.*; import models.enumeration.*; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoHeadException; import org.tmatesoft.svn.core.SVNException; import play.data.Form; import play.db.ebean.Transactional; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; import playRepository.Commit; import playRepository.PlayRepository; import playRepository.RepositoryService; import scala.reflect.io.FileOperationException; import utils.AccessControl; import utils.Constants; import utils.HttpUtil; import utils.ErrorViews; import utils.LabelSearchUtil; import views.html.project.*; import javax.servlet.ServletException; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.*; import static play.data.Form.form; import static play.libs.Json.toJson; /** * ProjectApp * */ public class ProjectApp extends Controller { private static final int LOGO_FILE_LIMIT_SIZE = 1024*1000*5; public static final String[] LOGO_TYPE = {"jpg", "jpeg", "png", "gif", "bmp"}; private static final int MAX_FETCH_PROJECTS = 1000; private static final int COMMIT_HISTORY_PAGE = 0; private static final int COMMIT_HISTORY_SHOW_LIMIT = 10; private static final int RECENLTY_ISSUE_SHOW_LIMIT = 10; private static final int RECENLTY_POSTING_SHOW_LIMIT = 10; private static final int RECENT_PULL_REQUEST_SHOW_LIMIT = 10; private static final int PROJECT_COUNT_PER_PAGE = 10; private static final String HTML = "text/html"; private static final String JSON = "application/json"; /** * getProject * @param userName * @param projectName * @return */ public static Project getProject(String userName, String projectName) { return Project.findByOwnerAndProjectName(userName, projectName); } /** * Overview .<p /> * * {@code loginId} {@code projectName} .<br /> * unauthorized .<br /> * , , .<br /> * * @param loginId * @param projectName * @return , * @throws IOException Signals that an I/O exception has occurred. * @throws ServletException the servlet exception * @throws SVNException the svn exception * @throws GitAPIException the git api exception */ public static Result project(String loginId, String projectName) throws IOException, ServletException, SVNException, GitAPIException { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); // No project matches given parameters'" + loginId + "' and project_name '" + projectName + "'")); } project.fixInvalidForkData(); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } PlayRepository repository = RepositoryService.getRepository(project); List<Commit> commits = null; try { commits = repository.getHistory(COMMIT_HISTORY_PAGE, COMMIT_HISTORY_SHOW_LIMIT, null, null); } catch (NoHeadException e) { // NOOP } List<Issue> issues = Issue.findRecentlyCreated(project, RECENLTY_ISSUE_SHOW_LIMIT); List<Posting> postings = Posting.findRecentlyCreated(project, RECENLTY_POSTING_SHOW_LIMIT); List<PullRequest> pullRequests = PullRequest.findRecentlyReceived(project, RECENT_PULL_REQUEST_SHOW_LIMIT); List<History> histories = History.makeHistory(loginId, project, commits, issues, postings, pullRequests); return ok(overview.render("title.projectHome", project, histories)); } /** * .<p /> * * ({@link models.User#anonymous}) redirect .<br /> * .<br /> * * @return , */ public static Result newProjectForm() { if (UserApp.currentUser().isAnonymous()) { flash(Constants.WARNING, "user.login.alert"); return redirect(routes.UserApp.loginForm()); } else { return ok(create.render("title.newProject", form(Project.class))); } } /** * () .<p /> * * {@code loginId} {@code projectName} .<br /> * unauthorized .<br /> * * @param loginId * @param projectName * @return */ public static Result settingForm(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } Form<Project> projectForm = form(Project.class).fill(project); return ok(setting.render("menu.admin", projectForm, project)); } /** * (Role / ) Overview redirect .<p /> * * {@code loginId} {@code projectName} <br /> * badRequest .<br /> * badRequest .<br /> * * @return , , * @throws Exception */ @Transactional public static Result newProject() throws Exception { if( !AccessControl.isCreatable(UserApp.currentUser(), ResourceType.PROJECT) ){ return forbidden(ErrorViews.Forbidden.render("'" + UserApp.currentUser().name + "' has no permission")); } Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest(); if (Project.exists(UserApp.currentUser().loginId, filledNewProjectForm.field("name").value())) { flash(Constants.WARNING, "project.name.duplicate"); filledNewProjectForm.reject("name"); return badRequest(create.render("title.newProject", filledNewProjectForm)); } else if (filledNewProjectForm.hasErrors()) { filledNewProjectForm.reject("name"); flash(Constants.WARNING, "project.name.alert"); return badRequest(create.render("title.newProject", filledNewProjectForm)); } else { Project project = filledNewProjectForm.get(); project.owner = UserApp.currentUser().loginId; ProjectUser.assignRole(UserApp.currentUser().id, Project.create(project), RoleType.MANAGER); RepositoryService.createRepository(project); return redirect(routes.ProjectApp.project(project.owner, project.name)); } } /** * .<p /> * * redirect.<br /> * {@code loginId} badRequest .<br /> * ({@code filePart}) (1MB) badRequest .<br /> * ({@code filePart}) (1MB) () .<br /> * * @param loginId user login id * @param projectName the project name * @return * @throws IOException Signals that an I/O exception has occurred. * @throws NoSuchAlgorithmException the no such algorithm exception * @throws ServletException * @throws UnsupportedOperationException */ @Transactional public static Result settingProject(String loginId, String projectName) throws IOException, NoSuchAlgorithmException, UnsupportedOperationException, ServletException { Form<Project> filledUpdatedProjectForm = form(Project.class).bindFromRequest(); Project updatedProject = filledUpdatedProjectForm.get(); if (!AccessControl.isAllowed(UserApp.currentUser(), updatedProject.asResource(), Operation.UPDATE)) { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.settingForm(loginId, updatedProject.name)); } if (!Project.projectNameChangeable(updatedProject.id, loginId, updatedProject.name)) { flash(Constants.WARNING, "project.name.duplicate"); filledUpdatedProjectForm.reject("name"); } MultipartFormData body = request().body().asMultipartFormData(); FilePart filePart = body.getFile("logoPath"); if (!isEmptyFilePart(filePart)) { if(!isImageFile(filePart.getFilename())) { flash(Constants.WARNING, "project.logo.alert"); filledUpdatedProjectForm.reject("logoPath"); } else if (filePart.getFile().length() > LOGO_FILE_LIMIT_SIZE) { flash(Constants.WARNING, "project.logo.fileSizeAlert"); filledUpdatedProjectForm.reject("logoPath"); } else { Attachment.deleteAll(updatedProject.asResource()); new Attachment().store(filePart.getFile(), filePart.getFilename(), updatedProject.asResource()); } } if (filledUpdatedProjectForm.hasErrors()) { return badRequest(setting.render("title.projectSetting", filledUpdatedProjectForm, Project.find.byId(updatedProject.id))); } Project project = Project.find.byId(updatedProject.id); PlayRepository repository = RepositoryService.getRepository(project); if (!repository.renameTo(updatedProject.name)) { throw new FileOperationException("fail repository rename to " + project.owner + "/" + updatedProject.name); } updatedProject.update(); return redirect(routes.ProjectApp.settingForm(loginId, updatedProject.name)); } /** * {@code filePart} .<p /> * @param filePart * @return {@code filePart} null true, {@code filename} null true, {@code fileLength} 0 true */ private static boolean isEmptyFilePart(FilePart filePart) { return filePart == null || filePart.getFilename() == null || filePart.getFilename().length() <= 0; } /** * {@code filename} .<p /> * * {@link controllers.ProjectApp#LOGO_TYPE} . * @param filename the filename * @return true, if is image file */ public static boolean isImageFile(String filename) { boolean isImageFile = false; for(String suffix : LOGO_TYPE) { if(filename.toLowerCase().endsWith(suffix)) isImageFile = true; } return isImageFile; } /** * .<p /> * * {@code loginId} {@code projectName} .<br /> * unauthorized .<br /> * * @param loginId user login id * @param projectName the project name * @return , */ public static Result deleteForm(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } Form<Project> projectForm = form(Project.class).fill(project); return ok(delete.render("title.projectSetting", projectForm, project)); } /** * .<p /> * * {@code loginId} {@code projectName} .<br /> * redirect. <br /> * * @param loginId the user login id * @param projectName the project name * @return the result * @throws Exception the exception */ public static Result deleteProject(String loginId, String projectName) throws Exception { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.DELETE)) { RepositoryService.deleteRepository(loginId, projectName, project.vcs); project.delete(); // XHR 204 No Content Location if(HttpUtil.isRequestedWithXHR(request())){ response().setHeader("Location", routes.Application.index().toString()); return status(204); } return redirect(routes.Application.index()); } else { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.settingForm(loginId, projectName)); } } /** * .<p /> * * {@code loginId} {@code projectName} .<br /> * .<br /> * Role .<br /> * unauthorized <br /> * * @param loginId the user login id * @param projectName the project name * @return , , Role */ public static Result members(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } project.cleanEnrolledUsers(); return ok(views.html.project.members.render("title.memberList", ProjectUser.findMemberListByProject(project.id), project, Role.getActiveRoles())); } /** * , * * * - * - / * - / * * @param loginId * @param projectName * @param number * @param resourceType * @return */ public static Result mentionList(String loginId, String projectName, Long number, String resourceType) { String prefer = HttpUtil.getPreferType(request(), HTML, JSON); if (prefer == null) { return status(Http.Status.NOT_ACCEPTABLE); } else { response().setHeader("Vary", "Accept"); } Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } List<User> userList = new ArrayList<>(); collectAuthorAndCommenter(project, number, userList, resourceType); addProjectMemberList(project, userList); userList.remove(UserApp.currentUser()); List<Map<String, String>> mentionList = new ArrayList<>(); collectedUsersToMap(mentionList, userList); return ok(toJson(mentionList)); } /** * CommitDiff * * ( ) * - * - * - * * @param ownerLoginId * @param projectName * @param commitId * @return * @throws IOException * @throws UnsupportedOperationException * @throws ServletException * @throws GitAPIException * @throws SVNException */ public static Result mentionListAtCommitDiff(String ownerLoginId, String projectName, String commitId, Long pullRequestId) throws IOException, UnsupportedOperationException, ServletException, GitAPIException, SVNException { Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } PullRequest pullRequest = null; Project fromProject = project; if( pullRequestId != -1 ){ pullRequest = PullRequest.findById(pullRequestId); if( pullRequest != null) fromProject = pullRequest.fromProject; } Commit commit = RepositoryService.getRepository(fromProject).getCommit(commitId); List<User> userList = new ArrayList<>(); addCommitAuthor(commit, userList); addCodeCommenters(commitId, fromProject.id, userList); addProjectMemberList(project, userList); userList.remove(UserApp.currentUser()); List<Map<String, String>> mentionList = new ArrayList<>(); collectedUsersToMap(mentionList, userList); return ok(toJson(mentionList)); } /** * Pull-Request * * ( ) * - * - Pull Request * - Commit Author * - Pull Request * * @param ownerLoginId * @param projectName * @param commitId * @param pullRequestId * @return * @throws IOException * @throws UnsupportedOperationException * @throws ServletException * @throws GitAPIException * @throws SVNException */ public static Result mentionListAtPullRequest(String ownerLoginId, String projectName, String commitId, Long pullRequestId) throws IOException, UnsupportedOperationException, ServletException, GitAPIException, SVNException { Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } PullRequest pullRequest = PullRequest.findById(pullRequestId); List<User> userList = new ArrayList<>(); addCommentAuthors(pullRequestId, userList); addProjectMemberList(project, userList); if(!commitId.isEmpty()) { addCommitAuthor(RepositoryService.getRepository(pullRequest.fromProject).getCommit(commitId), userList); } userList.add(pullRequest.contributor); userList.remove(UserApp.currentUser()); List<Map<String, String>> mentionList = new ArrayList<>(); collectedUsersToMap(mentionList, userList); return ok(toJson(mentionList)); } private static void addCommentAuthors(Long pullRequestId, List<User> userList) { List<PullRequestComment> comments = PullRequest.findById(pullRequestId).comments; for (PullRequestComment codeComment : comments) { final User commenter = User.findByLoginId(codeComment.authorLoginId); if(userList.contains(commenter)) { userList.remove(commenter); } userList.add(commenter); } Collections.reverse(userList); } private static void addCodeCommenters(String commitId, Long projectId, List<User> userList) { List<CommitComment> comments = CommitComment.find.where().eq("commitId", commitId).eq("project.id", projectId).findList(); for (CommitComment codeComment : comments) { User commentAuthor = User.findByLoginId(codeComment.authorLoginId); if( userList.contains(commentAuthor) ) { userList.remove(commentAuthor); } userList.add(commentAuthor); } Collections.reverse(userList); } private static void addCommitAuthor(Commit commit, List<User> userList) { if(!commit.getAuthor().isAnonymous() && !userList.contains(commit.getAuthor())) { userList.add(commit.getAuthor()); } //fallback: additional search by email id if (commit.getAuthorEmail() != null){ User authorByEmail = User.findByLoginId(commit.getAuthorEmail().substring(0, commit.getAuthorEmail().lastIndexOf("@"))); if(!authorByEmail.isAnonymous() && !userList.contains(authorByEmail)) { userList.add(authorByEmail); } } } private static void collectAuthorAndCommenter(Project project, Long number, List<User> userList, String resourceType) { AbstractPosting posting = null; switch (ResourceType.getValue(resourceType)) { case ISSUE_POST: posting = AbstractPosting.findByNumber(Issue.finder, project, number); break; case BOARD_POST: posting = AbstractPosting.findByNumber(Posting.finder, project, number); break; default: return; } if(posting != null) { for(Comment comment: posting.getComments()) { User commentUser = User.findByLoginId(comment.authorLoginId); if (userList.contains(commentUser)) { userList.remove(commentUser); } userList.add(commentUser); } Collections.reverse(userList); // recent commenter first! User postAuthor = User.findByLoginId(posting.authorLoginId); if( !userList.contains(postAuthor) ) { userList.add(postAuthor); } } } private static void collectedUsersToMap(List<Map<String, String>> users, List<User> userList) { for(User user: userList) { Map<String, String> projectUserMap = new HashMap<>(); if(!user.loginId.equals(Constants.ADMIN_LOGIN_ID) && user != null){ projectUserMap.put("username", user.loginId); projectUserMap.put("name", user.name); projectUserMap.put("image", user.avatarUrl); users.add(projectUserMap); } } } private static void addProjectMemberList(Project project, List<User> userList) { for(ProjectUser projectUser: project.projectUser) { if(!userList.contains(projectUser.user)){ userList.add(projectUser.user); } } } /** * .<p /> * * redirect .<br /> * .<br /> * {@code loginId} {@code projectName} .<br /> * <br /> * UPDATE redirect .<br /> * null redirect .<br /> * redirect .<br /> * * @param loginId the user login id * @param projectName the project name * @return , , Role */ public static Result newMember(String loginId, String projectName) { // TODO change into view validation Form<User> addMemberForm = form(User.class).bindFromRequest(); if (addMemberForm.hasErrors()){ flash(Constants.WARNING, "project.member.notExist"); return redirect(routes.ProjectApp.members(loginId, projectName)); } User user = User.findByLoginId(form(User.class).bindFromRequest().get().loginId); Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.members(loginId, projectName)); } else if (user.isAnonymous()) { flash(Constants.WARNING, "project.member.notExist"); return redirect(routes.ProjectApp.members(loginId, projectName)); } else if (!ProjectUser.isMember(user.id, project.id)){ ProjectUser.assignRole(user.id, project.id, RoleType.MEMBER); project.cleanEnrolledUsers(); } else{ flash(Constants.WARNING, "project.member.alreadyMember"); } return redirect(routes.ProjectApp.members(loginId, projectName)); } /** * .<p /> * * {@code loginId} {@code projectName} .<br /> * redirect .<br /> * forbidden .<br /> * * @param loginId the user login id * @param projectName the project name * @param userId * @return the result */ public static Result deleteMember(String loginId, String projectName, Long userId) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (UserApp.currentUser().id.equals(userId) || AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { if (project.isOwner(User.find.byId(userId))) { return forbidden(ErrorViews.Forbidden.render("project.member.ownerCannotLeave", project)); } ProjectUser.delete(userId, project.id); return redirect(routes.ProjectApp.members(loginId, projectName)); } else { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } } /** * Role NO_CONTENT .<p /> * * {@code loginId} {@code projectName} .<br /> * Role .<br /> * <br /> * forbidden .<br /> * forbidden .<br /> * * @param loginId the user login id * @param projectName the project name * @param userId the user id * @return */ public static Result editMember(String loginId, String projectName, Long userId) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { if (project.isOwner(User.find.byId(userId))) { return forbidden(ErrorViews.Forbidden.render("project.member.ownerMustBeAManager", project)); } ProjectUser.assignRole(userId, project.id, form(Role.class) .bindFromRequest().get().id); return status(Http.Status.NO_CONTENT); } else { return forbidden(ErrorViews.Forbidden.render("project.member.isManager", project)); } } /** * accepted Content-type JSON .<p /> * HTML JSON NOT_ACCEPTABLE .<br /> * <br /> * 1. JSON ( )<br /> * {@code query} .<br /> * {@link ProjectApp#MAX_FETCH_PROJECTS} .<br /> * {@code owner} {@code name} JSON .<br /> * <br /> * 2. <br /> * ( : {@link #PROJECT_COUNT_PER_PAGE}) <br /> * ({@code query}), ({@code state}) .<br /> * * @param query the query * @param state the state * @param pageNum the page num * @return json json , html java */ public static Result projects(String query, String state, int pageNum) { String prefer = HttpUtil.getPreferType(request(), HTML, JSON); if (prefer == null) { return status(Http.Status.NOT_ACCEPTABLE); } response().setHeader("Vary", "Accept"); if (prefer.equals(JSON)) { return getProjectsToJSON(query); } else { return getPagingProjects(query, state, pageNum); } } /** * . * * when : , , * * / / Overview {@code query} * @{code state} . * * @param query ( / / Overview) * @param state (/) * @param pageNum * @return {@code query} @{code state} */ private static Result getPagingProjects(String query, String state, int pageNum) { ExpressionList<Project> el = Project.find.where(); if (StringUtils.isNotBlank(query)) { Junction<Project> junction = el.disjunction(); junction.icontains("owner", query) .icontains("name", query) .icontains("overview", query); List<Object> ids = Project.find.where().icontains("labels.name", query).findIds(); if (!ids.isEmpty()) { junction.idIn(ids); } junction.endJunction(); } Project.State stateType = Project.State.valueOf(state.toUpperCase()); if (stateType == Project.State.PUBLIC) { el.eq("isPublic", true); } else if (stateType == Project.State.PRIVATE) { el.eq("isPublic", false); } Set<Long> labelIds = LabelSearchUtil.getLabelIds(request()); if (CollectionUtils.isNotEmpty(labelIds)) { el.add(LabelSearchUtil.createLabelSearchExpression(el.query(), labelIds)); } el.orderBy("createdDate desc"); Page<Project> projects = el.findPagingList(PROJECT_COUNT_PER_PAGE).getPage(pageNum - 1); return ok(views.html.project.list.render("title.projectList", projects, query, state)); } /** * JSON . * * / / Overview {@code query} {@link #MAX_FETCH_PROJECTS} * JSON . * * @param query ( / / Overview) * @return JSON */ private static Result getProjectsToJSON(String query) { ExpressionList<Project> el = Project.find.where().disjunction() .icontains("owner", query) .icontains("name", query) .icontains("overview", query) .endJunction(); int total = el.findRowCount(); if (total > MAX_FETCH_PROJECTS) { el.setMaxRows(MAX_FETCH_PROJECTS); response().setHeader("Content-Range", "items " + MAX_FETCH_PROJECTS + "/" + total); } List<String> projectNames = new ArrayList<>(); for (Project project: el.findList()) { projectNames.add(project.owner + "/" + project.name); } return ok(toJson(projectNames)); } /** * JSON .<p /> * * {@code loginId} {@code projectName} .<br /> * forbidden .<br /> * application/json not_acceptable .<br /> * * * @param owner the owner login id * @param projectName the project name * @return JSON */ public static Result labels(String owner, String projectName) { Project project = Project.findByOwnerAndProjectName(owner, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } if (!request().accepts("application/json")) { return status(Http.Status.NOT_ACCEPTABLE); } Map<Long, Map<String, String>> labels = new HashMap<>(); for (Label label: project.labels) { Map<String, String> tagMap = new HashMap<>(); tagMap.put("category", label.category); tagMap.put("name", label.name); labels.put(label.id, tagMap); } return ok(toJson(labels)); } /** * JSON .<p /> * * {@code loginId} {@code projectName} .<br /> * forbidden .<br /> * null empty JSON .<br /> * empty JSON .<br /> * * @param ownerName the owner name * @param projectName the project name * @return the result */ public static Result attachLabel(String ownerName, String projectName) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } // Get category and name from the request. Return 400 Bad Request if name is not given. Map<String, String[]> data = request().body().asFormUrlEncoded(); String category = HttpUtil.getFirstValueFromQuery(data, "category"); String name = HttpUtil.getFirstValueFromQuery(data, "name"); if (name == null || name.length() == 0) { // A label must have its name. return badRequest(ErrorViews.BadRequest.render("Label name is missing.", project)); } Label label = Label.find .where().eq("category", category).eq("name", name).findUnique(); boolean isCreated = false; if (label == null) { // Create new label if there is no label which has the given name. label = new Label(category, name); label.save(); isCreated = true; } Boolean isAttached = project.attachLabel(label); if (!isCreated && !isAttached) { // Something is wrong. This case is not possible. play.Logger.warn( "A label '" + label + "' is created but failed to attach to project '" + project + "'."); } if (isAttached) { // Return the attached label. The return type is Map<Long, String> // even if there is only one label, to unify the return type with // ProjectApp.labels(). Map<Long, Map<String, String>> labels = new HashMap<>(); Map<String, String> labelMap = new HashMap<>(); labelMap.put("category", label.category); labelMap.put("name", label.name); labels.put(label.id, labelMap); if (isCreated) { return created(toJson(labels)); } else { return ok(toJson(labels)); } } else { // Return 204 No Content if the label is already attached. return status(Http.Status.NO_CONTENT); } } /** * .<p /> * * _method delete badRequest .<br /> * notfound . * * @param ownerName the owner name * @param projectName the project name * @param id the id * @return the result */ public static Result detachLabel(String ownerName, String projectName, Long id) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.labelsAsResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } // _method must be 'delete' Map<String, String[]> data = request().body().asFormUrlEncoded(); if (!HttpUtil.getFirstValueFromQuery(data, "_method").toLowerCase() .equals("delete")) { return badRequest(ErrorViews.BadRequest.render("_method must be 'delete'.", project)); } Label tag = Label.find.byId(id); if (tag == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } project.detachLabel(tag); return status(Http.Status.NO_CONTENT); } }
package be.ibridge.kettle.trans; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.security.ProtectionDomain; public class KettleURLClassLoader extends URLClassLoader { private String name; public KettleURLClassLoader(URL[] url, ClassLoader classLoader) { super(url, classLoader); } public KettleURLClassLoader(URL[] url, ClassLoader classLoader, String name) { this(url, classLoader); this.name = name; } public String toString() { return super.toString()+" : "+name; } public void setName(String name) { this.name = name; } public String getName() { return name; } /* Cglib doe's not creates custom class loader (to access package methotds and classes ) it uses reflection to invoke "defineClass", but you can call protected method in subclass without problems: */ public Class loadClass(String name, ProtectionDomain protectionDomain) { Class loaded = findLoadedClass(name); if (loaded == null) { // Get the jar, load the bytes from the jar file, construct class from scratch as in snippet below... /* loaded = super.findClass(name); URL url = super.findResource(newName); InputStream clis = getResourceAsStream(newName); */ String newName = name.replace('.','/'); InputStream is = super.getResourceAsStream(newName); byte[] driverBytes = toBytes( is ); loaded = super.defineClass(name, driverBytes, 0, driverBytes.length, protectionDomain); } return loaded; } private byte[] toBytes(InputStream is) { byte[] retval = new byte[0]; try { int a = is.available(); while (a>0) { byte[] buffer = new byte[a]; is.read(buffer); byte[] newretval = new byte[retval.length+a]; for (int i=0;i<retval.length;i++) newretval[i] = retval[i]; // old part for (int i=0;i<a;i++) newretval[retval.length+i] = buffer[i]; // new part retval = newretval; a = is.available(); // see what's left } return retval; } catch(Exception e) { System.out.println(Messages.getString("KettleURLClassLoader.Exception.UnableToReadClass")+e.toString()); //$NON-NLS-1$ return null; } } }
package cc.mallet.fst; import java.util.ArrayList; import java.util.Collections; import cc.mallet.fst.TransducerTrainer.ByInstanceIncrements; import cc.mallet.types.FeatureVectorSequence; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import cc.mallet.types.Sequence; /** * Trains CRF by stochastic gradient. Most effective on large training sets. * * @author kedarb * */ public class CRFTrainerByStochasticGradient extends ByInstanceIncrements { CRF crf; // t is the decaying factor. lambda is some regularization depending on the // training set size and the gaussian prior. double learningRate, t, lambda; int iterationCount = 0; boolean converged = false; CRF.Factors expectations, constraints; public CRFTrainerByStochasticGradient(CRF crf, double learningRate) { this.crf = crf; this.learningRate = learningRate; this.expectations = new CRF.Factors(crf); this.constraints = new CRF.Factors(crf); } public int getIteration() { return iterationCount; } public Transducer getTransducer() { return crf; } public boolean isFinishedTraining() { return converged; } // Best way to choose learning rate is to run training on a sample and set // it to the rate that produces maximum increase in likelihood or accuracy. // Then, to be conservative just halve the learning rate. // In general, eta = 1/(lambda*t) where // lambda=priorVariance*numTrainingInstances // After an initial eta_0 is set, t_0 = 1/(lambda*eta_0) // After each training step eta = 1/(lambda*(t+t_0)), t=0,1,2,..,Infinity /** Automatically set the learning rate to one that would be good */ public void setLearningRateByLikelihood (InstanceList trainingSample) { int numIterations = 10; double bestLearningRate = Double.NEGATIVE_INFINITY; double bestLikelihoodChange = Double.NEGATIVE_INFINITY; double currLearningRate = 5e-11; while (currLearningRate < 1) { currLearningRate *= 2; crf.parameters.zero(); double beforeLikelihood = computeLikelihood(trainingSample); double likelihoodChange = trainSample(trainingSample, numIterations, currLearningRate) - beforeLikelihood; System.out.println("likelihood change = " + likelihoodChange + " for eta=" + currLearningRate); if (likelihoodChange > bestLikelihoodChange) { bestLikelihoodChange = likelihoodChange; bestLearningRate = currLearningRate; } } // reset the parameters crf.parameters.zero(); // conservative estimate for learning rate bestLearningRate /= 2; System.out.println("Setting learning rate to " + bestLearningRate); setLearningRate(bestLearningRate); } private double trainSample(InstanceList trainingSample, int numIterations, double rate) { double lambda = trainingSample.size(); double t = 1 / (lambda * rate); double loglik = Double.NEGATIVE_INFINITY; for (int i = 0; i < numIterations; i++) { loglik = 0.0; for (int j = 0; j < trainingSample.size(); j++) { rate = 1 / (lambda * t); loglik += trainSingle(trainingSample.get(j), rate); t += 1.0; } } return loglik; } private double computeLikelihood(InstanceList trainingSample) { double loglik = 0.0; for (int i = 0; i < trainingSample.size(); i++) { Instance trainingInstance = trainingSample.get(i); FeatureVectorSequence fvs = (FeatureVectorSequence) trainingInstance .getData(); Sequence labelSequence = (Sequence) trainingInstance.getTarget(); loglik += new SumLatticeDefault(crf, fvs, labelSequence, constraints.new Incrementor()).getTotalWeight(); loglik -= new SumLatticeDefault(crf, fvs, null, expectations.new Incrementor()).getTotalWeight(); } constraints.zero(); expectations.zero(); return loglik; } public void setLearningRate(double r) { this.learningRate = r; } public double getLearningRate() { return this.learningRate; } public boolean train(InstanceList trainingSet, int numIterations) { assert (expectations.structureMatches(crf.parameters)); assert (constraints.structureMatches(crf.parameters)); lambda = 1.0 / trainingSet.size(); t = 1.0 / (lambda * learningRate); converged = false; ArrayList<Integer> trainingIndices = new ArrayList<Integer>(); for (int i = 0; i < trainingSet.size(); i++) trainingIndices.add(i); double oldLoglik = Double.NEGATIVE_INFINITY; while (numIterations iterationCount++; // shuffle the indices Collections.shuffle(trainingIndices); double loglik = 0.0; for (int i = 0; i < trainingSet.size(); i++) { learningRate = 1.0 / (lambda * t); loglik += trainSingle(trainingSet.get(trainingIndices.get(i))); t += 1.0; } System.out.println("loglikelihood[" + numIterations + "] = " + loglik); if (Math.abs(loglik - oldLoglik) < 1e-3) { converged = true; break; } oldLoglik = loglik; runEvaluators(); } return converged; } // TODO Add some way to train by batches of instances, where the batch // memberships are determined externally public boolean trainIncremental(InstanceList trainingSet) { this.train(trainingSet, 1); return false; } public boolean trainIncremental(Instance trainingInstance) { assert (expectations.structureMatches(crf.parameters)); trainSingle(trainingInstance); return false; } private double trainSingle(Instance trainingInstance) { return trainSingle(trainingInstance, learningRate); } private double trainSingle(Instance trainingInstance, double rate) { double singleLoglik = 0.0; constraints.zero(); expectations.zero(); FeatureVectorSequence fvs = (FeatureVectorSequence) trainingInstance .getData(); Sequence labelSequence = (Sequence) trainingInstance.getTarget(); singleLoglik += new SumLatticeDefault(crf, fvs, labelSequence, constraints.new Incrementor()).getTotalWeight(); singleLoglik -= new SumLatticeDefault(crf, fvs, null, expectations.new Incrementor()).getTotalWeight(); // Calculate parameter gradient given these instances: // (constraints - expectations) constraints.plusEquals(expectations, -1); // Change the parameters a little by this difference, // obeying weightsFrozen crf.parameters.plusEquals(constraints, rate, true); return singleLoglik; } }
package com.echsylon.atlantis; import java.util.LinkedHashMap; import java.util.Map; import static com.echsylon.atlantis.Utils.isAnyEmpty; /** * This class is responsible for keeping track of any header key/value pairs. It * gives convenience hints on certain expected behavior based on which headers * are present in the current collection. */ class HeaderManager extends LinkedHashMap<String, String> { private boolean expectedBody = false; private boolean expectedChunked = false; private boolean expectedContinue = false; /** * Adds a header key/value pair to the internal collection. Any existing * header with the same key will be overwritten. * * @param key The key of the header. * @param value The corresponding header value. * @return Any previous value for the given key. */ @Override public String put(String key, String value) { if (isAnyEmpty(key, value)) return null; if (containsKey(key)) value += ("; " + get(key)); String previous = super.put(key, value); if (key.equalsIgnoreCase("expect")) expectedContinue = value.equalsIgnoreCase("100-continue"); if (key.equalsIgnoreCase("transfer-encoding")) expectedChunked = value.equalsIgnoreCase("chunked"); if (key.equalsIgnoreCase("content-length")) try { expectedBody = Long.parseLong(value) > 0L; } catch (NumberFormatException e) { expectedBody = false; } return previous; } @Override public String putIfAbsent(String key, String value) { return !containsKey(key) ? put(key, value) : get(key); } @Override public void putAll(Map<? extends String, ? extends String> headers) { for (Entry<? extends String, ? extends String> entry : headers.entrySet()) put(entry.getKey(), entry.getValue()); } /** * Returns a boolean flag indicating whether there is a "Content-Length" * header with a value greater than 0. * * @return Boolean true if there is a "Content-Length" header and a * corresponding value greater than 0, false otherwise. */ boolean isExpectedToHaveBody() { return expectedBody; } /** * Returns a boolean flag indicating whether there is an "Expect" header * with a "100-continue" value. * * @return Boolean true if there is an "Expect" header and a corresponding * "100-Continue" value, false otherwise. */ boolean isExpectedToContinue() { return expectedContinue; } /** * Returns a boolean flag indicating whether there is a "Transfer-Encoding" * header with a "chunked" value. * * @return Boolean true if there is a "Transfer-Encoding" header and a * corresponding "chunked" value, false otherwise. */ boolean isExpectedToBeChunked() { return expectedChunked; } }
package com.android.deskclock.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; /** * When this layout is in the Horizontal orientation and one and only one child is a TextView with a * non-null android:ellipsize, this layout will reduce android:maxWidth of that TextView to ensure * the siblings are not truncated. This class is useful when that ellipsize-text-view "starts" * before other children of this view group. This layout has no effect if: * <ul> * <li>the orientation is not horizontal</li> * <li>any child has weights.</li> * <li>more than one child has a non-null android:ellipsize.</li> * </ul> * * <p>The purpose of this horizontal-linear-layout is to ensure that when the sum of widths of the * children are greater than this parent, the maximum width of the ellipsize-text-view, is reduced * so that no siblings are truncated.</p> * * <p>For example: Given Text1 has android:ellipsize="end" and Text2 has android:ellipsize="none", * as Text1 and/or Text2 grow in width, both will consume more width until Text2 hits the end * margin, then Text1 will cease to grow and instead shrink to accommodate any further growth in * Text2.</p> * <ul> * <li>|[text1]|[text2] |</li> * <li>|[text1 text1]|[text2 text2] |</li> * <li>|[text...]|[text2 text2 text2]|</li> * </ul> */ public class EllipsizeLayout extends LinearLayout { @SuppressWarnings("unused") public EllipsizeLayout(Context context) { this(context, null); } public EllipsizeLayout(Context context, AttributeSet attrs) { super(context, attrs); } /** * This override only acts when the LinearLayout is in the Horizontal orientation and is in it's * final measurement pass(MeasureSpec.EXACTLY). In this case only, this class * <ul> * <li>Identifies the one TextView child with the non-null android:ellipsize.</li> * <li>Re-measures the needed width of all children (by calling measureChildWithMargins with * the width measure specification to MeasureSpec.UNSPECIFIED.)</li> * <li>Sums the children's widths.</li> * <li>Whenever the sum of the children's widths is greater than this parent was allocated, * the maximum width of the one TextView child with the non-null android:ellipsize is * reduced.</li> * </ul> * * @param widthMeasureSpec horizontal space requirements as imposed by the parent * @param heightMeasureSpec vertical space requirements as imposed by the parent */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (getOrientation() == HORIZONTAL && (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY)) { int totalLength = 0; // If any of the constraints of this class are exceeded, outOfSpec becomes true // and the no alterations are made to the ellipsize-text-view. boolean outOfSpec = false; TextView ellipsizeView = null; final int count = getChildCount(); final int parentWidth = MeasureSpec.getSize(widthMeasureSpec); final int queryWidthMeasureSpec = MeasureSpec. makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.UNSPECIFIED); for (int ii = 0; ii < count && !outOfSpec; ++ii) { final View child = getChildAt(ii); if (child != null && child.getVisibility() != GONE) { // Identify the ellipsize view if (child instanceof TextView) { final TextView tv = (TextView) child; if (tv.getEllipsize() != null) { if (ellipsizeView == null) { ellipsizeView = tv; // Clear the maximum width on ellipsizeView before measurement ellipsizeView.setMaxWidth(Integer.MAX_VALUE); } else { // TODO: support multiple android:ellipsize outOfSpec = true; } } } // Ask the child to measure itself measureChildWithMargins(child, queryWidthMeasureSpec, 0, heightMeasureSpec, 0); // Get the layout parameters to check for a weighted width and to add the // child's margins to the total length. final LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) child.getLayoutParams(); if (layoutParams != null) { outOfSpec |= (layoutParams.weight > 0f); totalLength += child.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin; } else { outOfSpec = true; } } } // Last constraint test outOfSpec |= (ellipsizeView == null) || (totalLength == 0); if (!outOfSpec && totalLength > parentWidth) { int maxWidth = ellipsizeView.getMeasuredWidth() - (totalLength - parentWidth); // TODO: Respect android:minWidth (easy with @TargetApi(16)) final int minWidth = 0; if (maxWidth < minWidth) { maxWidth = minWidth; } ellipsizeView.setMaxWidth(maxWidth); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
package com.axelby.podax; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.joda.time.DateTime; import org.joda.time.Weeks; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.os.AsyncTask; import android.os.Bundle; import android.sax.Element; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Xml; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class PopularSubscriptionActivity extends Activity { private class FeedDetails { private String title; private String description; private int podcastCount; private Date lastBuildDate; private Date oldestPodcastDate; private FeedDetails() { podcastCount = 0; lastBuildDate = new Date(); } } ProgressDialog _dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.popularsubscription); String title = getIntent().getExtras().getString(Constants.EXTRA_TITLE); TextView titleView = (TextView) findViewById(R.id.title); titleView.setText(title); Button add_subscription = (Button) findViewById(R.id.add_subscription); add_subscription.setOnClickListener(new OnClickListener() { public void onClick(View v) { ContentValues values = new ContentValues(); values.put(SubscriptionProvider.COLUMN_URL, getIntent().getExtras().getString(Constants.EXTRA_URL)); getContentResolver().insert(SubscriptionProvider.URI, values); UpdateService.updateSubscriptions(PopularSubscriptionActivity.this); finish(); } }); _dialog = ProgressDialog.show(this, "", "Loading Subscription...", true, true); String url = getIntent().getExtras().getString(Constants.EXTRA_URL); new AsyncTask<String, Void, FeedDetails>() { @Override protected FeedDetails doInBackground(String... urls) { if (urls.length != 1) return null; final FeedDetails details = new FeedDetails(); RootElement root = new RootElement("rss"); Element channel = root.getChild("channel"); channel.getChild("title").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { details.title = body; } }); channel.getChild("description").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { details.description = body; } }); channel.getChild("lastBuildDate").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { details.lastBuildDate = parseRFC822Date(body); } }); channel.getChild("item").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { details.podcastCount++; } }); channel.getChild("item").getChild("pubDate").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { Date pubDate = parseRFC822Date(body); if (pubDate == null) return; if (details.oldestPodcastDate == null || pubDate.before(details.oldestPodcastDate)) details.oldestPodcastDate = pubDate; } }); HttpGet get = new HttpGet(urls[0]); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); Xml.parse(response.getEntity().getContent(), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return details; } @Override protected void onPostExecute(FeedDetails result) { TextView title = (TextView) findViewById(R.id.title); title.setText(result.title); if (result.lastBuildDate != null && result.oldestPodcastDate != null) { DateTime lastBuildDate = new DateTime(result.lastBuildDate); DateTime oldestPodcastDate = new DateTime(result.oldestPodcastDate); Weeks weeks = Weeks.weeksBetween(oldestPodcastDate, lastBuildDate); if (weeks.getWeeks() > 0) { float podcastsPerWeek = (float)result.podcastCount / weeks.getWeeks(); podcastsPerWeek = Math.round(podcastsPerWeek * 10) / 10.0f; result.description = result.description + "\n\nAverages " + podcastsPerWeek + " podcasts per week"; } } TextView description = (TextView) findViewById(R.id.description); description.setText(result.description); _dialog.dismiss(); } }.execute(url); } public static Date parseRFC822Date(String date) { for (SimpleDateFormat format : SubscriptionUpdater.rfc822DateFormats) { try { return format.parse(date); } catch (ParseException e) { } } return null; } }
package jade.mtp.iiop; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Date; import java.util.Calendar; import org.omg.CORBA.*; import FIPA.*; // OMG IDL Stubs import jade.core.AID; import jade.mtp.InChannel; import jade.mtp.OutChannel; import jade.mtp.MTP; import jade.mtp.MTPException; import jade.mtp.TransportAddress; import jade.domain.FIPAAgentManagement.Envelope; /** Implementation of <code><b>fipa.mts.mtp.iiop.std</b></code> specification for delivering ACL messages over the OMG IIOP transport protocol. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class MessageTransportProtocol implements MTP { private static class MTSImpl extends FIPA._MTSImplBase { private InChannel.Dispatcher dispatcher; public MTSImpl(InChannel.Dispatcher disp) { dispatcher = disp; } public void message(FipaMessage aFipaMessage) { FIPA.Envelope[] envelopes = aFipaMessage.messageEnvelopes; byte[] payload = aFipaMessage.messageBody; // System.out.println("\n\n"+(new java.util.Date()).toString()+" RECEIVED IIOP MESSAGE"+new String(payload)); Envelope env = new Envelope(); // Read all the envelopes sequentially, so that later slots // overwrite earlier ones. for(int e = 0; e < envelopes.length; e++) { FIPA.Envelope IDLenv = envelopes[e]; // Read in the 'to' slot if(IDLenv.to.length > 0) env.clearAllTo(); for(int i = 0; i < IDLenv.to.length; i++) { AID id = unmarshalAID(IDLenv.to[i]); env.addTo(id); } // Read in the 'from' slot if(IDLenv.to.length > 0) { AID id = unmarshalAID(IDLenv.from[0]); env.setFrom(id); } // Read in the 'intended-receiver' slot if(IDLenv.intendedReceiver.length > 0) env.clearAllIntendedReceiver(); for(int i = 0; i < IDLenv.intendedReceiver.length; i++) { AID id = unmarshalAID(IDLenv.intendedReceiver[i]); env.addIntendedReceiver(id); } // Read in the 'encrypted' slot if(IDLenv.encrypted.length > 0) env.clearAllEncrypted(); for(int i = 0; i < IDLenv.encrypted.length; i++) { String word = IDLenv.encrypted[i]; env.addEncrypted(word); } // Read in the other slots if(IDLenv.comments.length() > 0) env.setComments(IDLenv.comments); if(IDLenv.aclRepresentation.length() > 0) env.setAclRepresentation(IDLenv.aclRepresentation); if(IDLenv.payloadLength > 0) env.setPayloadLength(Integer.toString(IDLenv.payloadLength)); if(IDLenv.payloadEncoding.length() > 0) env.setPayloadEncoding(IDLenv.payloadEncoding); if(IDLenv.date.length > 0) { Date d = unmarshalDateTime(IDLenv.date[0]); env.setDate(d); } // FIXME: need to unmarshal 'received' slot // FIXME: need to unmarshal user properties } // Dispatch the message dispatcher.dispatchMessage(env, payload); } private AID unmarshalAID(FIPA.AgentID id) { AID result = new AID(); result.setName(id.name); for(int i = 0; i < id.addresses.length; i++) result.addAddresses(id.addresses[i]); for(int i = 0; i < id.resolvers.length; i++) result.addResolvers(unmarshalAID(id.resolvers[i])); return result; } private Date unmarshalDateTime(FIPA.DateTime d) { Date result = new Date(); return result; } } // End of MTSImpl class private ORB myORB; private MTSImpl server; public MessageTransportProtocol() { myORB = ORB.init(new String[0], null); } public TransportAddress activate(InChannel.Dispatcher disp) throws MTPException { server = new MTSImpl(disp); myORB.connect(server); return new IIOPAddress(myORB, server); } public void activate(InChannel.Dispatcher disp, TransportAddress ta) throws MTPException { throw new MTPException("User supplied transport address not supported."); } public void deactivate(TransportAddress ta) throws MTPException { myORB.disconnect(server); } public void deactivate() throws MTPException { myORB.disconnect(server); } public void deliver(String addr, Envelope env, byte[] payload) throws MTPException { try { TransportAddress ta = strToAddr(addr); IIOPAddress iiopAddr = (IIOPAddress)ta; FIPA.MTS objRef = iiopAddr.getObject(); // Fill in the 'to' field of the IDL envelope Iterator itTo = env.getAllTo(); List to = new ArrayList(); while(itTo.hasNext()) { AID id = (AID)itTo.next(); to.add(marshalAID(id)); } FIPA.AgentID[] IDLto = new FIPA.AgentID[to.size()]; for(int i = 0; i < to.size(); i++) IDLto[i] = (FIPA.AgentID)to.get(i); // Fill in the 'from' field of the IDL envelope AID from = env.getFrom(); FIPA.AgentID[] IDLfrom = new FIPA.AgentID[] { marshalAID(from) }; // Fill in the 'intended-receiver' field of the IDL envelope Iterator itIntendedReceiver = env.getAllIntendedReceiver(); List intendedReceiver = new ArrayList(); while(itIntendedReceiver.hasNext()) { AID id = (AID)itIntendedReceiver.next(); intendedReceiver.add(marshalAID(id)); } FIPA.AgentID[] IDLintendedReceiver = new FIPA.AgentID[intendedReceiver.size()]; for(int i = 0; i < intendedReceiver.size(); i++) IDLintendedReceiver[i] = (FIPA.AgentID)intendedReceiver.get(i); // Fill in the 'encrypted' field of the IDL envelope Iterator itEncrypted = env.getAllEncrypted(); List encrypted = new ArrayList(); while(itEncrypted.hasNext()) { String word = (String)itEncrypted.next(); encrypted.add(word); } String[] IDLencrypted = new String[encrypted.size()]; for(int i = 0; i < encrypted.size(); i++) IDLencrypted[i] = (String)encrypted.get(i); // Fill in the other fields of the IDL envelope ... String IDLcomments = env.getComments(); String IDLaclRepresentation = env.getAclRepresentation(); String payloadLength = env.getPayloadLength(); int IDLpayloadLength = Integer.parseInt(payloadLength); String IDLpayloadEncoding = env.getPayloadEncoding(); FIPA.DateTime[] IDLdate = new FIPA.DateTime[] { marshalDateTime(env.getDate()) }; FIPA.ReceivedObject[] IDLreceived = new FIPA.ReceivedObject[] { }; // FIXME: need to marshal 'received' slot FIPA.Property[][] IDLtransportBehaviour = new FIPA.Property[][] { }; FIPA.Property[] IDLuserDefinedProperties = new FIPA.Property[] { }; // FIXME: need to marshal user properties FIPA.Envelope IDLenv = new FIPA.Envelope(IDLto, IDLfrom, IDLcomments, IDLaclRepresentation, IDLpayloadLength, IDLpayloadEncoding, IDLdate, IDLencrypted, IDLintendedReceiver, IDLreceived, IDLtransportBehaviour, IDLuserDefinedProperties); FipaMessage msg = new FipaMessage(new FIPA.Envelope[] { IDLenv }, payload); objRef.message(msg); // System.out.println("\n\n"+(new java.util.Date()).toString()+" SENT IIOP MESSAGE TO ADDRESS iiop://"+addr.getHost()+":"+addr.getPort()+".\n"+ new String(payload)); } catch(ClassCastException cce) { cce.printStackTrace(); throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public TransportAddress strToAddr(String rep) throws MTPException { return new IIOPAddress(myORB, rep); } public String addrToStr(TransportAddress ta) throws MTPException { try { IIOPAddress addr = (IIOPAddress)ta; return addr.getIOR(); } catch(ClassCastException cce) { throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public String getName() { return "iiop"; } private FIPA.AgentID marshalAID(AID id) { String name = id.getName(); String[] addresses = id.getAddressesArray(); AID[] resolvers = id.getResolversArray(); FIPA.Property[] userDefinedProperties = new FIPA.Property[] { }; int numOfResolvers = resolvers.length; FIPA.AgentID result = new FIPA.AgentID(name, addresses, new AgentID[numOfResolvers], userDefinedProperties); for(int i = 0; i < numOfResolvers; i++) { result.resolvers[i] = marshalAID(resolvers[i]); // Recursively marshal all resolvers, which are, in turn, AIDs. } return result; } private FIPA.DateTime marshalDateTime(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); short year = (short)cal.get(Calendar.YEAR); short month = (short)cal.get(Calendar.MONTH); short day = (short)cal.get(Calendar.DAY_OF_MONTH); short hour = (short)cal.get(Calendar.HOUR_OF_DAY); short minutes = (short)cal.get(Calendar.MINUTE); short seconds = (short)cal.get(Calendar.SECOND); short milliseconds = 0; // FIXME: This is truncated to the second char typeDesignator = ' '; // FIXME: Uses local timezone ? FIPA.DateTime result = new FIPA.DateTime(year, month, day, hour, minutes, seconds, milliseconds, typeDesignator); return result; } } // End of class MessageTransportProtocol /** This class represents an IIOP address. Three syntaxes are allowed for an IIOP address (all case-insensitive): <code> IIOPAddress ::= "ior:" (HexDigit HexDigit+) | "iiop://" "ior:" (HexDigit HexDigit)+ | "iiop://" HostName ":" portNumber "/" objectKey ObjectKey = WORD </code> Notice that, in the third case, BIG_ENDIAN is assumed by default. In the first and second case, instead, the indianess information is contained within the IOR definition. **/ class IIOPAddress implements TransportAddress { public static final byte BIG_ENDIAN = 0; public static final byte LITTLE_ENDIAN = 1; private static final String TYPE_ID = "IDL:FIPA/MTS:1.0"; private static final int TAG_INTERNET_IOP = 0; private static final byte IIOP_MAJOR = 1; private static final byte IIOP_MINOR = 0; private ORB orb; private String ior; private String host; private short port; private String objectKey; private CDRCodec codecStrategy; public IIOPAddress(ORB anOrb, FIPA.MTS objRef) throws MTPException { orb = anOrb; String s = orb.object_to_string(objRef); if(s.toLowerCase().startsWith("ior:")) initFromIOR(s); else if(s.toLowerCase().startsWith("iiop:")) initFromURL(s, BIG_ENDIAN); else if(s.toLowerCase().startsWith("corbaloc:")) initFromURL(s, BIG_ENDIAN); else throw new MTPException("Invalid string prefix"); } public IIOPAddress(ORB anOrb, String s) throws MTPException { orb = anOrb; if(s.toLowerCase().startsWith("ior:")) initFromIOR(s); else if(s.toLowerCase().startsWith("iiop:")) initFromURL(s, BIG_ENDIAN); else if(s.toLowerCase().startsWith("corbaloc:")) initFromURL(s, BIG_ENDIAN); else throw new MTPException("Invalid string prefix"); } private void initFromIOR(String s) throws MTPException { // Store stringified IOR ior = new String(s.toUpperCase()); // Remove 'IOR:' prefix to get Hex digits String hexString = ior.substring(4); short endianness = Short.parseShort(hexString.substring(0, 2), 16); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(hexString); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(hexString); break; default: throw new MTPException("Invalid endianness specifier"); } // Read 'string type_id' field String typeID = codecStrategy.readString(); if(!typeID.equalsIgnoreCase(TYPE_ID)) throw new MTPException("Invalid type ID" + typeID); // Read 'sequence<TaggedProfile> profiles' field // Read sequence length int seqLen = codecStrategy.readLong(); for(int i = 0; i < seqLen; i++) { // Read 'ProfileId tag' field int tag = codecStrategy.readLong(); byte[] profile = codecStrategy.readOctetSequence(); if(tag == TAG_INTERNET_IOP) { // Process IIOP profile CDRCodec profileBodyCodec; switch(profile[0]) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(profile); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(profile); break; default: throw new MTPException("Invalid endianness specifier"); } // Read IIOP version byte versionMajor = profileBodyCodec.readOctet(); byte versionMinor = profileBodyCodec.readOctet(); if(versionMajor != 1) throw new MTPException("IIOP version not supported"); // Read 'string host' field host = profileBodyCodec.readString(); // Read 'unsigned short port' field port = profileBodyCodec.readShort(); // Read 'sequence<octet> object_key' field and convert it // into a String object byte[] keyBuffer = profileBodyCodec.readOctetSequence(); objectKey = new String(keyBuffer); codecStrategy = null; } } } private void initFromURL(String s, short endianness) throws MTPException { // Remove 'iiop://' prefix to get URL host, port and file s = s.substring(7); int colonPos = s.indexOf(':'); int slashPos = s.indexOf('/'); if((colonPos == -1) || (slashPos == -1)) throw new MTPException("Invalid URL string"); host = new String(s.substring(0, colonPos)); port = Short.parseShort(s.substring(colonPos + 1, slashPos)); objectKey = new String(s.substring(slashPos + 1, s.length())); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } codecStrategy.writeString(TYPE_ID); // Write '1' as profiles sequence length codecStrategy.writeLong(1); codecStrategy.writeLong(TAG_INTERNET_IOP); CDRCodec profileBodyCodec; switch(endianness) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } // Write IIOP 1.0 profile to auxiliary CDR codec profileBodyCodec.writeOctet(IIOP_MAJOR); profileBodyCodec.writeOctet(IIOP_MINOR); profileBodyCodec.writeString(host); profileBodyCodec.writeShort(port); byte[] objKey = objectKey.getBytes(); profileBodyCodec.writeOctetSequence(objKey); byte[] encapsulatedProfile = profileBodyCodec.writtenBytes(); // Write encapsulated profile to main IOR codec codecStrategy.writeOctetSequence(encapsulatedProfile); String hexString = codecStrategy.writtenString(); ior = "IOR:" + hexString; codecStrategy = null; } public String getURL() { int portNum = port; if(portNum < 0) portNum += 65536; return "iiop://" + host + ":" + portNum + "/" + objectKey; } public String getIOR() { return ior; } public FIPA.MTS getObject() { return FIPA.MTSHelper.narrow(orb.string_to_object(ior)); } private static abstract class CDRCodec { private static final char[] HEX = { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; protected byte[] readBuffer; protected StringBuffer writeBuffer; protected int readIndex = 0; protected int writeIndex = 0; protected CDRCodec(String hexString) { // Put all Hex digits into a byte array readBuffer = bytesFromHexString(hexString); readIndex = 1; writeBuffer = new StringBuffer(255); } protected CDRCodec(byte[] hexDigits) { readBuffer = new byte[hexDigits.length]; System.arraycopy(hexDigits, 0, readBuffer, 0, readBuffer.length); readIndex = 1; writeBuffer = new StringBuffer(255); } public String writtenString() { return new String(writeBuffer); } public byte[] writtenBytes() { return bytesFromHexString(new String(writeBuffer)); } public byte readOctet() { return readBuffer[readIndex++]; } public byte[] readOctetSequence() { int seqLen = readLong(); byte[] result = new byte[seqLen]; System.arraycopy(readBuffer, readIndex, result, 0, seqLen); readIndex += seqLen; return result; } public String readString() { int strLen = readLong(); // This includes '\0' terminator String result = new String(readBuffer, readIndex, strLen - 1); readIndex += strLen; return result; } // These depend on endianness, so are deferred to subclasses public abstract short readShort(); // 16 bits public abstract int readLong(); // 32 bits public abstract long readLongLong(); // 64 bits // Writes a couple of hexadecimal digits representing the given byte. // All other marshalling operations ultimately use this method to modify // the write buffer public void writeOctet(byte b) { char[] digits = new char[2]; digits[0] = HEX[(b & 0xF0) >> 4]; // High nibble digits[1] = HEX[b & 0x0F]; // Low nibble writeBuffer.append(digits); writeIndex++; } public void writeOctetSequence(byte[] seq) { int seqLen = seq.length; writeLong(seqLen); for(int i = 0; i < seqLen; i++) writeOctet(seq[i]); } public void writeString(String s) { int strLen = s.length() + 1; // This includes '\0' terminator writeLong(strLen); byte[] bytes = s.getBytes(); for(int i = 0; i < s.length(); i++) writeOctet(bytes[i]); writeOctet((byte)0x00); } // These depend on endianness, so are deferred to subclasses public abstract void writeShort(short s); // 16 bits public abstract void writeLong(int i); // 32 bits public abstract void writeLongLong(long l); // 64 bits protected void setReadAlignment(int align) { while((readIndex % align) != 0) readIndex++; } protected void setWriteAlignment(int align) { while(writeIndex % align != 0) writeOctet((byte)0x00); } private byte[] bytesFromHexString(String hexString) { int hexLen = hexString.length() / 2; byte[] result = new byte[hexLen]; for(int i = 0; i < hexLen; i ++) { String currentDigit = hexString.substring(2*i, 2*(i + 1)); Short s = Short.valueOf(currentDigit, 16); result[i] = s.byteValue(); } return result; } } // End of CDRCodec class private static class BigEndianCodec extends CDRCodec { public BigEndianCodec(String ior) { super(ior); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public BigEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)((readBuffer[readIndex++] << 8) + readBuffer[readIndex++]); return result; } public int readLong() { setReadAlignment(4); int result = (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public long readLongLong() { setReadAlignment(8); long result = (readBuffer[readIndex++] << 56) + (readBuffer[readIndex++] << 48); result += (readBuffer[readIndex++] << 40) + (readBuffer[readIndex++] << 32); result += (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)((s & 0xFF00) >> 8)); writeOctet((byte)(s & 0x00FF)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)((i & 0xFF000000) >> 24)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)(i & 0x000000FF)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)(l & 0x00000000000000FFL)); } } // End of BigEndianCodec class private static class LittleEndianCodec extends CDRCodec { public LittleEndianCodec(String ior) { super(ior); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public LittleEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)(readBuffer[readIndex++] + (readBuffer[readIndex++] << 8)); return result; } public int readLong() { setReadAlignment(4); int result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8) + (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); return result; } public long readLongLong() { setReadAlignment(8); long result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8); result += (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); result += (readBuffer[readIndex++] << 32) + (readBuffer[readIndex++] << 40); result += (readBuffer[readIndex++] << 48) + (readBuffer[readIndex++] << 56); return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)(s & 0x00FF)); writeOctet((byte)((s & 0xFF00) >> 8)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)(i & 0x000000FF)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0xFF000000) >> 24)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)(l & 0x00000000000000FFL)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); } } // End of LittleEndianCodec class public String getProto() { return "iiop"; } public String getHost() { return host; } public String getPort() { return Short.toString(port); } public String getFile() { return objectKey; } public String getAnchor() { return ""; } } // End of IIOPAddress class
package im.actor.core.js; import com.google.gwt.core.client.JsArray; import im.actor.core.*; import im.actor.core.api.ApiAuthSession; import im.actor.core.entity.MentionFilterResult; import im.actor.core.entity.Peer; import im.actor.core.js.entity.*; import im.actor.core.js.modules.JsBindedValueCallback; import im.actor.core.js.providers.JsNotificationsProvider; import im.actor.core.js.providers.JsPhoneBookProvider; import im.actor.core.js.utils.HtmlMarkdownUtils; import im.actor.core.js.utils.IdentityUtils; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.CommandCallback; import im.actor.core.viewmodel.UserVM; import im.actor.runtime.Log; import im.actor.runtime.Storage; import im.actor.runtime.js.JsFileSystemProvider; import im.actor.runtime.js.fs.JsBlob; import im.actor.runtime.js.fs.JsFile; import im.actor.runtime.js.mvvm.JsDisplayListCallback; import im.actor.runtime.js.utils.JsPromise; import im.actor.runtime.js.utils.JsPromiseExecutor; import im.actor.runtime.markdown.MarkdownParser; import org.timepedia.exporter.client.Export; import org.timepedia.exporter.client.ExportPackage; import org.timepedia.exporter.client.Exportable; import java.util.List; @ExportPackage("actor") @Export("ActorApp") public class JsFacade implements Exportable { private static final String TAG = "JsMessenger"; private static final String APP_NAME = "Actor Web App"; private static final int APP_ID = 3; private static final String APP_KEY = "278f13e07eee8398b189bced0db2cf66703d1746e2b541d85f5b42b1641aae0e"; private static final String[] EndpointsProduction = { "wss://front1-ws-mtproto-api-rev2.actor.im/", "wss://front2-ws-mtproto-api-rev2.actor.im/" }; private static final String[] EndpointsDev1 = { "wss://front1-ws-mtproto-api-rev2-dev1.actor.im/" }; private JsMessenger messenger; private JsFileSystemProvider provider; @Export public static JsFacade production() { return new JsFacade(EndpointsProduction); } @Export public static JsFacade dev1() { return new JsFacade(EndpointsDev1); } @Export public JsFacade() { this(EndpointsProduction); } @Export public JsFacade(String[] endpoints) { provider = (JsFileSystemProvider) Storage.getFileSystemRuntime(); String clientName = IdentityUtils.getClientName(); String uniqueId = IdentityUtils.getUniqueId(); ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.setApiConfiguration(new ApiConfiguration(APP_NAME, APP_ID, APP_KEY, clientName, uniqueId)); configuration.setPhoneBookProvider(new JsPhoneBookProvider()); configuration.setNotificationProvider(new JsNotificationsProvider()); // Is Web application configuration.setPlatformType(PlatformType.WEB); // Device Category // Only Desktop is supported for JS library configuration.setDeviceCategory(DeviceCategory.DESKTOP); // Adding endpoints for (String endpoint : endpoints) { configuration.addEndpoint(endpoint); } messenger = new JsMessenger(configuration.build()); Log.d(TAG, "JsMessenger created"); } public boolean isLoggedIn() { return messenger.isLoggedIn(); } public int getUid() { return messenger.myUid(); } public boolean isElectron() { return messenger.isElectron(); } // Auth public String getAuthState() { return Enums.convert(messenger.getAuthState()); } public String getAuthPhone() { return "" + messenger.getAuthPhone(); } public void requestSms(String phone, final JsAuthSuccessClosure success, final JsAuthErrorClosure error) { try { long res = Long.parseLong(phone); messenger.requestStartPhoneAuth(res).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { success.onResult(Enums.convert(res)); } @Override public void onError(Exception e) { String tag = "INTERNAL_ERROR"; String message = "Internal error"; boolean canTryAgain = false; if (e instanceof RpcException) { tag = ((RpcException) e).getTag(); message = e.getMessage(); canTryAgain = ((RpcException) e).isCanTryAgain(); } error.onError(tag, message, canTryAgain, getAuthState()); } }); } catch (Exception e) { Log.e(TAG, e); im.actor.runtime.Runtime.postToMainThread(new Runnable() { @Override public void run() { error.onError("PHONE_NUMBER_INVALID", "Invalid phone number", false, getAuthState()); } }); } } public void sendCode(String code, final JsAuthSuccessClosure success, final JsAuthErrorClosure error) { try { messenger.validateCode(code).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { success.onResult(Enums.convert(res)); } @Override public void onError(Exception e) { String tag = "INTERNAL_ERROR"; String message = "Internal error"; boolean canTryAgain = false; if (e instanceof RpcException) { tag = ((RpcException) e).getTag(); message = e.getMessage(); canTryAgain = ((RpcException) e).isCanTryAgain(); } error.onError(tag, message, canTryAgain, getAuthState()); } }); } catch (Exception e) { e.printStackTrace(); im.actor.runtime.Runtime.postToMainThread(new Runnable() { @Override public void run() { error.onError("PHONE_CODE_INVALID", "Invalid code number", false, getAuthState()); } }); } } public void signUp(String name, final JsAuthSuccessClosure success, final JsAuthErrorClosure error) { messenger.signUp(name, null, null).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { success.onResult(Enums.convert(res)); } @Override public void onError(Exception e) { String tag = "INTERNAL_ERROR"; String message = "Internal error"; boolean canTryAgain = false; if (e instanceof RpcException) { tag = ((RpcException) e).getTag(); message = e.getMessage(); canTryAgain = ((RpcException) e).isCanTryAgain(); } error.onError(tag, message, canTryAgain, getAuthState()); } }); } public JsPromise loadSessions() { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.loadSessions().start(new CommandCallback<List<ApiAuthSession>>() { @Override public void onResult(List<ApiAuthSession> res) { JsArray<JsAuthSession> jsSessions = JsArray.createArray().cast(); for (ApiAuthSession session : res) { jsSessions.push(JsAuthSession.create(session)); } resolve(jsSessions); } @Override public void onError(Exception e) { Log.e(TAG, e); reject(e.getMessage()); } }); } }); } public JsPromise terminateSession(final int id) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.terminateSession(id).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { resolve(res); } @Override public void onError(Exception e) { Log.e(TAG, e); reject(e.getMessage()); } }); } }); } public JsPromise terminateAllSessions() { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.terminateAllSessions().start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { resolve(res); } @Override public void onError(Exception e) { Log.e(TAG, e); reject(e.getMessage()); } }); } }); } // Dialogs public void bindDialogs(JsDisplayListCallback<JsDialog> callback) { if (callback == null) { return; } messenger.getSharedDialogList().subscribe(callback); } public void unbindDialogs(JsDisplayListCallback<JsDialog> callback) { if (callback == null) { return; } messenger.getSharedDialogList().unsubscribe(callback); } // Contacts public void bindContacts(JsDisplayListCallback<JsContact> callback) { if (callback == null) { return; } messenger.getSharedContactList().subscribe(callback); } public void unbindContacts(JsDisplayListCallback<JsContact> callback) { if (callback == null) { return; } messenger.getSharedContactList().unsubscribe(callback); } // Chats public void bindChat(JsPeer peer, JsDisplayListCallback<JsMessage> callback) { if (callback == null) { return; } messenger.getSharedChatList(peer.convert()).subscribeInverted(callback); } public void unbindChat(JsPeer peer, JsDisplayListCallback<JsMessage> callback) { if (callback == null) { return; } messenger.getSharedChatList(peer.convert()).unsubscribeInverted(callback); } public void onMessageShown(JsPeer peer, JsMessage message) { if (message.isOnServer()) { messenger.onMessageShown(peer.convert(), Long.parseLong(message.getSortKey())); } } public JsPromise deleteChat(final JsPeer peer) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.deleteChat(peer.convert()).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "deleteChat:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "deleteChat:error"); reject(e.getMessage()); } }); } }); } public JsPromise clearChat(final JsPeer peer) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.clearChat(peer.convert()).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "clearChat:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "clearChat:error"); reject(e.getMessage()); } }); } }); } // Peers public JsPeer getUserPeer(int uid) { return JsPeer.create(Peer.user(uid)); } public JsPeer getGroupPeer(int gid) { return JsPeer.create(Peer.group(gid)); } // Users public JsUser getUser(int uid) { return messenger.getJsUser(uid).get(); } public void bindUser(int uid, JsBindedValueCallback callback) { if (callback == null) { return; } messenger.getJsUser(uid).subscribe(callback); } public void unbindUser(int uid, JsBindedValueCallback callback) { if (callback == null) { return; } messenger.getJsUser(uid).unsubscribe(callback); } // Groups public JsGroup getGroup(int gid) { return messenger.getJsGroup(gid).get(); } public void bindGroup(int gid, JsBindedValueCallback callback) { if (callback == null) { return; } messenger.getJsGroup(gid).subscribe(callback); } public void unbindGroup(int gid, JsBindedValueCallback callback) { if (callback == null) { return; } messenger.getJsGroup(gid).unsubscribe(callback); } // Actions public void sendMessage(JsPeer peer, String text) { messenger.sendMessageWithMentionsDetect(peer.convert(), text); } public void sendMarkdownMessage(JsPeer peer, String text, String markdownText) { messenger.sendMessageWithMentionsDetect(peer.convert(), text, markdownText); } public void sendFile(JsPeer peer, JsFile file) { String descriptor = provider.registerUploadFile(file); messenger.sendDocument(peer.convert(), file.getName(), file.getMimeType(), descriptor); } public void sendPhoto(final JsPeer peer, final JsFile file) { messenger.sendPhoto(peer.convert(), file); } public void sendClipboardPhoto(final JsPeer peer, final JsBlob blob) { messenger.sendClipboardPhoto(peer.convert(), blob); } // Drafts public void saveDraft(JsPeer peer, String text) { messenger.saveDraft(peer.convert(), text); } public String loadDraft(JsPeer peer) { return messenger.loadDraft(peer.convert()); } public JsArray<JsMentionFilterResult> findMentions(int gid, String query) { List<MentionFilterResult> res = messenger.findMentions(gid, query); JsArray<JsMentionFilterResult> mentions = JsArray.createArray().cast(); for (MentionFilterResult m : res) { mentions.push(JsMentionFilterResult.create(m)); } return mentions; } // Typing public void onTyping(JsPeer peer) { messenger.onTyping(peer.convert()); } public JsTyping getTyping(JsPeer peer) { return messenger.getTyping(peer.convert()).get(); } public void bindTyping(JsPeer peer, JsBindedValueCallback callback) { messenger.getTyping(peer.convert()).subscribe(callback); } public void unbindTyping(JsPeer peer, JsBindedValueCallback callback) { messenger.getTyping(peer.convert()).unsubscribe(callback); } // Updating state public void bindConnectState(JsBindedValueCallback callback) { messenger.getOnlineStatus().subscribe(callback); } public void unbindConnectState(JsBindedValueCallback callback) { messenger.getOnlineStatus().unsubscribe(callback); } public void bindGlobalCounter(JsBindedValueCallback callback) { messenger.getGlobalCounter().subscribe(callback); } public void unbindGlobalCounter(JsBindedValueCallback callback) { messenger.getGlobalCounter().unsubscribe(callback); } public void bindTempGlobalCounter(JsBindedValueCallback callback) { messenger.getTempGlobalCounter().subscribe(callback); } public void unbindTempGlobalCounter(JsBindedValueCallback callback) { messenger.getTempGlobalCounter().unsubscribe(callback); } // Events public void onAppVisible() { messenger.onAppVisible(); } public void onAppHidden() { messenger.onAppHidden(); } public void onConversationOpen(JsPeer peer) { messenger.onConversationOpen(peer.convert()); } public void onConversationClosed(JsPeer peer) { messenger.onConversationClosed(peer.convert()); } public void onDialogsOpen() { messenger.onDialogsOpen(); } public void onDialogsClosed() { messenger.onDialogsClosed(); } public void onProfileOpen(int uid) { messenger.onProfileOpen(uid); } public void onProfileClosed(int uid) { messenger.onProfileClosed(uid); } public void onDialogsEnd() { messenger.loadMoreDialogs(); } public void onChatEnd(JsPeer peer) { messenger.loadMoreHistory(peer.convert()); } // Profile public JsPromise editMyName(final String newName) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.editMyName(newName).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "editMyName:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "editMyName:error"); reject(e.getMessage()); } }); } }); } public JsPromise editMyNick(final String newNick) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.editMyNick(newNick).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "editMyNick:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "editMyNick:error"); reject(e.getMessage()); } }); } }); } public JsPromise editMyAbout(final String newAbout) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.editMyAbout(newAbout).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "editMyAbout:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "editMyAbout:error"); reject(e.getMessage()); } }); } }); } public void editMyAvatar(final JsFile file) { String descriptor = provider.registerUploadFile(file); messenger.changeMyAvatar(descriptor); } public JsPromise editName(final int uid, final String newName) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.editName(uid, newName).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "editName:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "editName:error"); reject(e.getMessage()); } }); } }); } public JsPromise joinGroupViaLink(final String url) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.joinGroupViaLink(url).start(new CommandCallback<Integer>() { @Override public void onResult(Integer res) { Log.d(TAG, "joinGroupViaLink:result"); resolve(JsPeer.create(Peer.group(res))); } @Override public void onError(Exception e) { Log.d(TAG, "joinGroupViaLink:error"); reject(e.getMessage()); } }); } }); } public JsPromise editGroupTitle(final int gid, final String newTitle) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.editGroupTitle(gid, newTitle).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "editGroupTitle:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "editGroupTitle:error"); reject(e.getMessage()); } }); } }); } public JsPromise createGroup(final String title, final JsFile file, final int[] uids) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { String avatarDescriptor = provider.registerUploadFile(file); //noinspection ConstantConditions messenger.createGroup(title, avatarDescriptor, uids).start(new CommandCallback<Integer>() { @Override public void onResult(Integer res) { Log.d(TAG, "createGroup:result"); resolve(JsPeer.create(Peer.group(res))); } @Override public void onError(Exception e) { Log.d(TAG, "createGroup:error"); reject(e.getMessage()); } }); } }); } public JsPromise inviteMember(final int gid, final int uid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.inviteMember(gid, uid).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "inviteMember:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "inviteMember:error"); reject(e.getMessage()); } }); } }); } public JsPromise kickMember(final int gid, final int uid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.kickMember(gid, uid).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "kickMember:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "kickMember:error"); reject(e.getMessage()); } }); } }); } public JsPromise leaveGroup(final int gid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.leaveGroup(gid).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "leaveGroup:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "leaveGroup:error"); reject(e.getMessage()); } }); } }); } public JsPromise getIntegrationToken(final int gid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.requestIntegrationToken(gid).start(new CommandCallback<String>() { @Override public void onResult(String res) { Log.d(TAG, "getIntegrationToken:result"); resolve(res); } @Override public void onError(Exception e) { Log.d(TAG, "getIntegrationToken:error"); reject(e.getMessage()); } }); } }); } public JsPromise revokeIntegrationToken(final int gid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.revokeIntegrationToken(gid).start(new CommandCallback<String>() { @Override public void onResult(String res) { Log.d(TAG, "revokeIntegrationToken:result"); resolve(res); } @Override public void onError(Exception e) { Log.d(TAG, "revokeIntegrationToken:error"); reject(e.getMessage()); } }); } }); } public JsPromise getInviteLink(final int gid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.requestInviteLink(gid).start(new CommandCallback<String>() { @Override public void onResult(String res) { Log.d(TAG, "getInviteLink:result"); resolve(res); } @Override public void onError(Exception e) { Log.d(TAG, "getInviteLink:error"); reject(e.getMessage()); } }); } }); } public JsPromise revokeInviteLink(final int gid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.revokeInviteLink(gid).start(new CommandCallback<String>() { @Override public void onResult(String res) { Log.d(TAG, "revokeInviteLink:result"); resolve(res); } @Override public void onError(Exception e) { Log.d(TAG, "revokeInviteLink:error"); reject(e.getMessage()); } }); } }); } public JsPromise addContact(final int uid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.addContact(uid).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "addContact:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "addContact:error"); reject(e.getMessage()); } }); } }); } public JsPromise findUsers(final String query) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { messenger.findUsers(query).start(new CommandCallback<UserVM[]>() { @Override public void onResult(UserVM[] users) { Log.d(TAG, "findUsers:result"); JsArray<JsUser> jsUsers = JsArray.createArray().cast(); for (UserVM user : users) { jsUsers.push(messenger.getJsUser(user.getId()).get()); } resolve(jsUsers); } @Override public void onError(Exception e) { Log.d(TAG, "findUsers:error"); reject(e.getMessage()); } }); } }); } public JsPromise removeContact(final int uid) { return JsPromise.create(new JsPromiseExecutor() { @Override public void execute() { //noinspection ConstantConditions messenger.removeContact(uid).start(new CommandCallback<Boolean>() { @Override public void onResult(Boolean res) { Log.d(TAG, "removeContact:result"); resolve(); } @Override public void onError(Exception e) { Log.d(TAG, "removeContact:error"); reject(e.getMessage()); } }); } }); } // Settings public void changeNotificationsEnabled(JsPeer peer, boolean isEnabled) { messenger.changeNotificationsEnabled(peer.convert(), isEnabled); } public boolean isNotificationsEnabled(JsPeer peer) { return messenger.isNotificationsEnabled(peer.convert()); } public boolean isSendByEnterEnabled() { return messenger.isSendByEnterEnabled(); } public void changeSendByEnter(boolean sendByEnter) { messenger.changeSendByEnter(sendByEnter); } public boolean isGroupsNotificationsEnabled() { return messenger.isGroupNotificationsEnabled(); } public void changeGroupNotificationsEnabled(boolean enabled) { messenger.changeGroupNotificationsEnabled(enabled); } public boolean isOnlyMentionNotifications() { return messenger.isGroupNotificationsOnlyMentionsEnabled(); } public void changeIsOnlyMentionNotifications(boolean enabled) { messenger.changeGroupNotificationsOnlyMentionsEnabled(enabled); } public boolean isSoundEffectsEnabled() { return messenger.isConversationTonesEnabled(); } public boolean isShowNotificationsTextEnabled() { return messenger.isShowNotificationsText(); } public void changeIsShowNotificationTextEnabled(boolean value) { messenger.changeShowNotificationTextEnabled(value); } public void changeSoundEffectsEnabled(boolean enabled) { messenger.changeConversationTonesEnabled(enabled); } public String renderMarkdown(final String markdownText) { try { return HtmlMarkdownUtils.processText(markdownText, MarkdownParser.MODE_FULL); } catch (Exception e) { Log.e("Markdown", e); return "[Error while processing text]"; } } }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.jme.model; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import org.lwjgl.opengl.GLContext; import com.jme.bounding.BoundingVolume; import com.jme.math.Matrix4f; import com.jme.math.Vector3f; import com.jme.renderer.Renderer; import com.jme.scene.Spatial; import com.jme.scene.TriMesh; import com.jme.scene.VBOInfo; import com.jme.scene.batch.SharedBatch; import com.jme.scene.batch.TriangleBatch; import com.jme.scene.state.GLSLShaderObjectsState; import com.jme.scene.state.RenderState; import com.jme.system.DisplaySystem; import com.jme.util.ShaderAttribute; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.InputCapsule; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; import com.jme.util.geom.BufferUtils; import com.samskivert.util.ArrayUtil; import com.samskivert.util.HashIntMap; import com.samskivert.util.ListUtil; import com.threerings.jme.Log; import com.threerings.jme.util.JmeUtil; import com.threerings.jme.util.ShaderCache; /** * A triangle mesh that deforms according to a bone hierarchy. */ public class SkinMesh extends ModelMesh { /** The maximum number of bone matrices that we can use for hardware skinning. */ public static final int MAX_SHADER_BONE_COUNT = 32; /** The maximum number of bones influencing a single vertex for hardware skinning. */ public static final int MAX_SHADER_BONES_PER_VERTEX = 4; /** Represents the vertex weights of a group of vertices influenced by the * same set of bones. */ public static class WeightGroup implements Savable { /** The number of vertices in this weight group. */ public int vertexCount; /** The bones influencing this group. */ public Bone[] bones; /** The array of interleaved weights (of length <code>vertexCount * * boneIndices.length</code>): weights for first vertex, weights for * second, etc. */ public float[] weights; /** * Rebinds this weight group for a prototype instance. * * @param bmap the mapping from prototype to instance bones */ public WeightGroup rebind (HashMap<Bone, Bone> bmap) { WeightGroup wgroup = new WeightGroup(); wgroup.vertexCount = vertexCount; wgroup.bones = new Bone[bones.length]; for (int ii = 0; ii < bones.length; ii++) { wgroup.bones[ii] = bmap.get(bones[ii]); } wgroup.weights = weights; return wgroup; } // documentation inherited public Class getClassTag () { return getClass(); } // documentation inherited public void read (JMEImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); vertexCount = capsule.readInt("vertexCount", 0); bones = ArrayUtil.copy(capsule.readSavableArray("bones", null), new Bone[0]); weights = capsule.readFloatArray("weights", null); } // documentation inherited public void write (JMEExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(vertexCount, "vertexCount", 0); capsule.write(bones, "bones", null); capsule.write(weights, "weights", null); } private static final long serialVersionUID = 1; } /** Represents a bone that influences the mesh. */ public static class Bone implements Savable { /** The node that defines the bone's position. */ public ModelNode node; /** The inverse of the bone's model space reference transform. */ public transient Matrix4f invRefTransform; /** The bone's current transform in model space. */ public transient Matrix4f transform; public Bone (ModelNode node) { this(); this.node = node; } public Bone () { transform = new Matrix4f(); } /** * Rebinds this bone for a prototype instance. * * @param pnodes a mapping from prototype nodes to instance nodes */ public Bone rebind (HashMap pnodes) { Bone bone = new Bone((ModelNode)pnodes.get(node)); bone.invRefTransform = invRefTransform; bone.transform = new Matrix4f(); return bone; } // documentation inherited public Class getClassTag () { return getClass(); } // documentation inherited public void read (JMEImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); node = (ModelNode)capsule.readSavable("node", null); } // documentation inherited public void write (JMEExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(node, "node", null); } private static final long serialVersionUID = 1; } /** * No-arg constructor for deserialization. */ public SkinMesh () { } /** * Creates an empty mesh. */ public SkinMesh (String name) { super(name); } /** * Sets the array of weight groups that determine how bones affect * each vertex. */ public void setWeightGroups (WeightGroup[] weightGroups) { _weightGroups = weightGroups; // compile a list of all referenced bones HashSet<Bone> bones = new HashSet<Bone>(); for (WeightGroup group : weightGroups) { Collections.addAll(bones, group.bones); } _bones = bones.toArray(new Bone[bones.size()]); } @Override // documentation inherited public void reconstruct ( FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, FloatBuffer textures, IntBuffer indices) { super.reconstruct(vertices, normals, colors, textures, indices); // initialize the quantized frame table _frames = new HashIntMap<Object>(); } @Override // documentation inherited public Spatial putClone (Spatial store, Model.CloneCreator properties) { SkinMesh mstore = (SkinMesh)properties.originalToCopy.get(this); if (mstore != null) { return mstore; } else if (store == null) { mstore = new SkinMesh(getName()); } else { mstore = (SkinMesh)store; } GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState( RenderState.RS_GLSL_SHADER_OBJECTS); if (sstate == null) { // vertices and normals must be cloned if not using a shader properties.removeProperty("vertices"); properties.removeProperty("normals"); } properties.removeProperty("displaylistid"); super.putClone(mstore, properties); if (sstate == null) { properties.addProperty("vertices"); properties.addProperty("normals"); } else { // for the shader, we must create a separate instance with different uniforms GLSLShaderObjectsState msstate = DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState(); msstate.setProgramID(sstate.getProgramID()); msstate.attribs = sstate.attribs; mstore.setRenderState(msstate); } properties.addProperty("displaylistid"); mstore._frames = _frames; mstore._useDisplayLists = _useDisplayLists; mstore._invRefTransform = _invRefTransform; mstore._bones = new Bone[_bones.length]; HashMap<Bone, Bone> bmap = new HashMap<Bone, Bone>(); for (int ii = 0; ii < _bones.length; ii++) { bmap.put(_bones[ii], mstore._bones[ii] = _bones[ii].rebind(properties.originalToCopy)); } mstore._weightGroups = new WeightGroup[_weightGroups.length]; for (int ii = 0; ii < _weightGroups.length; ii++) { mstore._weightGroups[ii] = _weightGroups[ii].rebind(bmap); } mstore._ovbuf = _ovbuf; mstore._onbuf = _onbuf; mstore._vbuf = (sstate == null) ? new float[_vbuf.length] : _vbuf; mstore._nbuf = (sstate == null) ? new float[_nbuf.length] : _nbuf; return mstore; } @Override // documentation inherited public void read (JMEImporter im) throws IOException { super.read(im); InputCapsule capsule = im.getCapsule(this); setWeightGroups(ArrayUtil.copy(capsule.readSavableArray( "weightGroups", null), new WeightGroup[0])); } @Override // documentation inherited public void write (JMEExporter ex) throws IOException { super.write(ex); OutputCapsule capsule = ex.getCapsule(this); capsule.write(_weightGroups, "weightGroups", null); } @Override // documentation inherited public void expandModelBounds () { BoundingVolume obound = (BoundingVolume)getBatch(0).getModelBound().clone(null); updateModelBound(); getBatch(0).getModelBound().mergeLocal(obound); } @Override // documentation inherited public void setReferenceTransforms () { _invRefTransform = new Matrix4f(); if (parent instanceof ModelNode) { Matrix4f transform = new Matrix4f(); JmeUtil.setTransform(getLocalTranslation(), getLocalRotation(), getLocalScale(), transform); ((ModelNode)parent).getModelTransform().mult(transform, _invRefTransform); _invRefTransform.invertLocal(); } for (Bone bone : _bones) { bone.invRefTransform = _invRefTransform.mult(bone.node.getModelTransform()).invert(); } } @Override // documentation inherited public void lockStaticMeshes ( Renderer renderer, boolean useVBOs, boolean useDisplayLists) { // we can use VBOs for color, texture, and indices if (useVBOs && renderer.supportsVBO()) { VBOInfo vboinfo = new VBOInfo(false); vboinfo.setVBOColorEnabled(true); vboinfo.setVBOTextureEnabled(true); vboinfo.setVBOIndexEnabled(!_translucent); setVBOInfo(vboinfo); // use VBOs for shader attributes GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState( RenderState.RS_GLSL_SHADER_OBJECTS); if (sstate != null) { for (ShaderAttribute attrib : sstate.attribs.values()) { attrib.useVBO = true; } } } _useDisplayLists = useDisplayLists && !_translucent; } @Override // documentation inherited public void configureShaders (ShaderCache scache) { if (_disableShaders || !GLContext.getCapabilities().GL_ARB_vertex_shader || _bones.length > MAX_SHADER_BONE_COUNT) { return; } int bonesPerVertex = 0; for (WeightGroup group : _weightGroups) { bonesPerVertex = Math.max(group.bones.length, bonesPerVertex); } if (bonesPerVertex > MAX_SHADER_BONES_PER_VERTEX) { return; } GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState( RenderState.RS_GLSL_SHADER_OBJECTS); if (sstate == null) { sstate = DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState(); setShaderAttributes(sstate, bonesPerVertex); setRenderState(sstate); } if (!scache.configureState(sstate, "media/jme/skin.vert", null, "MAX_BONE_COUNT " + MAX_SHADER_BONE_COUNT, "BONES_PER_VERTEX " + bonesPerVertex)) { clearRenderState(RenderState.RS_GLSL_SHADER_OBJECTS); _disableShaders = true; return; } } @Override // documentation inherited public void storeMeshFrame (int frameId, boolean blend) { _storeFrameId = frameId; _storeBlend = blend; } @Override // documentation inherited public void setMeshFrame (int frameId) { TriangleBatch batch = getBatch(0), tbatch = (TriangleBatch)_frames.get(frameId); if (batch instanceof SharedBatch) { ((SharedBatch)batch).setTarget(tbatch); } else { clearBatches(); addBatch(new SharedBatch(tbatch)); getBatch(0).updateRenderState(); } } @Override // documentation inherited public void blendMeshFrames (int frameId1, int frameId2, float alpha) { BlendFrame frame1 = (BlendFrame)_frames.get(frameId1), frame2 = (BlendFrame)_frames.get(frameId2); frame1.blend(frame2, alpha, _vbuf, _nbuf); FloatBuffer vbuf = getVertexBuffer(0), nbuf = getNormalBuffer(0); vbuf.rewind(); vbuf.put(_vbuf); nbuf.rewind(); nbuf.put(_nbuf); } @Override // documentation inherited public void updateWorldData (float time) { super.updateWorldData(time); if (_weightGroups == null || _storeFrameId == -1 || getCullMode() == CULL_ALWAYS) { return; } // update the bone transforms for (Bone bone : _bones) { _invRefTransform.mult(bone.node.getModelTransform(), bone.transform); bone.transform.multLocal(bone.invRefTransform); } // if we're using shaders, initialize the uniform variables with the bone transforms GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState( RenderState.RS_GLSL_SHADER_OBJECTS); if (sstate != null) { for (int ii = 0; ii < _bones.length; ii++) { sstate.setUniform("boneTransforms[" + ii + "]", _bones[ii].transform, true); } return; } // deform the mesh according to the positions of the bones (this code // is ugly as sin because it's optimized at a low level) Bone[] bones; int vertexCount, jj, kk, ww; float[] weights; Matrix4f m; float weight, ovx, ovy, ovz, onx, ony, onz, vx, vy, vz, nx, ny, nz; for (int ii = 0, bidx = 0; ii < _weightGroups.length; ii++) { vertexCount = _weightGroups[ii].vertexCount; bones = _weightGroups[ii].bones; weights = _weightGroups[ii].weights; for (jj = 0, ww = 0; jj < vertexCount; jj++) { ovx = _ovbuf[bidx]; ovy = _ovbuf[bidx + 1]; ovz = _ovbuf[bidx + 2]; onx = _onbuf[bidx]; ony = _onbuf[bidx + 1]; onz = _onbuf[bidx + 2]; vx = vy = vz = 0f; nx = ny = nz = 0f; for (kk = 0; kk < bones.length; kk++) { m = bones[kk].transform; weight = weights[ww++]; vx += (ovx*m.m00 + ovy*m.m01 + ovz*m.m02 + m.m03) * weight; vy += (ovx*m.m10 + ovy*m.m11 + ovz*m.m12 + m.m13) * weight; vz += (ovx*m.m20 + ovy*m.m21 + ovz*m.m22 + m.m23) * weight; nx += (onx*m.m00 + ony*m.m01 + onz*m.m02) * weight; ny += (onx*m.m10 + ony*m.m11 + onz*m.m12) * weight; nz += (onx*m.m20 + ony*m.m21 + onz*m.m22) * weight; } _vbuf[bidx] = vx; _vbuf[bidx + 1] = vy; _vbuf[bidx + 2] = vz; _nbuf[bidx++] = nx; _nbuf[bidx++] = ny; _nbuf[bidx++] = nz; } } // if skinning in real time, copy the data from arrays to buffers; // otherwise, store the mesh as an animation frame if (_storeFrameId == 0) { FloatBuffer vbuf = getVertexBuffer(0), nbuf = getNormalBuffer(0); vbuf.rewind(); vbuf.put(_vbuf); nbuf.rewind(); nbuf.put(_nbuf); } else { storeFrame(); _storeFrameId = -1; } } /** * Stores the current frame data for later use. */ protected void storeFrame () { if (_storeBlend) { _frames.put(_storeFrameId, new BlendFrame( (float[])_vbuf.clone(), (float[])_nbuf.clone())); } else { TriangleBatch batch = getBatch(0), tbatch = new TriangleBatch(); tbatch.setParentGeom(DUMMY_MESH); tbatch.setColorBuffer(batch.getColorBuffer()); int nunits = batch.getNumberOfUnits(); for (int ii = 0; ii < nunits; ii++) { tbatch.setTextureBuffer(batch.getTextureBuffer(ii), ii); } tbatch.setIndexBuffer(batch.getIndexBuffer()); tbatch.setVertexBuffer(BufferUtils.createFloatBuffer(_vbuf)); tbatch.setNormalBuffer(BufferUtils.createFloatBuffer(_nbuf)); VBOInfo ovboinfo = batch.getVBOInfo(); if (ovboinfo != null) { VBOInfo vboinfo = new VBOInfo(true); vboinfo.setVBOIndexEnabled(!_translucent); vboinfo.setVBOColorID(ovboinfo.getVBOColorID()); for (int ii = 0; ii < nunits; ii++) { vboinfo.setVBOTextureID(ii, ovboinfo.getVBOTextureID(ii)); } vboinfo.setVBOIndexID(ovboinfo.getVBOIndexID()); tbatch.setVBOInfo(vboinfo); } else if (_useDisplayLists) { tbatch.lockMeshes( DisplaySystem.getDisplaySystem().getRenderer()); } _frames.put(_storeFrameId, tbatch); } } @Override // documentation inherited protected void storeOriginalBuffers () { super.storeOriginalBuffers(); FloatBuffer vbuf = getVertexBuffer(0), nbuf = getNormalBuffer(0); vbuf.rewind(); nbuf.rewind(); FloatBuffer.wrap(_ovbuf = new float[vbuf.capacity()]).put(vbuf); FloatBuffer.wrap(_onbuf = new float[nbuf.capacity()]).put(nbuf); _vbuf = new float[_ovbuf.length]; _nbuf = new float[_onbuf.length]; } /** * Initializes the skin shader attributes (bone indices and weights) in the supplied state. */ protected void setShaderAttributes (GLSLShaderObjectsState sstate, int bonesPerVertex) { int size = getBatch(0).getVertexCount() * bonesPerVertex; ByteBuffer bibuf = BufferUtils.createByteBuffer(size); FloatBuffer bwbuf = BufferUtils.createFloatBuffer(size); for (WeightGroup group : _weightGroups) { byte[] indices = new byte[bonesPerVertex]; for (int ii = 0; ii < indices.length; ii++) { indices[ii] = (byte)((ii < group.bones.length) ? ListUtil.indexOf(_bones, group.bones[ii]) : 0); } for (int ii = 0, widx = 0; ii < group.vertexCount; ii++) { bibuf.put(indices); for (int jj = 0; jj < bonesPerVertex; jj++) { bwbuf.put((jj < group.bones.length) ? group.weights[widx++] : 0f); } } } bibuf.rewind(); bwbuf.rewind(); sstate.setAttributePointer("boneIndices", bonesPerVertex, false, false, 0, bibuf); sstate.setAttributePointer("boneWeights", bonesPerVertex, false, 0, bwbuf); } /** A stored frame used for linear blending. */ protected static class BlendFrame { /** The skinned vertex and normal values. */ public float[] vbuf, nbuf; public BlendFrame (float[] vbuf, float[] nbuf) { this.vbuf = vbuf; this.nbuf = nbuf; } public void blend ( BlendFrame next, float alpha, float[] rvbuf, float[] rnbuf) { float[] nvbuf = next.vbuf, nnbuf = next.nbuf; float ialpha = 1f - alpha; for (int ii = 0, nn = vbuf.length; ii < nn; ii++) { rvbuf[ii] = vbuf[ii] * ialpha + nvbuf[ii] * alpha; rnbuf[ii] = nbuf[ii] * ialpha + nnbuf[ii] * alpha; } } } /** Pre-skinned {@link TriangleBatch}es or {@link BlendFrame}s shared * between all instances corresponding to frame ids from * {@link #storeAnimationFrame}. */ protected HashIntMap<Object> _frames; /** Whether or to use display lists if VBOs are unavailable for quantized * meshes. */ protected boolean _useDisplayLists; /** The inverse of the model space reference transform. */ protected Matrix4f _invRefTransform; /** The groups of vertices influenced by different sets of bones. */ protected WeightGroup[] _weightGroups; /** The bones referenced by the weight groups. */ protected Bone[] _bones; /** The original (undeformed) vertex and normal buffers and the deformed * versions. */ protected float[] _onbuf, _ovbuf, _nbuf; /** The frame id to store on the next update. If 0, don't store any frame * and skin the mesh as normal. If -1, a frame has been stored and thus * skinning should only take place when further frames are requested. */ protected int _storeFrameId; /** Whether or not the stored frame id will be used for blending. */ protected boolean _storeBlend; /** Set if we determine that our shaders don't compile to prevent us from trying again. */ protected static boolean _disableShaders; /** A dummy mesh that simply hold transformation values. */ protected static final TriMesh DUMMY_MESH = new TriMesh(); private static final long serialVersionUID = 1; }
package org.bouncycastle.tsp.cms; import java.net.URL; import org.bouncycastle.asn1.DERBoolean; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.cms.Attributes; import org.bouncycastle.asn1.cms.MetaData; import org.bouncycastle.cms.CMSException; import org.bouncycastle.operator.DigestCalculator; public class CMSTimeStampedGenerator { protected MetaData metaData; protected URL dataUri; /** * Set the dataURL to be included in message. * * @param dataUri URL for the data the initial message imprint digest is based on. */ public void setDataUri(URL dataUri) { this.dataUri = dataUri; } /** * Set the MetaData for the generated message. * * @param hashProtected true if the MetaData should be included in first imprint calculation, false otherwise. * @param fileName optional file name, may be null. * @param mediaType optional media type, may be null. */ public void setMetaData(boolean hashProtected, String fileName, String mediaType) { setMetaData(hashProtected, fileName, mediaType, null); } /** * Set the MetaData for the generated message. * * @param hashProtected true if the MetaData should be included in first imprint calculation, false otherwise. * @param fileName optional file name, may be null. * @param mediaType optional media type, may be null. * @param attributes optional attributes, may be null. */ public void setMetaData(boolean hashProtected, String fileName, String mediaType, Attributes attributes) { DERUTF8String asn1FileName = null; if (fileName != null) { asn1FileName = new DERUTF8String(fileName); } DERIA5String asn1MediaType = null; if (mediaType != null) { asn1MediaType = new DERIA5String(mediaType); } setMetaData(hashProtected, asn1FileName, asn1MediaType, attributes); } private void setMetaData(boolean hashProtected, DERUTF8String fileName, DERIA5String mediaType, Attributes attributes) { this.metaData = new MetaData(new DERBoolean(hashProtected), fileName, mediaType, attributes); } /** * Initialise the passed in calculator with the MetaData for this message, if it is * required as part of the initial message imprint calculation. After initialisation the * calculator can then be used to calculate the initial message imprint digest for the first * timestamp. * * @param calculator the digest calculator to be initialised. * @throws CMSException if the MetaData is required and cannot be processed */ public void initialiseMessageImprintDigestCalculator(DigestCalculator calculator) throws CMSException { MetaDataUtil util = new MetaDataUtil(metaData); util.initialiseMessageImprintDigestCalculator(calculator); } }
package com.ecyrd.jspwiki.parser; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.*; import javax.xml.transform.Result; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.oro.text.GlobCompiler; import org.apache.oro.text.regex.*; import org.jdom.*; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.auth.WikiSecurityException; import com.ecyrd.jspwiki.auth.acl.Acl; import com.ecyrd.jspwiki.plugin.PluginException; import com.ecyrd.jspwiki.plugin.PluginManager; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.render.CleanTextRenderer; import com.ecyrd.jspwiki.render.RenderingManager; /** * Parses JSPWiki-style markup into a WikiDocument DOM tree. This class is the * heart and soul of JSPWiki : make sure you test properly anything that is added, * or else it breaks down horribly. * * @author Janne Jalkanen * @since 2.4 */ public class JSPWikiMarkupParser extends MarkupParser { /** Name of the outlink image; relative path to the JSPWiki directory. */ private static final String OUTLINK_IMAGE = "images/out.png"; /** The value for anchor element <tt>class</tt> attributes when used * for wiki page (normal) links. The value is "wikipage". */ public static final String CLASS_WIKIPAGE = "wikipage"; /** The value for anchor element <tt>class</tt> attributes when used * for edit page links. The value is "editpage". */ public static final String CLASS_EDITPAGE = "editpage"; /** The value for anchor element <tt>class</tt> attributes when used * for interwiki page links. The value is "interwiki". */ public static final String CLASS_INTERWIKI = "interwiki"; protected static final int READ = 0; protected static final int EDIT = 1; protected static final int EMPTY = 2; // Empty message protected static final int LOCAL = 3; protected static final int LOCALREF = 4; protected static final int IMAGE = 5; protected static final int EXTERNAL = 6; protected static final int INTERWIKI = 7; protected static final int IMAGELINK = 8; protected static final int IMAGEWIKILINK = 9; protected static final int ATTACHMENT = 10; private static Logger log = Logger.getLogger( JSPWikiMarkupParser.class ); private boolean m_isbold = false; private boolean m_isitalic = false; private boolean m_istable = false; private boolean m_isPre = false; private boolean m_isEscaping = false; private boolean m_isdefinition = false; private boolean m_isPreBlock = false; /** Contains style information, in multiple forms. */ private Stack m_styleStack = new Stack(); // general list handling private int m_genlistlevel = 0; private StringBuffer m_genlistBulletBuffer = new StringBuffer(10); // stores the # and * pattern private boolean m_allowPHPWikiStyleLists = true; private boolean m_isOpenParagraph = false; /** Keeps image regexp Patterns */ private List m_inlineImagePatterns; /** Parser for extended link functionality. */ private LinkParser m_linkParser = new LinkParser(); private PatternMatcher m_inlineMatcher = new Perl5Matcher(); /** Keeps track of any plain text that gets put in the Text nodes */ private StringBuffer m_plainTextBuf = new StringBuffer(20); private Element m_currentElement; /** * This property defines the inline image pattern. It's current value * is jspwiki.translatorReader.inlinePattern */ public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern"; /** If true, consider CamelCase hyperlinks as well. */ public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks"; /** If true, all hyperlinks are translated as well, regardless whether they are surrounded by brackets. */ public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris"; /** If true, all outward links (external links) have a small link image appended. */ public static final String PROP_USEOUTLINKIMAGE = "jspwiki.translatorReader.useOutlinkImage"; /** If true, all outward attachment info links have a small link image appended. */ public static final String PROP_USEATTACHMENTIMAGE = "jspwiki.translatorReader.useAttachmentImage"; /** If set to "true", all external links are tagged with 'rel="nofollow"' */ public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow"; /** If true, then considers CamelCase links as well. */ private boolean m_camelCaseLinks = false; /** If true, then generate special output for wysiwyg editing in certain cases */ private boolean m_wysiwygEditorMode = false; /** If true, consider URIs that have no brackets as well. */ // FIXME: Currently reserved, but not used. private boolean m_plainUris = false; /** If true, all outward links use a small link image. */ private boolean m_useOutlinkImage = true; private boolean m_useAttachmentImage = true; /** If true, allows raw HTML. */ private boolean m_allowHTML = false; private boolean m_useRelNofollow = false; private PatternCompiler m_compiler = new Perl5Compiler(); static final String WIKIWORD_REGEX = "(^|[[:^alnum:]]+)([[:upper:]]+[[:lower:]]+[[:upper:]]+[[:alnum:]]*|(http://|https://|mailto:)([A-Za-z0-9_/\\.\\+\\?\\ private PatternMatcher m_camelCaseMatcher = new Perl5Matcher(); private Pattern m_camelCasePattern; private int m_rowNum = 1; /** * The default inlining pattern. Currently "*.png" */ public static final String DEFAULT_INLINEPATTERN = "*.png"; /** * This list contains all IANA registered URI protocol * types as of September 2004 + a few well-known extra types. * * JSPWiki recognises all of them as external links. * * This array is sorted during class load, so you can just dump * here whatever you want in whatever order you want. */ static final String[] c_externalLinks = { "http:", "ftp:", "https:", "mailto:", "news:", "file:", "rtsp:", "mms:", "ldap:", "gopher:", "nntp:", "telnet:", "wais:", "prospero:", "z39.50s", "z39.50r", "vemmi:", "imap:", "nfs:", "acap:", "tip:", "pop:", "dav:", "opaquelocktoken:", "sip:", "sips:", "tel:", "fax:", "modem:", "soap.beep:", "soap.beeps", "xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:", "h323:", "ipp:", "tftp:", "mupdate:", "pres:", "im:", "mtqp", "smb:" }; private static final String INLINE_IMAGE_PATTERNS = "JSPWikiMarkupParser.inlineImagePatterns"; private static final String CAMELCASE_PATTERN = "JSPWikiMarkupParser.camelCasePattern"; private static String[] CLASS_TYPES = { CLASS_WIKIPAGE, CLASS_EDITPAGE, "", "footnote", "footnoteref", "", "external", CLASS_INTERWIKI, "external", CLASS_WIKIPAGE, "attachment" }; /** * This Comparator is used to find an external link from c_externalLinks. It * checks if the link starts with the other arraythingie. */ private static Comparator c_startingComparator = new StartingComparator(); static { Arrays.sort( c_externalLinks ); } /** * Creates a markup parser. */ public JSPWikiMarkupParser( WikiContext context, Reader in ) { super( context, in ); initialize(); } /** * @param engine The WikiEngine this reader is attached to. Is * used to figure out of a page exits. */ // FIXME: parsers should be pooled for better performance. private void initialize() { PatternCompiler compiler = new GlobCompiler(); List compiledpatterns; // We cache compiled patterns in the engine, since their creation is // really expensive compiledpatterns = (List)m_engine.getAttribute( INLINE_IMAGE_PATTERNS ); if( compiledpatterns == null ) { compiledpatterns = new ArrayList(20); Collection ptrns = getImagePatterns( m_engine ); // Make them into Regexp Patterns. Unknown patterns // are ignored. for( Iterator i = ptrns.iterator(); i.hasNext(); ) { try { compiledpatterns.add( compiler.compile( (String)i.next(), GlobCompiler.DEFAULT_MASK|GlobCompiler.READ_ONLY_MASK ) ); } catch( MalformedPatternException e ) { log.error("Malformed pattern in properties: ", e ); } } m_engine.setAttribute( INLINE_IMAGE_PATTERNS, compiledpatterns ); } m_inlineImagePatterns = Collections.unmodifiableList(compiledpatterns); m_camelCasePattern = (Pattern) m_engine.getAttribute( CAMELCASE_PATTERN ); if( m_camelCasePattern == null ) { try { m_camelCasePattern = m_compiler.compile( WIKIWORD_REGEX, Perl5Compiler.DEFAULT_MASK|Perl5Compiler.READ_ONLY_MASK ); } catch( MalformedPatternException e ) { log.fatal("Internal error: Someone put in a faulty pattern.",e); throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader"); } m_engine.setAttribute( CAMELCASE_PATTERN, m_camelCasePattern ); } // Set the properties. Properties props = m_engine.getWikiProperties(); String cclinks = (String)m_context.getPage().getAttribute( PROP_CAMELCASELINKS ); if( cclinks != null ) { m_camelCaseLinks = TextUtil.isPositive( cclinks ); } else { m_camelCaseLinks = TextUtil.getBooleanProperty( props, PROP_CAMELCASELINKS, m_camelCaseLinks ); } Boolean wysiwygVariable = (Boolean)m_context.getVariable( RenderingManager.WYSIWYG_EDITOR_MODE ); if( wysiwygVariable != null ) { m_wysiwygEditorMode = wysiwygVariable.booleanValue(); } m_plainUris = getLocalBooleanProperty( m_context, props, PROP_PLAINURIS, m_plainUris ); m_useOutlinkImage = getLocalBooleanProperty( m_context, props, PROP_USEOUTLINKIMAGE, m_useOutlinkImage ); m_useAttachmentImage = getLocalBooleanProperty( m_context, props, PROP_USEATTACHMENTIMAGE, m_useAttachmentImage ); m_allowHTML = getLocalBooleanProperty( m_context, props, MarkupParser.PROP_ALLOWHTML, m_allowHTML ); m_useRelNofollow = getLocalBooleanProperty( m_context, props, PROP_USERELNOFOLLOW, m_useRelNofollow ); if( m_engine.getUserManager().getUserDatabase() == null || m_engine.getAuthorizationManager() == null ) { disableAccessRules(); } m_context.getPage().setHasMetadata(); } /** * This is just a simple helper method which will first check the context * if there is already an override in place, and if there is not, * it will then check the given properties. * * @param context WikiContext to check first * @param props Properties to check next * @param key What key are we searching for? * @param defValue Default value for the boolean * @return True or false */ private static boolean getLocalBooleanProperty( WikiContext context, Properties props, String key, boolean defValue ) { Object bool = context.getVariable(key); if( bool != null ) { return TextUtil.isPositive( (String) bool ); } return TextUtil.getBooleanProperty( props, key, defValue ); } /** * Figure out which image suffixes should be inlined. * @return Collection of Strings with patterns. */ // FIXME: Does not belong here; should be elsewhere public static Collection getImagePatterns( WikiEngine engine ) { Properties props = engine.getWikiProperties(); ArrayList ptrnlist = new ArrayList(); for( Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); if( name.startsWith( PROP_INLINEIMAGEPTRN ) ) { String ptrn = TextUtil.getStringProperty( props, name, null ); ptrnlist.add( ptrn ); } } if( ptrnlist.size() == 0 ) { ptrnlist.add( DEFAULT_INLINEPATTERN ); } return ptrnlist; } /** * Returns link name, if it exists; otherwise it returns null. */ private String linkExists( String page ) { try { if( page == null || page.length() == 0 ) return null; return m_engine.getFinalPageName( page ); } catch( ProviderException e ) { log.warn("TranslatorReader got a faulty page name!",e); return page; // FIXME: What would be the correct way to go back? } } /** * Calls a transmutator chain. * * @param list Chain to call * @param text Text that should be passed to the mutate() method * of each of the mutators in the chain. * @return The result of the mutation. */ protected String callMutatorChain( Collection list, String text ) { if( list == null || list.size() == 0 ) { return text; } for( Iterator i = list.iterator(); i.hasNext(); ) { StringTransmutator m = (StringTransmutator) i.next(); text = m.mutate( m_context, text ); } return text; } /** * Calls the heading listeners. * * @param param A Heading object. */ protected void callHeadingListenerChain( Heading param ) { List list = m_headingListenerChain; for( Iterator i = list.iterator(); i.hasNext(); ) { HeadingListener h = (HeadingListener) i.next(); h.headingAdded( m_context, param ); } } /** * Creates a JDOM anchor element. Can be overridden to change the URL creation, * if you really know what you are doing. * * @param type One of the types above * @param link URL to which to link to * @param text Link text * @param section If a particular section identifier is required. * @return An A element. * @since 2.4.78 */ protected Element createAnchor(int type, String link, String text, String section) { Element el = new Element("a"); el.setAttribute("class",CLASS_TYPES[type]); el.setAttribute("href",link+section); el.addContent(text); return el; } private Element makeLink( int type, String link, String text, String section, Iterator attributes ) { Element el = null; if( text == null ) text = link; text = callMutatorChain( m_linkMutators, text ); section = (section != null) ? ("#"+section) : ""; // Make sure we make a link name that can be accepted // as a valid URL. if( link.length() == 0 ) { type = EMPTY; } switch(type) { case READ: el = createAnchor( READ, m_context.getURL(WikiContext.VIEW, link), text, section ); break; case EDIT: el = createAnchor( EDIT, m_context.getURL(WikiContext.EDIT,link), text, "" ); el.setAttribute("title","Create '"+link+"'"); break; case EMPTY: el = new Element("u").addContent(text); break; // These two are for local references - footnotes and // references to footnotes. // We embed the page name (or whatever WikiContext gives us) // to make sure the links are unique across Wiki. case LOCALREF: el = createAnchor( LOCALREF, "#ref-"+m_context.getName()+"-"+link, "["+text+"]", "" ); break; case LOCAL: el = new Element("a").setAttribute("class","footnote"); el.setAttribute("name", "ref-"+m_context.getName()+"-"+link.substring(1)); el.addContent("["+text+"]"); break; // With the image, external and interwiki types we need to // make sure nobody can put in Javascript or something else // annoying into the links themselves. We do this by preventing // a haxor from stopping the link name short with quotes in // fillBuffer(). case IMAGE: el = new Element("img").setAttribute("class","inline"); el.setAttribute("src",link); el.setAttribute("alt",text); break; case IMAGELINK: el = new Element("img").setAttribute("class","inline"); el.setAttribute("src",link); el.setAttribute("alt",text); el = createAnchor(IMAGELINK,text,"","").addContent(el); break; case IMAGEWIKILINK: String pagelink = m_context.getURL(WikiContext.VIEW,text); el = new Element("img").setAttribute("class","inline"); el.setAttribute("src",link); el.setAttribute("alt",text); el = createAnchor(IMAGEWIKILINK,pagelink,"","").addContent(el); break; case EXTERNAL: el = createAnchor( EXTERNAL, link, text, section ); if( m_useRelNofollow ) el.setAttribute("rel","nofollow"); break; case INTERWIKI: el = createAnchor( INTERWIKI, link, text, section ); break; case ATTACHMENT: String attlink = m_context.getURL( WikiContext.ATTACH, link ); String infolink = m_context.getURL( WikiContext.INFO, link ); String imglink = m_context.getURL( WikiContext.NONE, "images/attachment_small.png" ); el = createAnchor( ATTACHMENT, attlink, text, "" ); pushElement(el); popElement(el.getName()); if( m_useAttachmentImage ) { el = new Element("img").setAttribute("src",imglink); el.setAttribute("border","0"); el.setAttribute("alt","(info)"); el = new Element("a").setAttribute("href",infolink).addContent(el); } else { el = null; } break; default: break; } if( el != null && attributes != null ) { while( attributes.hasNext() ) { Attribute attr = (Attribute)attributes.next(); if( attr != null ) { el.setAttribute(attr); } } } if( el != null ) { flushPlainText(); m_currentElement.addContent( el ); } return el; } /** * Figures out if a link is an off-site link. This recognizes * the most common protocols by checking how it starts. * * @since 2.4 */ public static boolean isExternalLink( String link ) { int idx = Arrays.binarySearch( c_externalLinks, link, c_startingComparator ); // We need to check here once again; otherwise we might // get a match for something like "h". if( idx >= 0 && link.startsWith(c_externalLinks[idx]) ) return true; return false; } /** * Returns true, if the link in question is an access * rule. */ private static boolean isAccessRule( String link ) { return link.startsWith("{ALLOW") || link.startsWith("{DENY"); } /** * Matches the given link to the list of image name patterns * to determine whether it should be treated as an inline image * or not. */ private boolean isImageLink( String link ) { if( m_inlineImages ) { link = link.toLowerCase(); for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); ) { if( m_inlineMatcher.matches( link, (Pattern) i.next() ) ) return true; } } return false; } private static boolean isMetadata( String link ) { return link.startsWith("{SET"); } /** * These are all of the HTML 4.01 block-level elements. */ private static final String[] BLOCK_ELEMENTS = { "address", "blockquote", "div", "dl", "fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "noscript", "ol", "p", "pre", "table", "ul" }; private static final boolean isBlockLevel( String name ) { return Arrays.binarySearch( BLOCK_ELEMENTS, name ) >= 0; } /** * This method peeks ahead in the stream until EOL and returns the result. * It will keep the buffers untouched. * * @return The string from the current position to the end of line. */ // FIXME: Always returns an empty line, even if the stream is full. private String peekAheadLine() throws IOException { String s = readUntilEOL().toString(); if( s.length() > PUSHBACK_BUFFER_SIZE ) { log.warn("Line is longer than maximum allowed size ("+PUSHBACK_BUFFER_SIZE+" characters. Attempting to recover..."); pushBack( s.substring(0,PUSHBACK_BUFFER_SIZE-1) ); } else { try { pushBack( s ); } catch( IOException e ) { log.warn("Pushback failed: the line is probably too long. Attempting to recover."); } } return s; } /** * Writes HTML for error message. */ public static Element makeError( String error ) { return new Element("span").setAttribute("class","error").addContent(error); } private int flushPlainText() { int numChars = m_plainTextBuf.length(); if( numChars > 0 ) { String buf; if( !m_allowHTML ) { buf = escapeHTMLEntities(m_plainTextBuf); } else { buf = m_plainTextBuf.toString(); } // We must first empty the buffer because the side effect of // calling makeCamelCaseLink() is to call this routine. m_plainTextBuf = new StringBuffer(20); try { // This is the heaviest part of parsing, and therefore we can // do some optimization here. // 1) Only when the length of the buffer is big enough, we try to do the match if( m_camelCaseLinks && !m_isEscaping && buf.length() > 3 ) { // System.out.println("Buffer="+buf); while( m_camelCaseMatcher.contains( buf, m_camelCasePattern ) ) { MatchResult result = m_camelCaseMatcher.getMatch(); String firstPart = buf.substring(0,result.beginOffset(0)); String prefix = result.group(1); if( prefix == null ) prefix = ""; String camelCase = result.group(2); String protocol = result.group(3); String uri = protocol+result.group(4); buf = buf.substring(result.endOffset(0)); m_currentElement.addContent( firstPart ); // Check if the user does not wish to do URL or WikiWord expansion if( prefix.endsWith("~") || prefix.indexOf('[') != -1 ) { if( prefix.endsWith("~") ) { if( m_wysiwygEditorMode ) { m_currentElement.addContent( "~" ); } prefix = prefix.substring(0,prefix.length()-1); } if( camelCase != null ) { m_currentElement.addContent( prefix+camelCase ); } else if( protocol != null ) { m_currentElement.addContent( prefix+uri ); } continue; } // Fine, then let's check what kind of a link this was // and emit the proper elements if( protocol != null ) { char c = uri.charAt(uri.length()-1); if( c == '.' || c == ',' ) { uri = uri.substring(0,uri.length()-1); buf = c + buf; } // System.out.println("URI match "+uri); m_currentElement.addContent( prefix ); makeDirectURILink( uri ); } else { // System.out.println("Matched: '"+camelCase+"'"); // System.out.println("Split to '"+firstPart+"', and '"+buf+"'"); // System.out.println("prefix="+prefix); m_currentElement.addContent( prefix ); makeCamelCaseLink( camelCase ); } } m_currentElement.addContent( buf ); } else { // No camelcase asked for, just add the elements m_currentElement.addContent( buf ); } } catch( IllegalDataException e ) { // Here we make sure it does not stop parsing. m_currentElement.addContent( makeError(e.getMessage()) ); } } return numChars; } /** * Escapes XML entities in a HTML-compatible way (i.e. does not escape * entities that are already escaped). * * @param buf * @return */ private String escapeHTMLEntities(StringBuffer buf) { StringBuffer tmpBuf = new StringBuffer( buf.length() + 20 ); for( int i = 0; i < buf.length(); i++ ) { char ch = buf.charAt(i); if( ch == '<' ) { tmpBuf.append("&lt;"); } else if( ch == '>' ) { tmpBuf.append("&gt;"); } else if( ch == '&' ) { for( int j = (i < buf.length()-1 ) ? i+1 : i; j < buf.length(); j++ ) { int ch2 = buf.charAt(j); if( ch2 == ';' ) { tmpBuf.append(ch); break; } if( ch2 != '#' && !Character.isLetterOrDigit( (char)ch2) ) { tmpBuf.append("&amp;"); break; } } } else { tmpBuf.append( ch ); } } return tmpBuf.toString(); } private Element pushElement( Element e ) { flushPlainText(); m_currentElement.addContent( e ); m_currentElement = e; return e; } private Element addElement( Content e ) { if( e != null ) { flushPlainText(); m_currentElement.addContent( e ); } return m_currentElement; } /** * All elements that can be empty by the HTML DTD. */ // Keep sorted. private static final String[] EMPTY_ELEMENTS = { "area", "base", "br", "col", "hr", "img", "input", "link", "meta", "p", "param" }; /** * Goes through the current element stack and pops all elements until this * element is found - this essentially "closes" and element. * * @param s * @return The new current element, or null, if there was no such element in the entire stack. */ private Element popElement( String s ) { int flushedBytes = flushPlainText(); Element currEl = m_currentElement; while( currEl.getParentElement() != null ) { if( currEl.getName().equals(s) && !currEl.isRootElement() ) { m_currentElement = currEl.getParentElement(); // Check if it's okay for this element to be empty. Then we will // trick the JDOM generator into not generating an empty element, // by putting an empty string between the tags. Yes, it's a kludge // but what'cha gonna do about it. :-) if( flushedBytes == 0 && Arrays.binarySearch( EMPTY_ELEMENTS, s ) < 0 ) { currEl.addContent(""); } return m_currentElement; } currEl = currEl.getParentElement(); } return null; } /** * Reads the stream until it meets one of the specified * ending characters, or stream end. The ending character will be left * in the stream. */ private String readUntil( String endChars ) throws IOException { StringBuffer sb = new StringBuffer( 80 ); int ch = nextToken(); while( ch != -1 ) { if( ch == '\\' ) { ch = nextToken(); if( ch == -1 ) { break; } } else { if( endChars.indexOf((char)ch) != -1 ) { pushBack( ch ); break; } } sb.append( (char) ch ); ch = nextToken(); } return sb.toString(); } /** * Reads the stream while the characters that have been specified are * in the stream, returning then the result as a String. */ private String readWhile( String endChars ) throws IOException { StringBuffer sb = new StringBuffer( 80 ); int ch = nextToken(); while( ch != -1 ) { if( endChars.indexOf((char)ch) == -1 ) { pushBack( ch ); break; } sb.append( (char) ch ); ch = nextToken(); } return sb.toString(); } private JSPWikiMarkupParser m_cleanTranslator; /** * Does a lazy init. Otherwise, we would get into a situation * where HTMLRenderer would try and boot a TranslatorReader before * the TranslatorReader it is contained by is up. */ private JSPWikiMarkupParser getCleanTranslator() { if( m_cleanTranslator == null ) { WikiContext dummyContext = new WikiContext( m_engine, m_context.getHttpRequest(), m_context.getPage() ); m_cleanTranslator = new JSPWikiMarkupParser( dummyContext, null ); m_cleanTranslator.m_allowHTML = true; } return m_cleanTranslator; } /** * Modifies the "hd" parameter to contain proper values. Because * an "id" tag may only contain [a-zA-Z0-9:_-], we'll replace the * % after url encoding with '_'. */ // FIXME: This method should probably be public and in an util class somewhere private String makeHeadingAnchor( String baseName, String title, Heading hd ) { hd.m_titleText = title; title = MarkupParser.wikifyLink( title ); hd.m_titleSection = m_engine.encodeName(title); hd.m_titleAnchor = "section-"+m_engine.encodeName(baseName)+ "-"+hd.m_titleSection; hd.m_titleAnchor = hd.m_titleAnchor.replace( '%', '_' ); hd.m_titleAnchor = hd.m_titleAnchor.replace( '/', '_' ); return hd.m_titleAnchor; } private String makeSectionTitle( String title ) { title = title.trim(); String outTitle; try { JSPWikiMarkupParser dtr = getCleanTranslator(); dtr.setInputReader( new StringReader(title) ); CleanTextRenderer ctt = new CleanTextRenderer(m_context, dtr.parse()); outTitle = ctt.getString(); } catch( IOException e ) { log.fatal("CleanTranslator not working", e); throw new InternalWikiException("CleanTranslator not working as expected, when cleaning title"+ e.getMessage() ); } return outTitle; } /** * Returns XHTML for the start of the heading. Also sets the * line-end emitter. * @param level * @param title the title for the heading * @param hd a List to which heading should be added */ public Element makeHeading( int level, String title, Heading hd ) { Element el = null; String pageName = m_context.getPage().getName(); String outTitle = makeSectionTitle( title ); hd.m_level = level; switch( level ) { case Heading.HEADING_SMALL: el = new Element("h4").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd )); break; case Heading.HEADING_MEDIUM: el = new Element("h3").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd )); break; case Heading.HEADING_LARGE: el = new Element("h2").setAttribute("id",makeHeadingAnchor( pageName, outTitle, hd )); break; } return el; } /** * When given a link to a WikiName, we just return * a proper HTML link for it. The local link mutator * chain is also called. */ private Element makeCamelCaseLink( String wikiname ) { String matchedLink; callMutatorChain( m_localLinkMutatorChain, wikiname ); if( (matchedLink = linkExists( wikiname )) != null ) { makeLink( READ, matchedLink, wikiname, null, null ); } else { makeLink( EDIT, wikiname, wikiname, null, null ); } return m_currentElement; } /** Holds the image URL for the duration of this parser */ private String m_outlinkImageURL = null; /** * Returns an element for the external link image (out.png). However, * this method caches the URL for the lifetime of this MarkupParser, * because it's commonly used, and we'll end up with possibly hundreds * our thousands of references to it... It's a lot faster, too. * * @return An element containing the HTML for the outlink image. */ private Element outlinkImage() { Element el = null; if( m_useOutlinkImage ) { if( m_outlinkImageURL == null ) { m_outlinkImageURL = m_context.getURL( WikiContext.NONE, OUTLINK_IMAGE ); } el = new Element("img").setAttribute("class", "outlink"); el.setAttribute( "src", m_outlinkImageURL ); el.setAttribute("alt",""); } return el; } /** * Takes an URL and turns it into a regular wiki link. Unfortunately, * because of the way that flushPlainText() works, it already encodes * all of the XML entities. But so does WikiContext.getURL(), so we * have to do a reverse-replace here, so that it can again be replaced in makeLink. * <p> * What a crappy problem. * * @param url * @return */ private Element makeDirectURILink( String url ) { Element result; String last = null; if( url.endsWith(",") || url.endsWith(".") ) { last = url.substring( url.length()-1 ); url = url.substring( 0, url.length()-1 ); } callMutatorChain( m_externalLinkMutatorChain, url ); if( isImageLink( url ) ) { result = handleImageLink( StringUtils.replace(url,"&amp;","&"), url, false ); } else { result = makeLink( EXTERNAL, StringUtils.replace(url,"&amp;","&"), url, null, null ); addElement( outlinkImage() ); } if( last != null ) { m_plainTextBuf.append(last); } return result; } /** * Image links are handled differently: * 1. If the text is a WikiName of an existing page, * it gets linked. * 2. If the text is an external link, then it is inlined. * 3. Otherwise it becomes an ALT text. * * @param reallink The link to the image. * @param link Link text portion, may be a link to somewhere else. * @param hasLinkText If true, then the defined link had a link text available. * This means that the link text may be a link to a wiki page, * or an external resource. */ // FIXME: isExternalLink() is called twice. private Element handleImageLink( String reallink, String link, boolean hasLinkText ) { String possiblePage = MarkupParser.cleanLink( link ); if( isExternalLink( link ) && hasLinkText ) { return makeLink( IMAGELINK, reallink, link, null, null ); } else if( ( linkExists( possiblePage ) ) != null && hasLinkText ) { // System.out.println("Orig="+link+", Matched: "+matchedLink); callMutatorChain( m_localLinkMutatorChain, possiblePage ); return makeLink( IMAGEWIKILINK, reallink, link, null, null ); } else { return makeLink( IMAGE, reallink, link, null, null ); } } private Element handleAccessRule( String ruleLine ) { if( m_wysiwygEditorMode ) { m_currentElement.addContent( "[" + ruleLine + "]" ); } if( !m_parseAccessRules ) return m_currentElement; Acl acl; WikiPage page = m_context.getPage(); // UserDatabase db = m_context.getEngine().getUserDatabase(); if( ruleLine.startsWith( "{" ) ) ruleLine = ruleLine.substring( 1 ); if( ruleLine.endsWith( "}" ) ) ruleLine = ruleLine.substring( 0, ruleLine.length() - 1 ); log.debug("page="+page.getName()+", ACL = "+ruleLine); try { acl = m_engine.getAclManager().parseAcl( page, ruleLine ); page.setAcl( acl ); log.debug( acl.toString() ); } catch( WikiSecurityException wse ) { return makeError( wse.getMessage() ); } return m_currentElement; } /** * Handles metadata setting [{SET foo=bar}] */ private Element handleMetadata( String link ) { if( m_wysiwygEditorMode ) { m_currentElement.addContent( "[" + link + "]" ); } try { String args = link.substring( link.indexOf(' '), link.length()-1 ); String name = args.substring( 0, args.indexOf('=') ); String val = args.substring( args.indexOf('=')+1, args.length() ); name = name.trim(); val = val.trim(); if( val.startsWith("'") ) val = val.substring( 1 ); if( val.endsWith("'") ) val = val.substring( 0, val.length()-1 ); // log.debug("SET name='"+name+"', value='"+val+"'."); if( name.length() > 0 && val.length() > 0 ) { val = m_engine.getVariableManager().expandVariables( m_context, val ); m_context.getPage().setAttribute( name, val ); } } catch( Exception e ) { return makeError(" Invalid SET found: "+link); } return m_currentElement; } /** * Emits a processing instruction that will disable markup escaping. This is * very useful if you want to emit HTML directly into the stream. * */ private void disableOutputEscaping() { addElement( new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "") ); } /** * Gobbles up all hyperlinks that are encased in square brackets. */ private Element handleHyperlinks( String linktext, int pos ) { StringBuffer sb = new StringBuffer(linktext.length()+80); if( isAccessRule( linktext ) ) { return handleAccessRule( linktext ); } if( isMetadata( linktext ) ) { return handleMetadata( linktext ); } if( PluginManager.isPluginLink( linktext ) ) { try { PluginContent pluginContent = m_engine.getPluginManager().parsePluginLine( m_context, linktext, pos ); addElement( pluginContent ); pluginContent.executeParse( m_context ); } catch( PluginException e ) { log.info( "Failed to insert plugin", e ); log.info( "Root cause:",e.getRootThrowable() ); if( !m_wysiwygEditorMode ) { return addElement( makeError("Plugin insertion failed: "+e.getMessage()) ); } } return m_currentElement; } try { LinkParser.Link link = m_linkParser.parse(linktext); linktext = link.getText(); String linkref = link.getReference(); // Yes, we now have the components separated. // linktext = the text the link should have // linkref = the url or page name. // In many cases these are the same. [linktext|linkref]. if( VariableManager.isVariableLink( linktext ) ) { Content el = new VariableContent(linktext); addElement( el ); } else if( isExternalLink( linkref ) ) { // It's an external link, out of this Wiki callMutatorChain( m_externalLinkMutatorChain, linkref ); if( isImageLink( linkref ) ) { handleImageLink( linkref, linktext, link.hasReference() ); } else { makeLink( EXTERNAL, linkref, linktext, null, link.getAttributes() ); addElement( outlinkImage() ); } } else if( link.isInterwikiLink() ) { // It's an interwiki link // InterWiki links also get added to external link chain // after the links have been resolved. // FIXME: There is an interesting issue here: We probably should // URLEncode the wikiPage, but we can't since some of the // Wikis use slashes (/), which won't survive URLEncoding. // Besides, we don't know which character set the other Wiki // is using, so you'll have to write the entire name as it appears // in the URL. Bugger. String extWiki = link.getExternalWiki(); String wikiPage = link.getExternalWikiPage(); if( m_wysiwygEditorMode ) { makeLink( INTERWIKI, extWiki + ":" + wikiPage, linktext, null, link.getAttributes() ); } else{ String urlReference = m_engine.getInterWikiURL( extWiki ); if( urlReference != null ) { urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage ); urlReference = callMutatorChain( m_externalLinkMutatorChain, urlReference ); if( isImageLink(urlReference) ) { handleImageLink( urlReference, linktext, link.hasReference() ); } else { makeLink( INTERWIKI, urlReference, linktext, null, link.getAttributes() ); } if( isExternalLink(urlReference) ) { addElement( outlinkImage() ); } } else { addElement( makeError("No InterWiki reference defined in properties for Wiki called '" + extWiki + "'!)") ); } } } else if( linkref.startsWith(" { // It defines a local footnote makeLink( LOCAL, linkref, linktext, null, link.getAttributes() ); } else if( TextUtil.isNumber( linkref ) ) { // It defines a reference to a local footnote makeLink( LOCALREF, linkref, linktext, null, link.getAttributes() ); } else { int hashMark = -1; // Internal wiki link, but is it an attachment link? String attachment = findAttachment( linkref ); if( attachment != null ) { callMutatorChain( m_attachmentLinkMutatorChain, attachment ); if( isImageLink( linkref ) ) { attachment = m_context.getURL( WikiContext.ATTACH, attachment ); sb.append( handleImageLink( attachment, linktext, link.hasReference() ) ); } else { makeLink( ATTACHMENT, attachment, linktext, null, link.getAttributes() ); } } else if( (hashMark = linkref.indexOf(' { // It's an internal Wiki link, but to a named section String namedSection = linkref.substring( hashMark+1 ); linkref = linkref.substring( 0, hashMark ); linkref = MarkupParser.cleanLink( linkref ); callMutatorChain( m_localLinkMutatorChain, linkref ); String matchedLink; if( (matchedLink = linkExists( linkref )) != null ) { String sectref = "section-"+m_engine.encodeName(matchedLink)+"-"+namedSection; sectref = sectref.replace('%', '_'); makeLink( READ, matchedLink, linktext, sectref, link.getAttributes() ); } else { makeLink( EDIT, linkref, linktext, null, link.getAttributes() ); } } else { // It's an internal Wiki link linkref = MarkupParser.cleanLink( linkref ); callMutatorChain( m_localLinkMutatorChain, linkref ); String matchedLink = linkExists( linkref ); if( matchedLink != null ) { makeLink( READ, matchedLink, linktext, null, link.getAttributes() ); } else { makeLink( EDIT, linkref, linktext, null, link.getAttributes() ); } } } } catch( ParseException e ) { log.info("Parser failure: ",e); addElement( makeError( "Parser failed: "+e.getMessage() ) ); } return m_currentElement; } private String findAttachment( String linktext ) { AttachmentManager mgr = m_engine.getAttachmentManager(); Attachment att = null; try { att = mgr.getAttachmentInfo( m_context, linktext ); } catch( ProviderException e ) { log.warn("Finding attachments failed: ",e); return null; } if( att != null ) { return att.getName(); } else if( linktext.indexOf('/') != -1 ) { return linktext; } return null; } /** * Pushes back any string that has been read. It will obviously * be pushed back in a reverse order. * * @since 2.1.77 */ private void pushBack( String s ) throws IOException { for( int i = s.length()-1; i >= 0; i { pushBack( s.charAt(i) ); } } private Element handleBackslash() throws IOException { int ch = nextToken(); if( ch == '\\' ) { int ch2 = nextToken(); if( ch2 == '\\' ) { pushElement( new Element("br").setAttribute("clear","all")); return popElement("br"); } pushBack( ch2 ); pushElement( new Element("br") ); return popElement("br"); } pushBack( ch ); return null; } private Element handleUnderscore() throws IOException { int ch = nextToken(); Element el = null; if( ch == '_' ) { if( m_isbold ) { el = popElement("b"); } else { el = pushElement( new Element("b") ); } m_isbold = !m_isbold; } else { pushBack( ch ); } return el; } /** * For example: italics. */ private Element handleApostrophe() throws IOException { int ch = nextToken(); Element el = null; if( ch == '\'' ) { if( m_isitalic ) { el = popElement("i"); } else { el = pushElement( new Element("i") ); } m_isitalic = !m_isitalic; } else { pushBack( ch ); } return el; } private Element handleOpenbrace( boolean isBlock ) throws IOException { int ch = nextToken(); if( ch == '{' ) { int ch2 = nextToken(); if( ch2 == '{' ) { m_isPre = true; m_isEscaping = true; m_isPreBlock = isBlock; if( isBlock ) { startBlockLevel(); return pushElement( new Element("pre") ); } return pushElement( new Element("span").setAttribute("style","font-family:monospace; white-space:pre;") ); } pushBack( ch2 ); return pushElement( new Element("tt") ); } pushBack( ch ); return null; } /** * Handles both }} and }}} */ private Element handleClosebrace() throws IOException { int ch2 = nextToken(); if( ch2 == '}' ) { int ch3 = nextToken(); if( ch3 == '}' ) { if( m_isPre ) { if( m_isPreBlock ) { popElement( "pre" ); } else { popElement( "span" ); } m_isPre = false; m_isEscaping = false; return m_currentElement; } m_plainTextBuf.append("}}}"); return m_currentElement; } pushBack( ch3 ); if( !m_isEscaping ) { return popElement("tt"); } } pushBack( ch2 ); return null; } private Element handleDash() throws IOException { int ch = nextToken(); if( ch == '-' ) { int ch2 = nextToken(); if( ch2 == '-' ) { int ch3 = nextToken(); if( ch3 == '-' ) { // Empty away all the rest of the dashes. // Do not forget to return the first non-match back. while( (ch = nextToken()) == '-' ); pushBack(ch); startBlockLevel(); pushElement( new Element("hr") ); return popElement( "hr" ); } pushBack( ch3 ); } pushBack( ch2 ); } pushBack( ch ); return null; } private Element handleHeading() throws IOException { Element el = null; int ch = nextToken(); Heading hd = new Heading(); if( ch == '!' ) { int ch2 = nextToken(); if( ch2 == '!' ) { String title = peekAheadLine(); el = makeHeading( Heading.HEADING_LARGE, title, hd); } else { pushBack( ch2 ); String title = peekAheadLine(); el = makeHeading( Heading.HEADING_MEDIUM, title, hd ); } } else { pushBack( ch ); String title = peekAheadLine(); el = makeHeading( Heading.HEADING_SMALL, title, hd ); } callHeadingListenerChain( hd ); if( el != null ) pushElement(el); return el; } /** * Reads the stream until the next EOL or EOF. Note that it will also read the * EOL from the stream. */ private StringBuffer readUntilEOL() throws IOException { int ch; StringBuffer buf = new StringBuffer( 256 ); while( true ) { ch = nextToken(); if( ch == -1 ) break; buf.append( (char) ch ); if( ch == '\n' ) break; } return buf; } /** Controls whether italic is restarted after a paragraph shift */ private boolean m_restartitalic = false; private boolean m_restartbold = false; private boolean m_newLine; /** * Starts a block level element, therefore closing * a potential open paragraph tag. */ private void startBlockLevel() { // These may not continue over block level limits in XHTML popElement("i"); popElement("b"); popElement("tt"); if( m_isOpenParagraph ) { m_isOpenParagraph = false; popElement("p"); m_plainTextBuf.append("\n"); // Just small beautification } m_restartitalic = m_isitalic; m_restartbold = m_isbold; m_isitalic = false; m_isbold = false; } private static String getListType( char c ) { if( c == '*' ) { return "ul"; } else if( c == ' { return "ol"; } throw new InternalWikiException("Parser got faulty list type: "+c); } /** * Like original handleOrderedList() and handleUnorderedList() * however handles both ordered ('#') and unordered ('*') mixed together. */ // FIXME: Refactor this; it's a bit messy. private Element handleGeneralList() throws IOException { startBlockLevel(); String strBullets = readWhile( "* // String strBulletsRaw = strBullets; // to know what was original before phpwiki style substitution int numBullets = strBullets.length(); // override the beginning portion of bullet pattern to be like the previous // to simulate PHPWiki style lists if(m_allowPHPWikiStyleLists) { // only substitute if different if(!( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals (m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) ) { if(numBullets <= m_genlistlevel) { // Substitute all but the last character (keep the expressed bullet preference) strBullets = (numBullets > 1 ? m_genlistBulletBuffer.substring(0, numBullets-1) : "") + strBullets.substring(numBullets-1, numBullets); } else { strBullets = m_genlistBulletBuffer + strBullets.substring(m_genlistlevel, numBullets); } } } // Check if this is still of the same type if( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals (m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) { if( numBullets > m_genlistlevel ) { pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel++) ) ) ); for( ; m_genlistlevel < numBullets; m_genlistlevel++ ) { // bullets are growing, get from new bullet list pushElement( new Element("li") ); pushElement( new Element( getListType(strBullets.charAt(m_genlistlevel)) )); } } else if( numBullets < m_genlistlevel ) { // Close the previous list item. // buf.append( m_renderer.closeListItem() ); popElement( "li" ); for( ; m_genlistlevel > numBullets; m_genlistlevel { // bullets are shrinking, get from old bullet list popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) ); if( m_genlistlevel > 0 ) { popElement( "li" ); } } } else { if( m_genlistlevel > 0 ) { popElement( "li" ); } } } else { // The pattern has changed, unwind and restart int numEqualBullets; int numCheckBullets; // find out how much is the same numEqualBullets = 0; numCheckBullets = Math.min(numBullets,m_genlistlevel); while( numEqualBullets < numCheckBullets ) { // if the bullets are equal so far, keep going if( strBullets.charAt(numEqualBullets) == m_genlistBulletBuffer.charAt(numEqualBullets)) numEqualBullets++; // otherwise giveup, we have found how many are equal else break; } //unwind for( ; m_genlistlevel > numEqualBullets; m_genlistlevel { popElement( getListType( m_genlistBulletBuffer.charAt(m_genlistlevel-1) ) ); if( m_genlistlevel > 0 ) { popElement("li"); } } //rewind pushElement( new Element(getListType( strBullets.charAt(numEqualBullets++) ) ) ); for(int i = numEqualBullets; i < numBullets; i++) { pushElement( new Element("li") ); pushElement( new Element( getListType( strBullets.charAt(i) ) ) ); } m_genlistlevel = numBullets; } // Push a new list item, and eat away any extra whitespace pushElement( new Element("li") ); readWhile(" "); // work done, remember the new bullet list (in place of old one) m_genlistBulletBuffer.setLength(0); m_genlistBulletBuffer.append(strBullets); return m_currentElement; } private Element unwindGeneralList() { //unwind for( ; m_genlistlevel > 0; m_genlistlevel { popElement( "li" ); popElement( getListType(m_genlistBulletBuffer.charAt(m_genlistlevel-1)) ); } m_genlistBulletBuffer.setLength(0); return null; } private Element handleDefinitionList() throws IOException { if( !m_isdefinition ) { m_isdefinition = true; startBlockLevel(); pushElement( new Element("dl") ); return pushElement( new Element("dt") ); } return null; } private Element handleOpenbracket() throws IOException { StringBuffer sb = new StringBuffer(40); int pos = getPosition(); int ch = nextToken(); boolean isPlugin = false; if( ch == '[' ) { if( m_wysiwygEditorMode ) { sb.append( '[' ); } sb.append( (char)ch ); while( (ch = nextToken()) == '[' ) { sb.append( (char)ch ); } } if( ch == '{' ) { isPlugin = true; } pushBack( ch ); if( sb.length() > 0 ) { m_plainTextBuf.append( sb ); return m_currentElement; } // Find end of hyperlink ch = nextToken(); int nesting = 1; // Check for nested plugins while( ch != -1 ) { int ch2 = nextToken(); pushBack(ch2); if( isPlugin ) { if( ch == '[' && ch2 == '{' ) { nesting++; } else if( nesting == 0 && ch == ']' && sb.charAt(sb.length()-1) == '}' ) { break; } else if( ch == '}' && ch2 == ']' ) { // NB: This will be decremented once at the end nesting } } else { if( ch == ']' ) { break; } } sb.append( (char) ch ); ch = nextToken(); } // If the link is never finished, do some tricks to display the rest of the line // unchanged. if( ch == -1 ) { log.debug("Warning: unterminated link detected!"); m_isEscaping = true; m_plainTextBuf.append( sb ); flushPlainText(); m_isEscaping = false; return m_currentElement; } return handleHyperlinks( sb.toString(), pos ); } /** * Reads the stream until the current brace is closed or stream end. */ private String readBraceContent( char opening, char closing ) throws IOException { StringBuffer sb = new StringBuffer(40); int braceLevel = 1; int ch; while(( ch = nextToken() ) != -1 ) { if( ch == '\\' ) { continue; } else if ( ch == opening ) { braceLevel++; } else if ( ch == closing ) { braceLevel if (braceLevel==0) { break; } } sb.append( (char)ch ); } return sb.toString(); } /** * Handles constructs of type %%(style) and %%class * @param newLine * @return * @throws IOException */ private Element handleDiv( boolean newLine ) throws IOException { int ch = nextToken(); Element el = null; if( ch == '%' ) { String style = null; String clazz = null; ch = nextToken(); // Style or class? if( ch == '(' ) { style = readBraceContent('(',')'); } else if( Character.isLetter( (char) ch ) ) { pushBack( ch ); clazz = readUntil( " \t\n\r" ); ch = nextToken(); // Pop out only spaces, so that the upcoming EOL check does not check the // next line. if( ch == '\n' || ch == '\r' ) { pushBack(ch); } } else { // Anything else stops. pushBack(ch); try { Boolean isSpan = (Boolean)m_styleStack.pop(); if( isSpan == null ) { // Fail quietly } else if( isSpan.booleanValue() ) { el = popElement( "span" ); } else { el = popElement( "div" ); } } catch( EmptyStackException e ) { log.debug("Page '"+m_context.getName()+"' closes a %%-block that has not been opened."); return m_currentElement; } return el; } // Check if there is an attempt to do something nasty style = StringEscapeUtils.unescapeHtml(style); if( style != null && style.indexOf("javascript:") != -1 ) { log.debug("Attempt to output javascript within CSS:"+style); return addElement( makeError("Attempt to output javascript!") ); } // Decide if we should open a div or a span? String eol = peekAheadLine(); if( eol.trim().length() > 0 ) { // There is stuff after the class el = new Element("span"); m_styleStack.push( Boolean.TRUE ); } else { startBlockLevel(); el = new Element("div"); m_styleStack.push( Boolean.FALSE ); } if( style != null ) el.setAttribute("style", style); if( clazz != null ) el.setAttribute("class", clazz ); el = pushElement( el ); return el; } pushBack(ch); return el; } private Element handleSlash( boolean newLine ) throws IOException { int ch = nextToken(); pushBack(ch); if( ch == '%' && !m_styleStack.isEmpty() ) { return handleDiv( newLine ); } return null; } private Element handleBar( boolean newLine ) throws IOException { Element el = null; if( !m_istable && !newLine ) { return null; } // If the bar is in the first column, we will either start // a new table or continue the old one. if( newLine ) { if( !m_istable ) { startBlockLevel(); el = pushElement( new Element("table").setAttribute("class","wikitable").setAttribute("border","1") ); m_istable = true; m_rowNum = 0; } m_rowNum++; Element tr = ( m_rowNum % 2 != 0 ) ? new Element("tr").setAttribute("class", "odd") : new Element("tr"); el = pushElement( tr ); } // Check out which table cell element to start; // a header element (th) or a regular element (td). int ch = nextToken(); if( ch == '|' ) { if( !newLine ) { el = popElement("th"); if( el == null ) popElement("td"); } el = pushElement( new Element("th") ); } else { if( !newLine ) { el = popElement("td"); if( el == null ) popElement("th"); } el = pushElement( new Element("td") ); pushBack( ch ); } return el; } /** * Generic escape of next character or entity. */ private Element handleTilde() throws IOException { int ch = nextToken(); if( ch == ' ' ) { if( m_wysiwygEditorMode ) { m_plainTextBuf.append( "~ " ); } return m_currentElement; } if( ch == '|' || ch == '~' || ch == '\\' || ch == '*' || ch == ' ch == '-' || ch == '!' || ch == '\'' || ch == '_' || ch == '[' || ch == '{' || ch == ']' || ch == '}' || ch == '%' ) { if( m_wysiwygEditorMode ) { m_plainTextBuf.append( '~' ); } m_plainTextBuf.append( (char)ch ); m_plainTextBuf.append(readWhile( ""+(char)ch )); return m_currentElement; } // No escape. pushBack( ch ); return null; } private void fillBuffer( Element startElement ) throws IOException { m_currentElement = startElement; boolean quitReading = false; m_newLine = true; disableOutputEscaping(); while(!quitReading) { int ch = nextToken(); if( ch == -1 ) break; // Check if we're actually ending the preformatted mode. // We still must do an entity transformation here. if( m_isEscaping ) { if( ch == '}' ) { if( handleClosebrace() == null ) m_plainTextBuf.append( (char) ch ); } else if( ch == -1 ) { quitReading = true; } else if( ch == '\r' ) { // DOS line feeds we ignore. } else if( ch == '<' ) { m_plainTextBuf.append( "&lt;" ); } else if( ch == '>' ) { m_plainTextBuf.append( "&gt;" ); } else if( ch == '&' ) { m_plainTextBuf.append( "&amp;" ); } else if( ch == '~' ) { String braces = readWhile("}"); if( braces.length() >= 3 ) { m_plainTextBuf.append("}}}"); braces = braces.substring(3); } else { m_plainTextBuf.append( (char) ch ); } for( int i = braces.length()-1; i >= 0; i { pushBack(braces.charAt(i)); } } else { m_plainTextBuf.append( (char) ch ); } continue; } // An empty line stops a list if( m_newLine && ch != '*' && ch != '#' && ch != ' ' && m_genlistlevel > 0 ) { m_plainTextBuf.append(unwindGeneralList()); } if( m_newLine && ch != '|' && m_istable ) { popElement("table"); m_istable = false; } int skip = parseToken( ch ); // The idea is as follows: If the handler method returns // an element (el != null), it is assumed that it has been // added in the stack. Otherwise the character is added // as is to the plaintext buffer. // For the transition phase, if s != null, it also gets // added in the plaintext buffer. switch( skip ) { case ELEMENT: m_newLine = false; break; case CHARACTER: m_plainTextBuf.append( (char) ch ); m_newLine = false; break; case IGNORE: break; } } popElement("domroot"); } public static final int CHARACTER = 0; public static final int ELEMENT = 1; public static final int IGNORE = 2; /** * Return CHARACTER, if you think this was a plain character; ELEMENT, if * you think this was a wiki markup element, and IGNORE, if you think * we should ignore this altogether. * * @param ch * @return {@link #ELEMENT}, {@link #CHARACTER} or {@link #IGNORE}. * @throws IOException */ protected int parseToken( int ch ) throws IOException { Element el = null; // Now, check the incoming token. switch( ch ) { case '\r': // DOS linefeeds we forget return IGNORE; case '\n': // Close things like headings, etc. // FIXME: This is not really very fast popElement("dl"); // Close definition lists. popElement("h2"); popElement("h3"); popElement("h4"); if( m_istable ) { popElement("tr"); } m_isdefinition = false; if( m_newLine ) { // Paragraph change. startBlockLevel(); // Figure out which elements cannot be enclosed inside // a <p></p> pair according to XHTML rules. String nextLine = peekAheadLine(); if( nextLine.length() == 0 || (nextLine.length() > 0 && !nextLine.startsWith("{{{") && !nextLine.startsWith(" !nextLine.startsWith("%%") && "*#!;".indexOf( nextLine.charAt(0) ) == -1) ) { pushElement( new Element("p") ); m_isOpenParagraph = true; if( m_restartitalic ) { pushElement( new Element("i") ); m_isitalic = true; m_restartitalic = false; } if( m_restartbold ) { pushElement( new Element("b") ); m_isbold = true; m_restartbold = false; } } } else { m_plainTextBuf.append("\n"); m_newLine = true; } return IGNORE; case '\\': el = handleBackslash(); break; case '_': el = handleUnderscore(); break; case '\'': el = handleApostrophe(); break; case '{': el = handleOpenbrace( m_newLine ); break; case '}': el = handleClosebrace(); break; case '-': if( m_newLine ) el = handleDash(); break; case '!': if( m_newLine ) { el = handleHeading(); } break; case ';': if( m_newLine ) { el = handleDefinitionList(); } break; case ':': if( m_isdefinition ) { popElement("dt"); el = pushElement( new Element("dd") ); m_isdefinition = false; } break; case '[': el = handleOpenbracket(); break; case '*': if( m_newLine ) { pushBack('*'); el = handleGeneralList(); } break; case ' if( m_newLine ) { pushBack(' el = handleGeneralList(); } break; case '|': el = handleBar( m_newLine ); break; case '~': el = handleTilde(); break; case '%': el = handleDiv( m_newLine ); break; case '/': el = handleSlash( m_newLine ); break; } return el != null ? ELEMENT : CHARACTER; } public WikiDocument parse() throws IOException { WikiDocument d = new WikiDocument( m_context.getPage() ); d.setContext( m_context ); Element rootElement = new Element("domroot"); d.setRootElement( rootElement ); try { fillBuffer( rootElement ); paragraphify(rootElement); } catch( IllegalDataException e ) { log.error("Page "+m_context.getName()+" contained something that cannot be added in the DOM tree",e); throw new IOException("Illegal page data: "+e.getMessage()); } return d; } /** * Checks out that the first paragraph is correctly installed. * * @param rootElement */ private void paragraphify(Element rootElement) { // Add the paragraph tag to the first paragraph List kids = rootElement.getContent(); if( rootElement.getChild("p") != null ) { ArrayList ls = new ArrayList(); int idxOfFirstContent = 0, count = 0; for( Iterator i = kids.iterator(); i.hasNext(); count++ ) { Content c = (Content) i.next(); if( c instanceof Element ) { String name = ((Element)c).getName(); if( isBlockLevel(name) ) break; } if( !(c instanceof ProcessingInstruction) ) { ls.add( c ); if( idxOfFirstContent == 0 ) idxOfFirstContent = count; } } // If there were any elements, then add a new <p> (unless it would // be an empty one) if( ls.size() > 0 ) { Element newel = new Element("p"); for( Iterator i = ls.iterator(); i.hasNext(); ) { Content c = (Content) i.next(); c.detach(); newel.addContent(c); } // Make sure there are no empty <p/> tags added. if( newel.getTextTrim().length() > 0 || !newel.getChildren().isEmpty() ) rootElement.addContent(idxOfFirstContent, newel); } } } /** * Compares two Strings, and if one starts with the other, then * returns null. Otherwise just like the normal Comparator * for strings. * * @author jalkanen * * @since */ private static class StartingComparator implements Comparator { public int compare( Object arg0, Object arg1 ) { String s1 = (String)arg0; String s2 = (String)arg1; if( s1.length() > s2.length() ) { if( s1.startsWith(s2) && s2.length() > 1 ) return 0; } else { if( s2.startsWith(s1) && s1.length() > 1 ) return 0; } return s1.compareTo( s2 ); } } }
package io.compgen.ngsutils.bed; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Iterator; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import io.compgen.common.StringLineReader; import io.compgen.common.StringUtils; import io.compgen.common.io.PeekableInputStream; import io.compgen.ngsutils.annotation.GenomeSpan; import io.compgen.ngsutils.bam.Strand; public class BedReader { public static Iterator<BedRecord> readFile(String filename) throws IOException { return readFile(filename, false); } public static Iterator<BedRecord> readFile(String filename, boolean ignoreStrand) throws IOException { if (filename.equals("-")) { return readInputStream(System.in, ignoreStrand); } return readFile(new File(filename), ignoreStrand); } public static Iterator<BedRecord> readFile(File file) throws IOException { return readInputStream(new FileInputStream(file), false); } public static Iterator<BedRecord> readFile(File file, boolean ignoreStrand) throws IOException { return readInputStream(new FileInputStream(file), ignoreStrand); } public static Iterator<BedRecord> readInputStream(final InputStream is) throws IOException { return readInputStream(is, false); } public static Iterator<BedRecord> readInputStream(final InputStream rawInput, final boolean ignoreStrand) throws IOException { PeekableInputStream peek = new PeekableInputStream(rawInput); byte[] magic = peek.peek(2); final InputStream is; if (Arrays.equals(magic, new byte[] {0x1f, (byte) 0x8B})) { // need to cast 0x8b because it is a neg. num in 2-complement is = new GzipCompressorInputStream(peek, true); } else { is = peek; } return new Iterator<BedRecord>() { BedRecord next = null; boolean first = true; Iterator<String> it = new StringLineReader(is).iterator(); @Override public boolean hasNext() { if (first) { loadNext(); first = false; } return next != null; } private void loadNext() { if (!it.hasNext()) { next = null; return; } while (it.hasNext()) { String line = it.next(); if (line == null || line.length() == 0 || line.charAt(0) == ' continue; } final String[] cols = StringUtils.strip(line).split("\t", -1); if (cols.length < 3) { continue; } final String chrom = cols[0]; final int start = Integer.parseInt(cols[1]); // file is 0-based final int end = Integer.parseInt(cols[2]); Strand strand = Strand.NONE; String name = ""; double score = 0; if (!ignoreStrand && cols.length > 5) { if (cols[5].equals("+")) { strand = Strand.PLUS; } else if (cols[5].equals("-")) { strand = Strand.MINUS; } else { // this shouldn't happen strand = Strand.NONE; } } if (cols.length > 3) { name = cols[3]; } if (cols.length > 4) { score = Double.parseDouble(cols[4]); } String[] extras = null; if (cols.length > 6) { extras = new String[cols.length-6]; for (int i=6; i<cols.length; i++) { extras[i-6] = cols[i]; } } GenomeSpan coord = new GenomeSpan(chrom, start, end, strand); next = new BedRecord(coord, name, score, extras); return; } try { is.close(); } catch (IOException e) { } } @Override public BedRecord next() { if (first) { loadNext(); first = false; } BedRecord cur = next; next = null; // this needed to avoid blank lines at the end returning the last record twice loadNext(); return cur; } @Override public void remove() { }}; } }
package org.apache.commons.lang; /** * <p>A range of characters. Able to understand the idea of a contiguous * sublist of an alphabet, a negated concept, and a set of characters.</p> * * <p>Used by <code>CharSet</code> to handle sets of characters.</p> * * @author <a href="bayard@generationjava.com">Henri Yandell</a> * @author Stephen Colebourne * @since 1.0 * @version $Id: CharRange.java,v 1.8 2003/07/26 15:33:34 scolebourne Exp $ */ class CharRange { /** * <p>Used internally to represent <code>null</code> in a char.</p> */ private static final char UNSET = 0; private char start; private char close; private boolean negated; /** * <p>Construct a <code>CharRange</code> over a single character.</p> * * @param start char over which this range is placed */ public CharRange(char start) { this.start = start; } /** * <p>Construct a <code>CharRange</code> over a set of characters.</p> * * @param start char start character in this range. inclusive * @param close char close character in this range. inclusive */ public CharRange(char start, char close) { this.start = start; this.close = close; } /** * <p>Construct a <code>CharRange</code> over a set of characters.</p> * * @param start String start first character is in this range (inclusive). * @param close String first character is close character in this * range (inclusive). * @throws NullPointerException if either String is <code>null</code> */ public CharRange(String start, String close) { this.start = start.charAt(0); this.close = close.charAt(0); } /** * <p>Get the start character for this character range.</p> * * @return start char (inclusive) */ public char getStart() { return this.start; } /** * <p>Get the end character for this character range.</p> * * @return end char (inclusive) */ public char getEnd() { return this.close; } /** * <p>Set the start character for this character range.</p> * * @param ch start char (inclusive) */ public void setStart(char ch) { this.start = ch; } /** * <p>Set the end character for this character range.</p> * * @param ch start char (inclusive) */ public void setEnd(char ch) { this.close = ch; } /** * <p>Is this <code>CharRange</code> over many characters.</p> * * @return boolean <code>true</code> is many characters */ public boolean isRange() { return this.close != UNSET; } /** * <p>Is the passed in character <code>ch</code> inside * this range.</p> * * @param ch character to test for * @return boolean <code>true</code> is in range */ public boolean inRange(char ch) { if( isRange() ) { return ((ch >= start) && (ch <= close)); } else { return start == ch; } } /** * <p>Checks if this <code>CharRange</code> is negated.</p> * * @return boolean <code>true</code> is negated */ public boolean isNegated() { return negated; } /** * <p>Sets this character range to be negated or not.</p> * * <p>This implies that this <code>CharRange</code> is over * all characters except the ones in this range.</p> * * @param negated <code>true</code> to negate the range */ public void setNegated(boolean negated) { this.negated = negated; } /** * <p>Output a string representation of the character range.</p> * * @return string representation */ public String toString() { String str = ""; if( isNegated() ) { str += "^"; } str += start; if( isRange() ) { str += "-"; str += close; } return str; } }
package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Abstract superclass for type-safe enums. * <p> * One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern. * <p> * <em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing Enum objects * should always be done using the equals() method, not ==. The equals() method will * try == first so in most cases the effect is the same. * <p> * To use this class, it must be subclassed. For example: * * <pre> * public final class ColorEnum extends Enum { * public static final ColorEnum RED = new ColorEnum("Red"); * public static final ColorEnum GREEN = new ColorEnum("Green"); * public static final ColorEnum BLUE = new ColorEnum("Blue"); * * private ColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ColorEnum.class); * } * } * </pre> * <p> * As shown, each enum has a name. This can be accessed using <code>getName</code>. * <p> * The <code>getEnum</code> and <code>iterator</code> methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class. * <p> * <em>NOTE:</em> This class originated in the Jakarta Avalon project. * </p> * * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @version $Id: Enum.java,v 1.3 2002/10/30 21:58:18 scolebourne Exp $ */ public abstract class Enum implements Comparable, Serializable { /** * An empty map, as JDK1.2 didn't have an empty map */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap()); /** * Map, key of class name, value of Entry. */ private static final Map cEnumClasses = new HashMap(); /** * The string representation of the Enum. */ private final String iName; /** * Enable the iterator to retain the source code order */ private static class Entry { /** Map of Enum name to Enum */ final Map map = new HashMap(50); /** List of Enums in source code order */ final List list = new ArrayList(25); /** * Restrictive constructor */ private Entry() { } } protected Enum(String name) { super(); if (name == null || name.length() == 0) { throw new IllegalArgumentException("The Enum name must not be empty"); } iName = name; Entry entry = (Entry) cEnumClasses.get(getClass().getName()); if (entry == null) { entry = new Entry(); cEnumClasses.put(getClass().getName(), entry); } entry.map.put(name, this); entry.list.add(this); } protected Object readResolve() { return Enum.getEnum(getClass(), getName()); } protected static Enum getEnum(Class enumClass, String name) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return null; } return (Enum) entry.map.get(name); } protected static Map getEnumMap(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return EMPTY_MAP; } return Collections.unmodifiableMap(entry.map); } protected static List getEnumList(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(entry.list); } protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } /** * Retrieve the name of this Enum item, set in the constructor. * * @return the <code>String</code> name of this Enum item */ public final String getName() { return iName; } /** * Tests for equality. Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast. * * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // shouldn't happen, but... return iName.equals(((Enum) other).iName); } else if (other.getClass().getName().equals(this.getClass().getName())) { // different classloaders try { // try to avoid reflection return iName.equals(((Enum) other).iName); } catch (ClassCastException ex) { // use reflection try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return iName.equals(name); } catch (NoSuchMethodException ex2) { // ignore - should never happen } catch (IllegalAccessException ex2) { // ignore - should never happen } catch (InvocationTargetException ex2) { // ignore - should never happen } return false; } } else { return false; } } /** * Returns a suitable hashCode for the enumeration. * * @return a hashcode based on the name */ public final int hashCode() { return 7 + iName.hashCode(); } /** * Tests for order. The default ordering is alphabetic by name, but this * can be overridden by subclasses. * * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { return iName.compareTo(((Enum) other).iName); } /** * Human readable description of this Enum item. For use when debugging. * * @return String in the form <code>type[name]</code>, for example: * <code>Color[Red]</code>. Note that the package name is stripped from * the type name. */ public String toString() { String shortName = getClass().getName(); int pos = shortName.lastIndexOf('.'); if (pos != -1) { shortName = shortName.substring(pos + 1); } return shortName + "[" + getName() + "]"; } }
package com.fsck.k9.mailstore; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.internet.MessageExtractor; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mailstore.LockableDatabase.DbCallback; import com.fsck.k9.mailstore.LockableDatabase.WrappedException; public class LocalMessage extends MimeMessage { protected MessageReference mReference; private final LocalStore localStore; private long mId; private int mAttachmentCount; private String mSubject; private String mPreview = ""; private boolean mHeadersLoaded = false; private long mThreadId; private long mRootId; private LocalMessage(LocalStore localStore) { this.localStore = localStore; } LocalMessage(LocalStore localStore, String uid, Folder folder) { this.localStore = localStore; this.mUid = uid; this.mFolder = folder; } void populateFromGetMessageCursor(Cursor cursor) throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); for (String flag : flags) { try { this.setFlagInternal(Flag.valueOf(flag), true); } catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } } } this.mId = cursor.getLong(5); this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6))); this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7))); this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8))); this.setReplyTo(Address.unpack(cursor.getString(9))); this.mAttachmentCount = cursor.getInt(10); this.setInternalDate(new Date(cursor.getLong(11))); this.setMessageId(cursor.getString(12)); final String preview = cursor.getString(14); mPreview = (preview == null ? "" : preview); if (this.mFolder == null) { LocalFolder f = new LocalFolder(this.localStore, cursor.getInt(13)); f.open(LocalFolder.OPEN_MODE_RW); this.mFolder = f; } mThreadId = (cursor.isNull(15)) ? -1 : cursor.getLong(15); mRootId = (cursor.isNull(16)) ? -1 : cursor.getLong(16); boolean deleted = (cursor.getInt(17) == 1); boolean read = (cursor.getInt(18) == 1); boolean flagged = (cursor.getInt(19) == 1); boolean answered = (cursor.getInt(20) == 1); boolean forwarded = (cursor.getInt(21) == 1); setFlagInternal(Flag.DELETED, deleted); setFlagInternal(Flag.SEEN, read); setFlagInternal(Flag.FLAGGED, flagged); setFlagInternal(Flag.ANSWERED, answered); setFlagInternal(Flag.FORWARDED, forwarded); } /** * Fetch the message text for display. This always returns an HTML-ified version of the * message, even if it was originally a text-only message. * @return HTML version of message for display purposes or null. * @throws MessagingException */ public String getTextForDisplay() throws MessagingException { String text = null; // First try and fetch an HTML part. Part part = MimeUtility.findFirstPartByMimeType(this, "text/html"); if (part == null) { // If that fails, try and get a text part. part = MimeUtility.findFirstPartByMimeType(this, "text/plain"); if (part != null && part.getBody() instanceof LocalTextBody) { text = ((LocalTextBody) part.getBody()).getBodyForDisplay(); } } else { // We successfully found an HTML part; do the necessary character set decoding. text = MessageExtractor.getTextFromPart(part); } return text; } /* Custom version of writeTo that updates the MIME message based on localMessage * changes. */ @Override public void writeTo(OutputStream out) throws IOException, MessagingException { if (!mHeadersLoaded) { loadHeaders(); } super.writeTo(out); } @Override public String getPreview() { return mPreview; } @Override public String getSubject() { return mSubject; } @Override public void setSubject(String subject) throws MessagingException { mSubject = subject; } @Override public void setMessageId(String messageId) { mMessageId = messageId; } @Override public void setUid(String uid) { super.setUid(uid); this.mReference = null; } @Override public boolean hasAttachments() { return (mAttachmentCount > 0); } public int getAttachmentCount() { return mAttachmentCount; } @Override public void setFrom(Address from) throws MessagingException { this.mFrom = new Address[] { from }; } @Override public void setReplyTo(Address[] replyTo) throws MessagingException { if (replyTo == null || replyTo.length == 0) { mReplyTo = null; } else { mReplyTo = replyTo; } } /* * For performance reasons, we add headers instead of setting them (see super implementation) * which removes (expensive) them before adding them */ @Override public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { if (type == RecipientType.TO) { if (addresses == null || addresses.length == 0) { this.mTo = null; } else { this.mTo = addresses; } } else if (type == RecipientType.CC) { if (addresses == null || addresses.length == 0) { this.mCc = null; } else { this.mCc = addresses; } } else if (type == RecipientType.BCC) { if (addresses == null || addresses.length == 0) { this.mBcc = null; } else { this.mBcc = addresses; } } else { throw new MessagingException("Unrecognized recipient type."); } } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } @Override public long getId() { return mId; } @Override public void setFlag(final Flag flag, final boolean set) throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { if (flag == Flag.DELETED && set) { delete(); } LocalMessage.super.setFlag(flag, set); } catch (MessagingException e) { throw new WrappedException(e); } /* * Set the flags on the message. */ ContentValues cv = new ContentValues(); cv.put("flags", LocalMessage.this.localStore.serializeFlags(getFlags())); cv.put("read", isSet(Flag.SEEN) ? 1 : 0); cv.put("flagged", isSet(Flag.FLAGGED) ? 1 : 0); cv.put("answered", isSet(Flag.ANSWERED) ? 1 : 0); cv.put("forwarded", isSet(Flag.FORWARDED) ? 1 : 0); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /* * If a message is being marked as deleted we want to clear out it's content * and attachments as well. Delete will not actually remove the row since we need * to retain the uid for synchronization purposes. */ private void delete() throws MessagingException { /* * Delete all of the message's content to save space. */ try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { String[] idArg = new String[] { Long.toString(mId) }; ContentValues cv = new ContentValues(); cv.put("deleted", 1); cv.put("empty", 1); cv.putNull("subject"); cv.putNull("sender_list"); cv.putNull("date"); cv.putNull("to_list"); cv.putNull("cc_list"); cv.putNull("bcc_list"); cv.putNull("preview"); cv.putNull("html_content"); cv.putNull("text_content"); cv.putNull("reply_to_list"); db.update("messages", cv, "id = ?", idArg); /* * Delete all of the message's attachments to save space. * We do this explicit deletion here because we're not deleting the record * in messages, which means our ON DELETE trigger for messages won't cascade */ try { ((LocalFolder) mFolder).deleteAttachments(mId); } catch (MessagingException e) { throw new WrappedException(e); } db.delete("attachments", "message_id = ?", idArg); return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } ((LocalFolder)mFolder).deleteHeaders(mId); this.localStore.notifyChange(); } /* * Completely remove a message from the local database * * TODO: document how this updates the thread structure */ @Override public void destroy() throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { LocalFolder localFolder = (LocalFolder) mFolder; localFolder.deleteAttachments(mId); if (hasThreadChildren(db, mId)) { // This message has children in the thread structure so we need to // make it an empty message. ContentValues cv = new ContentValues(); cv.put("id", mId); cv.put("folder_id", localFolder.getId()); cv.put("deleted", 0); cv.put("message_id", getMessageId()); cv.put("empty", 1); db.replace("messages", null, cv); // Nothing else to do return null; } // Get the message ID of the parent message if it's empty long currentId = getEmptyThreadParent(db, mId); // Delete the placeholder message deleteMessageRow(db, mId); /* * Walk the thread tree to delete all empty parents without children */ while (currentId != -1) { if (hasThreadChildren(db, currentId)) { // We made sure there are no empty leaf nodes and can stop now. break; } // Get ID of the (empty) parent for the next iteration long newId = getEmptyThreadParent(db, currentId); // Delete the empty message deleteMessageRow(db, currentId); currentId = newId; } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /** * Get ID of the the given message's parent if the parent is an empty message. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the parent for. * * @return Message ID of the parent message if there exists a parent and it is empty. * Otherwise {@code -1}. */ private long getEmptyThreadParent(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT m.id " + "FROM threads t1 " + "JOIN threads t2 ON (t1.parent = t2.id) " + "LEFT JOIN messages m ON (t2.message_id = m.id) " + "WHERE t1.message_id = ? AND m.empty = 1", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0)) ? cursor.getLong(0) : -1; } finally { cursor.close(); } } /** * Check whether or not a message has child messages in the thread structure. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the children for. * * @return {@code true} if the message has children. {@code false} otherwise. */ private boolean hasThreadChildren(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT COUNT(t2.id) " + "FROM threads t1 " + "JOIN threads t2 ON (t2.parent = t1.id) " + "WHERE t1.message_id = ?", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0) && cursor.getLong(0) > 0L); } finally { cursor.close(); } } /** * Delete a message from the 'messages' and 'threads' tables. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to delete. */ private void deleteMessageRow(SQLiteDatabase db, long messageId) { String[] idArg = { Long.toString(messageId) }; // Delete the message db.delete("messages", "id = ?", idArg); // Delete row in 'threads' table // TODO: create trigger for 'messages' table to get rid of the row in 'threads' table db.delete("threads", "message_id = ?", idArg); } private void loadHeaders() throws MessagingException { List<LocalMessage> messages = new ArrayList<LocalMessage>(); messages.add(this); mHeadersLoaded = true; // set true before calling populate headers to stop recursion getFolder().populateHeaders(messages); } @Override public void addHeader(String name, String value) throws MessagingException { if (!mHeadersLoaded) loadHeaders(); super.addHeader(name, value); } @Override public void addRawHeader(String name, String raw) { throw new RuntimeException("Not supported"); } @Override public void setHeader(String name, String value) throws MessagingException { if (!mHeadersLoaded) loadHeaders(); super.setHeader(name, value); } @Override public String[] getHeader(String name) throws MessagingException { if (!mHeadersLoaded) loadHeaders(); return super.getHeader(name); } @Override public void removeHeader(String name) throws MessagingException { if (!mHeadersLoaded) loadHeaders(); super.removeHeader(name); } @Override public Set<String> getHeaderNames() throws MessagingException { if (!mHeadersLoaded) loadHeaders(); return super.getHeaderNames(); } @Override public LocalMessage clone() { LocalMessage message = new LocalMessage(this.localStore); super.copy(message); message.mId = mId; message.mAttachmentCount = mAttachmentCount; message.mSubject = mSubject; message.mPreview = mPreview; message.mHeadersLoaded = mHeadersLoaded; return message; } public long getThreadId() { return mThreadId; } public long getRootId() { return mRootId; } public Account getAccount() { return localStore.getAccount(); } public MessageReference makeMessageReference() { if (mReference == null) { mReference = new MessageReference(); mReference.folderName = getFolder().getName(); mReference.uid = mUid; mReference.accountUuid = getFolder().getAccountUuid(); } return mReference; } @Override protected void copy(MimeMessage destination) { super.copy(destination); if (destination instanceof LocalMessage) { ((LocalMessage)destination).mReference = mReference; } } @Override public LocalFolder getFolder() { return (LocalFolder) super.getFolder(); } public String getUri() { return "email://messages/" + getAccount().getAccountNumber() + "/" + getFolder().getName() + "/" + getUid(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; final LocalMessage that = (LocalMessage) o; return !(getAccountUuid() != null ? !getAccountUuid().equals(that.getAccountUuid()) : that.getAccountUuid() != null); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (getAccountUuid() != null ? getAccountUuid().hashCode() : 0); return result; } private String getAccountUuid() { return getAccount().getUuid(); } }
package com.badlogic.gdx.utils; import java.util.Arrays; /** A bitset, without size limitation, allows comparison via bitwise operators to other bitfields. * @author mzechner */ public class Bits { long[] bits = { 0 }; /** * @param index the index of the bit * @return whether the bit is set * @throws ArrayIndexOutOfBoundsException if index < 0 */ public boolean get (int index) { final int word = index >>> 6; if(word >= bits.length) return false; return (bits[word] & (1L << (index & 0x3F))) != 0L; } /** * @param index the index of the bit to set * @throws ArrayIndexOutOfBoundsException if index < 0 */ public void set (int index) { final int word = index >>> 6; checkCapacity(word); bits[word] |= 1L << (index & 0x3F); } /** * @param index the index of the bit to flip */ public void flip(int index) { final int word = index >>> 6; checkCapacity(word); bits[word] ^= 1L << (index & 0x3F); } private void checkCapacity(int len) { if(len>=bits.length) { long[] newBits = new long[len+1]; System.arraycopy(bits, 0, newBits, 0, bits.length); bits = newBits; } } /** * @param index the index of the bit to clear * @throws ArrayIndexOutOfBoundsException if index < 0 */ public void clear (int index) { final int word = index >>> 6; if(word >= bits.length) return; bits[word] &= ~(1L << (index & 0x3F)); } /** * Clears the entire bitset */ public void clear () { int length = bits.length; for (int i = 0; i < length; i++) { bits[i] = 0L; } } /** * @return the number of bits currently stored, <b>not</b> the highset set bit! */ public int numBits() { return bits.length << 6; } }
package net.sourceforge.texlipse.model; /** * This class provides methods for retrieving partial matches from arrays. * Sorted arrays containing <code>AbstractEntry</code> -objects can be searched * for entries whose <code>key</code> starts with the given string. * * This class provides both a linear search algorithm (for a reference to test new * algorithms with) as well as a binary search algorithm. * * @author Oskar Ojala * @author Boris von Loesch */ public abstract class PartialRetriever { /** * Search the given (sorted) array of entries for all entries, * for which the start of the key matches the given search string. * * This version uses a trivial linear search, which performs in O(n). * * @param start The start of the searchable string * @param entries The entries to search * @return A two-element array with the lower (inclusive) and upper * (exclusive) bounds or {-1,-1} if no matching entries were found. */ protected int[] getCompletionsLin(String start, AbstractEntry[] entries) { int startIdx = -1, endIdx = -1; for (int i=0; i < entries.length; i++) { if (entries[i].key.startsWith(start)) { if (startIdx == -1) startIdx = i; } else if (startIdx != -1) { endIdx = i; break; } } if (startIdx != -1 && endIdx == -1) endIdx = startIdx + 1; return new int[] {startIdx, endIdx}; } /** * Returns (if exist) the position of the entry with the given name in * the array * @param entryname Name of the wanted entry * @param entries Sorted array of AbstractEntry * @return The position inside the array or -1 if the entry was not found */ protected int getEntry(String entryname, AbstractEntry[] entries){ if (entries == null || entries.length == 0) return -1; int start = 0; int end = entries.length; while (end-start>1 && !entries[(start+end)/2].key.equals(entryname)){ int c = entries[(start+end)/2].key.compareTo(entryname); if (c < 0) start = (start+end)/2; else end = (start+end)/2; } if (entries[(start+end)/2].key.equals(entryname)) return (start+end)/2; else return -1; } /** * Search the given (sorted) array of entries for all entries, * for which the start of the key matches the given search string. * * This version uses binary search for finding the lower and upper * bounds, resulting in O(log n) performance. * * @param start The start of the searchable string * @param entries The entries to search * @return A two-element array with the lower (inclusive) and upper * (exclusive) bounds or {-1,-1} if no matching entries were found. */ protected int[] getCompletionsBin(String start, AbstractEntry[] entries) { return this.getCompletionsBin(start, entries, new int[] {0, entries.length}); } /** * Search the given (sorted) array of entries for all entries, * for which the start of the key matches the given search string. * * This version uses binary search for finding the lower and upper * bounds, resulting in O(log n) performance. * * @param start The start of the searchable string * @param entries The entries to search * @param initBounds The initial lower and upper bounds to start the * search from * @return A two-element array with the lower (inclusive) and upper * (exclusive) bounds or {-1,-1} if no matching entries were found. */ protected int[] getCompletionsBin(String start, AbstractEntry[] entries, int[] initBounds) { int[] bounds = new int[] {-1,-1}; int left = initBounds[0], right = initBounds[1] - 1; int middle = right/2; if (left > right) return bounds; if (entries[left].key.startsWith(start)) right = middle = left; // get upper bound (inclusive) while (left < middle) { if (entries[middle].key.compareTo(start) >= 0) { right = middle; middle = (left + middle)/2; } else { left = middle; middle = (middle + right)/2; } } if (!entries[right].key.startsWith(start)) return bounds; bounds[0] = right; // get lower bound (exclusive) left = right; right = initBounds[1] - 1; if (entries[right].key.startsWith(start)) { bounds[1] = right + 1; return bounds; } middle = (left + right)/2; while (left < middle) { if (entries[middle].key.startsWith(start)) { left = middle; middle = (right + middle)/2; } else { right = middle; middle = (middle + left)/2; } } bounds[1] = right; return bounds; } }
package org.yamcs; import static java.util.concurrent.TimeUnit.NANOSECONDS; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UncheckedIOException; import java.io.Writer; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.yamcs.Spec.OptionType; import org.yamcs.logging.ConsoleFormatter; import org.yamcs.logging.Log; import org.yamcs.logging.YamcsLogManager; import org.yamcs.management.ManagementService; import org.yamcs.mdb.XtceDbFactory; import org.yamcs.protobuf.YamcsInstance.InstanceState; import org.yamcs.security.CryptoUtils; import org.yamcs.security.SecurityStore; import org.yamcs.tctm.Link; import org.yamcs.templating.Template; import org.yamcs.templating.Variable; import org.yamcs.time.RealtimeTimeService; import org.yamcs.time.TimeService; import org.yamcs.utils.ExceptionUtil; import org.yamcs.utils.TimeEncoding; import org.yamcs.utils.YObjectLoader; import org.yamcs.yarch.YarchDatabase; import org.yamcs.yarch.rocksdb.RDBFactory; import org.yamcs.yarch.rocksdb.RdbStorageEngine; import org.yaml.snakeyaml.Yaml; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import com.google.common.util.concurrent.Service.State; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.UncheckedExecutionException; import io.netty.util.ResourceLeakDetector; /** * * Yamcs server together with the global instances * * * @author nm * */ public class YamcsServer { private static final String CFG_SERVER_ID_KEY = "serverId"; private static final String CFG_SECRET_KEY = "secretKey"; public static final String CFG_CRASH_HANDLER_KEY = "crashHandler"; public static final String GLOBAL_INSTANCE = "_global"; private static final Log LOG = new Log(YamcsServer.class); private static final Pattern INSTANCE_PATTERN = Pattern.compile("yamcs\\.(.*)\\.yaml(.offline)?"); private static final YamcsServer YAMCS = new YamcsServer(); // used to schedule various tasks throughout the yamcs server (to avoid each service creating its own) ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("YamcsServer-general-executor").build()); /** * During shutdown, allow services this number of seconds for stopping */ public static final int SERVICE_STOP_GRACE_TIME = 10; static TimeService realtimeTimeService = new RealtimeTimeService(); // used for unit tests static TimeService mockupTimeService; private CrashHandler globalCrashHandler; private YamcsServerOptions options = new YamcsServerOptions(); private YConfiguration config; private Spec spec; private Map<ConfigScope, Map<String, Spec>> sectionSpecs = new HashMap<>(); private Map<String, CommandOption> commandOptions = new ConcurrentHashMap<>(); List<ServiceWithConfig> globalServiceList; Map<String, YamcsServerInstance> instances = new LinkedHashMap<>(); Map<String, Template> instanceTemplates = new HashMap<>(); List<ReadyListener> readyListeners = new ArrayList<>(); private SecurityStore securityStore; private PluginManager pluginManager; private String serverId; private byte[] secretKey; int maxOnlineInstances = 1000; int maxNumInstances = 20; Path incomingDir; Path cacheDir; Path instanceDefDir; /** * Creates services at global (if instance is null) or instance level. The services are not yet initialized. This * must be done in a second step, so that components can ask YamcsServer for other service instantiations. * * @param instance * if null, then start a global service, otherwise an instance service * @param services * list of service configuration; each of them is a string (=classname) or a map * @param targetLog * the logger to use for any messages * @throws IOException * @throws ValidationException */ static List<ServiceWithConfig> createServices(String instance, List<YConfiguration> servicesConfig, Log targetLog) throws ValidationException, IOException { ManagementService managementService = ManagementService.getInstance(); Set<String> names = new HashSet<>(); List<ServiceWithConfig> serviceList = new CopyOnWriteArrayList<>(); for (YConfiguration servconf : servicesConfig) { String servclass; String name = null; servclass = servconf.getString("class"); YConfiguration args = servconf.getConfigOrEmpty("args"); name = servconf.getString("name", servclass.substring(servclass.lastIndexOf('.') + 1)); String candidateName = name; int count = 1; while (names.contains(candidateName)) { candidateName = name + "-" + count; count++; } name = candidateName; boolean enabledAtStartup = servconf.getBoolean("enabledAtStartup", true); targetLog.info("Loading service {}", name); ServiceWithConfig swc; try { swc = createService(instance, servclass, name, args, enabledAtStartup); serviceList.add(swc); } catch (NoClassDefFoundError e) { targetLog.error("Cannot create service {}, with arguments {}: class {} not found", name, args, e.getMessage()); throw e; } catch (ValidationException e) { throw e; } catch (Exception e) { targetLog.error("Cannot create service {}, with arguments {}: {}", name, args, e.getMessage()); throw e; } if (managementService != null) { managementService.registerService(instance, name, swc.service); } names.add(name); } return serviceList; } public static void initServices(String instance, List<ServiceWithConfig> services) throws InitException { for (ServiceWithConfig swc : services) { swc.service.init(instance, swc.name, swc.args); } } public <T extends YamcsService> void addGlobalService( String name, Class<T> serviceClass, YConfiguration args) throws ValidationException, InitException { for (ServiceWithConfig otherService : YAMCS.globalServiceList) { if (otherService.getName().equals(name)) { throw new ConfigurationException(String.format( "A service named '%s' already exists", name)); } } LOG.info("Loading service {}", name); ServiceWithConfig swc = createService(null, serviceClass.getName(), name, args, true); swc.service.init(null, name, swc.args); YAMCS.globalServiceList.add(swc); ManagementService managementService = ManagementService.getInstance(); managementService.registerService(null, name, swc.service); } /** * Starts the specified list of services. * * @param serviceList * list of service configurations * @throws ConfigurationException */ public static void startServices(List<ServiceWithConfig> serviceList) throws ConfigurationException { for (ServiceWithConfig swc : serviceList) { if (!swc.enableAtStartup) { LOG.debug("NOT starting service {} because enableAtStartup=false (can be manually started)", swc.getName()); continue; } LOG.debug("Starting service {}", swc.getName()); swc.service.startAsync(); try { swc.service.awaitRunning(); } catch (IllegalStateException e) { // this happens when it fails, the next check will throw an error in this case } State result = swc.service.state(); if (result == State.FAILED) { throw new ConfigurationException("Failed to start service " + swc.service, swc.service.failureCause()); } } } public void shutDown() { long t0 = System.nanoTime(); LOG.debug("Yamcs is shutting down"); for (YamcsServerInstance ys : instances.values()) { ys.stopAsync(); } for (YamcsServerInstance ys : instances.values()) { LOG.debug("Awaiting termination of instance {}", ys.getName()); ys.awaitOffline(); } if (globalServiceList != null) { for (ServiceWithConfig swc : globalServiceList) { swc.getService().stopAsync(); } for (ServiceWithConfig swc : globalServiceList) { LOG.debug("Awaiting termination of service {}", swc.getName()); swc.getService().awaitTerminated(); } } // Shutdown database when we're sure no services are using it. RdbStorageEngine.getInstance().shutdown(); long stopTime = System.nanoTime() - t0; LOG.debug("Yamcs stopped in {}ms", NANOSECONDS.toMillis(stopTime)); YamcsLogManager.shutdown(); timer.shutdown(); } public static boolean hasInstance(String instance) { return YAMCS.instances.containsKey(instance); } public boolean hasInstanceTemplate(String template) { return instanceTemplates.containsKey(template); } /** * The serverId has to be unique among Yamcs servers connected to eachother. * <p> * It is used to distinguish the data generated by one particular server. * * @return */ public String getServerId() { return serverId; } public byte[] getSecretKey() { return secretKey; } /** * Registers the system-wide availability of a {@link CommandOption}. Command options represent additional arguments * that commands may require, but that are not used by Yamcs in building telecommand binary. * <p> * An example use case would be a custom TC {@link Link} that may support additional arguments for controlling its * behaviour. * <p> * While not enforced we recommend to call this method from a {@link Plugin#onLoad(YConfiguration)} hook as this * will avoid registering an option multiple times (attempts to do so would generate an error). * * @param option * the new command option. */ @Experimental public void addCommandOption(CommandOption option) { CommandOption previous = commandOptions.putIfAbsent(option.getId(), option); if (previous != null) { throw new IllegalArgumentException( "A command option with '" + option.getId() + "' was already registered with Yamcs"); } } /** * Returns the command options registered to this instance. */ public Collection<CommandOption> getCommandOptions() { return commandOptions.values(); } public boolean hasCommandOption(String id) { return commandOptions.containsKey(id); } public CommandOption getCommandOption(String id) { return commandOptions.get(id); } /** * Returns the main Yamcs configuration */ public YConfiguration getConfig() { return config; } /** * Returns the configuration specification for the config returned by {@link #getConfig()}. */ public Spec getSpec() { return spec; } private int getOnlineInstanceCount() { return (int) instances.values().stream().filter(ysi -> ysi.state() != InstanceState.OFFLINE).count(); } /** * Restarts a yamcs instance. * * @param instanceName * the name of the instance * * @return the newly created instance * @throws IOException */ public YamcsServerInstance restartInstance(String instanceName) throws IOException { YamcsServerInstance ysi = instances.get(instanceName); if (ysi.state() == InstanceState.RUNNING || ysi.state() == InstanceState.FAILED) { try { ysi.stop(); } catch (IllegalStateException e) { LOG.warn("Instance did not terminate normally", e); } } YarchDatabase.removeInstance(instanceName); XtceDbFactory.remove(instanceName); LOG.info("Re-loading instance '{}'", instanceName); YConfiguration instanceConfig = loadInstanceConfig(instanceName); ysi.init(instanceConfig); ysi.startAsync(); try { ysi.awaitRunning(); } catch (IllegalStateException e) { Throwable t = ExceptionUtil.unwind(e.getCause()); LOG.warn("Failed to start instance", t); throw new UncheckedExecutionException(t); } return ysi; } private YConfiguration loadInstanceConfig(String instanceName) { Path configFile = instanceDefDir.resolve(configFileName(instanceName)); if (Files.exists(configFile)) { try (InputStream is = Files.newInputStream(configFile)) { String confPath = configFile.toAbsolutePath().toString(); return new YConfiguration("yamcs." + instanceName, is, confPath); } catch (IOException e) { throw new ConfigurationException("Cannot load configuration from " + configFile.toAbsolutePath(), e); } } else { return YConfiguration.getConfiguration("yamcs." + instanceName); } } @SuppressWarnings("unchecked") private InstanceMetadata loadInstanceMetadata(String instanceName) throws IOException { Path metadataFile = instanceDefDir.resolve("yamcs." + instanceName + ".metadata"); if (Files.exists(metadataFile)) { try (InputStream in = Files.newInputStream(metadataFile)) { Map<String, Object> map = new Yaml().loadAs(in, Map.class); return new InstanceMetadata(map); } } return new InstanceMetadata(); } /** * Stop the instance (it will be offline after this) * * @param instanceName * the name of the instance * * @return the instance * @throws IOException */ public YamcsServerInstance stopInstance(String instanceName) throws IOException { YamcsServerInstance ysi = instances.get(instanceName); if (ysi.state() != InstanceState.OFFLINE) { try { ysi.stop(); } catch (IllegalStateException e) { LOG.error("Instance did not terminate normally", e); } } YarchDatabase.removeInstance(instanceName); XtceDbFactory.remove(instanceName); Path f = instanceDefDir.resolve(configFileName(instanceName)); if (Files.exists(f)) { LOG.debug("Renaming {} to {}.offline", f.toAbsolutePath(), f.getFileName()); Files.move(f, f.resolveSibling(configFileName(instanceName) + ".offline")); } return ysi; } public void removeInstance(String instanceName) throws IOException { stopInstance(instanceName); Files.deleteIfExists(instanceDefDir.resolve(configFileName(instanceName))); Files.deleteIfExists(instanceDefDir.resolve(configFileName(instanceName) + ".offline")); instances.remove(instanceName); } /** * Start the instance. If the instance is already started, do nothing. * * If the instance is FAILED, restart the instance * * If the instance is OFFLINE, rename the &lt;instance&gt;.yaml.offline to &lt;instance&gt;.yaml and start the * instance * * * @param instanceName * the name of the instance * * @return the instance * @throws IOException */ public YamcsServerInstance startInstance(String instanceName) throws IOException { YamcsServerInstance ysi = instances.get(instanceName); if (ysi.state() == InstanceState.RUNNING) { return ysi; } else if (ysi.state() == InstanceState.FAILED) { return restartInstance(instanceName); } if (getOnlineInstanceCount() >= maxOnlineInstances) { throw new LimitExceededException("Number of online instances already at the limit " + maxOnlineInstances); } if (ysi.state() == InstanceState.OFFLINE) { Path f = instanceDefDir.resolve(configFileName(instanceName) + ".offline"); if (Files.exists(f)) { Files.move(f, instanceDefDir.resolve(configFileName(instanceName))); } YConfiguration instanceConfig = loadInstanceConfig(instanceName); ysi.init(instanceConfig); } ysi.startAsync(); ysi.awaitRunning(); return ysi; } public PluginManager getPluginManager() { return pluginManager; } /** * Add the definition of an additional configuration section to the root Yamcs spec (yamcs.yaml). * * @param key * the name of this section. This represent a direct subkey of the main app config * @param spec * the specification of this configuration section. */ public void addConfigurationSection(String key, Spec spec) { addConfigurationSection(ConfigScope.YAMCS, key, spec); } /** * Add the definition of an additional configuration section to a particulat configuration type * * @param scope * the scope where this section belongs. When using file-based configuration this can be thought of as * the type of the configuration file. * @param key * the name of this section. This represent a direct subkey of the main app config * @param spec * the specification of this configuration section. */ public void addConfigurationSection(ConfigScope scope, String key, Spec spec) { Map<String, Spec> specs = sectionSpecs.computeIfAbsent(scope, x -> new HashMap<>()); specs.put(key, spec); } public Map<String, Spec> getConfigurationSections(ConfigScope scope) { Map<String, Spec> specs = sectionSpecs.get(scope); return specs != null ? specs : Collections.emptyMap(); } public synchronized YamcsServerInstance addInstance(String name, InstanceMetadata metadata, boolean offline, YConfiguration config) { if (instances.containsKey(name)) { throw new IllegalArgumentException(String.format("There already exists an instance named '%s'", name)); } LOG.info("Loading {} instance '{}'", offline ? "offline" : "online", name); YamcsServerInstance ysi = new YamcsServerInstance(name, metadata); ysi.addStateListener(new InstanceStateListener() { @Override public void failed(Throwable failure) { LOG.error("Instance {} failed", name, ExceptionUtil.unwind(failure)); } }); instances.put(name, ysi); if (!offline) { ysi.init(config); } ManagementService.getInstance().registerYamcsInstance(ysi); return ysi; } /** * Create a new instance based on a template. * * @param name * the name of the instance * @param templateName * the name of an available template * @param templateArgs * arguments to use while processing the template * @param labels * labels associated to this instance * @param customMetadata * custom metadata associated with this instance. * @throws IOException * when a disk operation failed * @return the newly create instance */ public synchronized YamcsServerInstance createInstance(String name, String templateName, Map<String, Object> templateArgs, Map<String, String> labels, Map<String, Object> customMetadata) throws IOException { if (instances.containsKey(name)) { throw new IllegalArgumentException(String.format("There already exists an instance named '%s'", name)); } if (!instanceTemplates.containsKey(templateName)) { throw new IllegalArgumentException(String.format("Unknown template '%s'", templateName)); } Template template = instanceTemplates.get(templateName); // Build instance metadata as a combination of internal properties and custom metadata from the caller InstanceMetadata metadata = new InstanceMetadata(); metadata.setTemplate(templateName); metadata.setTemplateArgs(templateArgs); metadata.setTemplateSource(template.getSource()); metadata.setLabels(labels); customMetadata.forEach((k, v) -> metadata.put(k, v)); String processed = template.process(metadata.getTemplateArgs()); Path confFile = instanceDefDir.resolve(configFileName(name)); try (Writer writer = Files.newBufferedWriter(confFile)) { writer.write(processed); } Path metadataFile = instanceDefDir.resolve("yamcs." + name + ".metadata"); try (Writer writer = Files.newBufferedWriter(metadataFile)) { Map<String, Object> metadataMap = metadata.toMap(); new Yaml().dump(metadataMap, writer); } YConfiguration instanceConfig; try (InputStream fis = Files.newInputStream(confFile)) { String subSystem = "yamcs." + name; String confPath = confFile.toString(); instanceConfig = new YConfiguration(subSystem, fis, confPath); } return addInstance(name, metadata, false, instanceConfig); } public synchronized YamcsServerInstance reconfigureInstance(String name, Map<String, Object> templateArgs, Map<String, String> labels) throws IOException { YamcsServerInstance ysi = instances.get(name); if (ysi == null) { throw new IllegalArgumentException(String.format("Unknown instance '%s'", name)); } String templateName = ysi.getTemplate(); if (!instanceTemplates.containsKey(templateName)) { throw new IllegalArgumentException(String.format("Unknown template '%s'", templateName)); } Template template = instanceTemplates.get(templateName); // Build instance metadata as a combination of internal properties and custom metadata from the caller InstanceMetadata metadata = ysi.metadata; metadata.setLabels(labels); metadata.setTemplateArgs(templateArgs); metadata.setTemplateSource(template.getSource()); String processed = template.process(metadata.getTemplateArgs()); Path confFile = instanceDefDir.resolve(configFileName(name)); try (Writer writer = Files.newBufferedWriter(confFile)) { writer.write(processed); } Path metadataFile = instanceDefDir.resolve("yamcs." + name + ".metadata"); try (Writer writer = Files.newBufferedWriter(metadataFile)) { Map<String, Object> metadataMap = metadata.toMap(); new Yaml().dump(metadataMap, writer); } return ysi; } private String deriveServerId() { try { String id; if (config.containsKey(CFG_SERVER_ID_KEY)) { id = config.getString(CFG_SERVER_ID_KEY); } else { id = InetAddress.getLocalHost().getHostName(); } serverId = id; LOG.debug("Using serverId {}", serverId); return serverId; } catch (ConfigurationException e) { throw e; } catch (UnknownHostException e) { String msg = "Cannot resolve local host. Make sure it's defined properly or alternatively add 'serverId: <name>' to yamcs.yaml"; LOG.warn(msg); throw new ConfigurationException(msg, e); } } private void deriveSecretKey() { if (config.containsKey(CFG_SECRET_KEY)) { // Should maybe only allow base64 encoded secret keys secretKey = config.getString(CFG_SECRET_KEY).getBytes(StandardCharsets.UTF_8); } else { LOG.warn("Generating random non-persisted secret key." + " Cryptographic verifications will not work across server restarts." + " Set 'secretKey: <secret>' in yamcs.yaml to avoid this message."); secretKey = CryptoUtils.generateRandomSecretKey(); } } public static List<YamcsServerInstance> getInstances() { return new ArrayList<>(YAMCS.instances.values()); } public YamcsServerInstance getInstance(String yamcsInstance) { return instances.get(yamcsInstance); } public Set<Template> getInstanceTemplates() { return new HashSet<>(instanceTemplates.values()); } public Template getInstanceTemplate(String name) { return instanceTemplates.get(name); } /** * Returns the time service for a given instance */ public static TimeService getTimeService(String yamcsInstance) { if (YAMCS.instances.containsKey(yamcsInstance)) { return YAMCS.instances.get(yamcsInstance).getTimeService(); } else { if (mockupTimeService != null) { return mockupTimeService; } else { return realtimeTimeService; // happens from unit tests } } } public SecurityStore getSecurityStore() { return securityStore; } public List<ServiceWithConfig> getGlobalServices() { return new ArrayList<>(globalServiceList); } public ServiceWithConfig getGlobalServiceWithConfig(String serviceName) { if (globalServiceList == null) { return null; } synchronized (globalServiceList) { for (ServiceWithConfig swc : globalServiceList) { if (swc.getName().equals(serviceName)) { return swc; } } } return null; } public <T extends YamcsService> T getService(String yamcsInstance, Class<T> serviceClass) { List<T> services = getServices(yamcsInstance, serviceClass); if (services.size() == 1) { return services.get(0); } else if (services.size() > 2) { throw new IllegalStateException(serviceClass.getName() + " is not a singleton service"); } else { return null; } } public <T extends YamcsService> List<T> getServices(String yamcsInstance, Class<T> serviceClass) { YamcsServerInstance ys = getInstance(yamcsInstance); if (ys == null) { return Collections.emptyList(); } return ys.getServices(serviceClass); } public static void setMockupTimeService(TimeService timeService) { mockupTimeService = timeService; } public YamcsService getGlobalService(String serviceName) { ServiceWithConfig serviceWithConfig = getGlobalServiceWithConfig(serviceName); return serviceWithConfig != null ? serviceWithConfig.getService() : null; } public <T extends YamcsService> T getGlobalService(Class<T> serviceClass) { List<T> services = getGlobalServices(serviceClass); if (services.size() == 1) { return services.get(0); } else if (services.size() > 2) { throw new IllegalStateException(serviceClass.getName() + " is not a singleton service"); } else { return null; } } @SuppressWarnings("unchecked") public <T extends YamcsService> List<T> getGlobalServices(Class<T> serviceClass) { List<T> services = new ArrayList<>(); if (globalServiceList != null) { for (ServiceWithConfig swc : globalServiceList) { if (serviceClass.isInstance(swc.service)) { services.add((T) swc.service); } } } return services; } static ServiceWithConfig createService(String instance, String serviceClass, String serviceName, YConfiguration args, boolean enabledAtStartup) throws ConfigurationException, ValidationException { YamcsService service = null; service = YObjectLoader.loadObject(serviceClass); if (args instanceof YConfiguration) { // try { Spec spec = service.getSpec(); if (spec != null) { if (LOG.isDebugEnabled()) { Map<String, Object> unsafeArgs = ((YConfiguration) args).getRoot(); Map<String, Object> safeArgs = spec.maskSecrets(unsafeArgs); LOG.debug("Raw args for {}: {}", serviceName, safeArgs); } args = spec.validate((YConfiguration) args); if (LOG.isDebugEnabled()) { Map<String, Object> unsafeArgs = ((YConfiguration) args).getRoot(); Map<String, Object> safeArgs = spec.maskSecrets(unsafeArgs); LOG.debug("Initializing {} with resolved args: {}", serviceName, safeArgs); } } // service.init(instance, serviceName, (YConfiguration) args); // } catch (InitException e) { // TODO should add this to throws instead // throw new ConfigurationException(e); } return new ServiceWithConfig(service, serviceClass, serviceName, args, enabledAtStartup); } // starts a service that has stopped or not yet started static YamcsService startService(String instance, String serviceName, List<ServiceWithConfig> serviceList) throws ConfigurationException, ValidationException, InitException { for (int i = 0; i < serviceList.size(); i++) { ServiceWithConfig swc = serviceList.get(i); if (swc.name.equals(serviceName)) { switch (swc.service.state()) { case RUNNING: case STARTING: // do nothing, service is already starting break; case NEW: // not yet started, start it now swc.service.startAsync(); break; case FAILED: case STOPPING: case TERMINATED: // start a new one swc = createService(instance, swc.serviceClass, serviceName, swc.args, swc.enableAtStartup); swc.service.init(instance, swc.getName(), swc.args); serviceList.set(i, swc); swc.service.startAsync(); break; } return swc.service; } } return null; } public void startGlobalService(String serviceName) throws ConfigurationException, ValidationException, InitException { startService(null, serviceName, globalServiceList); } public CrashHandler getCrashHandler(String yamcsInstance) { YamcsServerInstance ys = getInstance(yamcsInstance); if (ys != null) { return ys.getCrashHandler(); } else { return globalCrashHandler; // may happen if the instance name is not valid (in unit tests) } } public CrashHandler getGlobalCrashHandler() { return globalCrashHandler; } public Path getConfigDirectory() { return options.configDirectory; } public Path getDataDirectory() { return options.dataDir; } public Path getIncomingDirectory() { return incomingDir; } public Path getCacheDirectory() { return cacheDir; } /** * Register a listener that will be called when Yamcs has fully started. If you register a listener after Yamcs has * already started, your callback will not be executed. */ public void addReadyListener(ReadyListener readyListener) { readyListeners.add(readyListener); } /** * @return the (singleton) server */ public static YamcsServer getServer() { return YAMCS; } public static void main(String[] args) { long t0 = System.nanoTime(); // Run jcommander before setting up logging. // We want this to use standard streams. parseArgs(args); System.setProperty("jxl.nowarnings", "true"); if (System.getProperty("javax.net.ssl.trustStore") == null) { System.setProperty("javax.net.ssl.trustStore", YAMCS.options.configDirectory.resolve("trustStore").toString()); } try { setupLogging(); // Bootstrap YConfiguration such that it only considers physical files. // Not classpath resources. YConfiguration.setResolver(new FileBasedConfigurationResolver(YAMCS.options.configDirectory)); YAMCS.prepareStart(); } catch (Exception e) { Throwable t = ExceptionUtil.unwind(e); if (t instanceof ValidationException) { String path = ((ValidationException) t).getContext().getPath(); LOG.error("{}: {}", path, e.getMessage()); if (YAMCS.options.check) { System.out.println("Configuration Invalid"); } YamcsLogManager.shutdown(); System.exit(-1); } else { LOG.error("Failure while attempting to validate configuration", t); YamcsLogManager.shutdown(); System.exit(-1); } } if (YAMCS.options.check) { System.out.println("Configuration OK"); System.exit(0); } ResourceLeakDetector.setLevel(YAMCS.options.nettyLeakDetection); if (ResourceLeakDetector.isEnabled()) { LOG.info("Netty leak detection: " + ResourceLeakDetector.getLevel()); } // Good to go! try { LOG.info("Yamcs {}, build {}", YamcsVersion.VERSION, YamcsVersion.REVISION); YAMCS.start(); } catch (Exception e) { LOG.error("Could not start Yamcs", ExceptionUtil.unwind(e)); System.exit(-1); } YAMCS.reportReady(System.nanoTime() - t0); } private static void parseArgs(String[] args) { try { JCommander jcommander = new JCommander(YAMCS.options); jcommander.setProgramName("yamcsd"); jcommander.parse(args); if (YAMCS.options.help) { jcommander.usage(); System.exit(0); } else if (YAMCS.options.version) { System.out.println("Yamcs " + YamcsVersion.VERSION + ", build " + YamcsVersion.REVISION); PluginManager pluginManager = new PluginManager(); for (Plugin plugin : ServiceLoader.load(Plugin.class)) { PluginMetadata meta = pluginManager.getMetadata(plugin.getClass()); System.out.println(meta.getName() + " " + meta.getVersion()); } System.exit(0); } } catch (ParameterException | IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } private static void setupLogging() throws SecurityException, IOException { if (YAMCS.options.check) { Log.forceStandardStreams(Level.WARNING); return; } if (System.getProperty("java.util.logging.config.file") != null) { LOG.info("Logging configuration overriden via java property"); } else { Path configFile = YAMCS.options.configDirectory.resolve("logging.properties").toAbsolutePath(); if (Files.exists(configFile)) { try (InputStream in = Files.newInputStream(configFile)) { YamcsLogManager.setup(in); LOG.info("Logging enabled using {}", configFile); } } else { setupDefaultLogging(); } } // Intercept stdout/stderr for sending to the log system. Only catches line-terminated // string, but this should cover most uses cases. // NOTE: stream redirect gets disabled on shutdown, so keep the check dynamic. Logger stdoutLogger = Logger.getLogger("stdout"); System.setOut(new PrintStream(System.out) { @Override public void println(String x) { if (YAMCS.options.noStreamRedirect) { super.println(x); } else { stdoutLogger.info(x); } } @Override public void println(Object x) { if (YAMCS.options.noStreamRedirect) { super.println(x); } else { stdoutLogger.info(String.valueOf(x)); } } }); Logger stderrLogger = Logger.getLogger("stderr"); System.setErr(new PrintStream(System.err) { @Override public void println(String x) { if (YAMCS.options.noStreamRedirect) { super.println(x); } else { stderrLogger.severe(x); } } @Override public void println(Object x) { if (YAMCS.options.noStreamRedirect) { super.println(x); } else { stdoutLogger.info(String.valueOf(x)); } } }); } private static void setupDefaultLogging() throws SecurityException, IOException { Level logLevel = toLevel(YAMCS.options.verbose); // Not sure. This seems to be the best programmatic way. Changing Logger // instances directly only works on the weak instance. String defaultHandler = ConsoleHandler.class.getName(); String defaultFormatter = ConsoleFormatter.class.getName(); StringBuilder buf = new StringBuilder(); buf.append("handlers=").append(defaultHandler).append("\n"); buf.append(defaultHandler).append(".level=").append(logLevel).append("\n"); buf.append(defaultHandler).append(".formatter=").append(defaultFormatter).append("\n"); if (YAMCS.options.logConfig != null) { try (InputStream in = Files.newInputStream(YAMCS.options.logConfig)) { Properties props = new Properties(); props.load(in); props.forEach((logger, verbosity) -> { Level loggerLevel = toLevel(Integer.parseInt((String) verbosity)); buf.append(logger).append(".level=").append(loggerLevel).append("\n"); }); } } else { // This sets up the level for *everything*. buf.append(".level=").append(logLevel); } try (InputStream in = new ByteArrayInputStream(buf.toString().getBytes())) { YamcsLogManager.setup(in); } for (Handler handler : Logger.getLogger("").getHandlers()) { Formatter formatter = handler.getFormatter(); if (formatter instanceof ConsoleFormatter) { ((ConsoleFormatter) formatter).setEnableAnsiColors(!YAMCS.options.noColor); } } } private static Level toLevel(int verbosity) { switch (verbosity) { case 0: return Level.OFF; case 1: return Level.WARNING; case 2: return Level.INFO; case 3: return Level.FINE; default: return Level.ALL; } } public void prepareStart() throws ValidationException, IOException, InitException { pluginManager = new PluginManager(); pluginManager.discoverPlugins(); // Load the UTC-TAI.history file. // Give priority to a file in etc folder. Path utcTaiFile = options.configDirectory.resolve("UTC-TAI.history"); if (Files.exists(utcTaiFile)) { try (InputStream in = Files.newInputStream(utcTaiFile)) { TimeEncoding.setUp(in); } } else { // Default to a bundled version from classpath TimeEncoding.setUp(); } validateMainConfiguration(); discoverTemplates(); // Prevent RDBFactory from installing shutdown hooks, shutdown is organised by YamcsServer. RDBFactory.setRegisterShutdownHooks(false); // Create also services and instances so that they can validate too. addGlobalServicesAndInstances(); } public void validateMainConfiguration() throws ValidationException { Spec serviceSpec = new Spec(); serviceSpec.addOption("class", OptionType.STRING).withRequired(true); serviceSpec.addOption("args", OptionType.ANY); serviceSpec.addOption("name", OptionType.STRING); serviceSpec.addOption("enabledAtStartup", OptionType.BOOLEAN); Spec bucketSpec = new Spec(); bucketSpec.addOption("name", OptionType.STRING).withRequired(true); bucketSpec.addOption("path", OptionType.STRING); bucketSpec.addOption("maxSize", OptionType.INTEGER); bucketSpec.addOption("maxObjects", OptionType.INTEGER); spec = new Spec(); spec.addOption("services", OptionType.LIST).withElementType(OptionType.MAP) .withSpec(serviceSpec); spec.addOption("instances", OptionType.LIST).withElementType(OptionType.STRING); spec.addOption("buckets", OptionType.LIST).withElementType(OptionType.MAP) .withSpec(bucketSpec); spec.addOption("dataDir", OptionType.STRING).withDefault("yamcs-data"); spec.addOption("cacheDir", OptionType.STRING).withDefault("cache"); spec.addOption("incomingDir", OptionType.STRING).withDefault("yamcs-incoming"); spec.addOption(CFG_SERVER_ID_KEY, OptionType.STRING); spec.addOption(CFG_SECRET_KEY, OptionType.STRING).withSecret(true); spec.addOption("disabledPlugins", OptionType.LIST).withElementType(OptionType.STRING); spec.addOption("archive", OptionType.ANY); spec.addOption("rdbConfig", OptionType.ANY); Map<String, Spec> extraSections = getConfigurationSections(ConfigScope.YAMCS); extraSections.forEach((key, sectionSpec) -> { spec.addOption(key, OptionType.MAP).withSpec(sectionSpec) .withApplySpecDefaults(true); }); config = YConfiguration.getConfiguration("yamcs"); config = spec.validate(config); } public void start() throws PluginException { // Before starting anything, register a shutdown hook that will attempt graceful shutdown Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutDown(); } }); pluginManager.loadPlugins(); startServices(); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { String msg = String.format("Uncaught exception '%s' in thread %s: %s", e, t, Arrays.toString(e.getStackTrace())); LOG.error(msg); globalCrashHandler.handleCrash("UncaughtException", msg); }); } private void discoverTemplates() throws IOException { Path templatesDir = options.configDirectory.resolve("instance-templates"); if (!Files.exists(templatesDir)) { return; } try (Stream<Path> dirStream = Files.list(templatesDir)) { dirStream.filter(Files::isDirectory).forEach(p -> { Path templateFile = p.resolve("template.yaml"); if (Files.exists(templateFile)) { try { String name = p.getFileName().toString(); String source = new String(Files.readAllBytes(templateFile), StandardCharsets.UTF_8); Template template = new Template(name, source); Path metaFile = p.resolve("meta.yaml"); Map<String, Object> metaDef = new HashMap<>(); if (Files.exists(metaFile)) { try (InputStream in = Files.newInputStream(metaFile)) { metaDef = new Yaml().load(in); } } template.setDescription(YConfiguration.getString(metaDef, "description", null)); if (metaDef.containsKey("variables")) { List<Map<String, Object>> varDefs = YConfiguration.getList(metaDef, "variables"); for (Map<String, Object> varDef : varDefs) { String type = (String) varDef.getOrDefault("type", Variable.class.getName()); Variable variable = YObjectLoader.loadObject(type); variable.setName(YConfiguration.getString(varDef, "name")); variable.setLabel(YConfiguration.getString(varDef, "label", null)); variable.setRequired(YConfiguration.getBoolean(varDef, "required", true)); variable.setHelp(YConfiguration.getString(varDef, "help", null)); variable.setInitial(YConfiguration.getString(varDef, "initial", null)); if (varDef.containsKey("choices")) { variable.setChoices(YConfiguration.getList(varDef, "choices")); } template.addVariable(variable); } } addInstanceTemplate(template); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } } public void addInstanceTemplate(Template template) { instanceTemplates.put(template.getName(), template); } public void addGlobalServicesAndInstances() throws IOException, ValidationException, InitException { serverId = deriveServerId(); deriveSecretKey(); if (config.containsKey("crashHandler")) { globalCrashHandler = loadCrashHandler(config); } else { globalCrashHandler = new LogCrashHandler(); } if (options.dataDir == null) { options.dataDir = Paths.get(config.getString("dataDir")); } YarchDatabase.setHome(options.dataDir.toAbsolutePath().toString()); incomingDir = Paths.get(config.getString("incomingDir")); instanceDefDir = options.dataDir.resolve("instance-def"); if (YConfiguration.configDirectory != null) { cacheDir = YConfiguration.configDirectory.getAbsoluteFile().toPath(); } else { cacheDir = Paths.get(config.getString("cacheDir")).toAbsolutePath(); } Files.createDirectories(cacheDir); Path globalDir = options.dataDir.resolve(GLOBAL_INSTANCE); Files.createDirectories(globalDir); Files.createDirectories(instanceDefDir); if (config.containsKey("services")) { List<YConfiguration> services = config.getServiceConfigList("services"); globalServiceList = createServices(null, services, LOG); initServices(null, globalServiceList); } try { securityStore = new SecurityStore(); } catch (InitException e) { if (e.getCause() instanceof ValidationException) { throw (ValidationException) e.getCause(); } throw new ConfigurationException(e); } // Load user-configured instances. These are the ones that are explictly mentioned in yamcs.yaml int instanceCount = 0; if (config.containsKey("instances")) { for (String name : config.<String> getList("instances")) { if (instances.containsKey(name)) { throw new ConfigurationException("Duplicate instance specified: '" + name + "'"); } YConfiguration instanceConfig = YConfiguration.getConfiguration("yamcs." + name); addInstance(name, new InstanceMetadata(), false, instanceConfig); instanceCount++; } } // Load instances saved in storage try (Stream<Path> paths = Files.list(instanceDefDir)) { for (Path instanceDir : paths.collect(Collectors.toList())) { String dirname = instanceDir.getFileName().toString(); Matcher m = INSTANCE_PATTERN.matcher(dirname); if (!m.matches()) { continue; } String instanceName = m.group(1); boolean online = m.group(2) == null; if (online) { instanceCount++; if (instanceCount > maxOnlineInstances) { throw new ConfigurationException("Instance limit exceeded: " + instanceCount); } YConfiguration instanceConfig = loadInstanceConfig(instanceName); InstanceMetadata instanceMetadata = loadInstanceMetadata(instanceName); addInstance(instanceName, instanceMetadata, false, instanceConfig); } else { if (instances.size() > maxNumInstances) { LOG.warn("Number of instances exceeds the maximum {}, offline instance {} not loaded", maxNumInstances, instanceName); continue; } InstanceMetadata instanceMetadata = loadInstanceMetadata(instanceName); addInstance(instanceName, instanceMetadata, true, null); } } } } static CrashHandler loadCrashHandler(YConfiguration config) throws IOException { if (config.containsKey("crashHandler", "args")) { return YObjectLoader.loadObject(config.getSubString("crashHandler", "class"), config.getSubMap("crashHandler", "args")); } else { return YObjectLoader.loadObject(config.getSubString("crashHandler", "class")); } } private void startServices() { if (globalServiceList != null) { startServices(globalServiceList); } for (YamcsServerInstance ysi : instances.values()) { if (ysi.state() != InstanceState.OFFLINE) { ysi.startAsync(); } } } private void reportReady(long bootTime) { int instanceCount = getOnlineInstanceCount(); int serviceCount = globalServiceList.size() + getInstances().stream() .map(instance -> instance.services != null ? instance.services.size() : 0) .reduce(0, Integer::sum); String msg = String.format("Yamcs started in %dms. Started %d of %d instances and %d services", NANOSECONDS.toMillis(bootTime), instanceCount, instances.size(), serviceCount); if (options.noStreamRedirect) { System.out.println(msg); } else { // Associate the message with a specific logger LOG.info(msg); } // If started through systemd with Type=notify, Yamcs will have NOTIFY_SOCKET // env set. // Normally we would use systemd-notify to report success, but it suffers from String notifySocket = System.getenv("NOTIFY_SOCKET"); if (notifySocket != null) { try { String cmd = String.format("echo 'READY=1' | socat STDIO UNIX-SENDTO:%s", notifySocket); new ProcessBuilder("sh", "-c", cmd).inheritIO().start(); } catch (IOException e) { throw new UncheckedIOException(e); } } // Report start success to internal listeners readyListeners.forEach(ReadyListener::onReady); } public Processor getProcessor(String yamcsInstance, String processorName) { YamcsServerInstance ysi = getInstance(yamcsInstance); if (ysi == null) { return null; } return ysi.getProcessor(processorName); } public ScheduledThreadPoolExecutor getThreadPoolExecutor() { return timer; } static String configFileName(String yamcsInstance) { return "yamcs." + yamcsInstance + ".yaml"; } }
package io.github.xyzxqs.libs.xrv; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.Arrays; /** * @author xyzxqs (xyzxqs@gmail.com) */ class FuncMap<X, Y> { private static final int DEFAULT_CAPACITY = 10; private static final Object[] EMPTY_XDATA = {}; private static final int[] EMPTY_MAPER = {}; private static final YHolder[] EMPTY_YDATA = {}; /** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private static class YHolder { private Object value; private int refCount; } private int[] mapper; private int xLength; private Object[] xArray; private YHolder[] yArray; private int yLength; public FuncMap() { xArray = EMPTY_XDATA; yArray = EMPTY_YDATA; mapper = EMPTY_MAPER; } public FuncMap(int capacity) { xArray = new Object[capacity]; yArray = new YHolder[capacity]; mapper = new int[capacity]; } public void put(X x, Y y) { int xi = indexOfX(x); int yi = indexOfY(y); if (xi >= 0) { if (yi >= 0) { mapper[xi] = yi; } else { ensureYCapacity(yLength + 1); mapper[xi] = yLength; yArray[yLength++] = createY(y); } } else { ensureXCapacity(xLength + 1); if (yi >= 0) { mapper[xLength] = yi; } else { ensureYCapacity(yLength + 1); mapper[xLength] = yLength; yArray[yLength++] = createY(y); } xArray[xLength++] = x; } } private YHolder createY(Object y) { YHolder yHolder = new YHolder(); yHolder.value = y; yHolder.refCount = 1; return yHolder; } private void ensureXCapacity(int minCapacity) { if (xArray == EMPTY_XDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } // overflow-conscious code if (minCapacity - xArray.length > 0) growX(minCapacity); } private void ensureYCapacity(int minCapacity) { if (yArray == EMPTY_YDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } // overflow-conscious code if (minCapacity - yArray.length > 0) growY(minCapacity); } /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void growX(int minCapacity) { // overflow-conscious code int oldCapacity = xArray.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: xArray = Arrays.copyOf(xArray, newCapacity); mapper = Arrays.copyOf(mapper, newCapacity); } /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void growY(int minCapacity) { // overflow-conscious code int oldCapacity = yArray.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: yArray = Arrays.copyOf(yArray, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } @SuppressWarnings("unchecked") public X getXAt(int index) { if (index >= xLength) { throw new IndexOutOfBoundsException(); } else { return (X) xArray[index]; } } @SuppressWarnings("unchecked") public Y getYAt(int index) { if (index >= yLength) { throw new IndexOutOfBoundsException(); } else { return (Y) yArray[index]; } } @SuppressWarnings("unchecked") @NonNull public X[] getX(Y y) { int yi = indexOfY(y); int rc = yArray[yi].refCount; X[] rs = (X[]) new Object[yi >= 0 ? (rc - 1) : 0]; for (int i = 0, ri = 0; i < xLength && ri < rc; i++) { if (mapper[i] == yi) { rs[ri++] = (X) xArray[i]; } } return rs; } @SuppressWarnings("unchecked") @Nullable public Y getY(X x) { int xi = indexOfX(x); if (xi >= 0) { return (Y) yArray[mapper[xi]].value; } return null; } public int indexOfY(Y y) { for (int i = 0; i < yLength; i++) { if (yArray[i].value == y) { return i; } } return -1; } public int indexOfX(X x) { for (int i = 0; i < xLength; i++) { if (xArray[i] == x) { return i; } } return -1; } public boolean hasX(X x) { if (x == null) { return false; } else { for (int i = 0; i < xLength; i++) { if (x == xArray[i]) { return true; } } return false; } } public boolean hasY(Y y) { if (y == null) { return false; } else { for (int i = 0; i < xLength; i++) { if (y == yArray[i].value) { return true; } } return false; } } public boolean rmX(X x) { if (x == null) { return false; } else { int i = 0; for (; i < xLength; i++) { if (x == xArray[i]) { break; } } if (i < xLength) { int yi = mapper[i]; System.arraycopy(xArray, i + 1, xArray, i, xLength - 1 - i); System.arraycopy(mapper, i + 1, mapper, i, xLength - 1 - i); xLength YHolder yHolder = yArray[yi]; yHolder.refCount if (yHolder.refCount == 0) { yHolder.value = null; System.arraycopy(yArray, yi + 1, yArray, yi, yLength - 1 - yi); yLength for (int mi = 0; mi < xLength; mi++) { if (mapper[mi] > yi) { mapper[mi] } } } return true; } else { return false; } } } public boolean rmY(Y y) { int yi = indexOfY(y); if (yi == -1) { return false; } else { YHolder yHolder = yArray[yi]; yHolder.refCount = 0; yHolder.value = null; System.arraycopy(yArray, yi + 1, yArray, yi, yLength - 1 - yi); yLength for (int i = 0; i < xLength; i++) { if (mapper[i] == yi) { System.arraycopy(xArray, i + 1, xArray, i, xLength - 1 - i); System.arraycopy(mapper, i + 1, mapper, i, xLength - 1 - i); xLength } } for (int mi = 0; mi < xLength; mi++) { if (mapper[mi] > yi) { mapper[mi] } } return true; } } }
package com.kauailabs.navx.ftc; import android.os.Process; import android.os.SystemClock; import android.util.Log; import com.kauailabs.navx.AHRSProtocol; import com.kauailabs.navx.IMUProtocol; import com.kauailabs.navx.IMURegisters; import com.qualcomm.robotcore.hardware.DeviceInterfaceModule; import com.qualcomm.robotcore.hardware.I2cController; import com.qualcomm.robotcore.hardware.I2cDevice; import java.util.Arrays; /** * The AHRS class provides an interface to AHRS capabilities * of the KauaiLabs navX Robotics Navigation Sensor via I2C on the Android- * based FTC robotics control system, where communications occur via the * "Core Device Interface Module" produced by Modern Robotics, inc. * * The AHRS class enables access to basic connectivity and state information, * as well as key 6-axis and 9-axis orientation information (yaw, pitch, roll, * compass heading, fused (9-axis) heading and magnetic disturbance detection. * * Additionally, the ARHS class also provides access to extended information * including linear acceleration, motion detection, rotation detection and sensor * temperature. * * If used with navX-Aero-enabled devices, the AHRS class also provides access to * altitude, barometric pressure and pressure sensor temperature data * @author Scott */ public class AHRS { public enum BoardAxis { kBoardAxisX(0), kBoardAxisY(1), kBoardAxisZ(2); private int value; private BoardAxis(int value) { this.value = value; } public int getValue() { return this.value; } }; static public class BoardYawAxis { public BoardAxis board_axis; public boolean up; }; /** * The DeviceDataType specifies the * type of data to be retrieved from the sensor. Due to limitations in the * communication bandwidth, only a subset of all available data can be streamed * and still maintain a 50Hz update rate via the Core Device Interface Module, * since it is limited to a maximum of one 26-byte transfer every 10ms. * Note that if all data types are required, */ public enum DeviceDataType { /** * (default): All 6 and 9-axis processed data, sensor status and timestamp */ kProcessedData(0), /** * Unit Quaternions and unprocessed data from each individual sensor. Note that * this data does not include a timestamp. If a timestamp is needed, use * the kAll flag instead. */ kQuatAndRawData(1), /** * All processed and raw data, sensor status and timestamps. Note that on a * Android-based FTC robot using the "Core Device Interface Module", acquiring * all data requires to I2C transactions. */ kAll(3); private int value; private DeviceDataType(int value){ this.value = value; } public int getValue(){ return this.value; } }; /** * The AHRS Callback interface should be implemented if notifications * when new data is available are desired. * * This callback is invoked by the AHRS class whenever new data is r * eceived from the sensor. Note that this callback is occurring * within the context of the AHRS class IO thread, and it may * interrupt the thread running this opMode. Therefore, it is * very important to use thread synchronization techniques when * communicating between this callback and the rest of the * code in this opMode. * * The sensor_timestamp is accurate to 1 millisecond, and reflects * the time that the data was actually acquired. This callback will * only be invoked when a sensor data sample newer than the last * is received, so it is guaranteed that the same data sample will * not be delivered to this callback more than once. * * If the sensor is reset for some reason, the sensor timestamp * will be reset to 0. Therefore, if the sensor timestamp is ever * less than the previous sample, this indicates the sensor has * been reset. * * In order to be called back, the Callback interface must be registered * via the AHRS registerCallback() method. */ public interface Callback { void newProcessedDataAvailable( long timestamp ); void newQuatAndRawDataAvailable(); }; interface IoCallback { public boolean ioComplete( boolean read, int address, int len, byte[] data); }; private class BoardState { public short capability_flags; public byte update_rate_hz; public short accel_fsr_g; public short gyro_fsr_dps; public byte op_status; public byte cal_status; public byte selftest_status; } private static AHRS instance = null; private static boolean enable_logging = false; private static final int NAVX_DEFAULT_UPDATE_RATE_HZ = 50; private DeviceInterfaceModule dim = null; private navXIOThread io_thread_obj; private Thread io_thread; private int update_rate_hz = NAVX_DEFAULT_UPDATE_RATE_HZ; private Callback callback; AHRSProtocol.AHRSPosUpdate curr_data; BoardState board_state; AHRSProtocol.BoardID board_id; IMUProtocol.GyroUpdate raw_data_update; final int NAVX_I2C_DEV_7BIT_ADDRESS = 0x32; final int NAVX_I2C_DEV_8BIT_ADDRESS = NAVX_I2C_DEV_7BIT_ADDRESS << 1; protected AHRS(DeviceInterfaceModule dim, int dim_i2c_port, DeviceDataType data_type, int update_rate_hz) { this.callback = null; this.dim = dim; this.update_rate_hz = update_rate_hz; this.curr_data = new AHRSProtocol.AHRSPosUpdate(); this.board_state = new BoardState(); this.board_id = new AHRSProtocol.BoardID(); this.raw_data_update = new IMUProtocol.GyroUpdate(); io_thread_obj = new navXIOThread(dim_i2c_port, update_rate_hz, data_type, curr_data); io_thread_obj.start(); io_thread = new Thread(io_thread_obj); io_thread.start(); } /** * Registers a callback interface. This interface * will be called back when new data is available, * based upon a change in the sensor timestamp. *<p> * Note that this callback will occur within the context of the * device IO thread, which is not the same thread context the * caller typically executes in. */ public void registerCallback( Callback callback ) { this.callback = callback; } /** * Deregisters a previously registered callback interface. * * Be sure to deregister any callback which have been * previously registered, to ensure that the object * implementing the callback interface does not continue * to be accessed when no longer necessary. */ public void deregisterCallback() { this.callback = null; } public void close() { io_thread_obj.stop(); try { io_thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } instance = null; } /** * Returns the single instance (singleton) of the AHRS class. If the singleton * does not alrady exist, it will be created using the parameters passed in. * The default update rate will be used. * * If the singleton already exists, the parameters passed in will be ignored. * @return The singleton AHRS class instance. */ public static AHRS getInstance(DeviceInterfaceModule dim, int dim_i2c_port, DeviceDataType data_type) { if (instance == null) { instance = new AHRS(dim, dim_i2c_port, data_type, NAVX_DEFAULT_UPDATE_RATE_HZ); } return instance; } /** * Returns the single instance (singleton) of the AHRS class. If the singleton * does not alrady exist, it will be created using the parameters passed in, * including a custom update rate. Use this function if an update rate other than * the default is desired. * * @return The singleton AHRS class instance. */ public static AHRS getInstance(DeviceInterfaceModule dim, int dim_i2c_port, DeviceDataType data_type, byte update_rate_hz) { if (instance == null) { instance = new AHRS(dim, dim_i2c_port, data_type, update_rate_hz); } return instance; } /* Configures the AHRS class logging. To enable logging, * the input parameter should be set to 'true'. */ public static void setLogging( boolean enabled ) { enable_logging = enabled; } /* Returns 'true' if AHRS class logging is enabled, otherwise * returns 'false'. */ public static boolean getLogging() { return enable_logging; } /* Returns the "port number" on the Core Device Interface Module in which the navX-Model device is connected. */ public int getDimI2cPort() { return this.io_thread_obj.dim_port; } /* Returns the currently configured DeviceDataType. */ public DeviceDataType getDeviceDataType() { return this.io_thread_obj.data_type; } /** * Returns the current pitch value (in degrees, from -180 to 180) * reported by the sensor. Pitch is a measure of rotation around * the X Axis. * @return The current pitch value in degrees (-180 to 180). */ public float getPitch() { return curr_data.pitch; } /** * Returns the current roll value (in degrees, from -180 to 180) * reported by the sensor. Roll is a measure of rotation around * the X Axis. * @return The current roll value in degrees (-180 to 180). */ public float getRoll() { return curr_data.roll; } /** * Returns the current yaw value (in degrees, from -180 to 180) * reported by the sensor. Yaw is a measure of rotation around * the Z Axis (which is perpendicular to the earth). *<p> * Note that the returned yaw value will be offset by a user-specified * offset value; this user-specified offset value is set by * invoking the zeroYaw() method. * @return The current yaw value in degrees (-180 to 180). */ public float getYaw() { return curr_data.yaw; } /** * Returns the current tilt-compensated compass heading * value (in degrees, from 0 to 360) reported by the sensor. *<p> * Note that this value is sensed by a magnetometer, * which can be affected by nearby magnetic fields (e.g., the * magnetic fields generated by nearby motors). *<p> * Before using this value, ensure that (a) the magnetometer * has been calibrated and (b) that a magnetic disturbance is * not taking place at the instant when the compass heading * was generated. * @return The current tilt-compensated compass heading, in degrees (0-360). */ public float getCompassHeading() { return curr_data.compass_heading; } /** * Sets the user-specified yaw offset to the current * yaw value reported by the sensor. *<p> * This user-specified yaw offset is automatically * subtracted from subsequent yaw values reported by * the getYaw() method. */ public void zeroYaw() { io_thread_obj.zeroYaw(); } /** * Returns true if the sensor is currently performing automatic * gyro/accelerometer calibration. Automatic calibration occurs * when the sensor is initially powered on, during which time the * sensor should be held still, with the Z-axis pointing up * (perpendicular to the earth). *<p> * NOTE: During this automatic calibration, the yaw, pitch and roll * values returned may not be accurate. *<p> * Once calibration is complete, the sensor will automatically remove * an internal yaw offset value from all reported values. *<p> * @return Returns true if the sensor is currently automatically * calibrating the gyro and accelerometer sensors. */ public boolean isCalibrating() { return !((curr_data.cal_status & AHRSProtocol.NAVX_CAL_STATUS_IMU_CAL_STATE_MASK) == AHRSProtocol.NAVX_CAL_STATUS_IMU_CAL_COMPLETE); } /** * Indicates whether the sensor is currently connected * to the host computer. A connection is considered established * whenever communication with the sensor has occurred recently. *<p> * @return Returns true if a valid update has been recently received * from the sensor. */ public boolean isConnected() { return io_thread_obj.isConnected(); } /** * Returns the navX-Model device's currently configured update * rate. Note that the update rate that can actually be realized * is a value evenly divisible by the navX-Model device's internal * motion processor sample clock (200Hz). Therefore, the rate that * is returned may be lower than the requested sample rate. * * The actual sample rate is rounded down to the nearest integer * that is divisible by the number of Digital Motion Processor clock * ticks. For instance, a request for 58 Hertz will result in * an actual rate of 66Hz (200 / (200 / 58), using integer * math. * * @return Returns the current actual update rate in Hz * (cycles per second). */ public byte getActualUpdateRate() { final int NAVX_MOTION_PROCESSOR_UPDATE_RATE_HZ = 200; int integer_update_rate = board_state.update_rate_hz; int realized_update_rate = NAVX_MOTION_PROCESSOR_UPDATE_RATE_HZ / (NAVX_MOTION_PROCESSOR_UPDATE_RATE_HZ / integer_update_rate); return (byte)realized_update_rate; } /** * Returns the current number of data samples being transferred * from the navX-Model device in the last second. Note that this * number may be greater than the sensors update rate. * * @return Returns the count of data samples received in the * last second. */ public int getCurrentTransferRate() { return this.io_thread_obj.last_second_hertz; } /* Returns the number of navX-Model processed data samples * that were retrieved from the sensor that had a sensor * timestamp value equal to the timestamp of the last * sensor data sample. * * This information can be used to match the navX-Model * sensor update rate w/the effective update rate which * can be achieved in the Robot Controller, taking into * account the communication over the network with the * Core Device Interface Module. */ public int getDuplicateDataCount() { return this.io_thread_obj.getDuplicateDataCount(); } /** * Returns the count in bytes of data received from the * sensor. This could can be useful for diagnosing * connectivity issues. *<p> * If the byte count is increasing, but the update count * (see getUpdateCount()) is not, this indicates a software * misconfiguration. * @return The number of bytes received from the sensor. */ public double getByteCount() { return io_thread_obj.getByteCount(); } /** * Returns the count of valid updates which have * been received from the sensor. This count should increase * at the same rate indicated by the configured update rate. * @return The number of valid updates received from the sensor. */ public double getUpdateCount() { return io_thread_obj.getUpdateCount(); } /** * Returns the current linear acceleration in the X-axis (in G). *<p> * World linear acceleration refers to raw acceleration data, which * has had the gravity component removed, and which has been rotated to * the same reference frame as the current yaw value. The resulting * value represents the current acceleration in the x-axis of the * body (e.g., the robot) on which the sensor is mounted. *<p> * @return Current world linear acceleration in the X-axis (in G). */ public float getWorldLinearAccelX() { return curr_data.linear_accel_x; } /** * Returns the current linear acceleration in the Y-axis (in G). *<p> * World linear acceleration refers to raw acceleration data, which * has had the gravity component removed, and which has been rotated to * the same reference frame as the current yaw value. The resulting * value represents the current acceleration in the Y-axis of the * body (e.g., the robot) on which the sensor is mounted. *<p> * @return Current world linear acceleration in the Y-axis (in G). */ public float getWorldLinearAccelY() { return curr_data.linear_accel_y; } /** * Returns the current linear acceleration in the Z-axis (in G). *<p> * World linear acceleration refers to raw acceleration data, which * has had the gravity component removed, and which has been rotated to * the same reference frame as the current yaw value. The resulting * value represents the current acceleration in the Z-axis of the * body (e.g., the robot) on which the sensor is mounted. *<p> * @return Current world linear acceleration in the Z-axis (in G). */ public float getWorldLinearAccelZ() { return curr_data.linear_accel_z; } /** * Indicates if the sensor is currently detecting motion, * based upon the X and Y-axis world linear acceleration values. * If the sum of the absolute values of the X and Y axis exceed * a "motion threshold", the motion state is indicated. *<p> * @return Returns true if the sensor is currently detecting motion. */ public boolean isMoving() { return (curr_data.sensor_status & AHRSProtocol.NAVX_SENSOR_STATUS_MOVING) != 0; } /** * Indicates if the sensor is currently detecting yaw rotation, * based upon whether the change in yaw over the last second * exceeds the "Rotation Threshold." *<p> * Yaw Rotation can occur either when the sensor is rotating, or * when the sensor is not rotating AND the current gyro calibration * is insufficiently calibrated to yield the standard yaw drift rate. *<p> * @return Returns true if the sensor is currently detecting motion. */ public boolean isRotating() { return !((curr_data.sensor_status & AHRSProtocol.NAVX_SENSOR_STATUS_YAW_STABLE) != 0); } /** * Returns the current altitude, based upon calibrated readings * from a barometric pressure sensor, and the currently-configured * sea-level barometric pressure [navX Aero only]. This value is in units of meters. *<p> * NOTE: This value is only valid sensors including a pressure * sensor. To determine whether this value is valid, see * isAltitudeValid(). *<p> * @return Returns current altitude in meters (as long as the sensor includes * an installed on-board pressure sensor). */ public float getAltitude() { return curr_data.altitude; } /** * Indicates whether the current altitude (and barometric pressure) data is * valid. This value will only be true for a sensor with an onboard * pressure sensor installed. *<p> * If this value is false for a board with an installed pressure sensor, * this indicates a malfunction of the onboard pressure sensor. *<p> * @return Returns true if a working pressure sensor is installed. */ public boolean isAltitudeValid() { return (curr_data.sensor_status & AHRSProtocol.NAVX_SENSOR_STATUS_ALTITUDE_VALID) != 0; } /** * Returns the "fused" (9-axis) heading. *<p> * The 9-axis heading is the fusion of the yaw angle, the tilt-corrected * compass heading, and magnetic disturbance detection. Note that the * magnetometer calibration procedure is required in order to * achieve valid 9-axis headings. *<p> * The 9-axis Heading represents the sensor's best estimate of current heading, * based upon the last known valid Compass Angle, and updated by the change in the * Yaw Angle since the last known valid Compass Angle. The last known valid Compass * Angle is updated whenever a Calibrated Compass Angle is read and the sensor * has recently rotated less than the Compass Noise Bandwidth (~2 degrees). * @return Fused Heading in Degrees (range 0-360) */ public float getFusedHeading() { return curr_data.fused_heading; } /** * Indicates whether the current magnetic field strength diverges from the * calibrated value for the earth's magnetic field by more than the currently- * configured Magnetic Disturbance Ratio. *<p> * This function will always return false if the sensor's magnetometer has * not yet been calibrated; see isMagnetometerCalibrated(). * @return true if a magnetic disturbance is detected (or the magnetometer is uncalibrated). */ public boolean isMagneticDisturbance() { return (curr_data.sensor_status & AHRSProtocol.NAVX_SENSOR_STATUS_MAG_DISTURBANCE) != 0; } /** * Indicates whether the magnetometer has been calibrated. *<p> * Magnetometer Calibration must be performed by the user. *<p> * Note that if this function does indicate the magnetometer is calibrated, * this does not necessarily mean that the calibration quality is sufficient * to yield valid compass headings. *<p> * @return Returns true if magnetometer calibration has been performed. */ public boolean isMagnetometerCalibrated() { return (curr_data.cal_status & AHRSProtocol.NAVX_CAL_STATUS_MAG_CAL_COMPLETE) != 0; } /* Unit Quaternions */ public float getQuaternionW() { return ((float)curr_data.quat_w / 16384.0f); } public float getQuaternionX() { return ((float)curr_data.quat_x / 16384.0f); } public float getQuaternionY() { return ((float)curr_data.quat_y / 16384.0f); } public float getQuaternionZ() { return ((float)curr_data.quat_z / 16384.0f); } /** * Returns the current temperature (in degrees centigrade) reported by * the sensor's gyro/accelerometer circuit. *<p> * This value may be useful in order to perform advanced temperature- * correction of raw gyroscope and accelerometer values. *<p> * @return The current temperature (in degrees centigrade). */ public float getTempC() { return curr_data.mpu_temp; } public BoardYawAxis getBoardYawAxis() { BoardYawAxis yaw_axis = new BoardYawAxis(); short yaw_axis_info = (short)(board_state.capability_flags >> 3); yaw_axis_info &= 7; if ( yaw_axis_info == AHRSProtocol.OMNIMOUNT_DEFAULT) { yaw_axis.up = true; yaw_axis.board_axis = BoardAxis.kBoardAxisZ; } else { yaw_axis.up = (yaw_axis_info & 0x01) != 0; yaw_axis_info >>= 1; switch ( (byte)yaw_axis_info ) { case 0: yaw_axis.board_axis = BoardAxis.kBoardAxisX; break; case 1: yaw_axis.board_axis = BoardAxis.kBoardAxisY; break; case 2: default: yaw_axis.board_axis = BoardAxis.kBoardAxisZ; break; } } return yaw_axis; } public String getFirmwareVersion() { double version_number = (double)board_id.fw_ver_major; version_number += ((double)board_id.fw_ver_minor / 10); String fw_version = Double.toString(version_number); return fw_version; } private final float DEV_UNITS_MAX = 32768.0f; /** * Returns the current raw (unprocessed) X-axis gyro rotation rate (in degrees/sec). NOTE: this * value is un-processed, and should only be accessed by advanced users. * Typically, rotation about the X Axis is referred to as "Pitch". Calibrated * and Integrated Pitch data is accessible via the {@link #getPitch()} method. *<p> * @return Returns the current rotation rate (in degrees/sec). */ public float getRawGyroX() { return this.raw_data_update.gyro_x / (DEV_UNITS_MAX / (float)this.board_state.gyro_fsr_dps); } /** * Returns the current raw (unprocessed) Y-axis gyro rotation rate (in degrees/sec). NOTE: this * value is un-processed, and should only be accessed by advanced users. * Typically, rotation about the T Axis is referred to as "Roll". Calibrated * and Integrated Pitch data is accessible via the {@link #getRoll()} method. *<p> * @return Returns the current rotation rate (in degrees/sec). */ public float getRawGyroY() { return this.raw_data_update.gyro_y / (DEV_UNITS_MAX / (float)this.board_state.gyro_fsr_dps); } /** * Returns the current raw (unprocessed) Z-axis gyro rotation rate (in degrees/sec). NOTE: this * value is un-processed, and should only be accessed by advanced users. * Typically, rotation about the T Axis is referred to as "Yaw". Calibrated * and Integrated Pitch data is accessible via the {@link #getYaw()} method. *<p> * @return Returns the current rotation rate (in degrees/sec). */ public float getRawGyroZ() { return this.raw_data_update.gyro_z / (DEV_UNITS_MAX / (float)this.board_state.gyro_fsr_dps); } /** * Returns the current raw (unprocessed) X-axis acceleration rate (in G). NOTE: this * value is unprocessed, and should only be accessed by advanced users. This raw value * has not had acceleration due to gravity removed from it, and has not been rotated to * the world reference frame. Gravity-corrected, world reference frame-corrected * X axis acceleration data is accessible via the {@link #getWorldLinearAccelX()} method. *<p> * @return Returns the current acceleration rate (in G). */ public float getRawAccelX() { return this.raw_data_update.accel_x / (DEV_UNITS_MAX / (float)this.board_state.accel_fsr_g); } /** * Returns the current raw (unprocessed) Y-axis acceleration rate (in G). NOTE: this * value is unprocessed, and should only be accessed by advanced users. This raw value * has not had acceleration due to gravity removed from it, and has not been rotated to * the world reference frame. Gravity-corrected, world reference frame-corrected * Y axis acceleration data is accessible via the {@link #getWorldLinearAccelY()} method. *<p> * @return Returns the current acceleration rate (in G). */ public float getRawAccelY() { return this.raw_data_update.accel_y / (DEV_UNITS_MAX / (float)this.board_state.accel_fsr_g); } /** * Returns the current raw (unprocessed) Z-axis acceleration rate (in G). NOTE: this * value is unprocessed, and should only be accessed by advanced users. This raw value * has not had acceleration due to gravity removed from it, and has not been rotated to * the world reference frame. Gravity-corrected, world reference frame-corrected * Z axis acceleration data is accessible via the {@link #getWorldLinearAccelZ()} method. *<p> * @return Returns the current acceleration rate (in G). */ public float getRawAccelZ() { return this.raw_data_update.accel_z / (DEV_UNITS_MAX / (float)this.board_state.accel_fsr_g); } private final float UTESLA_PER_DEV_UNIT = 0.15f; /** * Returns the current raw (unprocessed) X-axis magnetometer reading (in uTesla). NOTE: * this value is unprocessed, and should only be accessed by advanced users. This raw value * has not been tilt-corrected, and has not been combined with the other magnetometer axis * data to yield a compass heading. Tilt-corrected compass heading data is accessible * via the {@link #getCompassHeading()} method. *<p> * @return Returns the mag field strength (in uTesla). */ public float getRawMagX() { return this.raw_data_update.mag_x / UTESLA_PER_DEV_UNIT; } /** * Returns the current raw (unprocessed) Y-axis magnetometer reading (in uTesla). NOTE: * this value is unprocessed, and should only be accessed by advanced users. This raw value * has not been tilt-corrected, and has not been combined with the other magnetometer axis * data to yield a compass heading. Tilt-corrected compass heading data is accessible * via the {@link #getCompassHeading()} method. *<p> * @return Returns the mag field strength (in uTesla). */ public float getRawMagY() { return this.raw_data_update.mag_y / UTESLA_PER_DEV_UNIT; } /** * Returns the current raw (unprocessed) Z-axis magnetometer reading (in uTesla). NOTE: * this value is unprocessed, and should only be accessed by advanced users. This raw value * has not been tilt-corrected, and has not been combined with the other magnetometer axis * data to yield a compass heading. Tilt-corrected compass heading data is accessible * via the {@link #getCompassHeading()} method. *<p> * @return Returns the mag field strength (in uTesla). */ public float getRawMagZ() { return this.raw_data_update.mag_z / UTESLA_PER_DEV_UNIT; } /** * Returns the current barometric pressure (in millibar) [navX Aero only]. *<p> *This value is valid only if a barometric pressure sensor is onboard. * * @return Returns the current barometric pressure (in millibar). */ public float getPressure() { // TODO implement for navX-Aero. return 0; } class navXIOThread implements Runnable, AHRS.IoCallback { int dim_port; int update_rate_hz; protected boolean keep_running; boolean request_zero_yaw; boolean is_connected; int byte_count; int update_count; DeviceDataType data_type; AHRSProtocol.AHRSPosUpdate ahrspos_update; long curr_sensor_timestamp; boolean cancel_all_reads; boolean first_bank; long last_valid_sensor_timestamp; int duplicate_sensor_data_count; int last_second_hertz; int hertz_counter; final int NAVX_REGISTER_FIRST = IMURegisters.NAVX_REG_WHOAMI; final int NAVX_REGISTER_PROC_FIRST = IMURegisters.NAVX_REG_SENSOR_STATUS_L; final int NAVX_REGISTER_RAW_FIRST = IMURegisters.NAVX_REG_QUAT_W_L; final int I2C_TIMEOUT_MS = 500; public navXIOThread( int port, int update_rate_hz, DeviceDataType data_type, AHRSProtocol.AHRSPosUpdate ahrspos_update) { this.dim_port = port; this.keep_running = false; this.update_rate_hz = update_rate_hz; this.request_zero_yaw = false; this.is_connected = false; this.byte_count = 0; this.update_count = 0; this.ahrspos_update = ahrspos_update; this.data_type = data_type; this.cancel_all_reads = false; this.first_bank = true; this.last_valid_sensor_timestamp = 0; this.duplicate_sensor_data_count = 0; this.last_second_hertz = 0; this.hertz_counter = 0; android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE); } public void start() { keep_running = true; } public void stop() { keep_running = false; } public void zeroYaw() { request_zero_yaw = true; } public int getByteCount() { return byte_count; } public int getDuplicateDataCount() { return duplicate_sensor_data_count; } public void addToByteCount( int new_byte_count ) { byte_count += new_byte_count; } public int getUpdateCount() { return update_count; } public void incrementUpdateCount() { update_count++; } public boolean isConnected() { return is_connected; } public void setConnected( boolean new_connected ) { is_connected = new_connected; } public boolean ioComplete( boolean read, int address, int len, byte[] data) { boolean restart = false; if ( address == NAVX_REGISTER_PROC_FIRST ) { if (!decodeNavxProcessedData(data, NAVX_REGISTER_PROC_FIRST, data.length)) { setConnected(false); } else { if ( curr_sensor_timestamp != last_valid_sensor_timestamp ) { addToByteCount(len); incrementUpdateCount(); if (callback != null) { callback.newProcessedDataAvailable(curr_sensor_timestamp); } if (data_type == DeviceDataType.kAll) { first_bank = false; } } else { duplicate_sensor_data_count++; } if ( ( curr_sensor_timestamp % 1000 ) < ( last_valid_sensor_timestamp % 1000 ) ) { /* Second roll over. Start the Hertz accumulator */ last_second_hertz = hertz_counter; hertz_counter = 1; } else { hertz_counter++; } last_valid_sensor_timestamp = curr_sensor_timestamp; if (data_type == DeviceDataType.kProcessedData) { if (!cancel_all_reads) { restart = true; } } } } else if ( address == this.NAVX_REGISTER_RAW_FIRST ) { if ( !decodeNavxQuatAndRawData(data, NAVX_REGISTER_RAW_FIRST, len) ) { setConnected(false); } else { addToByteCount(len); incrementUpdateCount(); if (callback != null) { callback.newQuatAndRawDataAvailable(); } if ( data_type == DeviceDataType.kQuatAndRawData) { if ( !cancel_all_reads) { restart = true; } } else if ( data_type == DeviceDataType.kAll ) { first_bank = true; } } } return restart; } @Override public void run() { final int DIM_MAX_I2C_READ_LEN = 26; final int NAVX_WRITE_COMMAND_BIT = 0x80; DimI2cDeviceReader navxReader[] = new DimI2cDeviceReader[3]; I2cDevice navXDevice = null; DimI2cDeviceWriter navxUpdateRateWriter = null; DimI2cDeviceWriter navxZeroYawWriter = null; byte[] update_rate_command = new byte[1]; update_rate_command[0] = (byte)update_rate_hz; byte[] zero_yaw_command = new byte[1]; zero_yaw_command[0] = AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW; if ( enable_logging ) { Log.i("navx_ftc", "Opening device on DIM port " + Integer.toString(dim_port)); } navXDevice = new I2cDevice(dim, dim_port); navxReader[0] = new DimI2cDeviceReader(navXDevice, NAVX_I2C_DEV_8BIT_ADDRESS, NAVX_REGISTER_FIRST, DIM_MAX_I2C_READ_LEN); navxReader[1] = new DimI2cDeviceReader(navXDevice, NAVX_I2C_DEV_8BIT_ADDRESS, NAVX_REGISTER_PROC_FIRST, DIM_MAX_I2C_READ_LEN); navxReader[2] = new DimI2cDeviceReader(navXDevice, NAVX_I2C_DEV_8BIT_ADDRESS, NAVX_REGISTER_RAW_FIRST, DIM_MAX_I2C_READ_LEN); /* The board state reader uses synchronous I/O. The processed and raw data readers use an asynchronous IO Completion mechanism. */ navxReader[1].registerIoCallback(this); navxReader[2].registerIoCallback(this); setConnected(false); while ( keep_running ) { try { if ( !is_connected ) { this.last_second_hertz = 0; this.last_valid_sensor_timestamp = 0; this.byte_count = 0; this.update_count = 0; this.first_bank = true; this.hertz_counter = 0; this.duplicate_sensor_data_count = 0; byte[] board_data = navxReader[0].startAndWaitForCompletion(I2C_TIMEOUT_MS); if (board_data != null) { if (decodeNavxBoardData(board_data, NAVX_REGISTER_FIRST, board_data.length)) { setConnected(true); first_bank = true; /* To handle the case where the device is reset, reconfigure the update rate whenever reconecting to the device. */ Thread.sleep(10); navxUpdateRateWriter = new DimI2cDeviceWriter(navXDevice, NAVX_I2C_DEV_8BIT_ADDRESS, NAVX_WRITE_COMMAND_BIT | IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_command); navxUpdateRateWriter.waitForCompletion(I2C_TIMEOUT_MS); /* Read back the current update rate */ Thread.sleep(10); board_data = navxReader[0].startAndWaitForCompletion(I2C_TIMEOUT_MS); if (!decodeNavxBoardData(board_data, NAVX_REGISTER_FIRST, board_data.length)) { setConnected(false); } Thread.sleep(100); global_dim_state_tracker.reset(); /* Wait for the I2C port to be ready, then continue w/normal operations. */ if ( !navXDevice.isI2cPortReady() ) { Thread.sleep(10); } } } } else { /* If connected, read sensor data and optionally zero yaw if requested */ if (request_zero_yaw) { /* if any reading is underway, wait for it to complete. */ cancel_all_reads = true; while ( navxReader[1].isBusy() || navxReader[2].isBusy() ) { Thread.sleep(1); } cancel_all_reads = false; navxZeroYawWriter = new DimI2cDeviceWriter(navXDevice, NAVX_I2C_DEV_8BIT_ADDRESS, NAVX_WRITE_COMMAND_BIT | IMURegisters.NAVX_REG_INTEGRATION_CTL, zero_yaw_command); navxZeroYawWriter.waitForCompletion(I2C_TIMEOUT_MS); request_zero_yaw = false; } /* Read Processed Data (kProcessedData or kAll) */ if ((data_type == DeviceDataType.kProcessedData) || ((data_type == DeviceDataType.kAll) && first_bank)) { if ( !navxReader[1].isBusy() ) { navxReader[1].start(I2C_TIMEOUT_MS, (data_type == DeviceDataType.kProcessedData)); } } /* Read Quaternion/Raw Data (kQuatAndRawData or kAll) */ if ((data_type == DeviceDataType.kQuatAndRawData) || ((data_type == DeviceDataType.kAll) && !first_bank)) { if ( !navxReader[2].isBusy() ) { navxReader[2].start(I2C_TIMEOUT_MS, (data_type == DeviceDataType.kQuatAndRawData)); } } Thread.sleep(10); } } catch (Exception ex) { } } /* Cancel any pending IO, and wait for them to complete (or timeout) */ cancel_all_reads = true; while ( navxReader[2].isBusy() || navxReader[2].isBusy() ) { try { if ( enable_logging ) { Log.i("navx_ftc", "Waiting for outstanding reads to complete."); } Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } navxReader[1].deregisterIoCallback(this); navxReader[2].deregisterIoCallback(this); global_dim_state_tracker.reset(); if ( enable_logging ) { Log.i("navx_ftc", "Closing I2C device."); } navXDevice.close(); } boolean decodeNavxBoardData(byte[] curr_data, int first_address, int len) { final int I2C_NAVX_DEVICE_TYPE = 50; boolean valid_data; if ( curr_data[IMURegisters.NAVX_REG_WHOAMI - first_address] == I2C_NAVX_DEVICE_TYPE ){ valid_data = true; board_id.hw_rev = curr_data[IMURegisters.NAVX_REG_HW_REV - first_address]; board_id.fw_ver_major = curr_data[IMURegisters.NAVX_REG_FW_VER_MAJOR - first_address]; board_id.fw_ver_minor = curr_data[IMURegisters.NAVX_REG_FW_VER_MINOR - first_address]; board_id.type = curr_data[IMURegisters.NAVX_REG_WHOAMI - first_address]; board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data, IMURegisters.NAVX_REG_GYRO_FSR_DPS_L - first_address); board_state.accel_fsr_g = (short) curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G - first_address]; board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ - first_address]; board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(curr_data, IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L - first_address); board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address]; board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address]; board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS - first_address]; } else { valid_data = false; } return valid_data; } boolean doesDataAppearValid( byte[] curr_data ) { boolean data_valid = false; boolean all_zeros = true; boolean all_ones = true; for ( int i = 0; i < curr_data.length; i++ ) { if ( curr_data[i] != (byte)0 ) { all_zeros = false; } if ( curr_data[i] != (byte)0xFF) { all_ones = false; } if ( !all_zeros && !all_ones ) { data_valid = true; break; } } return data_valid; } boolean decodeNavxProcessedData(byte[] curr_data, int first_address, int len) { long timestamp_low, timestamp_high; boolean data_valid = doesDataAppearValid(curr_data); if ( !data_valid ) { Arrays.fill(curr_data, (byte)0); } curr_sensor_timestamp = (long)AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L - first_address); ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address]; /* Update calibration status from the "shadow" in the upper 8-bits of sensor status. */ ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_H - first_address]; ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L - first_address); ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L - first_address); ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L - first_address); ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L - first_address); ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L - first_address); ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_I_L - first_address); ahrspos_update.linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L - first_address); ahrspos_update.linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L - first_address); ahrspos_update.linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L - first_address); return data_valid; } boolean decodeNavxQuatAndRawData(byte[] curr_data, int first_address, int len) { boolean data_valid = doesDataAppearValid(curr_data); if ( !data_valid ) { Arrays.fill(curr_data, (byte)0); } ahrspos_update.quat_w = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address); ahrspos_update.quat_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address); ahrspos_update.quat_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address); ahrspos_update.quat_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address); ahrspos_update.mpu_temp = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address); raw_data_update.gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address); raw_data_update.gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address); raw_data_update.gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address); raw_data_update.accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address); raw_data_update.accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address); raw_data_update.accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address); raw_data_update.mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address); raw_data_update.mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address); /* Unfortunately, the 26-byte I2C Transfer limit means we can't transfer the Z-axis magnetometer data. */ /* This magnetomer axis typically isn't used, so it's likely not going to be missed. */ //raw_data_update.mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address); return data_valid; } } public class DimI2cDeviceWriter { private final I2cDevice device; private final int dev_address; private final int mem_address; private boolean done; private Object synchronization_event; private DimStateTracker state_tracker; public DimI2cDeviceWriter(I2cDevice i2cDevice, int i2cAddress, int memAddress, byte[] data) { this.device = i2cDevice; this.dev_address = i2cAddress; this.mem_address = memAddress; done = false; this.synchronization_event = new Object(); this.state_tracker = getDimStateTrackerInstance(); i2cDevice.copyBufferIntoWriteBuffer(data); if ( !state_tracker.isModeCurrent(false,dev_address, mem_address, data.length)) { this.state_tracker.setMode(false,dev_address, mem_address, data.length); i2cDevice.enableI2cWriteMode(i2cAddress, memAddress, data.length); } i2cDevice.setI2cPortActionFlag(); i2cDevice.writeI2cCacheToController(); i2cDevice.registerForI2cPortReadyCallback(new I2cController.I2cPortReadyCallback() { public void portIsReady(int port) { DimI2cDeviceWriter.this.portDone(); } }); } public boolean isDone() { return this.done; } private void portDone() { /* TODO: the call to isI2cPortReady() may not be necessary, and should likely be removed. */ if ( device.isI2cPortReady() ) { device.deregisterForPortReadyCallback(); done = true; synchronized(synchronization_event) { synchronization_event.notify(); } } } public boolean waitForCompletion( long timeout_ms ) { if ( done ) return true; boolean success; synchronized(synchronization_event) { try { synchronization_event.wait(timeout_ms); success = true; } catch( InterruptedException ex ) { ex.printStackTrace(); success = false; } } return success; } } enum DimState { UNKNOWN, WAIT_FOR_MODE_CONFIG_COMPLETE, WAIT_FOR_I2C_TRANSFER_COMPLETION, WAIT_FOR_HOST_BUFFER_TRANSFER_COMPLETION, READY } private static DimStateTracker global_dim_state_tracker; public DimStateTracker getDimStateTrackerInstance() { if ( global_dim_state_tracker == null ) { global_dim_state_tracker = new DimStateTracker(); } return global_dim_state_tracker; } public class DimStateTracker { private boolean read_mode; private int device_address; private int mem_address; private int num_bytes; private DimState state; public DimStateTracker() { reset(); } public void reset() { read_mode = false; device_address = -1; mem_address = -1; num_bytes = -1; state = DimState.UNKNOWN; } public void setMode( boolean read_mode, int device_address, int mem_address, int num_bytes ) { this.read_mode = read_mode; this.device_address = device_address; this.mem_address = mem_address; this.num_bytes = num_bytes; } public boolean isModeCurrent( boolean read_mode, int device_address, int mem_address, int num_bytes ) { return ( ( this.read_mode == read_mode ) && ( this.device_address == device_address ) && ( this.mem_address == mem_address ) && ( this.num_bytes == num_bytes ) ); } public void setState( DimState new_state ) { this.state = new_state; } public DimState getState() { return this.state; } }; public class DimI2cDeviceReader { private final I2cDevice device; private final int dev_address; private final int mem_address; private final int num_bytes; private byte[] device_data; private Object synchronization_event; private boolean registered; I2cController.I2cPortReadyCallback callback; IoCallback ioCallback; DimState dim_state; DimStateTracker state_tracker; long read_start_timestamp; long timeout_ms; private boolean busy; private boolean continuous_read; private boolean continuous_first; public DimI2cDeviceReader(I2cDevice i2cDevice, int i2cAddress, int memAddress, int num_bytes) { this.ioCallback = null; this.device = i2cDevice; this.dev_address = i2cAddress; this.mem_address = memAddress; this.num_bytes = num_bytes; this.synchronization_event = new Object(); this.registered = false; this.state_tracker = getDimStateTrackerInstance(); this.busy = false; this.continuous_read = false; this.continuous_first = false; this.callback = new I2cController.I2cPortReadyCallback() { public void portIsReady(int port) { portDone(); } }; } public void registerIoCallback( IoCallback ioCallback ) { if ( enable_logging ) { Log.i("navx_ftc", "Registering reader IO Callbacks."); } this.ioCallback = ioCallback; } public void deregisterIoCallback( IoCallback ioCallback ) { this.ioCallback = null; if ( enable_logging ) { Log.i("navx_ftc", "Deregistering reader IO Callbacks."); } } public void start( long timeout_ms, boolean continuous ) { start_internal( timeout_ms, continuous, true ); } private void start_internal( long timeout_ms, boolean continuous, boolean first ) { device_data = null; this.continuous_read = continuous; this.continuous_first = continuous && first; DimState dim_state = state_tracker.getState(); /* Start a countdown timer, in case the IO doesn't complete as expected. */ this.timeout_ms = timeout_ms; read_start_timestamp = SystemClock.elapsedRealtime(); if ( !registered ) { device.registerForI2cPortReadyCallback(callback); registered = true; } if ( state_tracker.getState() == DimState.UNKNOWN || (!state_tracker.isModeCurrent(true, dev_address, mem_address, num_bytes ) ) ) { /* Force a read-mode transition (if address changed, or of was in write mode) */ state_tracker.setMode(true, dev_address, mem_address, num_bytes); state_tracker.setState(DimState.WAIT_FOR_MODE_CONFIG_COMPLETE); device.enableI2cReadMode(dev_address, mem_address, num_bytes); if ( enable_logging ) { Log.i("navx_ftc", "enableI2cReadMode"); } } else { if ( !device.isI2cPortReady() || !device.isI2cPortInReadMode()) { boolean fail = true; } /* Already in read mode at the correct address. Initiate the I2C Bus Read. */ state_tracker.setState(DimState.WAIT_FOR_I2C_TRANSFER_COMPLETION); if ( first || !continuous_read ) { device.setI2cPortActionFlag(); device.writeI2cCacheToController(); if ( enable_logging ) { Log.i("navx_ftc", "setI2cPortActionFlag/writeI2cCacheToController"); } } else { /* In this case, the I2C Bus Read was previously initiated in the portDone() callback function, in the WAIT_FOR_I2C_TRANSFER_COMPLETION case. */ } } busy = true; } public boolean isBusy() { long busy_period = SystemClock.elapsedRealtime() - read_start_timestamp; if ( busy && ( busy_period >= this.timeout_ms ) ) { if ( enable_logging ) { Log.w("navx_ftc portReady()", "TIMEOUT!!!"); } busy = false; state_tracker.reset(); } return busy; } private void portDone() { DimState dim_state = state_tracker.getState(); boolean fallthrough = false; switch ( dim_state ) { case WAIT_FOR_MODE_CONFIG_COMPLETE: /* The controller is now in Read Mode with the specified address/len. */ device.setI2cPortActionFlag(); state_tracker.setState(DimState.WAIT_FOR_I2C_TRANSFER_COMPLETION); device.writeI2cCacheToController(); if ( enable_logging ) { Log.i("navx_ftc portReady()", "WAIT_FOR_MODE_CONFIG_COMPLETE - " + Integer.toString(this.mem_address) + ", " + Integer.toString(this.num_bytes)); } break; case WAIT_FOR_I2C_TRANSFER_COMPLETION: state_tracker.setState(DimState.WAIT_FOR_HOST_BUFFER_TRANSFER_COMPLETION); device.readI2cCacheFromController(); if ( enable_logging ) { Log.i("navx_ftc portReady()", "WAIT_FOR_I2C_TRANSFER_COMPLETION - " + (continuous_read ? "Continuous " : "") + (continuous_first ? "First" : "")); } if ( continuous_read ) { /* Piggy-back the request for the next read. */ /* For this to work, the write cache already has the read address/len */ /* configured, and the only thing needed to trigger the IO is to change */ /* the "port action" flag. This is a very useful technique, since it */ /* allows another I2C read to start at the same time the read cache is */ /* being transferred from the controller over USB; Setting only the */ /* port action flag avoid over-writing the other bytes in the cache, */ /* which by may (race condition) have already been updated with the */ /* data read in the just-completed I2C read transaction. */ device.setI2cPortActionFlag(); device.writeI2cPortFlagOnlyToController(); /* Write *only* the flag. */ if ( continuous_first ) { continuous_first = false; break; } else { /* Fall through to WAIT_FOR_HOST_BUFFER_TRANSFER_COMPLETION case */ fallthrough = true; } } else { break; } case WAIT_FOR_HOST_BUFFER_TRANSFER_COMPLETION: /* The Read Cache has been successfully transferred to this host. */ device_data = this.device.getCopyOfReadBuffer(); boolean restarted = false; if ( enable_logging ) { Log.i("navx_ftc portReady()", "WAIT_FOR_HOST_BUFFER_TRANSFER_COMPLETION. " + (fallthrough ? "(Fallthrough)" : "") + ((device_data != null) ? " Valid Data" : " Null Data")); } if ( this.ioCallback != null ) { boolean repeat = ioCallback.ioComplete(true, this.mem_address, this.num_bytes, device_data); device_data = null; if (repeat) { start_internal(timeout_ms,continuous_read,false); restarted = true; } else { state_tracker.setState(DimState.READY); busy = false; continuous_read = false; } } else { state_tracker.setState(DimState.READY); busy = false; continuous_read = false; synchronized (synchronization_event) { synchronization_event.notify(); } } if ( !restarted ) { device.deregisterForPortReadyCallback(); } registered = false; break; } } public byte[] startAndWaitForCompletion(long timeout_ms ) { start(timeout_ms, false); return waitForCompletion(timeout_ms); } public byte[] waitForCompletion( long timeout_ms ) { if ( device_data != null ) return device_data; byte[] data; synchronized(synchronization_event) { try { synchronization_event.wait(timeout_ms); data = device_data; } catch( InterruptedException ex ) { ex.printStackTrace(); data = null; } } return data; } public byte[] getReadBuffer() { return device_data; } } }
package net.sourceforge.texlipse.model; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.bibparser.BibParser; import net.sourceforge.texlipse.editor.TexDocumentParseException; import net.sourceforge.texlipse.editor.TexEditor; import net.sourceforge.texlipse.outline.TexOutlinePage; import net.sourceforge.texlipse.properties.TexlipseProperties; import net.sourceforge.texlipse.texparser.FullTexParser; import net.sourceforge.texlipse.texparser.LatexRefExtractingParser; import net.sourceforge.texlipse.texparser.TexParser; import net.sourceforge.texlipse.treeview.views.TexOutlineTreeView; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ILock; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.SubStatusLineManager; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.Position; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.progress.WorkbenchJob; /** * LaTeX document model. Handles parsing of the document and updating * the outline, folding and content assist datastructures. * * @author Taavi Hupponen, Oskar Ojala */ public class TexDocumentModel implements IDocumentListener { /** * Job for performing the parsing in a background thread. * When parsing is done schedules the PostParseJob, which * updates the ui stuff. waits for the PostParseJob to finish. * * Monitor is polled often to detect cancellation. * * @author Taavi Hupponen * */ private class ParseJob extends Job { /** * @param name name of the job */ public ParseJob(String name) { super(name); } /** * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { try { // before parsing stuff, only takes time when run the first time if (bibContainer == null) { createReferenceContainers(); } pollCancel(monitor); // parsing ArrayList rootNodes; try { rootNodes = doParse(monitor); } catch (TexDocumentParseException e1) { return Status.CANCEL_STATUS; } pollCancel(monitor); // handling of parse results postParseJob.setRootNodes(rootNodes); postParseJob.schedule(); try { postParseJob.join(); } catch (InterruptedException e2) { return Status.CANCEL_STATUS; } // return parse status etc. IStatus result = postParseJob.getResult(); // parsing ok if (result != null && result.equals(Status.OK_STATUS)) { // cancel check must be here before setDirty(false)! try { lock.acquire(); pollCancel(monitor); setDirty(false); } finally { lock.release(); } return result; } // parsing not ok return Status.CANCEL_STATUS; } catch (Exception e) { return Status.CANCEL_STATUS; } } } /** * Job for updating the ui after parsing. Runs in the ui thread. * * Monitor is polled often to detect cancellation. * * @author Taavi Hupponen */ private class PostParseJob extends WorkbenchJob { private ArrayList rootNodes; /** * * @param name name of the job */ public PostParseJob(String name) { super(name); } /** * @param rootNodes */ public void setRootNodes(ArrayList rootNodes) { this.rootNodes = rootNodes; } /** * @see org.eclipse.ui.progress.UIJob#runInUIThread(org.eclipse.core.runtime.IProgressMonitor) */ public IStatus runInUIThread(IProgressMonitor monitor) { try { updateDocumentPositions(rootNodes, monitor); pollCancel(monitor); editor.updateCodeFolder(rootNodes, monitor); pollCancel(monitor); if (editor.getOutlinePage() != null) { editor.getOutlinePage().update(outlineInput); } return Status.OK_STATUS; } catch (Exception e) { // npe when exiting eclipse and saving return Status.CANCEL_STATUS; } } } /** * Job for performing the parsing in a background thread. When parsing is * done schedules the PostParseJob, which updates the input for the full * outline. waits for the PostParseJob to finish. * * Monitor is polled often to detect cancellation. * */ private class ParseJob2 extends Job { private IFile fileChanged; private String changedInput; /** * @param name name of the job */ public ParseJob2(String name) { super(name); } /** * * @param fileChanged the reference to the file which changed. */ public void setChangedFile(IFile fileChanged) { this.fileChanged = fileChanged; } /** * * @param changedInput the input which has changed */ public void setChangedInput(String changedInput) { this.changedInput = changedInput; } /** * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { try { // parsing ArrayList rootNodes; try { rootNodes = doFullParse(this.fileChanged, this.changedInput, monitor); } catch (TexDocumentParseException e1) { return Status.CANCEL_STATUS; } if (rootNodes == null) { return Status.CANCEL_STATUS; } pollCancel(monitor); // handling of parse results postParseJob2.setRootNodes(rootNodes); postParseJob2.schedule(); try { postParseJob2.join(); } catch (InterruptedException e2) { return Status.CANCEL_STATUS; } // return parse status etc. IStatus result = postParseJob2.getResult(); // parsing ok if (result != null && result.equals(Status.OK_STATUS)) { pollCancel(monitor); return result; } // parsing not ok return Status.CANCEL_STATUS; } catch (Exception e) { return Status.CANCEL_STATUS; } } } /** * Job for updating the full outline input. Runs in the ui thread. * * Monitor is polled often to detect cancellation. * * @author Taavi Hupponen */ private class PostParseJob2 extends WorkbenchJob { private ArrayList rootNodes; /** * @param name name of the job */ public PostParseJob2(String name) { super(name); } /** * @param rootNodes */ public void setRootNodes(ArrayList rootNodes) { this.rootNodes = rootNodes; } /** * @see org.eclipse.ui.progress.UIJob#runInUIThread(org.eclipse.core.runtime.IProgressMonitor) */ public IStatus runInUIThread(IProgressMonitor monitor) { try { createOutlineInput(rootNodes, monitor); pollCancel(monitor); if (editor.getFullOutline() != null) { editor.getFullOutline().update(fullOutlineInput); } return Status.OK_STATUS; } catch (Exception e) { // npe when exiting eclipse and saving return Status.CANCEL_STATUS; } } } private FullTexParser fullParser; private TexOutlineInput fullOutlineInput; // parsing jobs for the full outline. private ParseJob2 parseJob2; private PostParseJob2 postParseJob2; private TexEditor editor; private TexParser parser; private TexOutlineInput outlineInput; private ReferenceContainer bibContainer; private ReferenceContainer labelContainer; private TexCommandContainer commandContainer; private ReferenceManager refMana; private boolean firstRun = true; // used to synchronize ParseJob rescheduling private static ILock lock = Platform.getJobManager().newLock(); private boolean isDirty; private ParseJob parseJob; private PostParseJob postParseJob; // preferences private int parseDelay; private boolean autoParseEnabled; /** * Constructs a new document model. * * @param editor The editor this model is associated to. */ public TexDocumentModel(TexEditor editor) { this.editor = editor; this.isDirty = true; // initialize jobs parseJob = new ParseJob("Parsing"); postParseJob = new PostParseJob("Updating"); parseJob.setPriority(Job.DECORATE); postParseJob.setPriority(Job.DECORATE); parseJob2 = new ParseJob2("Parsing"); postParseJob2 = new PostParseJob2("Updating"); parseJob2.setPriority(Job.DECORATE); postParseJob2.setPriority(Job.DECORATE); // get preferences this.autoParseEnabled = TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(TexlipseProperties.AUTO_PARSING); this.parseDelay = TexlipsePlugin.getDefault().getPreferenceStore().getInt(TexlipseProperties.AUTO_PARSING_DELAY); // add preference change listener TexlipsePlugin.getDefault().getPreferenceStore() .addPropertyChangeListener(new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property = event.getProperty(); if (TexlipseProperties.AUTO_PARSING.equals(property)) { autoParseEnabled = TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(TexlipseProperties.AUTO_PARSING); } else if (TexlipseProperties.AUTO_PARSING_DELAY.equals(property)) { parseDelay = TexlipsePlugin.getDefault().getPreferenceStore().getInt(TexlipseProperties.AUTO_PARSING_DELAY); } } }); } /** * Initializes the model. Should be called immediately after constructing * an instance, otherwise parsing may fail. */ public void initializeModel() { MarkerHandler.getInstance().clearErrorMarkers(editor); MarkerHandler.getInstance().clearTaskMarkers(editor); createReferenceContainers(); } /** * Cancels possibly running parseJob and schedules it to run again * immediately. * * Called when new outline is created, so it is quite likely that there * is no parseJob running. * * If parseJob were running we could maybe use isDirty to figure out * if it would be smarter to wait for the running parseJob. */ public void updateNow() { parseJob.cancel(); parseJob.schedule(); } /** * Called from TexEditor.getAdapter(). If uptodate outline input is * found the outline is updated with it. * * If current outline is not uptodate, parsing job is started and * eventually outline is updated with fresh input. */ public void updateOutline() { if (!isDirty()) { this.editor.getOutlinePage().update(this.outlineInput); } else { this.updateNow(); } } /** * Cancels possibly running parseJob and schedules it to run again * immediately. * * Called when new outline is created, so it is quite likely that there * is no parseJob running. * * If parseJob were running we could maybe use isDirty to figure out * if it would be smarter to wait for the running parseJob. */ public void updateFullOutline() { parseJob2.cancel(); parseJob2.schedule(); } /** * Returns the reference (label and BibTeX) for this model * (ie. project). * * @return Returns the refMana. */ public ReferenceManager getRefMana() { if (refMana == null) { refMana = new ReferenceManager(bibContainer, labelContainer, commandContainer); } return refMana; } /** * Returns whether current OutlineInput is dirty, i.e. if the * document has been changed after latest parsing. * * @return true if document is dirty */ public synchronized boolean isDirty() { return this.isDirty; } /** * Does nothing atm. * * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { } /** * Called when document changes. Marks the document dirty and * schedules the parsing job. * * When we return from here this.isDirty must remain true * until new parseJob has finished. * * If the previous parseJob is not cancelled immediately * (parseJob.cancel() returns false) a smarter way to * calculate the next scheduling delay could be used. * However we should not spend much time in documentChanged() */ public void documentChanged(DocumentEvent event) { // set isDirty true and prevent possibly running parseJob from // changing it back to false // order of acquire, cancel and setDirty matters! try { lock.acquire(); parseJob.cancel(); this.setDirty(true); } finally { lock.release(); } // if parseJob was running, now it is either cancelled or it will // be before it tries setDirty(false) // inform outline that model is dirty TexOutlinePage outline = editor.getOutlinePage(); if (outline != null) { editor.getOutlinePage().modelGotDirty(); } TexOutlineTreeView fullOutline = editor.getFullOutline(); if(fullOutline != null) { fullOutline.modelGotDirty(); } // reschedule parsing with delay if (autoParseEnabled) { parseJob.schedule(parseDelay); parseJob2.setChangedFile(getCurrentProject().getFile(this.editor.getEditorInput().getName())); parseJob2.setChangedInput(event.getDocument().get()); parseJob2.schedule(parseDelay); } } /** * Parses the LaTeX-document and adds error markers if there were any * errors. Throws <code>TexDocumentParseException</code> if there were * fatal parse errors that prohibit building an outline. * @param monitor * * @throws TexDocumentParseException */ private ArrayList doParse(IProgressMonitor monitor) throws TexDocumentParseException { if (this.parser == null) { this.parser = new TexParser(this.editor.getDocumentProvider().getDocument(this.editor.getEditorInput())); } try { this.parser.parseDocument(labelContainer, bibContainer); } catch (IOException e) { TexlipsePlugin.log("Can't read file.", e); throw new TexDocumentParseException(e); } pollCancel(monitor); ArrayList errors = parser.getErrors(); List tasks = parser.getTasks(); MarkerHandler marker = MarkerHandler.getInstance(); // somewhat inelegantly ensures that errors marked in createProjectDatastructs() // aren't removed immediately if (!firstRun) { marker.clearErrorMarkers(editor); marker.clearTaskMarkers(editor); } else { firstRun = false; } if (errors.size() > 0) { marker.createErrorMarkers(editor, errors); } if (tasks.size() > 0) { marker.createTaskMarkers(editor, tasks); } if (parser.isFatalErrors()) { throw new TexDocumentParseException("Fatal errors in file, parsing aborted."); } updateReferences(monitor); ArrayList bibErrors = parser.getCites(); ArrayList refErrors = parser.getRefs(); if (bibErrors.size() > 0) { marker.createReferencingErrorMarkers(editor, bibErrors); } if (refErrors.size() > 0) { labelContainer.removeFalseEntries(refErrors); marker.createReferencingErrorMarkers(editor, refErrors); } return this.parser.getOutlineTree(); } /** * Parses the LaTeX-document and adds error markers if there were any * errors. Throws <code>TexDocumentParseException</code> if there were * fatal parse errors that prohibit building an outline. * @param monitor * @throws TexDocumentParseException */ private ArrayList doFullParse(IFile changedFile, String inputChanged, IProgressMonitor monitor) throws TexDocumentParseException { // create the full parser if not available yet. initialize it with the // project main file and a handle to the current project. if (this.fullParser == null) { try { IFile mainFile = TexlipseProperties .getProjectSourceFile(getCurrentProject()); this.fullParser = new FullTexParser(getCurrentProject(), mainFile); } catch (IllegalArgumentException e) { TexlipsePlugin.log("Project main file not set.", e); } } // if the actual document has changed if (changedFile != null) { this.fullParser.setChangedFile(changedFile); } if (inputChanged != null) { this.fullParser.setChangedInput(inputChanged); } // parse try { this.fullParser.parseDocument(labelContainer, bibContainer); } catch (IOException e) { TexlipsePlugin.log("Can't read file.", e); throw new TexDocumentParseException(e); } pollCancel(monitor); // error hadling ArrayList errors = fullParser.getErrors(); MarkerHandler marker = MarkerHandler.getInstance(); if (errors != null && errors.size() > 0) { marker.createErrorMarkers(editor, errors); } if (fullParser.isFatalErrors()) { throw new TexDocumentParseException( "Fatal errors in file, parsing aborted."); } return this.fullParser.getOutlineTree(); } /** * Traverses the OutlineNode tree and adds a Position for each * node to Document. * * Also adds the nodes to type lists of the OutlineInput and * calculates the tree depth. * * Old Positions are removed before adding new ones. * * @param rootNodes * @param monitor monitor for the job calling this method */ private void updateDocumentPositions(ArrayList rootNodes, IProgressMonitor monitor) { TexOutlineInput newOutlineInput = new TexOutlineInput(rootNodes); IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); // remove previous positions try { document.removePositionCategory("__outline"); } catch (BadPositionCategoryException bpce) { // do nothing, the category will be added again next, it does not exists the first time } document.addPositionCategory("__outline"); pollCancel(monitor); // add new positions for nodes and their children int maxDepth = 0; for (Iterator iter = rootNodes.iterator(); iter.hasNext(); ) { OutlineNode node = (OutlineNode) iter.next(); int localDepth = addNodePosition(node, document, 0, newOutlineInput); if (localDepth > maxDepth) { maxDepth = localDepth; } pollCancel(monitor); } pollCancel(monitor); // set the new outline input newOutlineInput.setTreeDepth(maxDepth); this.outlineInput = newOutlineInput; } /** * Handles a single node when traversing the outline tree. Used * recursively. * * @param node * @param document * @param parentDepth * @param newOutlineInput * @return */ private int addNodePosition(OutlineNode node, IDocument document, int parentDepth, TexOutlineInput newOutlineInput) { // add the Document position int beginOffset = 0; int length = 0; Position position = null; try { beginOffset = document.getLineOffset(node.getBeginLine() - 1); if (node.getEndLine() -1 == document.getNumberOfLines()) length = document.getLength() - beginOffset; else length = document.getLineOffset(node.getEndLine() - 1) - beginOffset; position = new Position(beginOffset, length); document.addPosition("__outline", position); } catch (BadLocationException bpe) { throw new OperationCanceledException(); } catch (BadPositionCategoryException bpce) { throw new OperationCanceledException(); } node.setPosition(position); // add node to outline input newOutlineInput.addNode(node); // iterate through the children List children = node.getChildren(); int maxDepth = parentDepth + 1; if (children != null) { for (Iterator iter = children.iterator(); iter.hasNext();) { int localDepth = addNodePosition((OutlineNode) iter.next(), document, parentDepth + 1, newOutlineInput); if (localDepth > maxDepth) { maxDepth = localDepth; } } } return maxDepth; } /** * Traverses the OutlineNode tree. * * Adds the nodes to type lists of the OutlineInput and * calculates the tree depth. * * @param rootNodes * @param monitor monitor for the job calling this method */ private void createOutlineInput(ArrayList rootNodes, IProgressMonitor monitor) { TexOutlineInput newOutlineInput = new TexOutlineInput(rootNodes); // set the depth and add nodes to the tree int maxDepth = 0; for (Iterator iter = rootNodes.iterator(); iter.hasNext();) { OutlineNode node = (OutlineNode) iter.next(); int localDepth = handleNode(node, 0, newOutlineInput); if (localDepth > maxDepth) { maxDepth = localDepth; } pollCancel(monitor); } pollCancel(monitor); // set the new outline input newOutlineInput.setTreeDepth(maxDepth); this.fullOutlineInput = newOutlineInput; } /** * Adds a node to the outline input. Calculates the depth of the tree. Used * recursively. * * @param node the current node. * @param parentDepth the depth to the parent. * @param newOutlineInput the input for the full outline. * @return */ private int handleNode(OutlineNode node, int parentDepth, TexOutlineInput newOutlineInput) { // add node to outline input newOutlineInput.addNode(node); // iterate through the children List children = node.getChildren(); int maxDepth = parentDepth + 1; if (children != null) { for (Iterator iter = children.iterator(); iter.hasNext();) { int localDepth = handleNode((OutlineNode) iter.next(), parentDepth + 1, newOutlineInput); if (localDepth > maxDepth) { maxDepth = localDepth; } } } return maxDepth; } /** * Updates the references and project data based on the data in the * parsed document. * * @param monitor Progress monitor */ private void updateReferences(IProgressMonitor monitor) { this.updateLabels(parser.getLabels()); this.updateCommands(parser.getCommands()); pollCancel(monitor); String[] bibs = parser.getBibs(); if (bibs != null) { this.updateBibs(bibs, ((FileEditorInput)editor.getEditorInput()).getFile()); } // After here we just store those fun properties... pollCancel(monitor); IProject project = getCurrentProject(); IFile cFile = ((FileEditorInput) editor.getEditorInput()).getFile(); //Only update Preamble, Bibstyle if main Document if (cFile.equals(TexlipseProperties.getProjectSourceFile(project))) { String preamble = parser.getPreamble(); if (preamble != null) { TexlipseProperties.setSessionProperty(project, TexlipseProperties.PREAMBLE_PROPERTY, preamble); } String bibstyle = parser.getBibstyle(); if (bibstyle != null) { String oldStyle = (String) TexlipseProperties.getSessionProperty(project, TexlipseProperties.BIBSTYLE_PROPERTY); if (oldStyle == null || !bibstyle.equals(oldStyle)) { TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBSTYLE_PROPERTY, bibstyle); // schedule running bibtex on the next build TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBFILES_CHANGED, new Boolean(true)); } } } } /** * Updates completions for the BibTeX -data * * @param bibNames Names of the BibTeX -files that the document uses * @param resource The resource of the document */ private void updateBibs(String[] bibNames, IResource resource) { IProject project = getCurrentProject(); for (int i=0; i < bibNames.length; i++) bibNames[i] += ".bib"; if (bibContainer.checkFreshness(bibNames)) { return; } TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBFILE_PROPERTY, bibNames); LinkedList newBibs = bibContainer.updateBibHash(bibNames); IPath path = resource.getFullPath().removeFirstSegments(1).removeLastSegments(1); if (!path.isEmpty()) path = path.addTrailingSeparator(); for (Iterator iter = newBibs.iterator(); iter.hasNext();) { String name = (String) iter.next(); IResource res = project.findMember(path + name); if (res != null) { BibParser parser = new BibParser(res.getLocation().toOSString()); try { ArrayList bibEntriesList = parser.getEntries(); if (bibEntriesList != null && bibEntriesList.size() > 0) { bibContainer.addRefSource(path + name, bibEntriesList); } else { MarkerHandler marker = MarkerHandler.getInstance(); marker.addFatalError(editor, "The BibTeX file " + res.getFullPath() + " contains fatal errors, parsing aborted."); continue; } } catch (IOException ioe) { TexlipsePlugin.log("Can't read BibTeX file " + res.getFullPath(), ioe); } } } bibContainer.organize(); } /** * Updates the labels. * @param labels */ private void updateLabels(ArrayList labels) { IResource resource = ((FileEditorInput)editor.getEditorInput()).getFile(); labelContainer.addRefSource(resource.getProjectRelativePath().toString(), labels); labelContainer.organize(); } /** * Updates the commands. * @param commands */ private void updateCommands(ArrayList commands) { IResource resource = ((FileEditorInput)editor.getEditorInput()).getFile(); commandContainer.addRefSource(resource.getProjectRelativePath().toString(), commands); commandContainer.organize(); } /** * Creates the reference containers. * */ private void createReferenceContainers() { boolean parseAll = false; IProject project = getCurrentProject(); ReferenceContainer bibCon = (ReferenceContainer) TexlipseProperties.getSessionProperty(project, TexlipseProperties.BIBCONTAINER_PROPERTY); if (bibCon == null) { bibContainer = new ReferenceContainer(); TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBCONTAINER_PROPERTY, bibContainer); parseAll = true; } else { bibContainer = bibCon; } ReferenceContainer labCon = (ReferenceContainer) TexlipseProperties.getSessionProperty(project, TexlipseProperties.LABELCONTAINER_PROPERTY); if (labCon == null) { labelContainer = new ReferenceContainer(); TexlipseProperties.setSessionProperty(project, TexlipseProperties.LABELCONTAINER_PROPERTY, labelContainer); parseAll = true; } else { labelContainer = labCon; } TexCommandContainer comCon = (TexCommandContainer) TexlipseProperties.getSessionProperty(project, TexlipseProperties.COMCONTAINER_PROPERTY); if (comCon == null) { commandContainer = new TexCommandContainer(); TexlipseProperties.setSessionProperty(project, TexlipseProperties.COMCONTAINER_PROPERTY, commandContainer); parseAll = true; } else { commandContainer = comCon; } if (parseAll) { createProjectDatastructs(project); } } /** * Creates all the project data structures. These include the reference * completions (BibTeX and label), command completions, the preamble, * the BibTeX style. * * @param project The current project */ private void createProjectDatastructs(IProject project) { IResource resource = ((FileEditorInput)editor.getEditorInput()).getFile(); IResource[] files = TexlipseProperties.getAllProjectFiles(project); if (files != null) { IFile mainFile = TexlipseProperties.getProjectSourceFile(project); for (int i = 0; i < files.length; i++) { IPath path = files[i].getFullPath(); String ext = files[i].getFileExtension(); // here are the file types we want to parse if ("tex".equals(ext) || "ltx".equals(ext) || "sty".equals(ext)) { try { String input = TexlipseProperties.getFileContents(files[i]); LatexRefExtractingParser lrep = new LatexRefExtractingParser(); lrep.parse(input); if (lrep.isFatalErrors()) { MarkerHandler marker = MarkerHandler.getInstance(); marker.addFatalError(editor, "The file " + files[i].getFullPath() + " contains fatal errors, parsing aborted."); continue; } ArrayList labels = lrep.getLabels(); if (labels.size() > 0) { labelContainer.addRefSource(files[i].getProjectRelativePath().toString(), labels); } ArrayList commands = lrep.getCommands(); if (commands.size() > 0) { commandContainer.addRefSource(files[i].getProjectRelativePath().toString(), commands); } //Only update Preamble, Bibstyle if main Document if (files[i].equals(mainFile)) { String[] bibs = lrep.getBibs(); if (bibs != null) this.updateBibs(bibs, files[i]); String preamble = lrep.getPreamble(); if (preamble != null) { TexlipseProperties.setSessionProperty(project, TexlipseProperties.PREAMBLE_PROPERTY, preamble); } String bibstyle = lrep.getBibstyle(); if (bibstyle != null) TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBSTYLE_PROPERTY, bibstyle); } } catch (IOException ioe) { TexlipsePlugin.log("Unable to open file " + files[i].getFullPath() + " for parsing", ioe); } } } // save time by doing this last labelContainer.organize(); commandContainer.organize(); } } /** * @return the current project */ private IProject getCurrentProject() { return ((FileEditorInput)editor.getEditorInput()).getFile().getProject(); } /** * Marks the current OutlineInput dirty. * @param dirty true if OutlineInput is marked dirty */ private synchronized void setDirty(boolean dirty) { this.isDirty = dirty; } /** * Cancels a job by throwing OperationCanceledException. * * Used by inner class jobs of this class. * * @param monitor releated to the Job polling the cancel state */ private void pollCancel(IProgressMonitor monitor) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } } /** * Write a message on the status line. * @param msg the message. */ public void setStatusLineErrorMessage(String msg){ SubStatusLineManager slm = (SubStatusLineManager) editor.getEditorSite().getActionBars().getStatusLineManager(); slm.setVisible(true); slm.setErrorMessage(msg); } /** * clean the status line * */ public void removeStatusLineErrorMessage(){ SubStatusLineManager slm = (SubStatusLineManager) editor.getEditorSite().getActionBars().getStatusLineManager(); slm.setVisible(false); } }
package Applications.PuncFeatures; import java.util.*; import HOSemiCRF.*; /** * Semi-Markov third order transition with word features * @author Nguyen Viet Cuong */ public class ThirdOrderTransitionWord extends FeatureType { public ArrayList<String> generateObsAt(DataSequence seq, int segStart, int segEnd) { ArrayList<String> obs = new ArrayList<String>(); if (segStart >= 3) { for (int i = segStart; i <= segEnd; i++) { obs.add("E3W." + seq.x(i)); } } return obs; } public int order() { return 3; } }
package kikaha.core.ssl; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.IOException; import kikaha.core.api.conf.Configuration; import kikaha.core.impl.conf.DefaultConfiguration; import lombok.val; import org.junit.Test; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; public class SSLContextFactoryTest { @Test public void ensureCannotToCreateASSLContextFromEmptyConfiguration() throws IOException { val config = createEmptyConfiguration(); val factory = createFactoryFrom( config ); val context = factory.createSSLContext(); assertNull( context ); } Configuration createEmptyConfiguration() { final Config defaultConfiguration = ConfigFactory.load(); final Config reference = ConfigFactory.load( "META-INF/reference" ).withFallback( defaultConfiguration ); return new DefaultConfiguration( reference, "default" ); } @Test public void ensureIsPossibleToCreateASSLContextFromDefaultConfiguration() throws IOException { val config = DefaultConfiguration.loadDefaultConfiguration(); val factory = createFactoryFrom( config ); val context = factory.createSSLContext(); assertNotNull( context ); } SSLContextFactory createFactoryFrom( final Configuration config ) { val factory = new SSLContextFactory(); factory.configuration = config; return factory; } }
package com.reactlibrary; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNPdfScannerPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNPdfScannerModule(reactContext)); } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package edu.jhu.hlt.rebar.stage; import java.util.HashSet; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.hadoop.io.Text; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.jhu.hlt.concrete.Communication; import edu.jhu.hlt.grommet.Stage; import edu.jhu.hlt.grommet.StageType; import edu.jhu.hlt.rebar.Configuration; import edu.jhu.hlt.rebar.Constants; import edu.jhu.hlt.rebar.RebarException; import edu.jhu.hlt.rebar.Util; import edu.jhu.hlt.rebar.accumulo.AbstractAccumuloClient; /** * @author max * */ public class StageCreator extends AbstractAccumuloClient implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(StageCreator.class); protected final BatchWriter stagesTableBW; protected final BatchWriter stagesIdxBW; protected final StageReader sr; public StageCreator() throws RebarException { this(Constants.getConnector()); } public StageCreator(Connector conn) throws RebarException { super(conn); try { this.tableOps.createTableIfNotExists(Constants.STAGES_TABLE_NAME); this.stagesTableBW = this.conn.createBatchWriter(Constants.STAGES_TABLE_NAME, defaultBwOpts.getBatchWriterConfig()); this.tableOps.createTableIfNotExists(Constants.STAGES_IDX_TABLE_NAME); this.stagesIdxBW = this.conn.createBatchWriter(Constants.STAGES_IDX_TABLE_NAME, defaultBwOpts.getBatchWriterConfig()); this.sr = new StageReader(this.conn); } catch (TableNotFoundException e) { throw new RebarException(e); } } @Override public void close() throws Exception { this.stagesIdxBW.close(); this.stagesTableBW.close(); } public void create(Stage stage) throws RebarException { if (this.sr.exists(stage.name)) throw new RebarException("Can't create a stage that exists."); if (stage.getType() == null) throw new RebarException("No type specified for stage."); Set<String> deps = stage.dependencies; for (String dep : deps) { if (!this.sr.exists(dep)) throw new RebarException("Dependency: " + dep + " doesn't exist; can't create that stage."); } try { // create entry in stage table final Mutation m = new Mutation(stage.name); m.put(Constants.STAGES_OBJ_COLF, "", new Value(this.serializer.serialize(stage))); this.stagesTableBW.addMutation(m); Mutation typeIdx = Util.generateEmptyValueMutation("type:"+stage.type.toString(), stage.name, ""); this.stagesIdxBW.addMutation(typeIdx); } catch (MutationsRejectedException | TException e) { throw new RebarException(e); } } public static boolean isValidStageName(Stage s) { return isValidStageName(s.name); } public static boolean isValidStageName(String stageName) { return stageName.startsWith(Constants.STAGES_PREFIX); } /* * (non-Javadoc) * * @see com.maxjthomas.dumpster.StageHandler.Iface#getAnnotatedDocumentCount(com.maxjthomas.dumpster.Stage) */ // @Override // public int getAnnotatedDocumentCount(Stage stage) throws TException { // try { // Scanner sc = this.conn.createScanner(Constants.STAGES_TABLE_NAME, Configuration.getAuths()); // Range r = new Range(stage.name); // sc.setRange(r); // sc.fetchColumnFamily(new Text(Constants.STAGES_DOCS_ANNOTATED_IDS_COLF)); // Iterator<Entry<Key, Value>> iter = sc.iterator(); // return Util.countIteratorResults(iter); // } catch (TableNotFoundException e) { // throw new TException(e); public void addAnnotatedDocument(Stage stage, Communication document) throws RebarException { try { final Mutation m = new Mutation(stage.name); m.put(Constants.STAGES_DOCS_ANNOTATED_IDS_COLF, document.id, Util.EMPTY_VALUE); this.stagesTableBW.addMutation(m); } catch (MutationsRejectedException e) { throw new RebarException(e); } finally { } } public Set<String> getAnnotatedDocumentIds(Stage s) throws RebarException { Set<String> ids = new HashSet<>(); try { Scanner sc = this.conn.createScanner(Constants.STAGES_TABLE_NAME, Configuration.getAuths()); Range r = new Range(s.name); sc.setRange(r); sc.fetchColumnFamily(new Text(Constants.STAGES_DOCS_ANNOTATED_IDS_COLF)); Iterator<Entry<Key, Value>> iter = sc.iterator(); while (iter.hasNext()) { ids.add(iter.next().getKey().getColumnQualifier().toString()); } return ids; } catch (TableNotFoundException e) { throw new RebarException(e); } } public static void main(String... args) throws Exception { if (args.length != 3) { logger.info("Use this program to create a stage with no dependencies, suitable for LIDs or Sections."); logger.info("Takes 3 arguments: stage-name, stage-description, stage-type."); logger.info("Stage type must be one of (case ignored):"); logger.info("SECTION"); logger.info("LANG_ID"); logger.info("Usage: {} <{}> <{}> <{}>", StageCreator.class.getSimpleName(), "stage-name", "stage-description", "stage-type"); System.exit(1); } String stageName = args[0]; if (new StageReader().exists(stageName)) { logger.info("Stage {} exists already. Choose a different name.", stageName); System.exit(1); } String stageDesc = args[1]; String stageTypeString = args[2]; StageType st; try { st = StageType.valueOf(stageTypeString.toUpperCase()); if (!(st == StageType.LANG_ID || st == StageType.SECTION)) { logger.info("Currently you can only create LANG_ID or SECTION stages, not {}.", st.toString()); System.exit(1); } } catch (IllegalArgumentException iae) { throw new RuntimeException(stageTypeString + " was not a valid stage."); } Stage s = new Stage() .setName(stageName) .setType(st) .setDescription(stageDesc) .setCreateTime(System.currentTimeMillis()) .setDependencies(new HashSet<String>()); try (StageCreator sc = new StageCreator()) { sc.create(s); } logger.info("Stage created successfully!"); System.exit(0); } }
package com.turo.pushy.apns; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http2.*; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.AsciiString; import io.netty.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.TimeUnit; class ApnsClientHandler extends Http2ConnectionHandler implements Http2FrameListener { private long nextStreamId = 1; private final Http2Connection.PropertyKey pushNotificationPropertyKey; private final Http2Connection.PropertyKey headersPropertyKey; private final Map<ApnsPushNotification, Promise<PushNotificationResponse<ApnsPushNotification>>> responsePromises = new IdentityHashMap<>(); private final String authority; private ScheduledFuture<?> pingTimeoutFuture; private long pingTimeoutMillis; private static final String APNS_PATH_PREFIX = "/3/device/"; private static final AsciiString APNS_EXPIRATION_HEADER = new AsciiString("apns-expiration"); private static final AsciiString APNS_TOPIC_HEADER = new AsciiString("apns-topic"); private static final AsciiString APNS_PRIORITY_HEADER = new AsciiString("apns-priority"); private static final AsciiString APNS_COLLAPSE_ID_HEADER = new AsciiString("apns-collapse-id"); private static final long STREAM_ID_RESET_THRESHOLD = Integer.MAX_VALUE - 1; private static final int INITIAL_PAYLOAD_BUFFER_CAPACITY = 4096; private static final Gson GSON = new GsonBuilder() .registerTypeAdapter(Date.class, new DateAsTimeSinceEpochTypeAdapter(TimeUnit.MILLISECONDS)) .create(); private static final Logger log = LoggerFactory.getLogger(ApnsClientHandler.class); public static class ApnsClientHandlerBuilder extends AbstractHttp2ConnectionHandlerBuilder<ApnsClientHandler, ApnsClientHandlerBuilder> { private String authority; private long idlePingIntervalMillis; public ApnsClientHandlerBuilder authority(final String authority) { this.authority = authority; return this; } public String authority() { return this.authority; } public long idlePingIntervalMillis() { return idlePingIntervalMillis; } public ApnsClientHandlerBuilder idlePingIntervalMillis(long idlePingIntervalMillis) { this.idlePingIntervalMillis = idlePingIntervalMillis; return this; } @Override protected final boolean isServer() { return false; } @Override protected boolean encoderEnforceMaxConcurrentStreams() { return true; } @Override public ApnsClientHandler build(final Http2ConnectionDecoder decoder, final Http2ConnectionEncoder encoder, final Http2Settings initialSettings) { Objects.requireNonNull(this.authority(), "Authority must be set before building an ApnsClientHandler."); final ApnsClientHandler handler = new ApnsClientHandler(decoder, encoder, initialSettings, this.authority(), this.idlePingIntervalMillis()); this.frameListener(handler); return handler; } @Override public ApnsClientHandler build() { return super.build(); } } protected ApnsClientHandler(final Http2ConnectionDecoder decoder, final Http2ConnectionEncoder encoder, final Http2Settings initialSettings, final String authority, final long idlePingIntervalMillis) { super(decoder, encoder, initialSettings); this.authority = authority; this.pushNotificationPropertyKey = this.connection().newKey(); this.headersPropertyKey = this.connection().newKey(); this.pingTimeoutMillis = idlePingIntervalMillis/2; } @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise) throws Http2Exception, InvalidKeyException, NoSuchAlgorithmException { if (message instanceof PushNotificationAndResponsePromise) { final PushNotificationAndResponsePromise pushNotificationAndResponsePromise = (PushNotificationAndResponsePromise) message; final ApnsPushNotification pushNotification = pushNotificationAndResponsePromise.getPushNotification(); if (this.responsePromises.containsKey(pushNotification)) { writePromise.tryFailure(new PushNotificationStillPendingException()); } else { this.responsePromises.put(pushNotification, pushNotificationAndResponsePromise.getResponsePromise()); pushNotificationAndResponsePromise.getResponsePromise().addListener(new GenericFutureListener<Future<PushNotificationResponse<ApnsPushNotification>>> () { @Override public void operationComplete(final Future<PushNotificationResponse<ApnsPushNotification>> future) { // Regardless of the outcome, when the response promise is finished, we want to remove it from // the map of pending promises. ApnsClientHandler.this.responsePromises.remove(pushNotification); } }); this.write(context, pushNotification, writePromise); } } else if (message instanceof ApnsPushNotification) { final ApnsPushNotification pushNotification = (ApnsPushNotification) message; final int streamId = (int) this.nextStreamId; final Http2Headers headers = getHeadersForPushNotification(pushNotification, streamId); final ChannelPromise headersPromise = context.newPromise(); this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise); log.trace("Wrote headers on stream {}: {}", streamId, headers); final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY); payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8)); final ChannelPromise dataPromise = context.newPromise(); this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise); log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload()); final PromiseCombiner promiseCombiner = new PromiseCombiner(); promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise); promiseCombiner.finish(writePromise); writePromise.addListener(new GenericFutureListener<ChannelPromise>() { @Override public void operationComplete(final ChannelPromise future) throws Exception { if (future.isSuccess()) { final Http2Stream stream = ApnsClientHandler.this.connection().stream(streamId); stream.setProperty(ApnsClientHandler.this.pushNotificationPropertyKey, pushNotification); } else { log.trace("Failed to write push notification on stream {}.", streamId, future.cause()); final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = ApnsClientHandler.this.responsePromises.get(pushNotification); if (responsePromise != null) { responsePromise.tryFailure(future.cause()); } else { log.error("Notification write failed, but no response promise found."); } } } }); this.nextStreamId += 2; if (this.nextStreamId >= STREAM_ID_RESET_THRESHOLD) { // This is very unlikely, but in the event that we run out of stream IDs (the maximum allowed is // 2^31, per https://httpwg.github.io/specs/rfc7540.html#StreamIdentifiers), we need to open a new // connection. Just closing the context should be enough; automatic reconnection should take things // from there. context.close(); } } else { // This should never happen, but in case some foreign debris winds up in the pipeline, just pass it through. log.error("Unexpected object in pipeline: {}", message); context.write(message, writePromise); } } protected Http2Headers getHeadersForPushNotification(final ApnsPushNotification pushNotification, final int streamId) { final Http2Headers headers = new DefaultHttp2Headers() .method(HttpMethod.POST.asciiName()) .authority(this.authority) .path(APNS_PATH_PREFIX + pushNotification.getToken()) .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0 : (int) (pushNotification.getExpiration().getTime() / 1000)); if (pushNotification.getCollapseId() != null) { headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId()); } if (pushNotification.getPriority() != null) { headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode()); } if (pushNotification.getTopic() != null) { headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic()); } return headers; } @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { log.trace("Sending ping due to inactivity."); final ByteBuf pingDataBuffer = context.alloc().ioBuffer(Long.SIZE, Long.SIZE); pingDataBuffer.writeLong(System.currentTimeMillis()); this.encoder().writePing(context, false, pingDataBuffer, context.newPromise()).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.pingTimeoutFuture = context.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); context.channel().close(); } }, pingTimeoutMillis, TimeUnit.MILLISECONDS); this.flush(context); } super.userEventTriggered(context, event); } @Override public void channelInactive(final ChannelHandlerContext context) { assert context.executor().inEventLoop(); final ClientNotConnectedException clientNotConnectedException = new ClientNotConnectedException("Client disconnected before receiving a response from the APNs server."); for (final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise : this.responsePromises.values()) { responsePromise.tryFailure(clientNotConnectedException); } this.responsePromises.clear(); } @Override public int onDataRead(final ChannelHandlerContext context, final int streamId, final ByteBuf data, final int padding, final boolean endOfStream) throws Http2Exception { log.trace("Received data from APNs gateway on stream {}: {}", streamId, data.toString(StandardCharsets.UTF_8)); final int bytesProcessed = data.readableBytes() + padding; if (endOfStream) { final Http2Stream stream = this.connection().stream(streamId); final Http2Headers headers = stream.getProperty(this.headersPropertyKey); final ApnsPushNotification pushNotification = stream.getProperty(this.pushNotificationPropertyKey); final ErrorResponse errorResponse = GSON.fromJson(data.toString(StandardCharsets.UTF_8), ErrorResponse.class); this.handleErrorResponse(context, streamId, headers, pushNotification, errorResponse); } else { log.error("Gateway sent a DATA frame that was not the end of a stream."); } return bytesProcessed; } protected void handleErrorResponse(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final ApnsPushNotification pushNotification, final ErrorResponse errorResponse) { final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status()); if (HttpResponseStatus.INTERNAL_SERVER_ERROR.equals(status)) { log.warn("APNs server reported an internal error when sending {}.", pushNotification); this.responsePromises.get(pushNotification).tryFailure(new ApnsServerException(GSON.toJson(errorResponse))); } else { this.responsePromises.get(pushNotification).trySuccess( new SimplePushNotificationResponse<>(pushNotification, HttpResponseStatus.OK.equals(status), errorResponse.getReason(), errorResponse.getTimestamp())); } } @Override public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final int streamDependency, final short weight, final boolean exclusive, final int padding, final boolean endOfStream) throws Http2Exception { this.onHeadersRead(context, streamId, headers, padding, endOfStream); } @Override public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final int padding, final boolean endOfStream) throws Http2Exception { log.trace("Received headers from APNs gateway on stream {}: {}", streamId, headers); final Http2Stream stream = this.connection().stream(streamId); if (endOfStream) { final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status()); final boolean success = HttpResponseStatus.OK.equals(status); if (!success) { log.warn("Gateway sent an end-of-stream HEADERS frame for an unsuccessful notification."); } final ApnsPushNotification pushNotification = stream.getProperty(this.pushNotificationPropertyKey); if (HttpResponseStatus.INTERNAL_SERVER_ERROR.equals(status)) { log.warn("APNs server reported an internal error when sending {}.", pushNotification); this.responsePromises.get(pushNotification).tryFailure(new ApnsServerException(null)); } else { this.responsePromises.get(pushNotification).trySuccess( new SimplePushNotificationResponse<>(pushNotification, success, null, null)); } } else { stream.setProperty(this.headersPropertyKey, headers); } } @Override public void onPriorityRead(final ChannelHandlerContext ctx, final int streamId, final int streamDependency, final short weight, final boolean exclusive) throws Http2Exception { } @Override public void onRstStreamRead(final ChannelHandlerContext ctx, final int streamId, final long errorCode) throws Http2Exception { } @Override public void onSettingsAckRead(final ChannelHandlerContext ctx) throws Http2Exception { } @Override public void onSettingsRead(final ChannelHandlerContext context, final Http2Settings settings) { log.trace("Received settings from APNs gateway: {}", settings); } @Override public void onPingRead(final ChannelHandlerContext ctx, final ByteBuf data) throws Http2Exception { } @Override public void onPingAckRead(final ChannelHandlerContext context, final ByteBuf data) { if (this.pingTimeoutFuture != null) { log.trace("Received reply to ping."); this.pingTimeoutFuture.cancel(false); } else { log.error("Received PING ACK, but no corresponding outbound PING found."); } } @Override public void onPushPromiseRead(final ChannelHandlerContext ctx, final int streamId, final int promisedStreamId, final Http2Headers headers, final int padding) throws Http2Exception { } @Override public void onGoAwayRead(final ChannelHandlerContext context, final int lastStreamId, final long errorCode, final ByteBuf debugData) throws Http2Exception { log.info("Received GOAWAY from APNs server: {}", debugData.toString(StandardCharsets.UTF_8)); } @Override public void onWindowUpdateRead(final ChannelHandlerContext ctx, final int streamId, final int windowSizeIncrement) throws Http2Exception { } @Override public void onUnknownFrame(final ChannelHandlerContext ctx, final byte frameType, final int streamId, final Http2Flags flags, final ByteBuf payload) throws Http2Exception { } }
package im.shimo.react.keyboard; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.support.annotation.Nullable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.widget.EditText; import android.widget.PopupWindow; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.yoga.YogaEdge; import com.facebook.yoga.YogaPositionType; import java.util.ArrayList; public class KeyboardView extends ReactRootAwareViewGroup implements LifecycleEventListener, AdjustResizeWithFullScreen.OnKeyboardStatusListener { private final static String TAG = "KeyboardView"; private final ThemedReactContext mThemedContext; private final UIManagerModule mNativeModule; private @Nullable volatile KeyboardCoverView mCoverView; private @Nullable volatile KeyboardContentView mContentView; private int navigationBarHeight; private int statusBarHeight; private RCTEventEmitter mEventEmitter; private int mKeyboardPlaceholderHeight; private float mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density; private boolean mContentVisible = true; private boolean mHideWhenKeyboardIsDismissed = true; private volatile int mChildCount; private View mEditFocusView; private volatile boolean initWhenAttached; private PopupWindow mContentViewPopupWindow; private int mMinContentViewHeight = 256; private boolean mKeyboardShownStatus; private int mCoverViewBottom; private int mUseBottom; private int mUseRight; private ValueAnimator translationSlide; // whether keyboard is shown private boolean mKeyboardShown = false; private volatile int mVisibility = -1; private int mOrientation = -1; private boolean isOrientationChange; public enum Events { EVENT_SHOW("onKeyboardShow"), EVENT_HIDE("onKeyboardHide"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } public KeyboardView(final ThemedReactContext context, int navigationBarHeight, int statusBarHeight) { super(context); this.mThemedContext = context; this.mNativeModule = mThemedContext.getNativeModule(UIManagerModule.class); this.navigationBarHeight = navigationBarHeight; this.statusBarHeight = statusBarHeight; mEventEmitter = context.getJSModule(RCTEventEmitter.class); context.addLifecycleEventListener(this); mContentViewPopupWindow = new PopupWindow(); mContentViewPopupWindow.setAnimationStyle(R.style.DialogAnimationSlide); mContentViewPopupWindow.setClippingEnabled(false); mContentViewPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT); mContentViewPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mContentViewPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { mContentViewPopupWindow.setAttachedInDecor(true); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) { //PopupWindowPopupWindow mContentViewPopupWindow.setBackgroundDrawable(null); } else { mContentViewPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } } @Override public void addView(View child, int index) { mChildCount++; final ViewGroup view = getReactRootView(); if (view == null) { if (child instanceof KeyboardCoverView) { mCoverView = (KeyboardCoverView) child; } else if (child instanceof KeyboardContentView) { mContentView = (KeyboardContentView) child; } initWhenAttached = true; } else { if (child instanceof KeyboardCoverView) { if (mCoverView != null) { removeView(mCoverView); } mCoverView = (KeyboardCoverView) child; view.addView(mCoverView); } else if (child instanceof KeyboardContentView) { if (mContentView != null) { removeView(mContentView); } mContentView = (KeyboardContentView) child; mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } if (KeyboardViewManager.DEBUG) { Log.e(TAG, "child = [" + child + "], index = [" + index + "]" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onAttachedToWindow,mOrientation=" + mOrientation); } if (mOrientation == -1) { mOrientation = getResources().getConfiguration().orientation; } AdjustResizeWithFullScreen.assistRegisterActivity(mThemedContext.getCurrentActivity(), statusBarHeight, navigationBarHeight, this); if (initWhenAttached) { initWhenAttached = false; final ViewGroup view = getReactRootView(); if (mCoverView != null) { if (mHideWhenKeyboardIsDismissed || (mContentView != null && mContentView.isShown())) { mCoverView.setVisibility(GONE); } else { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } view.addView(mCoverView); } if (mContentView != null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } } public void setHideWhenKeyboardIsDismissed(boolean hideWhenKeyboardIsDismissed) { mHideWhenKeyboardIsDismissed = hideWhenKeyboardIsDismissed; } public void setKeyboardPlaceholderHeight(int keyboardPlaceholderHeight) { if (AdjustResizeWithFullScreen.getKeyboardHeight() == 0) { mKeyboardPlaceholderHeight = (int) (keyboardPlaceholderHeight * mScale); } if (mContentView != null && mCoverView != null) { if (keyboardPlaceholderHeight > 0 && !mKeyboardShown) { final int height = AdjustResizeWithFullScreen.getKeyboardHeight(); final int useBottom = mCoverView.getBottom(); if (height != 0) { keepCoverViewOnScreenFrom(useBottom - height, height); } else { keepCoverViewOnScreenFrom(useBottom - mKeyboardPlaceholderHeight, mKeyboardPlaceholderHeight); } receiveEvent(Events.EVENT_SHOW); } } else if (mCoverView != null && !mContentVisible && !mHideWhenKeyboardIsDismissed && keyboardPlaceholderHeight == 0) { View viewGroup = mCoverView.getChildAt(0); while (!(viewGroup instanceof EditText) && ((ViewGroup) viewGroup).getChildCount() > 0) { viewGroup = ((ViewGroup) viewGroup).getChildAt(0); } if (viewGroup != null && viewGroup instanceof EditText) { //,ENEditText if (!viewGroup.isFocused()) { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } } } } public void setContentVisible(boolean contentVisible) { mContentVisible = contentVisible; if (contentVisible) { if (mCoverView == null) return; keepContentViewOnScreenFrom(mCoverView.getBottom()); } else { if (mEditFocusView != null) { if (mEditFocusView.isFocused()) { KeyboardUtil.showKeyboard(mEditFocusView); } else { mKeyboardShown = true; onKeyboardClosed(); } } } } @Override public void onKeyboardOpened() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardOpened" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (mKeyboardShown) return; mKeyboardShown = true; if (mEditFocusView == null) { mEditFocusView = mThemedContext.getCurrentActivity().getWindow().getDecorView().findFocus(); } if (mContentView != null && mContentView.isShown()) { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { mCoverView.setVisibility(VISIBLE); receiveEvent(Events.EVENT_SHOW); } } @Override public void onKeyboardClosed() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardClosed" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (!mKeyboardShown) return; mKeyboardShown = false; if (mContentView != null) { if (mContentVisible) { } else { if (mKeyboardPlaceholderHeight == 0) { receiveEvent(Events.EVENT_HIDE); } } } else { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { if (mEditFocusView.isFocused()) { if (!mContentVisible && mHideWhenKeyboardIsDismissed && (mContentView == null || !mContentView.isShown())) { mCoverView.setVisibility(GONE); } else { if (mContentView == null) { if (mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(GONE); } else { mCoverView.setVisibility(VISIBLE); } } else { mCoverView.setVisibility(VISIBLE); } } } else { if (!mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(VISIBLE); } else { mCoverView.setVisibility(GONE); } } } } @Override public boolean onKeyboardResize(int heightOfLayout, int bottom) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardResize,heightOfLayout=" + heightOfLayout); Log.e(TAG, "onKeyboardResize,mCoverView.isShown()=" + mCoverView.isShown()); } if (mCoverView != null && AdjustResizeWithFullScreen.isInit()) { if (mCoverView.isShown()) { int diff = AdjustResizeWithFullScreen.getWindowBottom() - heightOfLayout; if (mContentVisible && diff <= navigationBarHeight + statusBarHeight) { int coverViewBottom = mCoverView.getBottom(); if (!AdjustResizeWithFullScreen.isFullscreen() && coverViewBottom + AdjustResizeWithFullScreen.getKeyboardHeight() == AdjustResizeWithFullScreen.getWindowBottom()) { coverViewBottom -= diff; } keepCoverViewOnScreenFrom(coverViewBottom, bottom); return true; } else { keepCoverViewOnScreenFrom(heightOfLayout, bottom); return true; } } if (mKeyboardShown) { keepCoverViewOnScreenFrom(heightOfLayout, bottom); } } return true; } @Override public void addChildrenForAccessibility(ArrayList<View> outChildren) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow return false; } @Override public void onHostResume() { } @Override public void onHostPause() { } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (mVisibility != visibility) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onWindowVisibilityChanged,mVisibility=" + mVisibility + ",visibility=" + visibility + ",mUseBottom=" + mUseBottom + ",mKeyboardShownStatus=" + mKeyboardShownStatus); } if (mUseBottom == 0 && !mKeyboardShownStatus) { return; } if (visibility == VISIBLE) { int orientation = getResources().getConfiguration().orientation; final boolean isOchanged = isOrientationChange = mOrientation != orientation; if (isOchanged) { mOrientation = orientation; mKeyboardShownStatus = false; mVisibility = visibility; return; } if (mKeyboardShownStatus) { mKeyboardShownStatus = false; if (mEditFocusView != null) { mEditFocusView.setFocusable(true); mEditFocusView.requestFocus(); } } else { if (mCoverView == null || !mCoverView.isShown()) { mVisibility = visibility; return; } int diff = mUseBottom - AdjustResizeWithFullScreen.getUseBottom(); int diffR = mUseRight - getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); boolean isChanged = diff != 0 || diffR != 0 || isOchanged; if (isChanged) { keepCoverViewOnScreenFrom(mCoverViewBottom - diff, 0); } else { keepCoverViewOnScreenFrom(mCoverViewBottom, 0); } } mVisibility = visibility; } else if (visibility == GONE) { if (mEditFocusView != null && (KeyboardUtil.isKeyboardActive(mEditFocusView))) { mKeyboardShownStatus = true; } else { if (mCoverView != null) { mCoverViewBottom = mCoverView.getBottom(); mUseBottom = AdjustResizeWithFullScreen.getUseBottom(); mUseRight = getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); } } mVisibility = visibility; } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); receiveEvent(Events.EVENT_HIDE); onDropInstance(); } @Override public void onHostDestroy() { ((ReactContext) getContext()).removeLifecycleEventListener(this); onDropInstance(); } public void onDropInstance() { if (mCoverView != null) { removeView(mCoverView); } if (mContentView != null) { removeView(mContentView); } AdjustResizeWithFullScreen.assistUnRegister(mThemedContext.getCurrentActivity()); // mContentView = null; // mCoverView = null; mEditFocusView = null; // mContentViewPopupWindow.dismiss(); mContentViewPopupWindow.setContentView(null); mVisibility = -1; mKeyboardShown = mKeyboardShownStatus = false; mOrientation = -1; mContentVisible = false; mKeyboardPlaceholderHeight = 0; if (translationSlide != null) { translationSlide = null; } } @Override public void removeView(final View child) { if (child == null) return; ViewParent viewParent = child.getParent(); if (viewParent != null) { if (child.equals(mCoverView)) { mCoverView = null; ((ViewGroup) viewParent).removeView(child); if (!mContentVisible) { receiveEvent(Events.EVENT_HIDE); } mPreCoverBottom = mPreCoverHeight = mPreCoverWidth = 0; } else { mContentViewPopupWindow.dismiss(); ViewGroup parent = (ViewGroup) mContentView.getParent(); if (parent != null) { parent.removeView(mContentView); } mContentView = null; receiveEvent(Events.EVENT_HIDE); mPreContentWidth = mPreContentHeight = mPreContentTop = 0; } child.setVisibility(GONE); mChildCount } } @Override public void removeViewAt(int index) { if (index == 0 && mContentView != null) { removeView(mContentView); } else { removeView(mCoverView); } } @Override public int getChildCount() { return mChildCount; } @Override public View getChildAt(int index) { if (index == 0 && mContentView != null) { return mContentView; } else { return mCoverView; } } private void receiveEvent(Events event) { WritableMap map = Arguments.createMap(); map.putBoolean("keyboardShown", mKeyboardShown); mEventEmitter.receiveEvent(getId(), event.toString(), map); } private int mPreCoverHeight = 0; private int mPreCoverBottom = 0; private int mPreCoverWidth = 0; /** * CoverViewcoverViewcontentView */ private void keepCoverViewOnScreenFrom(final int height, final int bottom) { if (mCoverView != null) { ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); //maybe its null in this thread if (!isOrientationChange && mPreCoverBottom == bottom && mPreCoverHeight == height && mPreCoverWidth == useRight || mCoverView == null) { postContentView(); return; } mPreCoverBottom = bottom; mPreCoverHeight = height; mPreCoverWidth = useRight; try { ReactShadowNode coverShadowNode = mNativeModule.getUIImplementation().resolveShadowNode(mCoverView.getId()); if (bottom >= 0) { coverShadowNode.setPosition(YogaEdge.BOTTOM.intValue(), bottom); } coverShadowNode.setPosition(YogaEdge.TOP.intValue(), 0); coverShadowNode.setPositionType(YogaPositionType.ABSOLUTE); if (height > -1) { coverShadowNode.setStyleHeight(height); mNativeModule.updateNodeSize(mCoverView.getId(), useRight, height); } mNativeModule.getUIImplementation().dispatchViewUpdates(-1); postContentView(); } catch (Exception e) { e.printStackTrace(); } } private void postContentView() { mCoverView.post(new Runnable() { @Override public void run() { if (mContentVisible) { if (height > -1) { keepContentViewOnScreenFrom(height); } else { if (mCoverView == null) return; keepContentViewOnScreenFrom(mCoverView.getBottom()); } } } }); } }); if (translationSlide != null) { if (translationSlide.isRunning() || translationSlide.isStarted()) { translationSlide.cancel(); } } translationSlide = ObjectAnimator.ofFloat(mCoverView, "alpha", 0, 1); translationSlide.start(); } } private int mPreContentHeight = 0; private int mPreContentTop = 0; private int mPreContentWidth = 0; /** * mCoverViewbottom * * @param top */ private void keepContentViewOnScreenFrom(int top) { if (mContentView != null) { if (mContentViewPopupWindow.getContentView() == null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } if (mKeyboardShown) { if (top != AdjustResizeWithFullScreen.getUseBottom()) { top = AdjustResizeWithFullScreen.getUseBottom(); } } final int tempHeight = getContentViewHeight(top); final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { if (mContentView != null) { //maybe its null in this thread mNativeModule.updateNodeSize(mContentView.getId(), useRight, tempHeight); } } }); if (mContentViewPopupWindow.isShowing()) { boolean isOrientChanged = isOrientationChange; if (!isOrientChanged) { isOrientChanged = mOrientation == getResources().getConfiguration().orientation; } if (!isOrientChanged && mPreContentHeight == tempHeight && mPreContentTop == top && mPreContentWidth == useRight) { return; } if (isOrientChanged) { isOrientationChange = false; mOrientation = getResources().getConfiguration().orientation; } mContentViewPopupWindow.update(AdjustResizeWithFullScreen.getUseLeft(), top, useRight, tempHeight); } else { if (mContentViewPopupWindow.getHeight() != tempHeight) { mContentViewPopupWindow.setHeight(tempHeight); } if (mContentViewPopupWindow.getWidth() != useRight) { mContentViewPopupWindow.setWidth(useRight); } mContentViewPopupWindow.showAtLocation(AdjustResizeWithFullScreen.getDecorView(), Gravity.NO_GRAVITY, AdjustResizeWithFullScreen.getUseLeft(), top); } mPreContentHeight = tempHeight; mPreContentTop = top; mPreContentWidth = useRight; } } private int getContentViewHeight(int top) { int realKeyboardHeight = AdjustResizeWithFullScreen.getRemainingHeight(top); int keyboardHeight = AdjustResizeWithFullScreen.getKeyboardHeight(); if (realKeyboardHeight == 0 || realKeyboardHeight < keyboardHeight) { realKeyboardHeight = keyboardHeight; if (realKeyboardHeight == 0) { if (mKeyboardPlaceholderHeight != 0) { realKeyboardHeight = mKeyboardPlaceholderHeight; } else { realKeyboardHeight = mMinContentViewHeight; } } } return realKeyboardHeight; } }
package com.intellij.ide.actions; import com.intellij.ide.IdeBundle; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.IconLoader; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import java.io.File; public class CreateFileAction extends CreateElementActionBase { public CreateFileAction() { super(IdeBundle.message("action.create.new.file"), IdeBundle.message("action.create.new.file"), IconLoader.getIcon("/fileTypes/text.png")); } @NotNull protected PsiElement[] invokeDialog(final Project project, PsiDirectory directory) { MyInputValidator validator = new MyValidator(project, directory); Messages.showInputDialog(project, IdeBundle.message("prompt.enter.new.file.name"), IdeBundle.message("title.new.file"), Messages.getQuestionIcon(), null, validator); return validator.getCreatedElements(); } protected void checkBeforeCreate(String newName, PsiDirectory directory) throws IncorrectOperationException { directory.checkCreateFile(newName); } @NotNull protected PsiElement[] create(String newName, PsiDirectory directory) throws IncorrectOperationException { return new PsiElement[]{directory.createFile(newName)}; } protected String getActionName(PsiDirectory directory, String newName) { return IdeBundle.message("progress.creating.file", directory.getVirtualFile().getPresentableUrl(), File.separator, newName); } protected String getErrorTitle() { return IdeBundle.message("title.cannot.create.file"); } protected String getCommandName() { return IdeBundle.message("command.create.file"); } private class MyValidator extends MyInputValidator { public boolean checkInput(String inputString) { return true; } public boolean canClose(String inputString) { if (inputString.length() == 0) { return super.canClose(inputString); } FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(inputString); return type != null && super.canClose(inputString); } public MyValidator(Project project, PsiDirectory directory){ super(project, directory); } } }
package com.jadarstudios.developercapes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.IImageBuffer; import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureObject; import net.minecraft.util.ResourceLocation; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class DevCapesUtil { private static DevCapesUtil instance; public static final double version = 2.0; public DevCapesVersionChecker versionChecker; private HashMap<String, String> users; private HashMap<String, ResourceLocation> capeResources; private HashMap<String, ThreadDownloadImageData> downloadThreads; public boolean tickSetUp = false; /** * Object constructor. */ private DevCapesUtil() { users = new HashMap<String, String>(); capeResources = new HashMap<String, ResourceLocation>(); downloadThreads = new HashMap<String, ThreadDownloadImageData>(); versionChecker = new DevCapesVersionChecker(); new Thread(versionChecker).run(); } /** * Get's the current DeveloperCapesAPI instance, or creates a new one if * necessary. */ public static DevCapesUtil getInstance() { if (instance == null){ instance = new DevCapesUtil(); } return instance; } public void addFileUrl(String parTxtUrl) { if(!FMLCommonHandler.instance().getSide().equals(Side.CLIENT)) return; try{ URL url = new URL(parTxtUrl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; String username = ""; String group = ""; String capeUrl = ""; while ((line = reader.readLine()) != null){ // excludes commented lines if (!line.startsWith(" // loops through characters. for (int i = 0; i < line.length(); i++){ // when char : is found do stuff. if (line.charAt(i) == '='){ group = line.substring(0, i); String subLine = line.substring(i + 1); if (subLine.startsWith("http")){ capeUrl = subLine; ResourceLocation r = new ResourceLocation("DevCapes/" + group); ThreadDownloadImageData t = makeDownloadThread(r, capeUrl, null, new DevCapesImageBufferDownload()); this.addCapeResource(group, r); this.addDownloadThread(group, t); continue; }else{ username = subLine.toLowerCase(); addUser(username, group); } } } } } }catch(IOException e){ e.printStackTrace(); } // Makes sure to set up only one tick handler. if (!instance.tickSetUp){ // Sets up the tick handler for capes. TickRegistry.registerTickHandler(new DevCapesTickHandler(), Side.CLIENT); instance.tickSetUp = true; } } public void checkForUpdates() { } /** * Used to add user to users HashMap. * * @param parUsername * The Username to add. * @param parGroup * The group to add that Username to. */ public void addUser(String parUsername, String parGroup) { if (getUserGroup(parUsername) == null){ users.put(parUsername, parGroup); } } /** * Used to get user from users HashMap. * * @param parUsername * The Username to get from the users HashMap. * @return The Username found in the users HashMap. */ public String getUserGroup(String parUsername) { return users.get(parUsername.toLowerCase()); } /** * * Adds a cape ResourceLocation that is predownloaded. * * @param parGroup * @param parResource */ public void addCapeResource(String parGroup, ResourceLocation parResource) { if (getCapeResource(parGroup) == null){ capeResources.put(parGroup, parResource); } } /** * * Gets a cape ResourceLocation. * * @param parGroup * @return */ public ResourceLocation getCapeResource(String parGroup) { return capeResources.get(parGroup); } /** * * Adds an ThreadDownloadImageData. Needed to change cape. * * @param parGroup * @param parResource */ public void addDownloadThread(String parGroup, ThreadDownloadImageData parResource) { if (getDownloadThread(parGroup) == null){ downloadThreads.put(parGroup, parResource); } } /** * * Gets the ThreadDownloadImageData that is associated with the group. * * @param parGroup * @return */ public ThreadDownloadImageData getDownloadThread(String parGroup) { return downloadThreads.get(parGroup); } /** * * Used to download images. Copied from AbstractClientPlayer to remove * a conditional. * * @param par0ResourceLocation * @param par1Str * @param par2ResourceLocation * @param par3IImageBuffer * @return */ public static ThreadDownloadImageData makeDownloadThread(ResourceLocation par0ResourceLocation, String par1Str, ResourceLocation par2ResourceLocation, IImageBuffer par3IImageBuffer) { TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); TextureObject object = new ThreadDownloadImageData(par1Str, par2ResourceLocation, par3IImageBuffer); // Binds ResourceLocation to this. texturemanager.loadTexture(par0ResourceLocation, object); return (ThreadDownloadImageData)object; } }
package org.orbeon.oxf.util; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.xml.DOMConfigurator; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.DOMSerializer; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.properties.Properties; public class LoggerFactory { public static final String LOG4J_DOM_CONFIG_PROPERTY = "oxf.log4j-config"; public static final String LOG4J_DOM_CONFIG_PROPERTY_OLD = "oxf.servlet.log4j"; static { // 11-22-2004 d : Current log4j tries to load a default config. This is // why we are seeing a message about a log4j.properties being // loaded from the Axis jar. // Since this isn't a behaviour we want we hack around it by // specifying a file that doesn't exist. // 2008-05-05 a : It is clear if this solves a problem with an older version of // Axis we were shipping with Orbeon Forms back in 2004, or a more // complex interaction with a particular application server. // We don't think this is relevant anymore and are commenting this out. // Also see this thread on ops-users: // System.setProperty( "log4j.configuration", "-there-aint-no-such-file-" ); } private static final Logger logger = LoggerFactory.createLogger(LoggerFactory.class); public static Logger createLogger(Class clazz) { return Logger.getLogger(clazz.getName()); } /* * Init basic config until resource manager is setup. */ public static void initBasicLogger() { // 2008-07-25 a This has been here for a long time and it is not clear why it was put there. But this doesn't // seem to be a good idea, and is causing some problem. So: commenting. See discussion in this thread: // http://www.nabble.com/Problem-with-log-in-orbeon-with-multiple-webapp-to16932990.html#a18661451 // LogManager.resetConfiguration(); Logger root = Logger.getRootLogger(); root.setLevel(Level.INFO); root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN), ConsoleAppender.SYSTEM_ERR)); } /** * Init log4j. Needs Orbeon Forms Properties system up and running. */ public static void initLogger() { try { // Accept both xs:string and xs:anyURI types String log4jConfigURL = Properties.instance().getPropertySet().getStringOrURIAsString(LOG4J_DOM_CONFIG_PROPERTY); if (log4jConfigURL == null) log4jConfigURL = Properties.instance().getPropertySet().getStringOrURIAsString(LOG4J_DOM_CONFIG_PROPERTY_OLD); if (log4jConfigURL != null) { final Processor urlGenerator = PipelineUtils.createURLGenerator(log4jConfigURL, true); final DOMSerializer domSerializer = new DOMSerializer(); PipelineUtils.connect(urlGenerator, ProcessorImpl.OUTPUT_DATA, domSerializer, ProcessorImpl.INPUT_DATA); final PipelineContext pipelineContext = new PipelineContext(); urlGenerator.reset(pipelineContext); domSerializer.reset(pipelineContext); domSerializer.start(pipelineContext); final Object o = domSerializer.getW3CDocument(pipelineContext).getDocumentElement(); DOMConfigurator.configure((org.w3c.dom.Element) o); } else { logger.info("Property " + LOG4J_DOM_CONFIG_PROPERTY + " not set. Skipping logging initialization."); } } catch (Throwable e) { logger.error("Cannot load Log4J configuration. Skipping logging initialization", e); } } }
package hudson.cli; import hudson.FilePath; import hudson.FilePath.FileCallable; import jenkins.model.Jenkins; import jenkins.model.Jenkins.MasterComputer; import hudson.os.PosixAPI; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.util.Secret; import org.acegisecurity.Authentication; import org.acegisecurity.AuthenticationException; import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.acegisecurity.userdetails.UserDetails; import org.springframework.dao.DataAccessException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.Properties; /** * Represents the authentication credential store of the CLI client. * * <p> * This object encapsulates a remote manipulation of the credential store. * We store encrypted user names. * * @author Kohsuke Kawaguchi * @since 1.351 */ public class ClientAuthenticationCache implements Serializable { /** * Where the store should be placed. */ private final FilePath store; /** * Loaded contents of the store. */ private final Properties props = new Properties(); public ClientAuthenticationCache(Channel channel) throws IOException, InterruptedException { store = (channel==null ? MasterComputer.localChannel : channel).call(new Callable<FilePath, IOException>() { public FilePath call() throws IOException { File home = new File(System.getProperty("user.home")); return new FilePath(new File(home, ".hudson/cli-credentials")); } }); if (store.exists()) { props.load(store.read()); } } /** * Gets the persisted authentication for this Jenkins. * * @return {@link jenkins.model.Jenkins#ANONYMOUS} if no such credential is found, or if the stored credential is invalid. */ public Authentication get() { Jenkins h = Jenkins.getInstance(); Secret userName = Secret.decrypt(props.getProperty(getPropertyKey())); if (userName==null) return Jenkins.ANONYMOUS; // failed to decrypt try { UserDetails u = h.getSecurityRealm().loadUserByUsername(userName.getPlainText()); return new UsernamePasswordAuthenticationToken(u.getUsername(), "", u.getAuthorities()); } catch (AuthenticationException e) { return Jenkins.ANONYMOUS; } catch (DataAccessException e) { return Jenkins.ANONYMOUS; } } /** * Computes the key that identifies this Hudson among other Hudsons that the user has a credential for. */ private String getPropertyKey() { String url = Jenkins.getInstance().getRootUrl(); if (url!=null) return url; return Secret.fromString("key").toString(); } /** * Persists the specified authentication. */ public void set(Authentication a) throws IOException, InterruptedException { Jenkins h = Jenkins.getInstance(); // make sure that this security realm is capable of retrieving the authentication by name, // as it's not required. UserDetails u = h.getSecurityRealm().loadUserByUsername(a.getName()); props.setProperty(getPropertyKey(), Secret.fromString(u.getUsername()).getEncryptedValue()); save(); } /** * Removes the persisted credential, if there's one. */ public void remove() throws IOException, InterruptedException { if (props.remove(getPropertyKey())!=null) save(); } private void save() throws IOException, InterruptedException { store.act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(f); try { props.store(os,"Credential store"); } finally { os.close(); } // try to protect this file from other users, if we can. PosixAPI.get().chmod(f.getAbsolutePath(),0600); return null; } }); } }
package natlab; import java.io.*; import java.util.Map; import natlab.ast.ASTNode; import natlab.ast.Program; import beaver.Parser; import natlab.toolkits.scalar.*; /** * A utility for testing the structural flow analysis, * * This tool prints out the parse tree of the program of the input file, * and currently, it also prints out the structured string of the program. * The output file is named as: basename + ".tree" */ public class StructuralFlowAnalysisTool { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java natlab.StructuralFlowAnalysisTool {basename}"); System.exit(1); } String basename = args[0]; String filename = StaticFortranTool.getAbslouteName(basename); System.out.println("Converting 2 Fortran : "+filename); basename = filename; if(basename.substring(basename.length()-2).equals(".m") || basename.substring(basename.length()-2).equals(".n")) { basename = basename.substring(0,basename.length()-2); } try { BufferedReader in = new BufferedReader(new FileReader(filename)); CommentBuffer commentBuffer = new CommentBuffer(); NatlabScanner scanner = new NatlabScanner(in); scanner.setCommentBuffer(commentBuffer); NatlabParser parser = new NatlabParser(); parser.setCommentBuffer(commentBuffer); Program actual = (Program) parser.parse(scanner); PrintStream out = new PrintStream(basename + ".tree"); if(parser.hasError()) { for(String error : parser.getErrors()) { out.println(error); } } else { int startPos = actual.getStart(); int endPos = actual.getEnd(); out.println(Program.getLine(startPos) + " " + Program.getColumn(startPos)); out.println(Program.getLine(endPos) + " " + Program.getColumn(endPos)); out.print(actual.getStructureString()); out.println(); // out.print(actual.dumpTree()); } // Reaching Definitions Analysis example: // Using the Reaching-Def analysis need 3 steps: labeled [1],[2],[3] // [1] Generate use/def boxes each node of the tree, // here actual is the root. actual.generateUseBoxesList(); // Dump all of nodes by internal structure -- for debug purpose // out.println(); // out.print(actual.dumpTreeAll()); // Dump only the code-node -- for debug purpose // code-node: the node that we don't care about its subtree // Includes: simple-statement, assignment-stmt, ... out.println(); out.println(" out.println(" out.println(actual.dumpCodeTree()); // Set the debug flag and out stream, which will show analysis details // AbstractFlowAnalysis.setDebug(true, (PrintStream) out); // [2] Calling Reaching Defs directly ReachingDefs defsAnalysis = new ReachingDefs(actual); // [3] Retrieve the result // Sample code for outputting the result flow-set (after set) out.println(" // Retrieve after flow-sets Map<ASTNode, FlowSet> defsMap = defsAnalysis.getResult(); // Retrieve before flow-sets Map<ASTNode, FlowSet> beforeMap = defsAnalysis.getBeforeFlow(); // Go through each code-node, check its before/after flow-sets for(ASTNode node: defsAnalysis.getNodeList()) { FlowSet flowset = defsMap.get(node); FlowSet beforeSet = beforeMap.get(node); out.println("doAnalysis on: " + node.getNodeID() +" ["+ node.getDefBoxes()+"] ["+ node.getUseBoxes()); out.println("\t Before-Flow: " + beforeSet); out.println("\t After-Flow: " + flowset); } out.close(); in.close(); System.exit(0); } catch(IOException e) { e.printStackTrace(); System.exit(2); } catch (Parser.Exception e) { e.printStackTrace(); System.exit(3); } } }
package org.slf4j.impl; import java.util.logging.Level; import java.util.logging.LogRecord; import org.slf4j.Logger; /** * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in * conformity with the {@link Logger} interface. Note that the logging levels * mentioned in this class refer to those defined in the java.util.logging * package. * * @author Ceki G&uuml;lc&uuml; * @author Peter Royal */ public final class JDK14LoggerAdapter extends MarkerIgnoringBase { final java.util.logging.Logger logger; // WARN: JDK14LoggerAdapter constructor should have only package access so // that only JDK14LoggerFactory be able to create one. JDK14LoggerAdapter(java.util.logging.Logger logger) { this.logger = logger; } public String getName() { return logger.getName(); } /** * Is this logger instance enabled for the FINE level? * * @return True if this Logger is enabled for level FINE, false otherwise. */ public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } /** * Log a message object at level FINE. * * @param msg - * the message object to be logged */ public void debug(String msg) { log(Level.FINE, msg, null); } /** * Log a message at level FINE according to the specified format and argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for level FINE. * </p> * * @param format * the format string * @param arg * the argument */ public void debug(String format, Object arg) { if (logger.isLoggable(Level.FINE)) { String msgStr = MessageFormatter.format(format, arg); log(Level.FINE, msgStr, null); } } /** * Log a message at level FINE according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the FINE level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void debug(String format, Object arg1, Object arg2) { if (logger.isLoggable(Level.FINE)) { String msgStr = MessageFormatter.format(format, arg1, arg2); log(Level.FINE, msgStr, null); } } /** * Log a message at level FINE according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the FINE level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void debug(String format, Object[] argArray) { if (logger.isLoggable(Level.FINE)) { String msgStr = MessageFormatter.arrayFormat(format, argArray); log(Level.FINE, msgStr, null); } } /** * Log an exception (throwable) at level FINE with an accompanying message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void debug(String msg, Throwable t) { log(Level.FINE, msg, t); } /** * Is this logger instance enabled for the INFO level? * * @return True if this Logger is enabled for the INFO level, false otherwise. */ public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } /** * Log a message object at the INFO level. * * @param msg - * the message object to be logged */ public void info(String msg) { logger.info(msg); } /** * Log a message at level INFO according to the specified format and argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param arg * the argument */ public void info(String format, Object arg) { if (logger.isLoggable(Level.INFO)) { String msgStr = MessageFormatter.format(format, arg); log(Level.INFO, msgStr, null); } } /** * Log a message at the INFO level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void info(String format, Object arg1, Object arg2) { if (logger.isLoggable(Level.INFO)) { String msgStr = MessageFormatter.format(format, arg1, arg2); log(Level.INFO, msgStr, null); } } /** * Log a message at level INFO according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void info(String format, Object[] argArray) { if (logger.isLoggable(Level.INFO)) { String msgStr = MessageFormatter.arrayFormat(format, argArray); log(Level.INFO, msgStr, null); } } /** * Log an exception (throwable) at the INFO level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void info(String msg, Throwable t) { log(Level.INFO, msg, t); } /** * Is this logger instance enabled for the WARNING level? * * @return True if this Logger is enabled for the WARNING level, false * otherwise. */ public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } /** * Log a message object at the WARNING level. * * @param msg - * the message object to be logged */ public void warn(String msg) { log(Level.WARNING, msg, null); } /** * Log a message at the WARNING level according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARNING level. * </p> * * @param format * the format string * @param arg * the argument */ public void warn(String format, Object arg) { if (logger.isLoggable(Level.WARNING)) { String msgStr = MessageFormatter.format(format, arg); log(Level.WARNING, msgStr, null); } } /** * Log a message at the WARNING level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARNING level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void warn(String format, Object arg1, Object arg2) { if (logger.isLoggable(Level.WARNING)) { String msgStr = MessageFormatter.format(format, arg1, arg2); log(Level.WARNING, msgStr, null); } } /** * Log a message at level WARNING according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARNING level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void warn(String format, Object[] argArray) { if (logger.isLoggable(Level.WARNING)) { String msgStr = MessageFormatter.arrayFormat(format, argArray); log(Level.WARNING, msgStr, null); } } /** * Log an exception (throwable) at the WARNING level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void warn(String msg, Throwable t) { log(Level.WARNING, msg, t); } /** * Is this logger instance enabled for level SEVERE? * * @return True if this Logger is enabled for level SEVERE, false otherwise. */ public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } /** * Log a message object at the SEVERE level. * * @param msg - * the message object to be logged */ public void error(String msg) { log(Level.SEVERE, msg, null); } /** * Log a message at the SEVERE level according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the SEVERE level. * </p> * * @param format * the format string * @param arg * the argument */ public void error(String format, Object arg) { if (logger.isLoggable(Level.SEVERE)) { String msgStr = MessageFormatter.format(format, arg); log(Level.SEVERE, msgStr, null); } } /** * Log a message at the SEVERE level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the SEVERE level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void error(String format, Object arg1, Object arg2) { if (logger.isLoggable(Level.SEVERE)) { String msgStr = MessageFormatter.format(format, arg1, arg2); log(Level.SEVERE, msgStr, null); } } /** * Log a message at level INFO according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void error(String format, Object[] argArray) { if (logger.isLoggable(Level.SEVERE)) { String msgStr = MessageFormatter.arrayFormat(format, argArray); log(Level.SEVERE, msgStr, null); } } /** * Log an exception (throwable) at the SEVERE level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void error(String msg, Throwable t) { log(Level.SEVERE, msg, t); } private void log(Level level, String msg, Throwable t) { LogRecord record = new LogRecord(level, msg); record.setThrown(t); fillCallerData(record); logger.log(record); } static String SELF = JDK14LoggerAdapter.class.getName(); static String SUPER = MarkerIgnoringBase.class.getName(); private final void fillCallerData(LogRecord record) { StackTraceElement[] steArray = new Throwable().getStackTrace(); int selfIndex = -1; for (int i = 0; i < steArray.length; i++) { final String className = steArray[i].getClassName(); if (className.equals(SELF) || className.equals(SUPER)) { selfIndex = i; break; } } int found = -1; for (int i = selfIndex + 1; i < steArray.length; i++) { final String className = steArray[i].getClassName(); if (!(className.equals(SELF) || className.equals(SUPER))) { found = i; break; } } if (found != -1) { StackTraceElement ste = steArray[found]; record.setSourceClassName(ste.getClassName()); record.setSourceMethodName(ste.getMethodName()); } } }
package hudson.model; import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter; import hudson.Util; import hudson.security.ACL; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.IOException; /** * Authorization token to allow projects to trigger themselves under the secured environment. * * @author Kohsuke Kawaguchi * @see BuildableItem * @deprecated 2008-07-20 * Use {@link ACL} and {@link AbstractProject#BUILD}. This code is only here * for the backward compatibility. */ public final class BuildAuthorizationToken { private final String token; public BuildAuthorizationToken(String token) { this.token = token; } public static BuildAuthorizationToken create(StaplerRequest req) { if (req.getParameter("pseudoRemoteTrigger") != null) { String token = Util.fixEmpty(req.getParameter("authToken")); if(token!=null) return new BuildAuthorizationToken(token); } return null; } public static void checkPermission(AbstractProject project, BuildAuthorizationToken token, StaplerRequest req, StaplerResponse rsp) throws IOException { if (!Hudson.getInstance().isUseSecurity()) return; // everyone is authorized if(token!=null && token.token != null) { //check the provided token String providedToken = req.getParameter("token"); if (providedToken != null && providedToken.equals(token.token)) return; } project.checkPermission(AbstractProject.BUILD); } public String getToken() { return token; } public static final class ConverterImpl extends AbstractSingleValueConverter { public boolean canConvert(Class type) { return type== BuildAuthorizationToken.class; } public Object fromString(String str) { return new BuildAuthorizationToken(str); } @Override public String toString(Object obj) { return ((BuildAuthorizationToken)obj).token; } } }
package edu.ucsf.lava.core.session; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.ucsf.lava.core.audit.AuditManager; import edu.ucsf.lava.core.auth.model.AuthUser; import edu.ucsf.lava.core.environment.EnvironmentManager; import edu.ucsf.lava.core.manager.CoreManagerUtils; import edu.ucsf.lava.core.manager.LavaManager; import edu.ucsf.lava.core.manager.Managers; import edu.ucsf.lava.core.metadata.MetadataManager; import edu.ucsf.lava.core.scope.ScopeManager; import edu.ucsf.lava.core.scope.ScopeSessionAttributeHandler; import edu.ucsf.lava.core.scope.ScopeSessionAttributeHandlers; import edu.ucsf.lava.core.session.model.LavaServerInstance; import edu.ucsf.lava.core.session.model.LavaSession; public class SessionManager extends LavaManager{ public static String SESSION_MANAGER_NAME = "sessionManager"; protected final Log logger = LogFactory.getLog(getClass()); private List<LavaSessionPolicyHandler> policyHandlers; //injected protected LavaServerInstance serverInstance; protected MetadataManager metadataManager; protected ScopeManager scopeManager; protected EnvironmentManager environmentManager; protected AuditManager auditManager; protected Map<String,LavaSession> lavaSessions = new HashMap<String,LavaSession>(); public SessionManager(){ super(SESSION_MANAGER_NAME); } public void updateManagers(Managers managers) { super.updateManagers(managers); metadataManager = CoreManagerUtils.getMetadataManager(managers); scopeManager = CoreManagerUtils.getScopeManager(managers); environmentManager = CoreManagerUtils.getEnvironmentManager(managers); auditManager = CoreManagerUtils.getAuditManager(managers); } // Session Attribute Methods public Map getContextFromSession(HttpServletRequest request){ return scopeManager.getSessionAttributeHandlers().getContextFromSession(request); } public void setSessionAttribute(HttpServletRequest request,String attribute, Object object){ scopeManager.getSessionAttributeHandlers().setAttribute(request, attribute, object); } public Object getSessionAttribute(HttpServletRequest request,String attribute){ return scopeManager.getSessionAttributeHandlers().getAttribute(request, attribute); } public void addHandledAttribute(HttpServletRequest request,String scope, String attribute) { ScopeSessionAttributeHandlers attributeHandlers = scopeManager.getSessionAttributeHandlers(); ScopeSessionAttributeHandler handler = attributeHandlers.getHandlers().get(scope); handler.addHandledAttribute(attribute); } //LAVA Session Methods //calling from a request scope (so also initialize user and hostname if not already done public LavaSession getLavaSession(HttpServletRequest request) { LavaSession session = getLavaSession(request.getSession()); if(session == null){return null;} initializeUserAndHostNames(session, request); saveSession(session); return session; } public LavaSession getLavaSession(HttpSession httpSession) { if(httpSession == null){ return null; } if(lavaSessions.containsKey(httpSession.getId())){ return lavaSessions.get(httpSession.getId()); }else{ return null; } } public void removeLavaSessionFromCache(LavaSession session){ //session.release(true); } public void saveLavaSession(LavaSession session) { saveSession(session); } protected LavaSession saveSession(LavaSession session){ lavaSessions.put(session.getHttpSessionId(), session); return session; } protected void initializeUserAndHostNames(LavaSession session, HttpServletRequest request){ if(session.getHostname() == LavaSession.LAVASESSION_UNINITIALIZED_VALUE){ session.setHostname(getHostname(request)); } if(session.getUsername() == LavaSession.LAVASESSION_UNINITIALIZED_VALUE && ((HttpServletRequest)request).getRemoteUser()!= null){ session.setUsername(((HttpServletRequest)request).getRemoteUser()); } } protected String getHostname(HttpServletRequest request){ //first check for proxy header String host = request.getHeader("X-Forwarded-For"); if(host==null || host.equals("")){ host = request.getRemoteAddr(); if(host==null || host.equals("")){ host = LavaSession.LAVASESSION_UNINITIALIZED_VALUE; } }else if(host.contains(",")){ host = host.substring(0, host.indexOf(",")-1); } return host; } public boolean hasSessionExpired(LavaSession session,HttpServletRequest request){ for (LavaSessionPolicyHandler handler: policyHandlers){ if(handler.handlesSession(session, request)){ boolean result = handler.hasSessionExpired(session, request); saveSession(session); return result; } } logger.info("Unhandled session in sessionManager.hasSessionExpired"+ session.toString()); return false; } public boolean shouldSessionDisconnect(LavaSession session,HttpServletRequest request){ for (LavaSessionPolicyHandler handler: policyHandlers){ if(handler.handlesSession(session, request)){ boolean result = handler.shouldSessionDisconnect(session, request); saveSession(session); return result; } } logger.info("Unhandled session in sessionManager.shouldSessionDisconnect"+ session.toString()); return false; } public boolean willSessionDisconnectSoon(LavaSession session,HttpServletRequest request){ for (LavaSessionPolicyHandler handler: policyHandlers){ if(handler.handlesSession(session, request)){ //the should session disconnect needs to be called to ensure that all //disconnect handlers are checked. In practice, this will likely //already have been called before this method...but this is to make sure. handler.shouldSessionDisconnect(session, request); boolean result = handler.isDisconnectTimeWithinWarningWindow(session, request); saveSession(session); return result; } } logger.info("Unhandled session in sessionManager.willSessionDisconnectSoon"+ session.toString()); return false; } public void doSessionExpire(LavaSession session,HttpSession httpSession){ if(!session.isExpireTimeBeforeNow()){ session.setExpireTimestamp(new Timestamp(new Date().getTime())); } session.setCurrentStatus(LavaSession.LAVASESSION_STATUS_EXPIRED); saveSession(session); invalidateHttpSession(httpSession); } public void doSessionLogoff(LavaSession session,HttpSession httpSession) { AuthUser user = (AuthUser)AuthUser.MANAGER.getById(session.getUserId()); initializeSessionEventHandlerAuditing("logoff", user, session.getHostname()); if(session.getCurrentStatus().equals(LavaSession.LAVASESSION_STATUS_ACTIVE)){ session.setDisconnectDateTime(new Date()); session.setCurrentStatus(LavaSession.LAVASESSION_STATUS_LOGOFF); saveSession(session); } invalidateHttpSession(httpSession); finalizeSessionEventHandlerAuditing(); } public void doSessionDisconnect(LavaSession session,HttpSession httpSession){ if(!session.isDisconnectTimeBeforeNow()){ session.setDisconnectDateTime(new Date()); } session.setCurrentStatus(LavaSession.LAVASESSION_STATUS_DISCONNECTED); saveSession(session); invalidateHttpSession(httpSession); } public void setSessionAccessTimeToNow(LavaSession session,HttpServletRequest request){ session.setAccessTimestamp(new Timestamp(new Date().getTime())); saveSession(session); } public void updateSessionExpiration(LavaSession session, HttpServletRequest request){ for (LavaSessionPolicyHandler handler: policyHandlers){ if(handler.handlesSession(session, request)){ session.setExpireTimestamp(handler.determineExpireTime(session, request)); saveSession(session); updateHttpSessionExpiration(session,request); return; } } logger.info("Unhandled session in sessionManager.updateSessionExpiration"+ session.toString()); } protected void invalidateHttpSession(HttpSession httpSession){ // invalidating the HTTP session causes Acegi to do the following which clears the authentication, // so do not have to do this here: // SecurityContextHolder.getContext().setAuthentication(null); if(httpSession != null){ if(lavaSessions.containsKey(httpSession.getId())){ lavaSessions.remove(httpSession.getId()); } httpSession.invalidate(); } } protected void updateHttpSessionExpiration(LavaSession session,HttpServletRequest request){ HttpSession httpSession = request.getSession(); if(httpSession == null){return;} httpSession.setMaxInactiveInterval(-1); /*for (LavaSessionPolicyHandler handler: policyHandlers){ if(handler.handlesSession(session, request)){ httpSession.setMaxInactiveInterval(handler.getSecondsUntilExpiration(session, request)); return; } } logger.info("Unhandled session in sessionManager.updateHttpSessionExpiration"+ session.toString()); */ } public String getExpirationMessage(LavaSession session){ SimpleDateFormat dateFormat = new SimpleDateFormat("EE, MMMM d, yyyy hh:mm a"); return metadataManager.getMessage(LavaSessionHttpRequestWrapper.LAVASESSION_EXPIRED_MESSAGE_CODE, new Object[]{dateFormat.format(session.getExpireTimestamp())},Locale.getDefault()); } public String getDisconnectMessage(LavaSession session) { SimpleDateFormat dateFormat = new SimpleDateFormat("EE, MMMM d, yyyy hh:mm a"); return metadataManager.getMessage(LavaSessionHttpRequestWrapper.LAVASESSION_DISCONNECTED_MESSAGE_CODE, new Object[]{dateFormat.format(session.getDisconnectTime()), session.getDisconnectMessage()},Locale.getDefault()); } //NOTE: the messages being set as request parameters via the LavaSessionHttpRequestWrapper //have not worked yet. they did not work for session termination, i.e. were not available //after Acegi redirected to the login page. However, they may work in this situation, where //the session has not been terminated and there is no Acegi redirect involved public LavaSessionHttpRequestWrapper setPendingDisconnectMessage(LavaSession session,HttpServletRequest request){ LavaSessionHttpRequestWrapper requestWrapper = new LavaSessionHttpRequestWrapper(request); SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a, zzz"); requestWrapper.setLavaSessionMonitoringMessage( metadataManager.getMessage(LavaSessionHttpRequestWrapper.LAVASESSION_PENDING_DISCONNECT_MESSAGE_CODE, new Object[]{dateFormat.format(session.getDisconnectTime()), session.getDisconnectMessage()},Locale.getDefault())); return requestWrapper; } /** * Create the lava server instance entity...when created, not enough information about the runtime context is * available to fully name the server instance. Placeholder name is used until first user request. * @return */ public LavaServerInstance createLavaServerInstance(){ serverInstance = (LavaServerInstance)LavaServerInstance.MANAGER.create(); //serverInstance.save(); //serverInstance.refresh(); return serverInstance; } public LavaServerInstance getLavaServerInstance(){ if(serverInstance != null){ return serverInstance; } return createLavaServerInstance(); } public List<LavaSessionPolicyHandler> getPolicyHandlers() { return policyHandlers; } public void setPolicyHandlers(List<LavaSessionPolicyHandler> policyHandlers) { this.policyHandlers = policyHandlers; for (LavaSessionPolicyHandler handler: this.policyHandlers){ handler.setSessionMonitor(this); } } public Map<String, LavaSession> getLavaSessions() { return lavaSessions; } public void setLavaSessions(Map<String, LavaSession> lavaSessions) { this.lavaSessions = lavaSessions; } public LavaSession getLavaSession(String sessionId) { return lavaSessions.get(sessionId); } public void initializeSessionEventHandlerAuditing(String sessionEventName, AuthUser user, String host) { if (auditManager.isCurrentEventAudited()){return;} //do not reinitialize // session events (e.g. when session gets connected with user, or user logout) does not have its own "lava action/event", // but instead piggy-backs on top of normal lava actions. // TODO: better strategy in naming this audited "event"? auditManager.initializeAuditing(sessionEventName, sessionEventName, user.getId().toString(), user.getLogin(), host); } public void finalizeSessionEventHandlerAuditing() { auditManager.finalizeAuditing(); } }
package com.perpetumobile.bit.orm.record.field; import java.nio.ByteBuffer; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import org.apache.cassandra.thrift.Column; import org.json.simple.JSONObject; import com.perpetumobile.bit.orm.record.exception.FieldUnsupportedOperationException; import com.perpetumobile.bit.util.Util; /** * * @author Zoran Dukic */ abstract public class Field { public static final String NAME_SPACE_DELIMITER = "."; protected String fieldName = null; private ByteBuffer bbFieldName = null; protected boolean isSet = false; protected long timestamp = 0; public Field(String fieldName) { this.fieldName = fieldName; } public Field(ByteBuffer fieldName) { this.bbFieldName = fieldName; } abstract public boolean equalValue(Field f); public boolean equals(Object obj) { Field f = (Field)obj; if(getFieldName().equals(f.getFieldName())) { return equalValue(f); } return false; } public String getFieldName() { if(fieldName == null && bbFieldName != null) { fieldName = Util.toString(bbFieldName, FieldConfig.CHARSET_NAME); } return fieldName; } public ByteBuffer getByteBufferFieldName() { if(bbFieldName == null && fieldName != null) { bbFieldName = Util.toByteBuffer(fieldName, FieldConfig.CHARSET_NAME); } return bbFieldName; } public long getTimestamp() { return timestamp; } void setFieldName(String fieldName) { this.fieldName = fieldName; } abstract protected int bindImpl(ResultSet rs, int index) throws SQLException; public int bind(ResultSet rs, int index) throws SQLException { isSet = true; timestamp = Util.currentTimeMicros(); return bindImpl(rs, index); } protected void bindImpl(Column column) throws Exception { setByteBufferFieldValueImpl(column.value); } public void bind(Column column) throws Exception { isSet = true; timestamp = column.timestamp; bindImpl(column); } abstract public int setPreparedStatementParameter(PreparedStatement stmt, int index) throws SQLException; public boolean isSet() { return isSet; } public boolean isSet(String nameSpace) { boolean result = false; if(isSet) { int index = fieldName.indexOf(NAME_SPACE_DELIMITER); if(index == -1) { result = true; } else { String fieldNameSpace = fieldName.substring(0, index); if(fieldNameSpace.equals(nameSpace)) { result = true; } } } return result; } public boolean isAutoIncrement() { return false; } public String getSQLFieldValue() { return getFieldValue(); } public String getJSONFieldValue() { StringBuilder buf = new StringBuilder(); String value = getFieldValue(); if(value != null) { buf.append("\""); buf.append(JSONObject.escape(getFieldValue())); buf.append("\""); } else { buf.append("null"); } return buf.toString(); } // ByteBufferField interface abstract public ByteBuffer getByteBufferFieldValue(); abstract void setByteBufferFieldValueImpl(ByteBuffer fieldValue); public void setByteBufferFieldValue(ByteBuffer fieldValue) { if(fieldValue != null) { setByteBufferFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } } // StringField interface abstract public String getFieldValue(); abstract protected void setFieldValueImpl(String fieldValue); public void setFieldValue(String fieldValue) { if(fieldValue != null) { setFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } } // IntField interface public int getIntFieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setIntFieldValueImpl(int fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setIntFieldValue(int fieldValue) { setIntFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } // LongField interface public long getLongFieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setLongFieldValueImpl(long fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setLongFieldValue(long fieldValue) { setLongFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } // FloatField interface public float getFloatFieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setFloatFieldValueImpl(float fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setFloatFieldValue(float fieldValue) { setFloatFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } // DoubleField interface public double getDoubleFieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setDoubleFieldValueImpl(double fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setDoubleFieldValue(double fieldValue) { setDoubleFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } // MD5Field interface public String getMD5FieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setMD5FieldValueImpl(String fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setMD5FieldValue(String fieldValue) { if(fieldValue != null) { setMD5FieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } } // TimestampField interface public Timestamp getTimestampFieldValue() { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } protected void setTimestampFieldValueImpl(Timestamp fieldValue) { throw new FieldUnsupportedOperationException("Field Name: " + getFieldName()); } public void setTimestampFieldValue(Timestamp fieldValue) { if(fieldValue != null) { setTimestampFieldValueImpl(fieldValue); isSet = true; timestamp = Util.currentTimeMicros(); } } }
package org.xins.client; import java.util.HashMap; import java.util.Iterator; import org.xins.common.FormattedParameters; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.collections.PropertyReader; import org.xins.common.http.HTTPCallConfig; import org.xins.common.http.HTTPCallException; import org.xins.common.http.HTTPCallRequest; import org.xins.common.http.HTTPCallResult; import org.xins.common.http.HTTPServiceCaller; import org.xins.common.http.StatusCodeHTTPCallException; import org.xins.common.service.CallConfig; import org.xins.common.service.CallException; import org.xins.common.service.CallExceptionList; import org.xins.common.service.CallRequest; import org.xins.common.service.CallResult; import org.xins.common.service.ConnectionTimeOutCallException; import org.xins.common.service.ConnectionRefusedCallException; import org.xins.common.service.Descriptor; import org.xins.common.service.GenericCallException; import org.xins.common.service.IOCallException; import org.xins.common.service.ServiceCaller; import org.xins.common.service.SocketTimeOutCallException; import org.xins.common.service.TargetDescriptor; import org.xins.common.service.TotalTimeOutCallException; import org.xins.common.service.UnexpectedExceptionCallException; import org.xins.common.service.UnknownHostCallException; import org.xins.common.service.UnsupportedProtocolException; import org.xins.common.spec.ErrorCodeSpec; import org.xins.common.text.ParseException; import org.xins.common.text.TextUtils; import org.xins.common.xml.Element; public class XINSServiceCaller extends ServiceCaller { /** * The result parser. This field cannot be <code>null</code>. */ private final XINSCallResultParser _parser; /** * The <code>CAPI</code> object that uses this caller. This field is * <code>null</code> if this caller is not used by a <code>CAPI</code> * class. */ private AbstractCAPI _capi; /** * The map containing the service caller to call for the descriptor. * The key of the {@link HashMap} is a {@link TargetDescriptor} and the value * is a {@link ServiceCaller}. */ private HashMap<TargetDescriptor, ServiceCaller> _serviceCallers; public XINSServiceCaller(Descriptor descriptor, XINSCallConfig callConfig) throws IllegalArgumentException, UnsupportedProtocolException { // Call constructor of superclass super(descriptor, callConfig); // Initialize the fields _parser = new XINSCallResultParser(); } public XINSServiceCaller(Descriptor descriptor) throws IllegalArgumentException, UnsupportedProtocolException { this(descriptor, null); } /** * Constructs a new <code>XINSServiceCaller</code> with no * descriptor (yet) and the default HTTP method. * * <p>Before actual calls can be made, {@link #setDescriptor(Descriptor)} * should be used to set the descriptor. * * @since XINS 1.2.0 */ public XINSServiceCaller() { this((Descriptor) null, (XINSCallConfig) null); } /** * Checks if the specified protocol is supported (implementation method). * The protocol is the part in a URL before the string <code>"://"</code>). * * <p>This method should only ever be called from the * {@link #isProtocolSupported(String)} method. * * <p>The implementation of this method in class * <code>XINSServiceCaller</code> throws an * {@link UnsupportedOperationException} unless the protocol is * <code>"http"</code>, <code>"https"</code> or <code>"file"</code>. * * @param protocol * the protocol, guaranteed not to be <code>null</code> and guaranteed * to be in lower case. * * @return * <code>true</code> if the specified protocol is supported, or * <code>false</code> if it is not. * * @since XINS 1.2.0 */ protected boolean isProtocolSupportedImpl(String protocol) { return "http".equals(protocol) || "https".equals(protocol) || "file".equals(protocol); } @Override public void setDescriptor(Descriptor descriptor) { super.setDescriptor(descriptor); // Create the ServiceCaller for each descriptor if (_serviceCallers == null) { _serviceCallers = new HashMap<TargetDescriptor, ServiceCaller>(); } else { _serviceCallers.clear(); } // Create an HTTP- or File-caller for each descriptor if (descriptor != null) { for (TargetDescriptor target : descriptor.targets()) { String protocol = target.getProtocol().toLowerCase(); ServiceCaller caller; // HTTP or HTTPS protocol if ("http".equals(protocol) || "https".equals(protocol)) { caller = new HTTPServiceCaller(target); // FILE protocol } else if ("file".equals(protocol)) { caller = new FileServiceCaller(target); // Unsupported protocol } else { // TODO: Consider using a specific exception type throw new RuntimeException("Unsupported protocol \"" + protocol + "\" in descriptor."); } _serviceCallers.put(target, caller); } } } /** * Sets the associated <code>CAPI</code> instance. * * <p>This method is expected to be called only once, before any calls are * made with this caller. * * @param capi * the associated <code>CAPI</code> instance, or * <code>null</code>. */ void setCAPI(AbstractCAPI capi) { _capi = capi; } /** * Returns a default <code>CallConfig</code> object. This method is called * by the <code>ServiceCaller</code> constructor if no * <code>CallConfig</code> object was given. * * <p>The implementation of this method in class {@link XINSServiceCaller} * returns a standard {@link XINSCallConfig} object which has unconditional * fail-over disabled and the HTTP method set to * {@link org.xins.common.http.HTTPMethod#POST POST}. * * @return * a new {@link XINSCallConfig} instance with default settings, never * <code>null</code>. */ protected CallConfig getDefaultCallConfig() { return new XINSCallConfig(); } protected final void setXINSCallConfig(XINSCallConfig config) throws IllegalArgumentException { super.setCallConfig(config); } /** * Returns the <code>XINSCallConfig</code> associated with this service * caller. * * <p>This method is the type-safe equivalent of {@link #getCallConfig()}. * * @return * the fall-back {@link XINSCallConfig} object for this XINS service * caller, never <code>null</code>. * * @since XINS 1.2.0 */ public final XINSCallConfig getXINSCallConfig() { return (XINSCallConfig) getCallConfig(); } public XINSCallResult call(XINSCallRequest request, XINSCallConfig callConfig) throws IllegalArgumentException, GenericCallException, HTTPCallException, XINSCallException { // Determine when we started the call long start = System.currentTimeMillis(); // Perform the call XINSCallResult result; try { result = (XINSCallResult) doCall(request,callConfig); // Handle failures } catch (Throwable exception) { // Log that the call completely failed, unless the back-end returned // a functional error code. We assume that a functional error code // can never fail-over, so this issue will have been logged at the // correct (non-error) level already. if (!(exception instanceof UnsuccessfulXINSCallException) || ((UnsuccessfulXINSCallException) exception).getType() != ErrorCodeSpec.FUNCTIONAL) { // Determine how long the call took long duration = System.currentTimeMillis() - start; // Serialize all parameters, including the data section, for logging PropertyReader parameters = request.getParameters(); Element dataSection = request.getDataSection(); FormattedParameters params = new FormattedParameters(parameters, dataSection, "(null)", "&", 160); // Serialize the exception chain String chain = exception.getMessage(); Log.log_2113(request.getFunctionName(), params, duration, chain); } // Allow only GenericCallException, HTTPCallException and // XINSCallException to proceed if (exception instanceof GenericCallException) { throw (GenericCallException) exception; } if (exception instanceof HTTPCallException) { throw (HTTPCallException) exception; } if (exception instanceof XINSCallException) { throw (XINSCallException) exception; // Unknown kind of exception. This should never happen. Log and // re-throw the exception, wrapped within a ProgrammingException } else { throw Utils.logProgrammingError(exception); } } return result; } public XINSCallResult call(XINSCallRequest request) throws IllegalArgumentException, GenericCallException, HTTPCallException, XINSCallException { return call(request, null); } public Object doCallImpl(CallRequest request, CallConfig callConfig, TargetDescriptor target) throws IllegalArgumentException, ClassCastException, GenericCallException, HTTPCallException, XINSCallException { // Check preconditions MandatoryArgumentChecker.check("request", request, "callConfig", callConfig, "target", target); // Convert arguments to the appropriate classes XINSCallRequest xinsRequest = (XINSCallRequest) request; XINSCallConfig xinsConfig = (XINSCallConfig) callConfig; // Get URL, function and parameters (for logging) String url = target.getURL(); String function = xinsRequest.getFunctionName(); PropertyReader p = xinsRequest.getParameters(); Element dataSection = xinsRequest.getDataSection(); FormattedParameters params = new FormattedParameters(p, dataSection, "", "&", 160); // Get the time-out values (for logging) int totalTimeOut = target.getTotalTimeOut(); int connectionTimeOut = target.getConnectionTimeOut(); int socketTimeOut = target.getSocketTimeOut(); // Log: Right before the call is performed Log.log_2100(url, function, params); // Get the contained HTTP request from the XINS request HTTPCallRequest httpRequest = xinsRequest.getHTTPCallRequest(); // Convert XINSCallConfig to HTTPCallConfig HTTPCallConfig httpConfig = xinsConfig.getHTTPCallConfig(); // Determine the start time. Only required when an unexpected kind of // exception is caught. long start = System.currentTimeMillis(); // Perform the HTTP call HTTPCallResult httpResult; long duration; try { ServiceCaller serviceCaller = _serviceCallers.get(target); httpResult = (HTTPCallResult) serviceCaller.doCallImpl(httpRequest, httpConfig, target); // Call failed due to a generic service calling error } catch (GenericCallException exception) { duration = exception.getDuration(); if (exception instanceof UnknownHostCallException) { Log.log_2102(url, function, params, duration); } else if (exception instanceof ConnectionRefusedCallException) { Log.log_2103(url, function, params, duration); } else if (exception instanceof ConnectionTimeOutCallException) { Log.log_2104(url, function, params, duration, connectionTimeOut); } else if (exception instanceof SocketTimeOutCallException) { Log.log_2105(url, function, params, duration, socketTimeOut); } else if (exception instanceof TotalTimeOutCallException) { Log.log_2106(url, function, params, duration, totalTimeOut); } else if (exception instanceof IOCallException) { Log.log_2109(exception, url, function, params, duration); } else if (exception instanceof UnexpectedExceptionCallException) { Log.log_2111(exception.getCause(), url, function, params, duration); } else { String detail = "Unrecognized GenericCallException subclass " + exception.getClass().getName() + '.'; Utils.logProgrammingError(detail); } throw exception; // Call failed due to an HTTP-related error } catch (HTTPCallException exception) { duration = exception.getDuration(); if (exception instanceof StatusCodeHTTPCallException) { int code = ((StatusCodeHTTPCallException) exception).getStatusCode(); Log.log_2108(url, function, params, duration, code); } else { String detail = "Unrecognized HTTPCallException subclass " + exception.getClass().getName() + '.'; Utils.logProgrammingError(detail); } throw exception; // Unknown kind of exception. This should never happen. Log and re-throw // the exception, packed up as a CallException. } catch (Throwable exception) { duration = System.currentTimeMillis() - start; Utils.logProgrammingError(exception); String message = "Unexpected exception: " + exception.getClass().getName() + ". Message: " + TextUtils.quote(exception.getMessage()) + '.'; Log.log_2111(exception, url, function, params, duration); throw new UnexpectedExceptionCallException(request, target, duration, message, exception); } // Determine duration duration = httpResult.getDuration(); // Make sure data was received byte[] httpData = httpResult.getData(); if (httpData == null || httpData.length == 0) { // Log: No data was received Log.log_2110(url, function, params, duration, "No data received."); // Throw an appropriate exception throw InvalidResultXINSCallException.noDataReceived( xinsRequest, target, duration); } // Parse the result XINSCallResultData resultData; try { resultData = _parser.parse(httpData); // If parsing failed, then abort } catch (ParseException e) { // Create a message for the new exception String detail = e.getDetail(); String message = detail != null && detail.trim().length() > 0 ? "Failed to parse result: " + detail.trim() : "Failed to parse result."; // Log: Parsing failed Log.log_2110(url, function, params, duration, message); // Throw an appropriate exception throw InvalidResultXINSCallException.parseError( httpData, xinsRequest, target, duration, e); } // If the result is unsuccessful, then throw an exception String errorCode = resultData.getErrorCode(); if (errorCode != null) { boolean functionalError = false; ErrorCodeSpec.Type type = null; if (_capi != null) { functionalError = _capi.isFunctionalError(errorCode); } // Log this if (functionalError) { Log.log_2115(url, function, params, duration, errorCode); } else { Log.log_2112(url, function, params, duration, errorCode); } // Standard error codes (start with an underscore) if (errorCode.charAt(0) == '_') { if (errorCode.equals("_DisabledFunction")) { throw new DisabledFunctionException(xinsRequest, target, duration, resultData); } else if (errorCode.equals("_InternalError") || errorCode.equals("_InvalidResponse")) { throw new InternalErrorException( xinsRequest, target, duration, resultData); } else if (errorCode.equals("_InvalidRequest")) { throw new InvalidRequestException( xinsRequest, target, duration, resultData); } else { throw new UnacceptableErrorCodeXINSCallException( xinsRequest, target, duration, resultData); } // Non-standard error codes, CAPI not used } else if (_capi == null) { throw new UnsuccessfulXINSCallException( xinsRequest, target, duration, resultData, null); // Non-standard error codes, CAPI used } else { AbstractCAPIErrorCodeException ex = _capi.createErrorCodeException( xinsRequest, target, duration, resultData); if (ex != null) { ex.setType(type); throw ex; } else { // If the CAPI class was generated using a XINS release older // than 1.2.0, then it will not override the // 'createErrorCodeException' method and consequently the // method will return null. It cannot be determined here // whether the error code is acceptable or not String ver = _capi.getXINSVersion(); if (ver.startsWith("0.") || ver.startsWith("1.0.") || ver.startsWith("1.1.")) { throw new UnsuccessfulXINSCallException( xinsRequest, target, duration, resultData, null); } else { throw new UnacceptableErrorCodeXINSCallException( xinsRequest, target, duration, resultData); } } } } // Call completely succeeded Log.log_2101(url, function, params, duration); return resultData; } /** * Constructs an appropriate <code>CallResult</code> object for a * successful call attempt. This method is called from * {@link #doCall(CallRequest,CallConfig)}. * * <p>The implementation of this method in class * {@link XINSServiceCaller} expects an {@link XINSCallRequest} and * returns an {@link XINSCallResult}. * * @param request * the {@link CallRequest} that was to be executed, never * <code>null</code> when called from {@link #doCall(CallRequest,CallConfig)}; * should be an instance of class {@link XINSCallRequest}. * * @param succeededTarget * the {@link TargetDescriptor} for the service that was successfully * called, never <code>null</code> when called from * {@link #doCall(CallRequest,CallConfig)}. * * @param duration * the call duration in milliseconds, must be a non-negative number. * * @param exceptions * the list of {@link org.xins.common.service.CallException} instances, * or <code>null</code> if there were no call failures. * * @param result * the result from the call, which is the object returned by * {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)}, always an instance * of class {@link XINSCallResult}, never <code>null</code>; . * * @return * a {@link XINSCallResult} instance, never <code>null</code>. * * @throws ClassCastException * if either <code>request</code> or <code>result</code> is not of the * correct class. */ protected CallResult createCallResult(CallRequest request, TargetDescriptor succeededTarget, long duration, CallExceptionList exceptions, Object result) throws ClassCastException { XINSCallResult r = new XINSCallResult((XINSCallRequest) request, succeededTarget, duration, exceptions, (XINSCallResultData) result); return r; } /** * Determines whether a call should fail-over to the next selected target * based on a request, call configuration and exception list. * * @param request * the request for the call, as passed to {@link #doCall(CallRequest,CallConfig)}, * should not be <code>null</code>. * * @param callConfig * the call config that is currently in use, never <code>null</code>. * * @param exceptions * the current list of {@link CallException}s; never <code>null</code>. * * @return * <code>true</code> if the call should fail-over to the next target, or * <code>false</code> if it should not. */ protected boolean shouldFailOver(CallRequest request, CallConfig callConfig, CallExceptionList exceptions) { // Get the most recent exception CallException exception = exceptions.last(); boolean should; // Let the superclass look at this first. if (super.shouldFailOver(request, callConfig, exceptions)) { should = true; // Otherwise check if the request may fail-over from HTTP point-of-view // XXX: Note that this duplicates code that is already in the // HTTPServiceCaller. This may need to be refactored at some point. // It has been decided to take this approach since the // shouldFailOver method in class HTTPServiceCaller has protected // access. // An alternative solution that should be investigated is to // subclass HTTPServiceCaller. // A non-2xx HTTP status code indicates the request was not handled } else if (exception instanceof StatusCodeHTTPCallException) { int code = ((StatusCodeHTTPCallException) exception).getStatusCode(); should = (code < 200 || code > 299); // Some XINS error codes indicate the request was not accepted } else if (exception instanceof UnsuccessfulXINSCallException) { String s = ((UnsuccessfulXINSCallException) exception).getErrorCode(); should = ("_InvalidRequest".equals(s) || "_DisabledFunction".equals(s)); // Otherwise do not fail over } else { should = false; } return should; } }
package com.opengamma.maths; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.Test; public class EmptyTest { @Test public void testStuff() { assertTrue(true); } }
package io.daten.faster; import sun.misc.Unsafe; public final class FasterByteComparison { private static final Unsafe UNSAFE = UnsafeUtil.getTheUnsafe(); private FasterByteComparison() { // Utility Class } public static int compare(final byte[] buffer1, final byte[] buffer2) { return compare(buffer1, 0, buffer1.length, buffer2, 0, buffer2.length); } public static int compare(final byte[] buffer1, final int offset1, final int length1, final byte[] buffer2, final int offset2, final int length2) { final int minLength = Math.min(length1, length2); // Shortcut for (minLength / 8) * 8 final int fullWordBytes = minLength & ~7; final int memPos1 = offset1 + UnsafeUtil.BYTE_ARRAY_OFFSET; final int memPos2 = offset2 + UnsafeUtil.BYTE_ARRAY_OFFSET; for (int i = 0; i < fullWordBytes; i += Long.BYTES) { final long left = UNSAFE.getLong(buffer1, (long) memPos1 + (long) i); final long right = UNSAFE.getLong(buffer2, (long) memPos2 + (long) i); if (left != right) { if (PlatformUtil.IS_LITTLE_ENDIAN) { return Long.compareUnsigned(Long.reverseBytes(left), Long.reverseBytes(right)); } else { return Long.compareUnsigned(left, right); } } } for (int i = fullWordBytes; i < minLength; i++) { final int result = Long.compareUnsigned( buffer1[offset1 + i], buffer2[offset2 + i] ); if (result != 0) { return result; } } return length1 - length2; } }
package com.refresh.pos.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.util.Log; public class InventoryDaoAndroid extends SQLiteOpenHelper implements Dao { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "pos_database2"; public InventoryDaoAndroid(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL("CREATE TABLE product_catalog" + "(_id INTEGER PRIMARY KEY," + "name TEXT(100)," + "barcode TEXT(100)," + " sale_price DOUBLE );"); database.execSQL("CREATE TABLE stock" + "(_id INTEGER PRIMARY KEY," + "product_id INTEGER," + "amount INTEGER," + "cost DOUBLE," + "date_added DATETIME);"); Log.d("CREATE DATABASE", "Create Database Successfully."); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } @Override public List<Object> select(String queryString) { try { SQLiteDatabase database = this.getWritableDatabase(); List<Object> list = new ArrayList<Object>(); Cursor cursor = database.rawQuery(queryString, null); if (cursor != null) { if (cursor.moveToFirst()) { do { ContentValues content = new ContentValues(); String[] columnNames = cursor.getColumnNames(); for (String columnName : columnNames) { content.put(columnName, cursor.getString(cursor.getColumnIndex(columnName))); } list.add(content); } while (cursor.moveToNext()); } } cursor.close(); database.close(); return list; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public long insert(String tableName, Object content) { try { SQLiteDatabase database = this.getWritableDatabase(); long rows = database.insert(tableName, null, (ContentValues) content); database.close(); return rows; } catch (Exception e) { e.printStackTrace(); return -1; } } @Override public boolean update() { // TODO Auto-generated method stub return false; } @Override public boolean delete() { // TODO Auto-generated method stub return false; } public long getSize() { SQLiteDatabase database = this.getWritableDatabase(); SQLiteStatement byteStatement = database .compileStatement("SELECT SUM(LENGTH(_id)) FROM product_catalog"); long bytes = byteStatement.simpleQueryForLong(); return bytes; } }
package deltadak; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Rectangle2D; import javafx.scene.control.*; import javafx.scene.control.cell.TextFieldListCell; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Popup; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.StringConverter; import java.io.File; import java.io.Serializable; import java.net.URL; import java.security.CodeSource; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Objects; import java.util.ResourceBundle; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import static java.lang.Integer.min; /** * Class to control the UI */ // incorrect warning about LocalDate may be weakened to ChronoLocalDate (not // true) @SuppressWarnings("TypeMayBeWeakened") public class Controller implements Initializable { // main element of the UI is declared in interface.fxml @FXML GridPane gridPane; // used to transfer tasks with drag and drop private DataFormat dataFormat = new DataFormat("com.deltadak.Task"); private String databasePath; // database globals private Connection connection; private Statement statement; private int countID = 1; // layout globals private static final int NUMBER_OF_DAYS = 9; private static final int MAX_COLUMNS = 3; private static final int MAX_LIST_LENGTH = 7; private ContextMenu contextMenu; /** * Initialization method for the controller. */ @FXML public void initialize(final URL location, final ResourceBundle resourceBundle) { // some optional insertion for testing purposes // LocalDate today = LocalDate.now(); // LocalDate tomorrow = today.plusDays(1); // insertTask(today, "exam1", "2WA60",1); // insertTask(today, "exam2", "2WA60",2); // insertTask(today, "exam3", "2WA30",3); // insertTask(today, "exam4", "2WA30",4); // insertTask(tomorrow, "one", "2WA60",1); // insertTask(tomorrow, "two", "2WA60",2); // insertTask(tomorrow, "three", "2WA30",3); // insertTask(tomorrow, "boom", "2WA30",4); setDefaultDatabasePath(); setupContextMenu(); createTable(); // if not already exists setupGridPane(); } /** * inserts a task into the database, given * * @param day * - the date as a LocalDate * @param task * - the task as a string * @param label * - the label/course (code) as a string * @param order * - this is the i-th task on this day, as an int */ private void insertTask(final LocalDate day, final String task, final String label, final int order) { setHighestID(); // sets countID String dayString = localDateToString(day); String sql = "INSERT INTO tasks(id, day, task, label, orderInDay) " + "VALUES (" + countID + ", '" + dayString + "', '" + task + "','" + label + "'," + order + ")"; countID++; query(sql); } /** * Gets all the tasks on a given day. * * @param day * - the date for which to get all the tasks * * @return List<Task> */ private List<Task> getTasksDay(final LocalDate day) { String dayString = localDateToString(day); String sql = "SELECT task, label " + "FROM tasks " + "WHERE day = '" + dayString + "' ORDER BY orderInDay"; List<Task> tasks = new ArrayList<>(); setConnection(); try { statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { tasks.add(new Task(resultSet.getString("task"), resultSet.getString("label"))); } } catch (Exception e) { e.printStackTrace(); } return tasks; } /** * updates a day in the database * * @param day * - date for which to update * @param tasks * - List<Task> with the new tasks */ private void updateTasksDay(final LocalDate day, final List<Task> tasks) { System.out.println("updateTasksDay " + localDateToString(day)); // first remove all the items for this day that are currently in the // database before we add the new ones, // so we don't get double tasks deleteTasksDay(day); // then add the new tasks for (int i = 0; i < tasks.size(); i++) { insertTask(day, tasks.get(i).getText(), tasks.get(i).getLabel(), i); } } /** * Sets countID to the highest ID that's currently in the database. * To prevent double IDs */ private void setHighestID() { String sql = "SELECT * FROM tasks ORDER BY id DESC"; setConnection(); try { statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); if (resultSet.isBeforeFirst()) { // if the database is not empty, we set the id to be the // highest + 1 countID = resultSet.getInt("id") + 1; } else { // if the database is empty we set the id to 1 countID = 1; } statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Delete a task from the database given its id * * @param id * - id of a task (primary key in the database) */ public void deleteTask(final int id) { String sql = "DELETE FROM tasks WHERE id = " + id; query(sql); } /** * deletes all the tasks from the database where field task is empty * used when updating a day of which an item has been removed (by dragging) */ private void deleteEmptyTasks() { String sql = "DELETE FROM tasks WHERE task = '' "; query(sql); } /** * Deletes all tasks from the database for a given day. * * @param day * - the day of which all tasks have to be deleted. Calendar * object. */ private void deleteTasksDay(final LocalDate day) { String dayString = localDateToString(day); String sql = "DELETE FROM tasks WHERE day = '" + dayString + "'"; query(sql); } /** * sets the default path of the database to the directory the jar file is in */ private void setDefaultDatabasePath() { try { // get the directory of the jar CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath(); // set up the path of the database to make connection with the database databasePath = "jdbc:sqlite:" + jarDir + "\\plep.db"; System.out.println(databasePath); } catch (Exception e) { e.printStackTrace(); } } /** * used to change the directory of the database * not used yet because we only set default database */ // private void changeDirectory() { // Dialog chooseDialog = new Dialog(); // chooseDialog.setHeight(100); // chooseDialog.setWidth(300); //// chooseDialog.setResizable(true); // chooseDialog.setTitle("Decisions!"); // GridPane grid = new GridPane(); // grid.setPrefHeight(chooseDialog.getHeight()); // grid.setPrefWidth(chooseDialog.getWidth()); // Button browseButton = new Button("Browse"); // Text text = new Text("Choose database directory..."); // ButtonType browseButtonType = new ButtonType("OK", // ButtonBar.ButtonData.OK_DONE); // chooseDialog.getDialogPane().getButtonTypes().add(browseButtonType); // chooseDialog.getDialogPane().lookupButton(browseButtonType).setDisable(true); // browseButton.setOnMouseClicked(event -> { // System.out.println("button clicked"); // DirectoryChooser directoryChooser = new DirectoryChooser(); // directoryChooser.setTitle("Choose Directory"); // File directory = directoryChooser.showDialog(new Stage()); // String databaseDirectory = directory.getAbsolutePath(); // text.setText(databaseDirectory); // databasePath = "jdbc:sqlite:"; // databasePath += databaseDirectory + "\\plep.db"; // System.out.println(databasePath); // chooseDialog.getDialogPane().lookupButton(browseButtonType).setDisable(false); // grid.add(browseButton,0,1); // grid.add(text,0,0); // chooseDialog.getDialogPane().setContent(grid); // chooseDialog.showAndWait(); /** * Creates table with all the tasks, if it doesn't exist yet. */ private void createTable() { String sql = "CREATE TABLE IF NOT EXISTS tasks(" + "id INT PRIMARY KEY," + "day DATE," + "task CHAR(255)," + "label CHAR(10)," + "orderInDay INT)"; query(sql); } /** * Delete a given table from the database. * * @param tableName * - name of the table that has to be deleted */ public void deleteTable(final String tableName) { String sql = "DROP TABLE IF EXISTS " + tableName; query(sql); } /** * Sends query to the database. Don't use this when selecting data from the * database. (No method for that because we need to do something with the * data in the try-block). * * @param sql * - string with the sql query */ private void query(final String sql) { setConnection(); try { statement = connection.createStatement(); statement.executeUpdate(sql); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Connect to the database. * Use this before sending a query to the database. */ private void setConnection() { try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection(databasePath); } catch (Exception e) { e.printStackTrace(); } } /** * Converts LocalDate object to String object. * * @param localDate * to be converted * * @return String with eg 2017-03-25 */ private String localDateToString(final LocalDate localDate) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return localDate.format(formatter); } /** * sets up listviews for each day, initializes drag and drop, editing items */ private void setupGridPane() { for (int index = 0; index < NUMBER_OF_DAYS; index++) { // add days immediately, otherwise we can't use localDate in a // lambda expression (as it is not final) LocalDate localDate = LocalDate.now().plusDays(index - 1); ListView<Task> list = new ListView<>(); VBox vbox = setTitle(list, localDate); addVBoxToGridPane(vbox, index); List<Task> tasks = getTasksDay(localDate); list.setItems(convertArrayToObservableList(tasks)); list.setEditable(true); list.setPrefWidth(getListViewWidth()); list.setPrefHeight(getListViewHeight()); addLabelCells(list, localDate); //update database when editing is finished list.setOnEditCommit(event -> { updateTasksDay(localDate, convertObservableToArrayList(list.getItems())); deleteEmptyTasks(); //from database }); addDeleteKeyListener(list, localDate); cleanUp(list); } } /** * add title to listview * * @param list * to use * @param localDate * from which to make a title * * @return VBox with listview and title */ private VBox setTitle(final ListView<Task> list, final LocalDate localDate) { // vbox will contain a title above a list of tasks VBox vbox = new VBox(); Label title = new Label(localDateToString(localDate)); // the pane is used to align both properly (I think) Pane pane = new Pane(); vbox.getChildren().addAll(title, pane, list); VBox.setVgrow(pane, Priority.ALWAYS); return vbox; } /** * add a box containing listview and title * * @param vbox * to be added * @param index * at the i'th place (left to right, top to bottom) */ private void addVBoxToGridPane(final VBox vbox, final int index) { int row = index / MAX_COLUMNS; int column = index % MAX_COLUMNS; gridPane.add(vbox, column, row); } private void addDeleteKeyListener(final ListView<Task> list, final LocalDate localDate) { //add option to delete a task list.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.DELETE) { list.getItems() .remove(list.getSelectionModel().getSelectedIndex()); updateTasksDay(localDate, convertObservableToArrayList(list.getItems())); cleanUp(list); //cleaning up has to happen in the listener deleteEmptyTasks(); // from database } }); } /** * convert ObservableList to ArrayList * * @param list * to convert * * @return converted ObservableList */ private List<Task> convertObservableToArrayList( final ObservableList<Task> list) { return new ArrayList<>(list); } /** * convert (Array)List to ObservableList * * @param list * - List to be converted * * @return ObservableList */ private ObservableList<Task> convertArrayToObservableList( final List<Task> list) { return FXCollections.observableList(list); } /** * get height by total screen size * * @return intended listview height */ private int getListViewHeight() { Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); int totalHeight = (int)primaryScreenBounds.getHeight(); return totalHeight / (NUMBER_OF_DAYS / MAX_COLUMNS); } /** * get width by total screen size * * @return intended listview width */ private int getListViewWidth() { Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); int totalWidth = (int)primaryScreenBounds.getWidth(); return totalWidth / MAX_COLUMNS; } private void addLabelCells(final ListView<Task> list, final LocalDate day) { //no idea why the callback needs a ListCell and not a TextFieldListCell //anyway, editing is enabled by using TextFieldListCell instead of // ListCell list.setCellFactory(new Callback<ListView<Task>, ListCell<Task>>() { @Override public LabelCell call(final ListView<Task> param) { LabelCell labelCell = new LabelCell() {}; //update text on changes labelCell.setConverter(new TaskConverter(labelCell)); // update label on changes labelCell.comboBox.valueProperty().addListener( (observable, oldValue, newValue) -> labelCell.getItem() .setLabel(newValue)); setOnLabelChangeListener(labelCell, list, day); setOnDragDetected(labelCell); setOnDragOver(labelCell); setOnDragEntered(labelCell); setOnDragExited(labelCell); setOnDragDropped(labelCell, list, day); setOnDragDone(labelCell, list, day); setRightMouseClickListener(labelCell); return labelCell; } }); cleanUp(list); } private void setOnLabelChangeListener(final LabelCell labelCell, final ListView<Task> list, final LocalDate day) { // update label in database when selecting a different one labelCell.comboBox.getSelectionModel().selectedIndexProperty() .addListener((observable, oldValue, newValue) -> { updateTasksDay(day, convertObservableToArrayList( list.getItems())); deleteEmptyTasks(); // from database cleanUp(list); }); } private void setRightMouseClickListener(final LabelCell labelCell) { labelCell.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> { if (event.getButton() == MouseButton.SECONDARY) { System.out.println("right clicked"); contextMenu.show(labelCell, event.getScreenX(), event.getScreenY()); List<MenuItem> menuItems = contextMenu.getItems(); for (MenuItem menuItem : menuItems) { menuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println(menuItem.getText()); String colorString = convertColorToHex(menuItem.getText()); if(colorString.equals("#ffffffff")) { labelCell.setStyle("-fx-text-fill: none"); } else { labelCell.setStyle("-fx-background: " + colorString); } } }); } } }); } private void setOnDragDetected(final LabelCell labelCell) { labelCell.setOnDragDetected((MouseEvent event) -> { if (!labelCell.getItem().getText().equals("")) { Dragboard db = labelCell.startDragAndDrop(TransferMode.MOVE); ClipboardContent content = new ClipboardContent(); content.put(dataFormat, labelCell.getItem()); db.setContent(content); } event.consume(); }); } private void setOnDragOver(final LabelCell labelCell) { labelCell.setOnDragOver(event -> { if ((!Objects.equals(event.getGestureSource(), labelCell)) && event .getDragboard().hasContent(dataFormat)) { event.acceptTransferModes(TransferMode.MOVE); } event.consume(); }); } private void setOnDragEntered(final LabelCell labelCell) { labelCell.setOnDragEntered(event -> { if ((!Objects.equals(event.getGestureSource(), labelCell)) && event .getDragboard().hasContent(dataFormat)) { System.out.println("TODO: change color of listview"); //todo } event.consume(); }); } private void setOnDragExited(final LabelCell labelCell) { labelCell.setOnDragExited(event -> { System.out.println("TODO reset color of listview"); //todo event.consume(); }); } private void setOnDragDropped(final LabelCell labelCell, final ListView<Task> list, final LocalDate day) { labelCell.setOnDragDropped(event -> { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasContent(dataFormat)) { Task newTask = (Task)db.getContent(dataFormat); //insert new task, removing will happen in onDragDone int index = min(labelCell.getIndex(), list.getItems() .size()); // item can be dropped way below // the existing list //we have put an empty item instead of no items //because otherwise there are no listCells that can // receive an item if (list.getItems().get(index).getText().equals("")) { list.getItems().set(index, newTask); //replace empty item } else { list.getItems().add(index, newTask); } success = true; // update tasks in database updateTasksDay(day, convertObservableToArrayList(list.getItems())); } event.setDropCompleted(success); event.consume(); cleanUp(list); }); } private void setOnDragDone(final LabelCell labelCell, final ListView<Task> list, final LocalDate day) { labelCell.setOnDragDone(event -> { //ensures the original element is only removed on a // valid copy transfer (no dropping outside listviews) if (event.getTransferMode() == TransferMode.MOVE) { Dragboard db = event.getDragboard(); Task newTask = (Task)db.getContent(dataFormat); Task emptyTask = new Task("", ""); //remove original item //item can have been moved up (so index becomes one // too much) // or such that the index didn't change, like to // another day if (list.getItems().get(labelCell.getIndex()).getText() .equals(newTask.getText())) { list.getItems().set(labelCell.getIndex(), emptyTask); labelCell.setGraphic(null); // update in database updateTasksDay(day, convertObservableToArrayList( list.getItems())); // deleting blank row from database updating creates deleteEmptyTasks(); } else { list.getItems().set(labelCell.getIndex() + 1, emptyTask); } //prevent an empty list from refusing to receive // items, as it wouldn't contain any listcell if (list.getItems().size() < 1) { list.getItems().add(emptyTask); } } event.consume(); cleanUp(list); }); } /** * removes empty rows, and then fills up with empty rows * * @param list * to clean up */ private void cleanUp(final ListView<Task> list) { int i; //first remove empty items for (i = 0; i < list.getItems().size(); i++) { if (list.getItems().get(i).getText().equals("")) { list.getItems().remove(i); } } //fill up if necessary for (i = 0; i < MAX_LIST_LENGTH; i++) { if (i >= list.getItems().size()) { list.getItems().add(i, new Task("", "")); } } } private void setupContextMenu() { contextMenu = new ContextMenu(); RadioMenuItem firstRadioItem = new RadioMenuItem("Green"); RadioMenuItem secondRadioItem = new RadioMenuItem("Blue"); RadioMenuItem thirdRadioItem = new RadioMenuItem("Red"); RadioMenuItem defaultColor = new RadioMenuItem("White"); ToggleGroup group = new ToggleGroup(); firstRadioItem.setToggleGroup(group); secondRadioItem.setToggleGroup(group); thirdRadioItem.setToggleGroup(group); defaultColor.setToggleGroup(group); contextMenu.getItems().addAll( firstRadioItem, secondRadioItem, thirdRadioItem,defaultColor); } private String convertColorToHex(final String colorName) { String hex; switch (colorName) { case "Green": hex = "#7ef202"; break; case "Blue": hex = "#4286f4"; break; case "Red": hex = "#e64d4d"; break; case "White" : hex = "#ffffffff"; break; default: hex = "#ffffffff"; } return hex; } /** * custom ListCell */ private class LabelCell extends TextFieldListCell<Task> { HBox hbox = new HBox(); Label text = new Label(""); Pane pane = new Pane(); ObservableList<String> comboList = FXCollections .observableArrayList("0LAUK0", "2WF50", "2WA70", "2IPC0"); ComboBox<String> comboBox = new ComboBox<>(comboList); private LabelCell() { super(); hbox.getChildren().addAll(text, pane, comboBox); HBox.setHgrow(pane, Priority.ALWAYS); } /** * called when starting edit with (null, true) * and when finished edit with (task, false) * * @param task * to be updated * @param empty * whether to set empty? */ @Override public void updateItem(final Task task, final boolean empty) { super.updateItem(task, empty); setText(null); if (empty) { setGraphic(null); } else { text.setText( (task.getText() != null) ? task.getText() : "<null>"); comboBox.setValue( (task.getLabel() != null) ? task.getLabel() : "<null>"); setGraphic(hbox); } } } /** * custom stringconverter to define what editing a listcell means * this converter is set on each listcell */ private class TaskConverter extends StringConverter<Task> { private final ListCell<Task> cell; private TaskConverter(final ListCell<Task> cell) { this.cell = cell; } @Override public String toString(final Task task) { return task.getText(); } @Override public Task fromString(final String string) { Task task = cell.getItem(); task.setText(string); return task; } } //when transferred with the dragboard, the object is serialized //which I think means that a new object is created and you lose the // reference to the old one //which I think should be fine here, as only content matters static class Task implements Serializable { private String text; private String label; private Task(final String text, final String label) { this.text = text; this.label = label; } private String getText() { return text; } private void setText(final String text) { this.text = text; } private String getLabel() { return label; } private void setLabel(final String label) { this.label = label; } } }
package org.batfish.config; import com.google.common.collect.ImmutableList; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.batfish.common.BaseSettings; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.CoordConsts; import org.batfish.common.Version; import org.batfish.common.util.CommonUtil; import org.batfish.datamodel.Ip; import org.batfish.grammar.GrammarSettings; import org.batfish.identifiers.AnalysisId; import org.batfish.identifiers.NetworkId; import org.batfish.identifiers.QuestionId; import org.batfish.identifiers.SnapshotId; import org.batfish.main.Driver.RunMode; public final class Settings extends BaseSettings implements GrammarSettings { public static final String ARG_CHECK_BGP_REACHABILITY = "checkbgpsessionreachability"; public static final String ARG_COORDINATOR_HOST = "coordinatorhost"; public static final String ARG_COORDINATOR_POOL_PORT = "coordinatorpoolport"; public static final String ARG_COORDINATOR_REGISTER = "register"; private static final String ARG_DATAPLANE_ENGINE_NAME = "dataplaneengine"; private static final String ARG_DEBUG_FLAGS = "debugflags"; private static final String ARG_DISABLE_Z3_SIMPLIFICATION = "nosimplify"; private static final String ARG_EXIT_ON_FIRST_ERROR = "ee"; private static final String ARG_FLATTEN = "flatten"; private static final String ARG_FLATTEN_DESTINATION = "flattendst"; private static final String ARG_FLATTEN_ON_THE_FLY = "flattenonthefly"; private static final String ARG_GENERATE_STUBS = "gs"; private static final String ARG_GENERATE_STUBS_INPUT_ROLE = "gsinputrole"; private static final String ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX = "gsidregex"; private static final String ARG_GENERATE_STUBS_REMOTE_AS = "gsremoteas"; private static final String ARG_HELP = "help"; private static final String ARG_HISTOGRAM = "histogram"; private static final String ARG_IGNORE_UNKNOWN = "ignoreunknown"; private static final String ARG_IGNORE_UNSUPPORTED = "ignoreunsupported"; private static final String ARG_JOBS = "jobs"; private static final String ARG_LOG_TEE = "logtee"; private static final String ARG_MAX_PARSER_CONTEXT_LINES = "maxparsercontextlines"; private static final String ARG_MAX_PARSER_CONTEXT_TOKENS = "maxparsercontexttokens"; private static final String ARG_MAX_PARSE_TREE_PRINT_LENGTH = "maxparsetreeprintlength"; private static final String ARG_MAX_RUNTIME_MS = "maxruntime"; private static final String ARG_NO_SHUFFLE = "noshuffle"; public static final String ARG_PARENT_PID = "parentpid"; private static final String ARG_PRINT_PARSE_TREES = "ppt"; private static final String ARG_PRINT_PARSE_TREE_LINE_NUMS = "printparsetreelinenums"; private static final String ARG_PRINT_SYMMETRIC_EDGES = "printsymmetricedges"; public static final String ARG_RUN_MODE = "runmode"; private static final String ARG_SEQUENTIAL = "sequential"; private static final String ARG_SERIALIZE_TO_TEXT = "stext"; private static final String ARG_SERVICE_BIND_HOST = "servicebindhost"; public static final String ARG_SERVICE_HOST = "servicehost"; public static final String ARG_SERVICE_NAME = "servicename"; public static final String ARG_SERVICE_PORT = "serviceport"; private static final String ARG_TRACING_AGENT_HOST = "tracingagenthost"; private static final String ARG_TRACING_AGENT_PORT = "tracingagentport"; public static final String ARG_TRACING_ENABLE = "tracingenable"; private static final String ARG_THROW_ON_LEXER_ERROR = "throwlexer"; private static final String ARG_THROW_ON_PARSER_ERROR = "throwparser"; private static final String ARG_TIMESTAMP = "timestamp"; private static final String ARG_VERSION = "version"; private static final String ARG_Z3_TIMEOUT = "z3timeout"; private static final String ARGNAME_AS = "as"; private static final String ARGNAME_HOSTNAME = "hostname"; private static final String ARGNAME_JAVA_REGEX = "java-regex"; private static final String ARGNAME_LOG_LEVEL = "level-name"; private static final String ARGNAME_NAME = "name"; private static final String ARGNAME_NUMBER = "number"; private static final String ARGNAME_PATH = "path"; private static final String ARGNAME_PORT = "port"; private static final String ARGNAME_ROLE = "role"; private static final String ARGNAME_STRINGS = "string.."; private static final String EXECUTABLE_NAME = "batfish"; private static final String CAN_EXECUTE = "canexecute"; private static final String DIFFERENTIAL_QUESTION = "diffquestion"; public static final String TASK_ID = "taskid"; private static final String DEPRECATED_ARG_DELTA_ENVIRONMENT_NAME = "deltaenv"; private static final String DEPRECATED_ARG_ENVIRONMENT_NAME = "env"; private static final String DEPRECATED_ARG_OUTPUT_ENV = "outputenv"; private static final String DEPRECATED_ARG_DESC = "(ignored, provided for backwards compatibility)"; private TestrigSettings _activeTestrigSettings; private TestrigSettings _baseTestrigSettings; private final TestrigSettings _deltaTestrigSettings; private BatfishLogger _logger; public Settings() { this(new String[] {}); } public Settings(String[] args) { super( CommonUtil.getConfig( BfConsts.PROP_BATFISH_PROPERTIES_PATH, BfConsts.ABSPATH_CONFIG_FILE_NAME_BATFISH, ConfigurationLocator.class)); _baseTestrigSettings = new TestrigSettings(); _deltaTestrigSettings = new TestrigSettings(); initConfigDefaults(); initOptions(); parseCommandLine(args); } /** * Create a copy of some existing settings. * * @param other the {@link Settings to copy} */ public Settings(Settings other) { super(other._config); _baseTestrigSettings = new TestrigSettings(); _deltaTestrigSettings = new TestrigSettings(); _activeTestrigSettings = new TestrigSettings(); _logger = other._logger; initOptions(); } /** * Remove certain setting values * * @param keys a list of keys to clear */ public void clearValues(String... keys) { for (String s : keys) { _config.clearProperty(s); } } public boolean canExecute() { return _config.getBoolean(CAN_EXECUTE); } public boolean debugFlagEnabled(String flag) { return getDebugFlags().contains(flag); } public boolean flattenOnTheFly() { return _config.getBoolean(ARG_FLATTEN_ON_THE_FLY); } public TestrigSettings getActiveTestrigSettings() { return _activeTestrigSettings; } public @Nullable AnalysisId getAnalysisName() { String id = _config.getString(BfConsts.ARG_ANALYSIS_NAME); return id != null ? new AnalysisId(id) : null; } public boolean getAnalyze() { return _config.getBoolean(BfConsts.COMMAND_ANALYZE); } public boolean getAnswer() { return _config.getBoolean(BfConsts.COMMAND_ANSWER); } public int getAvailableThreads() { return Math.min(Runtime.getRuntime().availableProcessors(), getJobs()); } public TestrigSettings getBaseTestrigSettings() { return _baseTestrigSettings; } public NetworkId getContainer() { String id = _config.getString(BfConsts.ARG_CONTAINER); return id != null ? new NetworkId(id) : null; } public String getCoordinatorHost() { return _config.getString(ARG_COORDINATOR_HOST); } public int getCoordinatorPoolPort() { return _config.getInt(ARG_COORDINATOR_POOL_PORT); } public boolean getCoordinatorRegister() { return _config.getBoolean(ARG_COORDINATOR_REGISTER); } public boolean getDataPlane() { return _config.getBoolean(BfConsts.COMMAND_DUMP_DP); } public List<String> getDebugFlags() { return Arrays.asList(_config.getStringArray(ARG_DEBUG_FLAGS)); } public SnapshotId getDeltaTestrig() { String name = _config.getString(BfConsts.ARG_DELTA_TESTRIG); return name != null ? new SnapshotId(name) : null; } public TestrigSettings getDeltaTestrigSettings() { return _deltaTestrigSettings; } public boolean getDiffActive() { return _config.getBoolean(BfConsts.ARG_DIFF_ACTIVE); } public boolean getDifferential() { return _config.getBoolean(BfConsts.ARG_DIFFERENTIAL); } public boolean getDiffQuestion() { return _config.getBoolean(DIFFERENTIAL_QUESTION); } @Override public boolean getDisableUnrecognized() { return _config.getBoolean(BfConsts.ARG_DISABLE_UNRECOGNIZED); } public boolean getEnableCiscoNxParser() { return _config.getBoolean(BfConsts.ARG_ENABLE_CISCO_NX_PARSER); } public boolean getExitOnFirstError() { return _config.getBoolean(ARG_EXIT_ON_FIRST_ERROR); } public boolean getFlatten() { return _config.getBoolean(ARG_FLATTEN); } public Path getFlattenDestination() { return Paths.get(_config.getString(ARG_FLATTEN_DESTINATION)); } public boolean getGenerateStubs() { return _config.getBoolean(ARG_GENERATE_STUBS); } public String getGenerateStubsInputRole() { return _config.getString(ARG_GENERATE_STUBS_INPUT_ROLE); } public String getGenerateStubsInterfaceDescriptionRegex() { return _config.getString(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX); } public int getGenerateStubsRemoteAs() { return _config.getInt(ARG_GENERATE_STUBS_REMOTE_AS); } public boolean getHaltOnConvertError() { return _config.getBoolean(BfConsts.ARG_HALT_ON_CONVERT_ERROR); } public boolean getHaltOnParseError() { return _config.getBoolean(BfConsts.ARG_HALT_ON_PARSE_ERROR); } public boolean getHistogram() { return _config.getBoolean(ARG_HISTOGRAM); } public boolean getInitInfo() { return _config.getBoolean(BfConsts.COMMAND_INIT_INFO); } public int getJobs() { return _config.getInt(ARG_JOBS); } @Nullable public String getLogFile() { if (getTaskId() == null) { return null; } String tr = getTestrig().getId(); if (getDeltaTestrig() != null && !getDifferential()) { tr = getDeltaTestrig().getId(); } return getStorageBase() .resolve(getContainer().getId()) .resolve(BfConsts.RELPATH_SNAPSHOTS_DIR) .resolve(tr) .resolve(BfConsts.RELPATH_OUTPUT) .resolve(getTaskId() + BfConsts.SUFFIX_LOG_FILE) .toString(); } public BatfishLogger getLogger() { return _logger; } public String getLogLevel() { return _config.getString(BfConsts.ARG_LOG_LEVEL); } public boolean getLogTee() { return _config.getBoolean(ARG_LOG_TEE); } public int getParentPid() { return _config.getInt(ARG_PARENT_PID); } @Override public int getMaxParserContextLines() { return _config.getInt(ARG_MAX_PARSER_CONTEXT_LINES); } @Override public int getMaxParserContextTokens() { return _config.getInt(ARG_MAX_PARSER_CONTEXT_TOKENS); } @Override public int getMaxParseTreePrintLength() { return _config.getInt(ARG_MAX_PARSE_TREE_PRINT_LENGTH); } public int getMaxRuntimeMs() { return _config.getInt(ARG_MAX_RUNTIME_MS); } public boolean getPedanticRecord() { return !_config.getBoolean(BfConsts.ARG_PEDANTIC_SUPPRESS); } public boolean getPrettyPrintAnswer() { return _config.getBoolean(BfConsts.ARG_PRETTY_PRINT_ANSWER); } @Override public boolean getPrintParseTree() { return _config.getBoolean(ARG_PRINT_PARSE_TREES); } @Override public boolean getPrintParseTreeLineNums() { return _config.getBoolean(ARG_PRINT_PARSE_TREE_LINE_NUMS); } public boolean getPrintSymmetricEdgePairs() { return _config.getBoolean(ARG_PRINT_SYMMETRIC_EDGES); } public @Nullable QuestionId getQuestionName() { String name = _config.getString(BfConsts.ARG_QUESTION_NAME); return name != null ? new QuestionId(name) : null; } public boolean getRedFlagRecord() { return !_config.getBoolean(BfConsts.ARG_RED_FLAG_SUPPRESS); } public RunMode getRunMode() { return RunMode.valueOf(_config.getString(ARG_RUN_MODE).toUpperCase()); } public boolean getSequential() { return _config.getBoolean(ARG_SEQUENTIAL); } public boolean getSerializeIndependent() { return _config.getBoolean(BfConsts.COMMAND_PARSE_VENDOR_INDEPENDENT); } public boolean getSerializeToText() { return _config.getBoolean(ARG_SERIALIZE_TO_TEXT); } public boolean getSerializeVendor() { return _config.getBoolean(BfConsts.COMMAND_PARSE_VENDOR_SPECIFIC); } public String getServiceBindHost() { return _config.getString(ARG_SERVICE_BIND_HOST); } public String getServiceHost() { return _config.getString(ARG_SERVICE_HOST); } public String getServiceName() { return _config.getString(ARG_SERVICE_NAME); } public int getServicePort() { return _config.getInt(ARG_SERVICE_PORT); } public boolean getShuffleJobs() { return !_config.getBoolean(ARG_NO_SHUFFLE); } public boolean getSimplify() { return !_config.getBoolean(ARG_DISABLE_Z3_SIMPLIFICATION); } public boolean getSslDisable() { return _config.getBoolean(BfConsts.ARG_SSL_DISABLE); } @Nullable public Path getSslKeystoreFile() { return nullablePath(_config.getString(BfConsts.ARG_SSL_KEYSTORE_FILE)); } public String getSslKeystorePassword() { return _config.getString(BfConsts.ARG_SSL_KEYSTORE_PASSWORD); } public boolean getSslTrustAllCerts() { return _config.getBoolean(BfConsts.ARG_SSL_TRUST_ALL_CERTS); } public Path getSslTruststoreFile() { return _config.get(Path.class, BfConsts.ARG_SSL_TRUSTSTORE_FILE); } public String getSslTruststorePassword() { return _config.getString(BfConsts.ARG_SSL_TRUSTSTORE_PASSWORD); } public Path getStorageBase() { return Paths.get(_config.getString(BfConsts.ARG_STORAGE_BASE)); } public boolean getSynthesizeJsonTopology() { return _config.getBoolean(BfConsts.ARG_SYNTHESIZE_JSON_TOPOLOGY); } @Nullable public String getTaskId() { return _config.getString(TASK_ID); } public String getTaskPlugin() { return _config.getString(BfConsts.ARG_TASK_PLUGIN); } public SnapshotId getTestrig() { String name = _config.getString(BfConsts.ARG_TESTRIG); return name != null ? new SnapshotId(name) : null; } @Override public boolean getThrowOnLexerError() { return _config.getBoolean(ARG_THROW_ON_LEXER_ERROR); } @Override public boolean getThrowOnParserError() { return _config.getBoolean(ARG_THROW_ON_PARSER_ERROR); } public boolean getTimestamp() { return _config.getBoolean(ARG_TIMESTAMP); } public String getTracingAgentHost() { return _config.getString(ARG_TRACING_AGENT_HOST); } public Integer getTracingAgentPort() { return _config.getInt(ARG_TRACING_AGENT_PORT); } public boolean getTracingEnable() { return _config.getBoolean(ARG_TRACING_ENABLE); } public boolean getUnimplementedRecord() { return !_config.getBoolean(BfConsts.ARG_UNIMPLEMENTED_SUPPRESS); } public boolean getValidateSnapshot() { return _config.getBoolean(BfConsts.COMMAND_VALIDATE_SNAPSHOT); } public boolean getVerboseParse() { return _config.getBoolean(BfConsts.ARG_VERBOSE_PARSE); } public List<String> ignoreFilesWithStrings() { List<String> l = _config.getList(String.class, BfConsts.ARG_IGNORE_FILES_WITH_STRINGS); return l == null ? ImmutableList.of() : l; } public boolean ignoreUnknown() { return _config.getBoolean(ARG_IGNORE_UNKNOWN); } public boolean ignoreUnsupported() { return _config.getBoolean(ARG_IGNORE_UNSUPPORTED); } public int getZ3timeout() { return _config.getInt(ARG_Z3_TIMEOUT); } public String getDataPlaneEngineName() { return _config.getString(ARG_DATAPLANE_ENGINE_NAME); } private void initConfigDefaults() { setDefaultProperty(BfConsts.ARG_ANALYSIS_NAME, null); setDefaultProperty(BfConsts.ARG_BDP_DETAIL, false); setDefaultProperty(BfConsts.ARG_BDP_MAX_OSCILLATION_RECOVERY_ATTEMPTS, 0); setDefaultProperty(BfConsts.ARG_BDP_MAX_RECORDED_ITERATIONS, 5); setDefaultProperty(BfConsts.ARG_BDP_PRINT_ALL_ITERATIONS, false); setDefaultProperty(BfConsts.ARG_BDP_PRINT_OSCILLATING_ITERATIONS, false); setDefaultProperty(BfConsts.ARG_BDP_RECORD_ALL_ITERATIONS, false); setDefaultProperty(CAN_EXECUTE, true); setDefaultProperty(BfConsts.ARG_CONTAINER, null); setDefaultProperty(ARG_COORDINATOR_REGISTER, false); setDefaultProperty(ARG_COORDINATOR_HOST, "localhost"); setDefaultProperty(ARG_COORDINATOR_POOL_PORT, CoordConsts.SVC_CFG_POOL_PORT); setDefaultProperty(ARG_DEBUG_FLAGS, ImmutableList.of()); setDefaultProperty(BfConsts.ARG_DIFF_ACTIVE, false); setDefaultProperty(DIFFERENTIAL_QUESTION, false); setDefaultProperty(ARG_DEBUG_FLAGS, ImmutableList.of()); setDefaultProperty(BfConsts.ARG_DIFFERENTIAL, false); setDefaultProperty(BfConsts.ARG_DISABLE_UNRECOGNIZED, false); setDefaultProperty( BfConsts.ARG_ENABLE_CISCO_NX_PARSER, true); // TODO: enable CiscoNxParser by default and remove this flag. setDefaultProperty(ARG_DISABLE_Z3_SIMPLIFICATION, false); setDefaultProperty(ARG_EXIT_ON_FIRST_ERROR, false); setDefaultProperty(ARG_FLATTEN, false); setDefaultProperty(ARG_FLATTEN_DESTINATION, null); setDefaultProperty(ARG_FLATTEN_ON_THE_FLY, true); setDefaultProperty(ARG_GENERATE_STUBS, false); setDefaultProperty(ARG_GENERATE_STUBS_INPUT_ROLE, null); setDefaultProperty(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX, null); setDefaultProperty(ARG_GENERATE_STUBS_REMOTE_AS, null); setDefaultProperty(BfConsts.ARG_HALT_ON_CONVERT_ERROR, false); setDefaultProperty(BfConsts.ARG_HALT_ON_PARSE_ERROR, false); setDefaultProperty(ARG_HELP, false); setDefaultProperty(ARG_HISTOGRAM, false); setDefaultProperty(BfConsts.ARG_IGNORE_FILES_WITH_STRINGS, ImmutableList.of()); setDefaultProperty(ARG_IGNORE_UNSUPPORTED, true); setDefaultProperty(ARG_IGNORE_UNKNOWN, true); setDefaultProperty(ARG_JOBS, Integer.MAX_VALUE); setDefaultProperty(ARG_LOG_TEE, false); setDefaultProperty(BfConsts.ARG_LOG_LEVEL, "debug"); setDefaultProperty(ARG_MAX_PARSER_CONTEXT_LINES, 10); setDefaultProperty(ARG_MAX_PARSER_CONTEXT_TOKENS, 10); setDefaultProperty(ARG_MAX_PARSE_TREE_PRINT_LENGTH, 0); setDefaultProperty(ARG_MAX_RUNTIME_MS, 0); setDefaultProperty(ARG_CHECK_BGP_REACHABILITY, true); setDefaultProperty(ARG_NO_SHUFFLE, false); setDefaultProperty(BfConsts.ARG_PEDANTIC_SUPPRESS, false); setDefaultProperty(BfConsts.ARG_PRETTY_PRINT_ANSWER, false); setDefaultProperty(ARG_PARENT_PID, -1); setDefaultProperty(ARG_PRINT_PARSE_TREES, false); setDefaultProperty(ARG_PRINT_PARSE_TREE_LINE_NUMS, false); setDefaultProperty(ARG_PRINT_SYMMETRIC_EDGES, false); setDefaultProperty(BfConsts.ARG_QUESTION_NAME, null); setDefaultProperty(BfConsts.ARG_RED_FLAG_SUPPRESS, false); setDefaultProperty(ARG_RUN_MODE, RunMode.WORKER.toString()); setDefaultProperty(ARG_SEQUENTIAL, false); setDefaultProperty(ARG_SERIALIZE_TO_TEXT, false); setDefaultProperty(ARG_SERVICE_BIND_HOST, Ip.ZERO.toString()); setDefaultProperty(ARG_SERVICE_HOST, "localhost"); setDefaultProperty(ARG_SERVICE_NAME, "worker-service"); setDefaultProperty(ARG_SERVICE_PORT, BfConsts.SVC_PORT); setDefaultProperty(BfConsts.ARG_SSL_DISABLE, CoordConsts.SVC_CFG_POOL_SSL_DISABLE); setDefaultProperty(BfConsts.ARG_SSL_KEYSTORE_FILE, null); setDefaultProperty(BfConsts.ARG_SSL_KEYSTORE_PASSWORD, null); setDefaultProperty(BfConsts.ARG_SSL_TRUST_ALL_CERTS, false); setDefaultProperty(BfConsts.ARG_SSL_TRUSTSTORE_FILE, null); setDefaultProperty(BfConsts.ARG_SSL_TRUSTSTORE_PASSWORD, null); setDefaultProperty(BfConsts.ARG_STORAGE_BASE, null); setDefaultProperty(BfConsts.ARG_SYNTHESIZE_JSON_TOPOLOGY, false); setDefaultProperty(BfConsts.ARG_TASK_PLUGIN, null); setDefaultProperty(ARG_THROW_ON_LEXER_ERROR, true); setDefaultProperty(ARG_THROW_ON_PARSER_ERROR, true); setDefaultProperty(ARG_TIMESTAMP, false); setDefaultProperty(ARG_TRACING_AGENT_HOST, "localhost"); setDefaultProperty(ARG_TRACING_AGENT_PORT, 5775); setDefaultProperty(ARG_TRACING_ENABLE, false); setDefaultProperty(BfConsts.ARG_UNIMPLEMENTED_SUPPRESS, false); setDefaultProperty(BfConsts.ARG_VERBOSE_PARSE, false); setDefaultProperty(ARG_VERSION, false); setDefaultProperty(BfConsts.COMMAND_ANALYZE, false); setDefaultProperty(BfConsts.COMMAND_ANSWER, false); setDefaultProperty(BfConsts.COMMAND_DUMP_DP, false); setDefaultProperty(BfConsts.COMMAND_INIT_INFO, false); setDefaultProperty(BfConsts.COMMAND_PARSE_VENDOR_INDEPENDENT, false); setDefaultProperty(BfConsts.COMMAND_PARSE_VENDOR_SPECIFIC, false); setDefaultProperty(BfConsts.COMMAND_VALIDATE_SNAPSHOT, false); setDefaultProperty(ARG_Z3_TIMEOUT, 0); setDefaultProperty(ARG_DATAPLANE_ENGINE_NAME, "ibdp"); } private void initOptions() { addOption(BfConsts.ARG_ANALYSIS_NAME, "name of analysis", ARGNAME_NAME); addBooleanOption( BfConsts.ARG_BDP_DETAIL, "Set to true to print/record detailed protocol-specific information about routes in each" + "iteration rather than only protocol-independent information."); addOption( BfConsts.ARG_BDP_MAX_OSCILLATION_RECOVERY_ATTEMPTS, "Max number of recovery attempts when oscillation occurs during data plane computations", ARGNAME_NUMBER); addOption( BfConsts.ARG_BDP_MAX_RECORDED_ITERATIONS, "Max number of iterations to record when debugging BDP. To avoid extra fixed-point" + "computation when oscillations occur, set this at least as high as the length of the" + "cycle.", ARGNAME_NUMBER); addBooleanOption( BfConsts.ARG_BDP_PRINT_ALL_ITERATIONS, "Set to true to print all iterations when oscillation occurs. Make sure to either set max" + "recorded iterations to minimum necessary value, or simply record all iterations"); addBooleanOption( BfConsts.ARG_BDP_PRINT_OSCILLATING_ITERATIONS, "Set to true to print only oscillating iterations when oscillation occurs. Make sure to" + "set max recorded iterations to minimum necessary value."); addBooleanOption( BfConsts.ARG_BDP_RECORD_ALL_ITERATIONS, "Set to true to record all iterations, including during oscillation. Ignores max recorded " + "iterations value."); addBooleanOption( ARG_CHECK_BGP_REACHABILITY, "whether to check BGP session reachability during data plane computation"); addOption(BfConsts.ARG_CONTAINER, "name of container", ARGNAME_NAME); addOption( ARG_COORDINATOR_HOST, "hostname of coordinator for registration when running as service", ARGNAME_HOSTNAME); addOption(ARG_COORDINATOR_POOL_PORT, "coordinator pool manager listening port", ARGNAME_PORT); addBooleanOption(ARG_COORDINATOR_REGISTER, "register service with coordinator on startup"); addListOption(ARG_DEBUG_FLAGS, "a list of flags to enable debugging code", "debug flags"); addOption(BfConsts.ARG_DELTA_TESTRIG, "name of delta testrig", ARGNAME_NAME); addBooleanOption( BfConsts.ARG_DIFF_ACTIVE, "make differential snapshot the active one for questions about a single snapshot"); addBooleanOption( BfConsts.ARG_DIFFERENTIAL, "force treatment of question as differential (to be used when not answering question)"); addBooleanOption( BfConsts.ARG_DISABLE_UNRECOGNIZED, "disable parser recognition of unrecognized stanzas"); addBooleanOption(ARG_DISABLE_Z3_SIMPLIFICATION, "disable z3 simplification"); addBooleanOption( BfConsts.ARG_ENABLE_CISCO_NX_PARSER, "use the rewritten BGP parser for Cisco NX-OS devices"); addBooleanOption( ARG_EXIT_ON_FIRST_ERROR, "exit on first parse error (otherwise will exit on last parse error)"); addBooleanOption(ARG_FLATTEN, "flatten hierarchical juniper configuration files"); addOption( ARG_FLATTEN_DESTINATION, "output path to test rig in which flat juniper (and all other) configurations will be " + "placed", ARGNAME_PATH); addBooleanOption( ARG_FLATTEN_ON_THE_FLY, "flatten hierarchical juniper configuration files on-the-fly (line number references will " + "be spurious)"); addBooleanOption( BfConsts.COMMAND_INIT_INFO, "include parse/convert initialization info in answer"); addBooleanOption(ARG_GENERATE_STUBS, "generate stubs"); addOption( ARG_GENERATE_STUBS_INPUT_ROLE, "input role for which to generate stubs", ARGNAME_ROLE); addOption( ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX, "java regex to extract hostname of generated stub from description of adjacent interface", ARGNAME_JAVA_REGEX); addOption( ARG_GENERATE_STUBS_REMOTE_AS, "autonomous system number of stubs to be generated", ARGNAME_AS); addBooleanOption( BfConsts.ARG_HALT_ON_CONVERT_ERROR, "Halt on conversion error instead of proceeding with successfully converted configs"); addBooleanOption( BfConsts.ARG_HALT_ON_PARSE_ERROR, "Halt on parse error instead of proceeding with successfully parsed configs"); addBooleanOption(ARG_HELP, "print this message"); addOption( BfConsts.ARG_IGNORE_FILES_WITH_STRINGS, "ignore configuration files containing these strings", ARGNAME_STRINGS); addBooleanOption( ARG_IGNORE_UNKNOWN, "ignore configuration files with unknown format instead of crashing"); addBooleanOption( ARG_IGNORE_UNSUPPORTED, "ignore configuration files with unsupported format instead of crashing"); addOption(ARG_JOBS, "number of threads used by parallel jobs executor", ARGNAME_NUMBER); addOption(BfConsts.ARG_LOG_LEVEL, "log level", ARGNAME_LOG_LEVEL); addBooleanOption(ARG_HISTOGRAM, "build histogram of unimplemented features"); addBooleanOption(ARG_LOG_TEE, "print output to both logfile and standard out"); addOption( ARG_MAX_PARSER_CONTEXT_LINES, "max number of surrounding lines to print on parser error", ARGNAME_NUMBER); addOption( ARG_MAX_PARSER_CONTEXT_TOKENS, "max number of context tokens to print on parser error", ARGNAME_NUMBER); addOption( ARG_MAX_PARSE_TREE_PRINT_LENGTH, "max number of characters to print for parsetree pretty print " + "(<= 0 is treated as no limit)", ARGNAME_NUMBER); addOption(ARG_MAX_RUNTIME_MS, "maximum time (in ms) to allow a task to run", ARGNAME_NUMBER); addBooleanOption(ARG_NO_SHUFFLE, "do not shuffle parallel jobs"); addOption(ARG_PARENT_PID, "name of parent PID", ARGNAME_NUMBER); addBooleanOption(BfConsts.ARG_PEDANTIC_SUPPRESS, "suppresses pedantic warnings"); addBooleanOption(BfConsts.ARG_PRETTY_PRINT_ANSWER, "pretty print answer"); addBooleanOption(ARG_PRINT_PARSE_TREES, "print parse trees"); addBooleanOption( ARG_PRINT_PARSE_TREE_LINE_NUMS, "print line numbers when printing parse trees"); addBooleanOption( ARG_PRINT_SYMMETRIC_EDGES, "print topology with symmetric edges adjacent in listing"); addOption(BfConsts.ARG_QUESTION_NAME, "name of question", ARGNAME_NAME); addBooleanOption(BfConsts.ARG_RED_FLAG_SUPPRESS, "suppresses red-flag warnings"); addOption( ARG_RUN_MODE, "mode to run in", Arrays.stream(RunMode.values()).map(Object::toString).collect(Collectors.joining("|"))); addBooleanOption(ARG_SEQUENTIAL, "force sequential operation"); addBooleanOption(ARG_SERIALIZE_TO_TEXT, "serialize to text"); addOption( ARG_SERVICE_BIND_HOST, "local hostname used bind service (default is 0.0.0.0 which listens on all interfaces)", ARGNAME_HOSTNAME); addOption(ARG_SERVICE_HOST, "local hostname to report to coordinator", ARGNAME_HOSTNAME); addOption(ARG_SERVICE_NAME, "service name", "service_name"); addOption(ARG_SERVICE_PORT, "port for batfish service", ARGNAME_PORT); addBooleanOption( BfConsts.ARG_SSL_DISABLE, "whether to disable SSL during communication with coordinator"); addBooleanOption( BfConsts.ARG_SSL_TRUST_ALL_CERTS, "whether to trust all SSL certificates during communication with coordinator"); addOption(BfConsts.ARG_STORAGE_BASE, "path to the storage base", ARGNAME_PATH); addBooleanOption( BfConsts.ARG_SYNTHESIZE_JSON_TOPOLOGY, "synthesize json topology from interface ip subnet information"); addBooleanOption( BfConsts.ARG_SYNTHESIZE_TOPOLOGY, "synthesize topology from interface ip subnet information"); addOption(BfConsts.ARG_TASK_PLUGIN, "fully-qualified name of task plugin class", ARGNAME_NAME); addOption(BfConsts.ARG_TESTRIG, "name of testrig", ARGNAME_NAME); addBooleanOption(ARG_THROW_ON_LEXER_ERROR, "throw exception immediately on lexer error"); addBooleanOption(ARG_THROW_ON_PARSER_ERROR, "throw exception immediately on parser error"); addBooleanOption(ARG_TIMESTAMP, "print timestamps in log messages"); addOption(ARG_TRACING_AGENT_HOST, "jaeger agent host", "jaeger_agent_host"); addOption(ARG_TRACING_AGENT_PORT, "jaeger agent port", "jaeger_agent_port"); addBooleanOption(ARG_TRACING_ENABLE, "enable tracing"); addBooleanOption( BfConsts.ARG_UNIMPLEMENTED_SUPPRESS, "suppresses warnings about unimplemented configuration directives"); addBooleanOption( BfConsts.ARG_VERBOSE_PARSE, "(developer option) include parse/convert data in init-testrig answer"); addBooleanOption(BfConsts.COMMAND_ANALYZE, "run provided analysis"); addBooleanOption(BfConsts.COMMAND_ANSWER, "answer provided question"); addBooleanOption(BfConsts.COMMAND_DUMP_DP, "compute and serialize data plane"); addBooleanOption( BfConsts.COMMAND_PARSE_VENDOR_INDEPENDENT, "serialize vendor-independent configs"); addBooleanOption(BfConsts.COMMAND_PARSE_VENDOR_SPECIFIC, "serialize vendor configs"); addBooleanOption( BfConsts.COMMAND_VALIDATE_SNAPSHOT, "validate a snapshot that has been initialized"); addBooleanOption(ARG_VERSION, "print the version number of the code and exit"); addOption(ARG_Z3_TIMEOUT, "set a timeout (in milliseconds) for Z3 queries", "z3timeout"); addOption( ARG_DATAPLANE_ENGINE_NAME, "name of the dataplane generation engine to use.", "dataplane engine name"); // deprecated and ignored addOption(DEPRECATED_ARG_DELTA_ENVIRONMENT_NAME, DEPRECATED_ARG_DESC, "name"); addOption(DEPRECATED_ARG_ENVIRONMENT_NAME, DEPRECATED_ARG_DESC, "name"); addOption(DEPRECATED_ARG_OUTPUT_ENV, DEPRECATED_ARG_DESC, "name"); } public void parseCommandLine(String[] args) { initCommandLine(args); _config.setProperty(CAN_EXECUTE, true); // SPECIAL OPTIONS getStringOptionValue(BfConsts.ARG_LOG_LEVEL); if (getBooleanOptionValue(ARG_HELP)) { _config.setProperty(CAN_EXECUTE, false); printHelp(EXECUTABLE_NAME); return; } if (getBooleanOptionValue(ARG_VERSION)) { _config.setProperty(CAN_EXECUTE, false); System.out.print(Version.getCompleteVersionString()); return; } // REGULAR OPTIONS getStringOptionValue(BfConsts.ARG_ANALYSIS_NAME); getBooleanOptionValue(BfConsts.COMMAND_ANALYZE); getBooleanOptionValue(BfConsts.COMMAND_ANSWER); getBooleanOptionValue(BfConsts.ARG_BDP_RECORD_ALL_ITERATIONS); getBooleanOptionValue(BfConsts.ARG_BDP_DETAIL); getIntOptionValue(BfConsts.ARG_BDP_MAX_OSCILLATION_RECOVERY_ATTEMPTS); getIntOptionValue(BfConsts.ARG_BDP_MAX_RECORDED_ITERATIONS); getBooleanOptionValue(BfConsts.ARG_BDP_PRINT_ALL_ITERATIONS); getBooleanOptionValue(BfConsts.ARG_BDP_PRINT_OSCILLATING_ITERATIONS); getBooleanOptionValue(ARG_CHECK_BGP_REACHABILITY); getStringOptionValue(BfConsts.ARG_CONTAINER); getStringOptionValue(ARG_COORDINATOR_HOST); getIntOptionValue(ARG_COORDINATOR_POOL_PORT); getBooleanOptionValue(ARG_COORDINATOR_REGISTER); getBooleanOptionValue(BfConsts.COMMAND_DUMP_DP); getStringListOptionValue(ARG_DEBUG_FLAGS); getStringOptionValue(BfConsts.ARG_DELTA_TESTRIG); getBooleanOptionValue(BfConsts.ARG_DIFF_ACTIVE); getBooleanOptionValue(BfConsts.ARG_DIFFERENTIAL); getBooleanOptionValue(BfConsts.ARG_DISABLE_UNRECOGNIZED); getBooleanOptionValue(BfConsts.ARG_ENABLE_CISCO_NX_PARSER); getBooleanOptionValue(ARG_EXIT_ON_FIRST_ERROR); getBooleanOptionValue(ARG_FLATTEN); getPathOptionValue(ARG_FLATTEN_DESTINATION); getBooleanOptionValue(ARG_FLATTEN_ON_THE_FLY); getBooleanOptionValue(ARG_GENERATE_STUBS); getStringOptionValue(ARG_GENERATE_STUBS_INPUT_ROLE); getStringOptionValue(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX); getIntegerOptionValue(ARG_GENERATE_STUBS_REMOTE_AS); getBooleanOptionValue(BfConsts.ARG_HALT_ON_CONVERT_ERROR); getBooleanOptionValue(BfConsts.ARG_HALT_ON_PARSE_ERROR); getBooleanOptionValue(ARG_HISTOGRAM); getStringListOptionValue(BfConsts.ARG_IGNORE_FILES_WITH_STRINGS); getBooleanOptionValue(ARG_IGNORE_UNKNOWN); getBooleanOptionValue(ARG_IGNORE_UNSUPPORTED); getBooleanOptionValue(BfConsts.COMMAND_INIT_INFO); getIntOptionValue(ARG_JOBS); getBooleanOptionValue(ARG_LOG_TEE); getIntOptionValue(ARG_MAX_PARSER_CONTEXT_LINES); getIntOptionValue(ARG_MAX_PARSER_CONTEXT_TOKENS); getIntOptionValue(ARG_MAX_PARSE_TREE_PRINT_LENGTH); getIntOptionValue(ARG_MAX_RUNTIME_MS); getIntOptionValue(ARG_PARENT_PID); getBooleanOptionValue(BfConsts.ARG_PEDANTIC_SUPPRESS); getBooleanOptionValue(BfConsts.ARG_PRETTY_PRINT_ANSWER); getBooleanOptionValue(ARG_PRINT_PARSE_TREES); getBooleanOptionValue(ARG_PRINT_PARSE_TREE_LINE_NUMS); getBooleanOptionValue(ARG_PRINT_SYMMETRIC_EDGES); getStringOptionValue(BfConsts.ARG_QUESTION_NAME); getBooleanOptionValue(BfConsts.ARG_RED_FLAG_SUPPRESS); getStringOptionValue(ARG_RUN_MODE); getBooleanOptionValue(ARG_SEQUENTIAL); getBooleanOptionValue(BfConsts.COMMAND_PARSE_VENDOR_INDEPENDENT); getBooleanOptionValue(ARG_SERIALIZE_TO_TEXT); getBooleanOptionValue(BfConsts.COMMAND_PARSE_VENDOR_SPECIFIC); getStringOptionValue(ARG_SERVICE_BIND_HOST); getStringOptionValue(ARG_SERVICE_HOST); getStringOptionValue(ARG_SERVICE_NAME); getIntOptionValue(ARG_SERVICE_PORT); getBooleanOptionValue(ARG_NO_SHUFFLE); getBooleanOptionValue(ARG_DISABLE_Z3_SIMPLIFICATION); getBooleanOptionValue(BfConsts.ARG_SSL_DISABLE); getPathOptionValue(BfConsts.ARG_SSL_KEYSTORE_FILE); getStringOptionValue(BfConsts.ARG_SSL_KEYSTORE_PASSWORD); getBooleanOptionValue(BfConsts.ARG_SSL_TRUST_ALL_CERTS); getPathOptionValue(BfConsts.ARG_SSL_TRUSTSTORE_FILE); getStringOptionValue(BfConsts.ARG_SSL_TRUSTSTORE_PASSWORD); getPathOptionValue(BfConsts.ARG_STORAGE_BASE); getBooleanOptionValue(BfConsts.ARG_SYNTHESIZE_JSON_TOPOLOGY); getStringOptionValue(BfConsts.ARG_TASK_PLUGIN); getStringOptionValue(BfConsts.ARG_TESTRIG); getBooleanOptionValue(ARG_THROW_ON_LEXER_ERROR); getBooleanOptionValue(ARG_THROW_ON_PARSER_ERROR); getBooleanOptionValue(ARG_TIMESTAMP); getStringOptionValue(ARG_TRACING_AGENT_HOST); getIntegerOptionValue(ARG_TRACING_AGENT_PORT); getBooleanOptionValue(ARG_TRACING_ENABLE); getBooleanOptionValue(BfConsts.ARG_UNIMPLEMENTED_SUPPRESS); getBooleanOptionValue(BfConsts.COMMAND_VALIDATE_SNAPSHOT); getBooleanOptionValue(BfConsts.ARG_VERBOSE_PARSE); getIntegerOptionValue(ARG_Z3_TIMEOUT); getStringOptionValue(ARG_DATAPLANE_ENGINE_NAME); } public void setActiveTestrigSettings(TestrigSettings activeTestrigSettings) { _activeTestrigSettings = activeTestrigSettings; } public void setCanExecute(boolean canExecute) { _config.setProperty(CAN_EXECUTE, canExecute); } public void setContainer(String container) { _config.setProperty(BfConsts.ARG_CONTAINER, container); } public void setDebugFlags(List<String> debugFlags) { _config.setProperty(ARG_DEBUG_FLAGS, debugFlags); } public void setDeltaTestrig(SnapshotId testrig) { _config.setProperty(BfConsts.ARG_DELTA_TESTRIG, testrig != null ? testrig.getId() : null); } public void setDiffActive(boolean diffActive) { _config.setProperty(BfConsts.ARG_DIFF_ACTIVE, diffActive); } public void setDiffQuestion(boolean diffQuestion) { _config.setProperty(DIFFERENTIAL_QUESTION, diffQuestion); } @Override public void setDisableUnrecognized(boolean b) { _config.setProperty(BfConsts.ARG_DISABLE_UNRECOGNIZED, b); } public void setEnableCiscoNxParser(boolean b) { _config.setProperty(BfConsts.ARG_ENABLE_CISCO_NX_PARSER, b); } public void setHaltOnConvertError(boolean haltOnConvertError) { _config.setProperty(BfConsts.ARG_HALT_ON_CONVERT_ERROR, haltOnConvertError); } public void setHaltOnParseError(boolean haltOnParseError) { _config.setProperty(BfConsts.ARG_HALT_ON_PARSE_ERROR, haltOnParseError); } public void setInitInfo(boolean initInfo) { _config.setProperty(BfConsts.COMMAND_INIT_INFO, initInfo); } public void setLogger(BatfishLogger logger) { _logger = logger; } public void setMaxParserContextLines(int maxParserContextLines) { _config.setProperty(ARG_MAX_PARSER_CONTEXT_LINES, maxParserContextLines); } public void setMaxParserContextTokens(int maxParserContextTokens) { _config.setProperty(ARG_MAX_PARSER_CONTEXT_TOKENS, maxParserContextTokens); } public void setMaxParseTreePrintLength(int maxParseTreePrintLength) { _config.setProperty(ARG_MAX_PARSE_TREE_PRINT_LENGTH, maxParseTreePrintLength); } public void setMaxRuntimeMs(int runtimeMs) { _config.setProperty(ARG_MAX_RUNTIME_MS, runtimeMs); } @Override public void setPrintParseTree(boolean printParseTree) { _config.setProperty(ARG_PRINT_PARSE_TREES, printParseTree); } @Override public void setPrintParseTreeLineNums(boolean printParseTreeLineNums) { _config.setProperty(ARG_PRINT_PARSE_TREE_LINE_NUMS, printParseTreeLineNums); } public void setRunMode(RunMode runMode) { _config.setProperty(ARG_RUN_MODE, runMode.toString()); } public void setSequential(boolean sequential) { _config.setProperty(ARG_SEQUENTIAL, sequential); } public void setSslDisable(boolean sslDisable) { _config.setProperty(BfConsts.ARG_SSL_DISABLE, sslDisable); } public void setSslKeystoreFile(Path sslKeystoreFile) { _config.setProperty(BfConsts.ARG_SSL_KEYSTORE_FILE, sslKeystoreFile.toString()); } public void setSslKeystorePassword(String sslKeystorePassword) { _config.setProperty(BfConsts.ARG_SSL_KEYSTORE_PASSWORD, sslKeystorePassword); } public void setSslTrustAllCerts(boolean sslTrustAllCerts) { _config.setProperty(BfConsts.ARG_SSL_TRUST_ALL_CERTS, sslTrustAllCerts); } public void setSslTruststoreFile(Path sslTruststoreFile) { _config.setProperty(BfConsts.ARG_SSL_TRUSTSTORE_FILE, sslTruststoreFile.toString()); } public void setSslTruststorePassword(String sslTruststorePassword) { _config.setProperty(BfConsts.ARG_SSL_TRUSTSTORE_PASSWORD, sslTruststorePassword); } public void setStorageBase(Path storageBase) { _config.setProperty(BfConsts.ARG_STORAGE_BASE, storageBase.toString()); } public void setTaskId(String taskId) { _config.setProperty(TASK_ID, taskId); } public void setTestrig(String testrig) { _config.setProperty(BfConsts.ARG_TESTRIG, testrig); } @Override public void setThrowOnLexerError(boolean throwOnLexerError) { _config.setProperty(ARG_THROW_ON_LEXER_ERROR, throwOnLexerError); } @Override public void setThrowOnParserError(boolean throwOnParserError) { _config.setProperty(ARG_THROW_ON_PARSER_ERROR, throwOnParserError); } public void setValidateSnapshot(boolean validate) { _config.setProperty(BfConsts.COMMAND_VALIDATE_SNAPSHOT, validate); } public void setVerboseParse(boolean verboseParse) { _config.setProperty(BfConsts.ARG_VERBOSE_PARSE, verboseParse); } public void setZ3Timeout(int z3Timeout) { _config.setProperty(ARG_Z3_TIMEOUT, z3Timeout); } public void setDataplaneEngineName(String name) { _config.setProperty(ARG_DATAPLANE_ENGINE_NAME, name); } public void setQuestionName(QuestionId questionName) { _config.setProperty( BfConsts.ARG_QUESTION_NAME, questionName != null ? questionName.getId() : null); } }
package com.tang.intellij.lua.annotator; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.psi.PsiElement; import com.tang.intellij.lua.doc.psi.*; import com.tang.intellij.lua.highlighting.LuaHighlightingData; import com.tang.intellij.lua.psi.*; import org.jetbrains.annotations.NotNull; public class LuaAnnotator extends LuaVisitor implements Annotator { private AnnotationHolder myHolder; private LuaElementVisitor luaVisitor = new LuaElementVisitor(); private LuaDocElementVisitor docVisitor = new LuaDocElementVisitor(); @Override public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) { myHolder = annotationHolder; if (psiElement instanceof LuaDocPsiElement) { psiElement.accept(docVisitor); } else if (psiElement instanceof LuaPsiElement) { psiElement.accept(luaVisitor); } myHolder = null; } class LuaElementVisitor extends LuaVisitor { @Override public void visitLocalFuncDef(@NotNull LuaLocalFuncDef o) { LuaNameDef name = o.getNameDef(); if (name != null) { Annotation annotation = myHolder.createInfoAnnotation(name, null); annotation.setTextAttributes(DefaultLanguageHighlighterColors.INSTANCE_FIELD); } } @Override public void visitGlobalFuncDef(@NotNull LuaGlobalFuncDef o) { PsiElement name = o.getNameDef(); if (name != null) { Annotation annotation = myHolder.createInfoAnnotation(name, null); annotation.setTextAttributes(LuaHighlightingData.FIELD); } } @Override public void visitClassMethodName(@NotNull LuaClassMethodName o) { Annotation annotation = myHolder.createInfoAnnotation(o, null); annotation.setTextAttributes(DefaultLanguageHighlighterColors.INSTANCE_METHOD); } } class LuaDocElementVisitor extends LuaDocVisitor { @Override public void visitClassName(@NotNull LuaDocClassName o) { Annotation annotation = myHolder.createInfoAnnotation(o, null); annotation.setTextAttributes(DefaultLanguageHighlighterColors.CLASS_NAME); } @Override public void visitClassNameRef(@NotNull LuaDocClassNameRef o) { Annotation annotation = myHolder.createInfoAnnotation(o, null); annotation.setTextAttributes(DefaultLanguageHighlighterColors.CLASS_REFERENCE); } @Override public void visitParamNameRef(@NotNull LuaDocParamNameRef o) { Annotation annotation = myHolder.createInfoAnnotation(o, null); annotation.setTextAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT_TAG_VALUE); } } }
package mpicbg.imglib.type.numeric.integer; import mpicbg.imglib.container.DirectAccessContainer; import mpicbg.imglib.container.DirectAccessContainerFactory; import mpicbg.imglib.container.basictypecontainer.BitAccess; import mpicbg.imglib.container.basictypecontainer.array.BitArray; import mpicbg.imglib.cursor.Cursor; import mpicbg.imglib.type.numeric.integer.IntegerTypeImpl; public class Unsigned12BitType extends IntegerTypeImpl<Unsigned12BitType> { // the DirectAccessContainer final DirectAccessContainer<Unsigned12BitType, ? extends BitAccess> storage; // the adresses of the bits that we store int j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12; // the (sub)DirectAccessContainer that holds the information BitAccess b; // this is the constructor if you want it to read from an array public Unsigned12BitType( DirectAccessContainer<Unsigned12BitType, ? extends BitAccess> bitStorage ) { storage = bitStorage; updateIndex( 0 ); } // this is the constructor if you want it to be a variable public Unsigned12BitType( final short value ) { storage = null; updateIndex( 0 ); b = new BitArray( 12 ); set( value ); } // this is the constructor if you want it to be a variable public Unsigned12BitType() { this( (short)0 ); } @Override public DirectAccessContainer<Unsigned12BitType, ? extends BitAccess> createSuitableDirectAccessContainer( final DirectAccessContainerFactory storageFactory, final int dim[] ) { // create the container final DirectAccessContainer<Unsigned12BitType, ? extends BitAccess> container = storageFactory.createBitInstance( dim, 12 ); // create a Type that is linked to the container final Unsigned12BitType linkedType = new Unsigned12BitType( container ); // pass it to the DirectAccessContainer container.setLinkedType( linkedType ); return container; } @Override public void updateContainer( final Cursor<?> c ) { b = storage.update( c ); } @Override public Unsigned12BitType duplicateTypeOnSameDirectAccessContainer() { return new Unsigned12BitType( storage ); } public short get() { short value = 0; if ( b.getValue( j1 ) ) ++value; if ( b.getValue( j2 ) ) value += 2; if ( b.getValue( j3 ) ) value += 4; if ( b.getValue( j4 ) ) value += 8; if ( b.getValue( j5 ) ) value += 16; if ( b.getValue( j6 ) ) value += 32; if ( b.getValue( j7 ) ) value += 64; if ( b.getValue( j8 ) ) value += 128; if ( b.getValue( j9 ) ) value += 256; if ( b.getValue( j10 ) ) value += 512; if ( b.getValue( j11 ) ) value += 1024; if ( b.getValue( j12 ) ) value += 2048; return value; } public void set( final short value ) { b.setValue( j1, value % 2 == 1 ); b.setValue( j2, (value & 2) == 2 ); b.setValue( j3, (value & 4) == 4 ); b.setValue( j4, (value & 8) == 8 ); b.setValue( j5, (value & 16) == 16 ); b.setValue( j6, (value & 32) == 32 ); b.setValue( j7, (value & 64) == 64 ); b.setValue( j8, (value & 128) == 128 ); b.setValue( j9, (value & 256) == 256 ); b.setValue( j10, (value & 512) == 512 ); b.setValue( j11, (value & 1024) == 1024 ); b.setValue( j12, (value & 2048) == 2028 ); } @Override public int getInteger(){ return get(); } @Override public long getIntegerLong() { return get(); } @Override public void setInteger( final int f ) { set( (short)f ); } @Override public void setInteger( final long f ) { set( (short)f ); } @Override public double getMaxValue() { return 4095; } @Override public double getMinValue() { return 0; } @Override public void updateIndex( final int i ) { this.i = i; j1 = i * 12; j2 = j1 + 1; j3 = j1 + 2; j4 = j1 + 3; j5 = j1 + 4; j6 = j1 + 5; j7 = j1 + 6; j8 = j1 + 7; j9 = j1 + 8; j10 = j1 + 9; j11 = j1 + 10; j12 = j1 + 11; } @Override public void incIndex() { ++i; j1 += 12; j2 += 12; j3 += 12; j4 += 12; j5 += 12; j6 += 12; j7 += 12; j8 += 12; j9 += 12; j10 += 12; j11 += 12; j12 += 12; } @Override public void incIndex( final int increment ) { i += increment; final int inc12 = 12 * increment; j1 += inc12; j2 += inc12; j3 += inc12; j4 += inc12; j5 += inc12; j6 += inc12; j7 += inc12; j8 += inc12; j9 += inc12; j10 += inc12; j11 += inc12; j12 += inc12; } @Override public void decIndex() { --i; j1 -= 12; j2 -= 12; j3 -= 12; j4 -= 12; j5 -= 12; j6 -= 12; j7 -= 12; j8 -= 12; j9 -= 12; j10 -= 12; j11 -= 12; j12 -= 12; } @Override public void decIndex( final int decrement ) { i -= decrement; final int dec12 = 12 * decrement; j1 -= dec12; j2 -= dec12; j3 -= dec12; j4 -= dec12; j5 -= dec12; j6 -= dec12; j7 -= dec12; j8 -= dec12; j9 -= dec12; j10 -= dec12; j11 -= dec12; j12 -= dec12; } @Override public Unsigned12BitType[] createArray1D(int size1){ return new Unsigned12BitType[ size1 ]; } @Override public Unsigned12BitType[][] createArray2D(int size1, int size2){ return new Unsigned12BitType[ size1 ][ size2 ]; } @Override public Unsigned12BitType[][][] createArray3D(int size1, int size2, int size3) { return new Unsigned12BitType[ size1 ][ size2 ][ size3 ]; } @Override public Unsigned12BitType createVariable(){ return new Unsigned12BitType(); } @Override public Unsigned12BitType clone(){ return new Unsigned12BitType( get() ); } }
package s01basics; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.settings.GameSettings; /** * This is an example of a minimalistic FXGL game application. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public class BasicAppSample extends GameApplication { @Override protected void initSettings(GameSettings settings) { settings.setWidth(800); settings.setHeight(600); settings.setTitle("BasicAppSample"); settings.setVersion("0.1"); settings.setIntroEnabled(false); settings.setMenuEnabled(false); settings.setCloseConfirmation(false); settings.setProfilingEnabled(false); } public static void main(String[] args) { launch(args); } }
package com.topsradiance.anonymeyes.backend; import java.io.DataOutputStream; import java.net.HttpURLConnection; import java.net.URL; public class Endpoint { public static void request(String fname) { try { String addr = "http://localhost/new_video"; URL url = new URL(addr); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(50); con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes("filename=" + fname); wr.flush(); wr.close(); con.getResponseCode(); System.out.println("Request made to " + addr + " with content " + fname); } catch(Exception e) { e.printStackTrace(); } } }
package org.beiter.michael.db; import org.apache.commons.lang3.Validate; import java.sql.Connection; /** * This class specifies connection pool properties. */ // CHECKSTYLE:OFF // this is flagged in checkstyle with a missing whitespace before '}', which is a bug in checkstyle // suppress warnings about the constructor (required for producing java docs) // suppress warnings about the number of fields // suppress warnings about the long variable names that are "inherited" from Apache DBCP (which I used as a blueprint) // suppress warnings about the excessive number of public elements (triggered by the many getters and setters) // suppress warnings about a potential God class (not the case, this is triggered by the many getters and setters) @SuppressWarnings({"PMD.UnnecessaryConstructor", "PMD.TooManyFields", "PMD.LongVariable", "PMD.ExcessivePublicCount", "PMD.GodClass"}) // CHECKSTYLE:ON public class ConnectionProperties { /** * @see ConnectionProperties#setDriver(String) */ private String driver; /** * @see ConnectionProperties#setUrl(String) */ private String url; /** * @see ConnectionProperties#setUsername(String) */ private String username; /** * @see ConnectionProperties#setPassword(String) */ private String password; /** * @see ConnectionProperties#setMaxTotal(int) */ private int maxTotal; /** * @see ConnectionProperties#setMaxIdle(int) */ private int maxIdle; /** * @see ConnectionProperties#setMinIdle(int) */ private int minIdle; /** * @see ConnectionProperties#setMaxWaitMillis(long) */ private long maxWaitMillis; /** * @see ConnectionProperties#setTestOnCreate(boolean) */ private boolean testOnCreate; /** * @see ConnectionProperties#setTestOnBorrow(boolean) */ private boolean testOnBorrow; /** * @see ConnectionProperties#setTestOnReturn(boolean) */ private boolean testOnReturn; /** * @see ConnectionProperties#setTestWhileIdle(boolean) */ private boolean testWhileIdle; /** * @see ConnectionProperties#setTimeBetweenEvictionRunsMillis(long) */ private long timeBetweenEvictionRunsMillis; /** * @see ConnectionProperties#setNumTestsPerEvictionRun(int) */ private int numTestsPerEvictionRun; /** * @see ConnectionProperties#setMinEvictableIdleTimeMillis(long) */ private long minEvictableIdleTimeMillis; /** * @see ConnectionProperties#setSoftMinEvictableIdleTimeMillis(long) */ private long softMinEvictableIdleTimeMillis; /** * @see ConnectionProperties#setLifo(boolean) */ private boolean lifo; /** * @see ConnectionProperties#setDefaultAutoCommit(boolean) */ private boolean defaultAutoCommit; /** * @see ConnectionProperties#setDefaultReadOnly(boolean) */ private boolean defaultReadOnly; /** * @see ConnectionProperties#setDefaultTransactionIsolation(int) */ private int defaultTransactionIsolation; /** * @see ConnectionProperties#setCacheState(boolean) */ private boolean cacheState; /** * @see ConnectionProperties#setValidationQuery(String) */ private String validationQuery; /** * @see ConnectionProperties#setMaxConnLifetimeMillis(long) */ private long maxConnLifetimeMillis; /** * Constructs an empty set of connection properties, with most values being set to <code>null</code>, 0, or empty * (depending on the type of the property). Usually this constructor is used if this configuration POJO is populated * in an automated fashion (e.g. injection). If you need to build them manually (possibly with defaults), use or * create a properties builder. * <p/> * You can change the defaults with the setters. If you need more control over the pool than what is provided by * the available setters, consider using a JNDI controlled connection pool instead. * * @see org.beiter.michael.db.propsbuilder.MapBasedConnPropsBuilder#buildDefault() * @see org.beiter.michael.db.propsbuilder.MapBasedConnPropsBuilder#build(java.util.Map) */ public ConnectionProperties() { // no code here, constructor just for java docs } /** * @return The JDBC database driver class * @see ConnectionProperties#setDriver(String) */ public final String getDriver() { // no need for defensive copies of String return driver; } /** * The JDBC database driver class * * @param driver The JDBC database driver class */ public final void setDriver(final String driver) { // no need for validation, as we cannot possible validate all SQL driver names and null is allowed // no need for defensive copies of boolean this.driver = driver; } /** * @return The JDBC database URL of the form <code>jdbc:subprotocol:subname</code> * @see ConnectionProperties#setUrl(String) */ public final String getUrl() { // no need for defensive copies of String return url; } /** * The JDBC database URL of the form <code>jdbc:subprotocol:subname</code> * * @param url The JDBC database URL */ public final void setUrl(final String url) { // no need for validation, as we cannot possible validate all URL patterns and null is allowed // no need for defensive copies of boolean this.url = url; } /** * @return The username for the connection * @see ConnectionProperties#setUsername(String) */ public final String getUsername() { // no need for defensive copies of String return username; } /** * The username for the connection * * @param username The username for the connection */ public final void setUsername(final String username) { // no need for validation, as we cannot possible validate all username patterns and null is allowed // no need for defensive copies of boolean this.username = username; } /** * @return The password for the connection * @see ConnectionProperties#setUrl(String) */ public final String getPassword() { // no need for defensive copies of String return password; } /** * The password for the connection * * @param password The password for the connection */ public final void setPassword(final String password) { // no need for validation, as we cannot possible validate all password patterns and null is allowed // no need for defensive copies of boolean this.password = password; } /** * @return the maximum numbers of active connections * @see ConnectionProperties#setMaxTotal(int) */ public final int getMaxTotal() { // no need for defensive copies of int return maxTotal; } /** * The maximum number of active connections that can be allocated from this pool at the same time, or negative * for no limit. * * @param maxTotal the maximum numbers of active connections */ public final void setMaxTotal(final int maxTotal) { // no need for validation, as int cannot be null and all possible values are allowed // no need for defensive copies of int this.maxTotal = maxTotal; } /** * @return the maximum number of idle connections * @see ConnectionProperties#setMaxIdle(int) */ public final int getMaxIdle() { // no need for defensive copies of int return maxIdle; } /** * The maximum number of connections that can remain idle in the pool, without extra ones being released, or * negative for no limit. * * @param maxIdle the maximum number of idle connections */ public final void setMaxIdle(final int maxIdle) { // no need for validation, as int cannot be null and all possible values are allowed // no need for defensive copies of int this.maxIdle = maxIdle; } /** * @return the minimum number of idle connections * @see ConnectionProperties#setMinIdle(int) */ public final int getMinIdle() { // no need for defensive copies of int return minIdle; } /** * The minimum number of connections that can remain idle in the pool, without extra ones being created, or zero * to create none. * * @param minIdle the minimum number of idle connections */ public final void setMinIdle(final int minIdle) { Validate.inclusiveBetween(0, Integer.MAX_VALUE, minIdle); // no need for defensive copies of int this.minIdle = minIdle; } /** * @return the maximum number of milliseconds that the pool will wait for a connection * @see ConnectionProperties#setMaxWaitMillis(long) */ public final long getMaxWaitMillis() { // no need for defensive copies of long return maxWaitMillis; } /** * The maximum number of milliseconds that the pool will wait (when there are no available connections) for a * connection to be returned before throwing an exception, or -1 to wait indefinitely. * * @param maxWaitMillis the maximum number of milliseconds that the pool will wait for a connection */ public final void setMaxWaitMillis(final long maxWaitMillis) { Validate.inclusiveBetween(-1, Integer.MAX_VALUE, maxWaitMillis); // no need for defensive copies of long this.maxWaitMillis = maxWaitMillis; } /** * @return the indication of whether objects will be validated after creation * @see ConnectionProperties#setTestOnCreate(boolean) */ public final boolean isTestOnCreate() { // no need for defensive copies of boolean return testOnCreate; } /** * The indication of whether objects will be validated after creation. If the object fails to validate, the borrow * attempt that triggered the object creation will fail. * * @param testOnCreate the indication of whether objects will be validated after creation */ public final void setTestOnCreate(final boolean testOnCreate) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.testOnCreate = testOnCreate; } /** * @return the indication of whether objects will be validated before being borrowed from the pool * @see ConnectionProperties#setTestOnBorrow(boolean) */ public final boolean isTestOnBorrow() { // no need for defensive copies of boolean return testOnBorrow; } /** * The indication of whether objects will be validated before being borrowed from the pool. If the object fails to * validate, it will be dropped from the pool, and we will attempt to borrow another. * * @param testOnBorrow the indication of whether objects will be validated before being borrowed from the pool */ public final void setTestOnBorrow(final boolean testOnBorrow) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.testOnBorrow = testOnBorrow; } /** * @return the indication of whether objects will be validated before being returned to the pool * @see ConnectionProperties#setTestOnReturn(boolean) */ public final boolean isTestOnReturn() { // no need for defensive copies of boolean return testOnReturn; } /** * The indication of whether objects will be validated before being returned to the pool. * * @param testOnReturn the indication of whether objects will be validated before being returned to the pool */ public final void setTestOnReturn(final boolean testOnReturn) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.testOnReturn = testOnReturn; } /** * @return the indication of whether objects will be validated by the idle object evictor (if any) * @see ConnectionProperties#setTestWhileIdle(boolean) */ public final boolean isTestWhileIdle() { // no need for defensive copies of boolean return testWhileIdle; } /** * The indication of whether objects will be validated by the idle object evictor (if any). If an object fails * to validate, it will be dropped from the pool. * * @param testWhileIdle the indication of whether objects will be validated by the idle object evictor (if any) */ public final void setTestWhileIdle(final boolean testWhileIdle) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.testWhileIdle = testWhileIdle; } /** * @return the number of milliseconds to sleep between runs of the idle object evictor thread * @see ConnectionProperties#setTimeBetweenEvictionRunsMillis(long) */ public final long getTimeBetweenEvictionRunsMillis() { // no need for defensive copies of long return timeBetweenEvictionRunsMillis; } /** * The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle * object evictor thread will be run. * * @param timeBetweenEvictionRunsMillis the number of milliseconds to sleep between runs of the idle object evictor * thread */ public final void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) { // no need for validation, as long cannot be null and all possible values are allowed // no need for defensive copies of long this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } /** * @return the number of objects to examine during each run of the idle object evictor thread (if any) * @see ConnectionProperties#setNumTestsPerEvictionRun(int) */ public final int getNumTestsPerEvictionRun() { // no need for defensive copies of int return numTestsPerEvictionRun; } /** * The number of objects to examine during each run of the idle object evictor thread (if any). * * @param numTestsPerEvictionRun the number of objects to examine during each run of the idle object evictor thread * (if any) */ public final void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) { Validate.inclusiveBetween(1, Integer.MAX_VALUE, numTestsPerEvictionRun); // no need for defensive copies of long this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** * @return the minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the * idle object evictor (if any) * @see ConnectionProperties#setMinEvictableIdleTimeMillis(long) */ public final long getMinEvictableIdleTimeMillis() { // no need for defensive copies of long return minEvictableIdleTimeMillis; } /** * The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle * object evictor (if any). * * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before it is * eligable for eviction by the idle object evictor (if any). */ public final void setMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) { // no need for validation, as long cannot be null and all possible values are allowed // no need for defensive copies of long this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } /** * @return the minimum amount of time a connection may sit idle in the pool before it is eligible for eviction by * the idle connection evictor, with the extra condition that at least "minIdle" connections remain in the pool. * @see ConnectionProperties#setSoftMinEvictableIdleTimeMillis(long) */ public final long getSoftMinEvictableIdleTimeMillis() { // no need for defensive copies of long return softMinEvictableIdleTimeMillis; } /** * The minimum amount of time a connection may sit idle in the pool before it is eligible for eviction by the idle * connection evictor, with the extra condition that at least "<code>minIdle</code>" connections remain in the pool. * When <code>miniEvictableIdleTimeMillis</code> is set to a positive value, * <code>miniEvictableIdleTimeMillis</code> is examined first by the idle connection evictor - i.e. when idle * connections are visited by the evictor, idle time is first compared against * <code>miniEvictableIdleTimeMillis</code> (without considering the number of idle connections in the pool) and * then against <code>softMinEvictableIdleTimeMillis</code>, including the <code>minIdle</code> constraint. * * @param softMinEvictableIdleTimeMillis minimum amount of time a connection may sit idle in the pool before it is * eligible for eviction by the idle connection evictor, with the extra * condition that at least "minIdle" connections remain in the pool. */ public final void setSoftMinEvictableIdleTimeMillis(final long softMinEvictableIdleTimeMillis) { // no need for validation, as long cannot be null and all possible values are allowed // no need for defensive copies of long this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis; } /** * @return <code>true</code> if the pool returns the most recently used ("last in") connection, <code>false</code> * the pool behaves as a FIFO queue * @see ConnectionProperties#setLifo(boolean) */ public final boolean isLifo() { return lifo; } /** * <code>True</code> means that the pool returns the most recently used ("last in") connection in the pool (if * there are idle connections available). <code>False</code> means that the pool behaves as a FIFO queue - * connections are taken from the idle instance pool in the order that they are returned to the pool. * * @param lifo <code>true</code> if the pool returns the most recently used ("last in") connection, * <code>false</code> the pool behaves as a FIFO queue */ public final void setLifo(final boolean lifo) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.lifo = lifo; } public final boolean isDefaultAutoCommit() { // no need for defensive copies of boolean return defaultAutoCommit; } public final void setDefaultAutoCommit(final boolean defaultAutoCommit) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.defaultAutoCommit = defaultAutoCommit; } public final boolean isDefaultReadOnly() { // no need for defensive copies of boolean return defaultReadOnly; } public final void setDefaultReadOnly(final boolean defaultReadOnly) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.defaultReadOnly = defaultReadOnly; } public final int getDefaultTransactionIsolation() { // no need for defensive copies of int return defaultTransactionIsolation; } public final void setDefaultTransactionIsolation(final int defaultTransactionIsolation) { if (defaultTransactionIsolation != Connection.TRANSACTION_NONE && defaultTransactionIsolation != Connection.TRANSACTION_READ_COMMITTED && defaultTransactionIsolation != Connection.TRANSACTION_READ_UNCOMMITTED && defaultTransactionIsolation != Connection.TRANSACTION_REPEATABLE_READ && defaultTransactionIsolation != Connection.TRANSACTION_SERIALIZABLE ) { throw new IllegalArgumentException("TransactionIsolation level must be one of the JDBC supported levels"); } // no need for defensive copies of int this.defaultTransactionIsolation = defaultTransactionIsolation; } /** * @return If <code>true</code>, the pooled connection will cache the current <code>readOnly</code> and * <code>autoCommit</code> settings when first read or written and on all subsequent writes * @see ConnectionProperties#setCacheState(boolean) */ public final boolean isCacheState() { // no need for defensive copies of boolean return cacheState; } /** * If <code>true</code>, the pooled connection will cache the current <code>readOnly</code> and * <code>autoCommit</code> settings when first read or written and on all subsequent writes. This removes the need * for additional database queries for any further calls to the getter. If the underlying connection is accessed * directly and the readOnly and/or <code>autoCommit</code> settings changed the cached values will not reflect the * current state. In this case, caching should be disabled by setting this attribute to false. * * @param cacheState If <code>true</code>, the pooled connection will cache the current <code>readOnly</code> and * <code>autoCommit</code> settings when first read or written and on all subsequent writes */ public final void setCacheState(final boolean cacheState) { // no need for validation, as boolean cannot be null and all possible values are allowed // no need for defensive copies of boolean this.cacheState = cacheState; } /** * @return The SQL query that will be used to validate connections from the pool before returning them to the caller * @see ConnectionProperties#setValidationQuery(String) */ public final String getValidationQuery() { // no need for defensive copies of String return validationQuery; } /** * The SQL query that will be used to validate connections from the pool before returning them to the caller. If * specified, this query <strong>MUST</strong> be an SQL SELECT statement that returns at least one row. If not * specified (i.e. <code>null</code>), connections will be validation by calling the <code>isValid()</code> method. * * @param validationQuery The SQL query that will be used to validate connections from the pool before returning * them to the caller */ public final void setValidationQuery(final String validationQuery) { // no need for validation, as we cannot possible validate all SQL dialects and null is allowed for this string // no need for defensive copies of boolean this.validationQuery = validationQuery; } /** * @return The maximum lifetime in milliseconds of a connection * @see ConnectionProperties#setMaxConnLifetimeMillis(long) */ public final long getMaxConnLifetimeMillis() { // no need for defensive copies of long return maxConnLifetimeMillis; } /** * The maximum lifetime in milliseconds of a connection. After this time is exceeded the connection will fail the * next activation, passivation or validation test. A value of zero or less means the connection has an infinite * lifetime. * * @param maxConnLifetimeMillis The maximum lifetime in milliseconds of a connection */ public final void setMaxConnLifetimeMillis(final long maxConnLifetimeMillis) { // no need for validation, as long cannot be null and all possible values are allowed // no need for defensive copies of long this.maxConnLifetimeMillis = maxConnLifetimeMillis; } }
package com.xruby.runtime.builtin; import com.xruby.runtime.lang.*; import com.xruby.runtime.value.*; import java.math.BigInteger; import java.util.StringTokenizer; class String_capitalize extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; RubyString new_value = ObjectFactory.createString(value.toString()); new_value.capitalize(); return new_value; } } class String_strip extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; RubyString new_value = ObjectFactory.createString(value.toString()); new_value.strip(); return new_value; } } class String_operator_equal extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (!(arg instanceof RubyString)) { return ObjectFactory.FALSE_VALUE; } RubyString a = (RubyString) receiver; RubyString b = (RubyString) arg; if (a.toString().equals(b.toString())) { return ObjectFactory.TRUE_VALUE; } else { return ObjectFactory.FALSE_VALUE; } } } /// Upcases the contents of str, returning nil if no changes were made class String_upcase_danger extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; String new_value = value.toString().toUpperCase(); if (new_value.equals(value.toString())) { //no changes return ObjectFactory.NIL_VALUE; } else { return value.setString(new_value); } } } ///Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. class String_capitalize_danger extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; boolean changed = value.capitalize(); if (changed) { return receiver; } else { return ObjectFactory.NIL_VALUE; } } } class String_strip_danger extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; boolean changed = value.strip(); if (changed) { return receiver; } else { return ObjectFactory.NIL_VALUE; } } } class String_upcase extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; return ObjectFactory.createString(value.toString().toUpperCase()); } } class String_downcase extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; return ObjectFactory.createString(value.toString().toLowerCase()); } } /// Downcases the contents of str, returning nil if no changes were made. class String_downcase_danger extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; String new_value = value.toString().toLowerCase(); if (new_value.equals(value.toString())) { return ObjectFactory.NIL_VALUE; } else { return value.setString(new_value); } } } class String_to_f extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; return ObjectFactory.createFloat(Double.valueOf(value.toString())); } } class String_hex extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; String s = value.toString(); if (s.startsWith("0x")) { s = s.substring("0x".length()); } try { return ObjectFactory.createFixnum(Integer.valueOf(s, 16)); } catch (NumberFormatException e) { return ObjectFactory.FIXNUM0; } } } class String_to_i extends RubyVarArgMethod { public String_to_i() { super(1, false, 1); } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { String value = ((RubyString) receiver).toString(); value = value.replaceAll("[^+\\-a-zA-Z0-9]", ""); int end = value.indexOf('+', 1); int end1 = value.indexOf('-', 1); if (end < 0) { if (end1 < 0) { end = value.length(); } else { end = end1; } } else { if (end1 >= 0) { end = Math.min(end, end1); } } value = value.substring(0, end); int radix = 10; if (null != args) { radix = ((RubyFixnum) args.get(0)).intValue(); } if (radix >= 2 && radix <= 36) { BigInteger bigint; try { bigint = new BigInteger(value, radix); } catch (NumberFormatException e) { return ObjectFactory.FIXNUM0; } return RubyBignum.bignorm(bigint); } throw new RubyException(RubyRuntime.ArgumentErrorClass, "illegal radix " + radix); } } class String_to_s extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; return ObjectFactory.createString(value.toString()); } } class String_length extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString value = (RubyString) receiver; return ObjectFactory.createFixnum(value.length()); } } class String_initialize extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (args != null) { String new_value = RubyTypesUtil.convertToString(args.get(0)).toString(); ((RubyString) receiver).setString(new_value); } return receiver; } } class String_new extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { return ObjectFactory.createString((RubyClass) receiver, ""); } } class String_plus extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString v1 = (RubyString) receiver; RubyString v2 = (RubyString) arg; return ObjectFactory.createString(v1.toString() + v2.toString()); } } class String_sub extends String_gsub { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == block) { checkParameters1(args); RubyString g = (RubyString) receiver; RubyRegexp r = (RubyRegexp) args.get(0); RubyString s = (RubyString) args.get(1); return ObjectFactory.createString(r.sub(g, s)); } else { checkParameters2(args); RubyString g = (RubyString) receiver; RubyRegexp r = (RubyRegexp) args.get(0); return r.sub(g, block); } } } class String_sub_danger extends String_sub { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString g = (RubyString) receiver; if (null == block) { checkParameters1(args); RubyRegexp r = (RubyRegexp) args.get(0); RubyString s = (RubyString) args.get(1); String result = r.sub(g, s); if (g.toString().equals(result)) { return ObjectFactory.NIL_VALUE; } else { return g.setString(result); } } else { checkParameters2(args); RubyRegexp r = (RubyRegexp) args.get(0); return g.setString(r.sub(g, block).toString()); } } } class String_gsub extends RubyVarArgMethod { protected void checkParameters1(RubyArray args) { assertArgNumberEqual(args, 2); if (!(args.get(0) instanceof RubyRegexp)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong argument type " + args.get(0).getRubyClass().getName() + " (expected Regexp)"); } if (!(args.get(1) instanceof RubyString)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "can't convert " + args.get(1).getRubyClass().getName() + " into String"); } } protected void checkParameters2(RubyArray args) { assertArgNumberEqual(args, 1); if (!(args.get(0) instanceof RubyRegexp)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong argument type " + args.get(0).getRubyClass().getName() + " (expected Regexp)"); } } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == block) { checkParameters1(args); RubyString g = (RubyString) receiver; RubyRegexp r = (RubyRegexp) args.get(0); RubyString s = (RubyString) args.get(1); return ObjectFactory.createString(r.gsub(g, s)); } else { checkParameters2(args); RubyString g = (RubyString) receiver; RubyRegexp r = (RubyRegexp) args.get(0); return r.gsub(g, block); } } } class String_gsub_danger extends String_gsub { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString g = (RubyString) receiver; if (null == block) { checkParameters1(args); RubyRegexp r = (RubyRegexp) args.get(0); RubyString s = (RubyString) args.get(1); String result = r.gsub(g, s); if (g.toString().equals(result)) { return ObjectFactory.NIL_VALUE; } else { return g.setString(result); } } else { checkParameters2(args); RubyRegexp r = (RubyRegexp) args.get(0); return g.setString(r.gsub(g, block).toString()); } } } class String_split extends RubyVarArgMethod { public String_split() { super(2, false, 2); } private String[] split(RubyString s, String delimiter) { StringTokenizer t = new StringTokenizer(s.toString(), delimiter); int total = t.countTokens(); String[] r = new String[total]; for (int i = 0; i < total; ++i) { r[i] = t.nextToken(); } return r; } private String[] split(RubyString g, RubyRegexp r, RubyArray args) { if (args.size() <= 1) { return r.split(g.toString(), 0); } else { RubyFixnum i = (RubyFixnum) args.get(1); return r.split(g.toString(), i.intValue()); } } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString g = (RubyString) receiver; RubyValue r = (null == args) ? GlobalVariables.get("$;") : args.get(0); String[] splitResult; if (r == ObjectFactory.NIL_VALUE) { splitResult = split(g, " "); } else if (r instanceof RubyRegexp) { splitResult = split(g, (RubyRegexp) r, args); } else if (r instanceof RubyString) { splitResult = split(g, ((RubyString) r).toString()); } else { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong argument type " + r.getRubyClass() + " (expected Regexp)"); } RubyArray a = new RubyArray(splitResult.length); int i = 0; for (String str : splitResult) { if (0 != i || !str.equals("")) { //To conform ruby's behavior, discard the first empty element a.add(ObjectFactory.createString(str)); } ++i; } return a; } } class String_operator_compare extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (!(arg instanceof RubyString)) { return ObjectFactory.NIL_VALUE; } RubyString value1 = (RubyString) receiver; RubyString value2 = (RubyString) arg; int compare = value1.toString().compareTo(value2.toString()); if (compare > 0) { compare = 1; } else if (compare < 0) { compare = -1; } return ObjectFactory.createFixnum(compare); } } class String_casecmp extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (!(arg instanceof RubyString)) { return ObjectFactory.NIL_VALUE; } RubyString value1 = (RubyString) receiver; RubyString value2 = (RubyString) arg; int compare = value1.toString().toUpperCase().compareTo(value2.toString().toUpperCase()); if (compare > 0) { compare = 1; } else if (compare < 0) { compare = -1; } return ObjectFactory.createFixnum(compare); } } class String_operator_match extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (arg instanceof RubyRegexp) { RubyRegexp reg = (RubyRegexp) arg; int p = reg.matchPosition(((RubyString) receiver).toString()); if (p >= 0) { return ObjectFactory.createFixnum(p); } else { return ObjectFactory.NIL_VALUE; } } else { return RubyAPI.callPublicOneArgMethod(arg, receiver, null, CommonRubyID.matchID); } } } class String_format extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { String format = ((RubyString) receiver).toString(); String s; if (arg instanceof RubyArray) { s = String.format(format, Kernel_printf.buildFormatArg((RubyArray)arg, 0)); } else { s = String.format(format, Kernel_printf.buildFormatArg(new RubyArray(arg), 0)); } return ObjectFactory.createString(s); } } class String_access extends RubyVarArgMethod { public String_access() { super(2, false, 1); } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { String string = ((RubyString) receiver).toString(); if (args.size() == 1) { RubyValue arg = args.get(0); if (arg instanceof RubyString) { String str = ((RubyString) arg).toString(); if (string.indexOf(str) >= 0) { return ObjectFactory.createString(str); } else { return ObjectFactory.NIL_VALUE; } } else if (arg instanceof RubyRange) { RubyRange range = (RubyRange) arg; int start = RubyTypesUtil.convertToJavaInt(range.getLeft()); int end = RubyTypesUtil.convertToJavaInt(range.getRight()); return substring(string, start, end, range.isExcludeEnd()); } else if (arg instanceof RubyRegexp) { RubyRegexp regexp = (RubyRegexp) arg; RubyMatchData match = regexp.match(string); if (match != null) { return ObjectFactory.createString(match.to_s()); } else { return ObjectFactory.NIL_VALUE; } } else { int index = RubyTypesUtil.convertToJavaInt(arg); if (index < 0) { index = string.length() + index; } if (index < 0 || index >= string.length()) { return ObjectFactory.NIL_VALUE; } else { return ObjectFactory.createFixnum(string.charAt(index)); } } } else { int start = RubyTypesUtil.convertToJavaInt(args.get(0)); int length = RubyTypesUtil.convertToJavaInt(args.get(1)) - 1; return substring(string, start, start + length, false); } } private RubyValue substring(String string, int begin, int end, boolean isExcludeEnd) { if (begin < 0) { begin = string.length() + begin; } if (end < 0) { end = string.length() + end; } if (!isExcludeEnd) { ++end; } if (begin < 0 || end < 0 || begin >= end || begin > string.length() || end > string.length()) { return ObjectFactory.NIL_VALUE; } return ObjectFactory.createString(string.substring(begin, end)); } } class String_access_set extends RubyVarArgMethod { public String_access_set() { super(3, false, 2); } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { String string = ((RubyString) receiver).toString(); String replacement; int start, end; if (args.size() == 2) { RubyValue arg = args.get(0); replacement = ((RubyString) args.get(1)).toString(); if (arg instanceof RubyString) { String str = ((RubyString) arg).toString(); start = string.indexOf(str); if (start >= 0) { end = start + str.length(); } else { throw new RubyException(RubyRuntime.IndexErrorClass, "string not matched"); } } else if (arg instanceof RubyRange) { RubyRange range = (RubyRange) arg; start = RubyTypesUtil.convertToJavaInt(range.getLeft()); end = RubyTypesUtil.convertToJavaInt(range.getRight()); if (start >= string.length()) { throw new RubyException(RubyRuntime.RangeClass, range.toString() + " out of range"); } } else if (arg instanceof RubyRegexp) { RubyRegexp regexp = (RubyRegexp) arg; RubyMatchData match = regexp.match(string); if (match != null) { String matched = match.to_s(); start = string.indexOf(matched); end = matched.length() + start; } else { throw new RubyException(RubyRuntime.IndexErrorClass, "regexp not matched"); } } else { start = RubyTypesUtil.convertToJavaInt(arg); end = start + 1; } } else { replacement = ((RubyString) args.get(2)).toString(); start = RubyTypesUtil.convertToJavaInt(args.get(0)); end = RubyTypesUtil.convertToJavaInt(args.get(1)) + start; if (start >= string.length()) { throw new RubyException(RubyRuntime.RangeClass, String.format("index %d out of string", start)); } } ((RubyString) receiver).setString(replace(string, start, end, replacement)); return ObjectFactory.createString(replacement); } private String replace(String source, int start, int end, String replacement) { assert(start <= source.length() - 1); if (end < start) { end = start + 1; } StringBuffer result = new StringBuffer(source.substring(0, start)); result.append(replacement); result.append(source.substring(end)); return result.toString(); } } class String_operator_star extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { String string = ((RubyString) receiver).toString(); int count = RubyTypesUtil.convertToJavaInt(arg); if (count < 0) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "negative argument"); } StringBuilder result = new StringBuilder(); for (int i = 0; i < count; ++i) { result.append(string); } return ObjectFactory.createString(result); } } class String_each extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { block.invoke(receiver, new RubyArray(receiver)); return receiver; } } class String_each_byte extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { String string = ((RubyString) receiver).toString(); for (int i = 0; i < string.length(); ++i) { char c = string.charAt(i); block.invoke(receiver, new RubyArray(ObjectFactory.createFixnum((int) c))); } return receiver; } } class String_reverse_danger extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString string = (RubyString) receiver; string.reverse(); return string; } } class String_reverse extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); string.reverse(); return string; } } class String_chomp extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); RubyValue separator = (null != args) ? args.get(0) : GlobalVariables.get("$/"); string.chomp(((RubyString) separator).toString()); return string; } } class String_chomp_danger extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString string = (RubyString) receiver; RubyValue separator = (null == args) ? GlobalVariables.get("$/") : args.get(0); string.chomp(((RubyString) separator).toString()); return string; } } class String_scan extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString string = (RubyString) receiver; RubyRegexp regex = (RubyRegexp) arg; return string.scan(regex); } } class String_tr_danger extends RubyTwoArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) { RubyString string = (RubyString) receiver; RubyString from = (RubyString) arg1; RubyString to = (RubyString) arg2; return string.tr(from.toString(), to.toString()) ? string : ObjectFactory.NIL_VALUE; } } class String_tr extends RubyTwoArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) { RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); RubyString from = (RubyString) arg1; RubyString to = (RubyString) arg2; string.tr(from.toString(), to.toString()); return string; } } class String_tr_s_danger extends RubyTwoArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) { RubyString string = (RubyString) receiver; RubyString from = (RubyString) arg1; RubyString to = (RubyString) arg2; return string.tr_s(from.toString(), to.toString()) ? string : ObjectFactory.NIL_VALUE; } } class String_tr_s extends RubyTwoArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) { RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); RubyString from = (RubyString) arg1; RubyString to = (RubyString) arg2; string.tr_s(from.toString(), to.toString()); return string; } } class String_squeeze_danger extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString string = (RubyString) receiver; String arg = ((null == args) ? null : ((RubyString) args.get(0)).toString()); return string.squeeze(arg) ? string : ObjectFactory.NIL_VALUE; } } class String_squeeze extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); String arg = ((null == args) ? null : ((RubyString) args.get(0)).toString()); string.squeeze(arg); return string; } } class String_delete_danger extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == args) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments"); } RubyString string = (RubyString) receiver; String arg = ((RubyString) args.get(0)).toString(); return string.delete(arg) ? string : ObjectFactory.NIL_VALUE; } } class String_delete extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == args) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments"); } RubyString string = ObjectFactory.createString(((RubyString) receiver).toString()); String arg = ((RubyString) args.get(0)).toString(); string.delete(arg); return string; } } class String_unpack extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString s = (RubyString) receiver; RubyString format = ((RubyString) arg); return ArrayPacker.unpack(s.toString(), format.toString()); } } class String_concat extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString s = (RubyString) receiver; return s.appendString(arg); } } class String_count extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString s = (RubyString) receiver; if (null == args) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments"); } //TODO incomplete int n = 0; for (RubyValue v : args) { RubyString other_str = (RubyString) v; n += s.count(other_str.toString()); } return ObjectFactory.createFixnum(n); } } public class StringClassBuilder { public static void initialize() { RubyClass c = RubyRuntime.StringClass; c.defineMethod("strip", new String_strip()); c.defineMethod("strip!", new String_strip_danger()); c.defineMethod("capitalize", new String_capitalize()); c.defineMethod("==", new String_operator_equal()); c.defineMethod("upcase!", new String_upcase_danger()); c.defineMethod("capitalize!", new String_capitalize_danger()); c.defineMethod("upcase", new String_upcase()); c.defineMethod("downcase", new String_downcase()); c.defineMethod("to_f", new String_to_f()); c.defineMethod("to_i", new String_to_i()); c.defineMethod("hex", new String_hex()); c.defineMethod("to_s", new String_to_s()); c.defineMethod("length", new String_length()); c.defineMethod("downcase!", new String_downcase_danger()); c.defineMethod("initialize_copy", new String_initialize()); c.defineMethod("initialize", new String_initialize()); c.defineMethod("+", new String_plus()); c.defineMethod("gsub", new String_gsub()); c.defineMethod("gsub!", new String_gsub_danger()); c.defineMethod("sub", new String_sub()); c.defineMethod("sub!", new String_sub_danger()); c.defineMethod("split", new String_split()); c.defineMethod("<=>", new String_operator_compare()); c.defineMethod("casecmp", new String_casecmp()); c.defineMethod("=~", new String_operator_match()); c.defineMethod("[]", new String_access()); c.defineMethod("%", new String_format()); c.defineMethod("[]=", new String_access_set()); c.defineMethod("*", new String_operator_star()); RubyMethod each = new String_each(); c.defineMethod("each", each); c.defineMethod("each_line", each); c.defineMethod("each_byte", new String_each_byte()); c.defineMethod("reverse!", new String_reverse_danger()); c.defineMethod("reverse", new String_reverse()); c.defineMethod("chomp", new String_chomp()); c.defineMethod("chomp!", new String_chomp_danger()); c.defineMethod("scan", new String_scan()); c.defineMethod("tr!", new String_tr_danger()); c.defineMethod("tr", new String_tr()); c.defineMethod("tr_s!", new String_tr_s_danger()); c.defineMethod("tr_s", new String_tr_s()); c.defineMethod("squeeze!", new String_squeeze_danger()); c.defineMethod("squeeze", new String_squeeze()); c.defineMethod("delete!", new String_delete_danger()); c.defineMethod("delete", new String_delete()); c.defineMethod("unpack", new String_unpack()); RubyMethod concat = new String_concat(); c.defineMethod("concat", concat); c.defineMethod("<<", concat); c.defineMethod("count", new String_count()); c.defineAllocMethod(new String_new()); } }
package com.xtremelabs.droidsugar.fakes; import android.content.ContentResolver; import android.provider.Settings; import com.xtremelabs.droidsugar.util.FakeHelper; import com.xtremelabs.droidsugar.util.Implements; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; @SuppressWarnings({"UnusedDeclaration"}) @Implements(Settings.class) public class FakeSettings { private static class SettingsImpl { private static final WeakHashMap<ContentResolver, Map<String, Integer>> dataMap = new WeakHashMap<ContentResolver, Map<String, Integer>>(); public static boolean putInt(ContentResolver cr, String name, int value) { get(cr).put(name, value); return true; } public static int getInt(ContentResolver cr, String name, int def) { Integer value = get(cr).get(name); return value == null ? def : value; } private static Map<String, Integer> get(ContentResolver cr) { Map<String, Integer> map = dataMap.get(cr); if (map == null) { map = new HashMap<String, Integer>(); dataMap.put(cr, map); } return map; } } @Implements(Settings.System.class) public static class FakeSystem extends SettingsImpl { } @Implements(Settings.Secure.class) public static class FakeSecure extends SettingsImpl { } public static void setAirplaneMode(boolean isAirplaneMode) { Settings.System.putInt(FakeHelper.application.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, isAirplaneMode ? 1 : 0); setWifiOn(!isAirplaneMode); } public static void setWifiOn(boolean isOn) { Settings.Secure.putInt(FakeHelper.application.getContentResolver(), Settings.Secure.WIFI_ON, isOn ? 1 : 0); } }
package test.org.nakedobjects.object; import org.nakedobjects.object.NakedCollection; import org.nakedobjects.object.NakedObject; import org.nakedobjects.object.NakedObjectPersistor; import org.nakedobjects.object.NakedObjectSpecification; import org.nakedobjects.object.NakedReference; import org.nakedobjects.object.NakedValue; import org.nakedobjects.object.repository.NakedObjectsClient; import test.org.nakedobjects.object.defaults.MockObjectPersistor; import test.org.nakedobjects.object.reflect.DummyNakedObject; import test.org.nakedobjects.utility.configuration.TestConfiguration; public class TestSystem { private final DummyObjectLoader objectLoader; private NakedObjectsClient nakedObjects; private NakedObjectPersistor objectManager; private final DummyNakedObjectSpecificationLoader specificationLoader; public TestSystem() { specificationLoader = new DummyNakedObjectSpecificationLoader(); objectLoader = new DummyObjectLoader(); objectManager = new MockObjectPersistor(); } public void init() { nakedObjects = new NakedObjectsClient(); nakedObjects.setConfiguration(new TestConfiguration()); nakedObjects.setSpecificationLoader(specificationLoader); nakedObjects.setObjectLoader(objectLoader); nakedObjects.setObjectPersistor(objectManager); nakedObjects.init(); } public void addSpecification(NakedObjectSpecification specification) { specificationLoader.addSpecification(specification); } public void addNakedCollectionAdapter(NakedCollection collection) { objectLoader.addAdapter(collection.getObject(), collection); } public NakedObject createAdapterForTransient(Object associate) { NakedObject createAdapterForTransient = objectLoader.createAdapterForTransient(associate); objectLoader.addAdapter(associate, createAdapterForTransient); return createAdapterForTransient; } public void shutdown() { nakedObjects.shutdown(); } public void setObjectPersistor(NakedObjectPersistor objectManager) { this.objectManager = objectManager; } public void setupLoadedObject(Object forObject, NakedObject adapter) { ((DummyObjectLoader) objectLoader).addAdapter(forObject, adapter); } public void addLoadedIdentity(DummyOid oid, NakedReference adapter) { objectLoader.addIdentity(oid, adapter); } public void addValue(Object object, NakedValue adapter) { objectLoader.addAdapter(object, adapter); } public void addAdapter(Object object, DummyNakedObject adapter) { objectLoader.addAdapter(object, adapter); } public void addRecreated(DummyOid oid, DummyNakedObject adapter) { objectLoader.addRecreated(oid, adapter); } public void addRecreatedTransient(DummyNakedObject adapter) { objectLoader.addRecreatedTransient(adapter); } }
package com.david.projet_dahouet.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.david.projet_dahouet.model.Classe; import com.david.projet_dahouet.model.Proprietaire; import com.david.projet_dahouet.model.Serie; import com.david.projet_dahouet.model.Voilier; public class VoilierDAO { private static Connection c; public static ArrayList<Serie> getSerie() { c = Connect.cConnect(); ArrayList<Serie> listSerie = new ArrayList<>(); // test avec select Statement stm; try { stm = c.createStatement(); String sql = "select * from serie"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String nom = new String(rs.getString("NOM_SERIE")); int id = rs.getInt("ID_SERIE"); Serie serie = new Serie(nom, id); listSerie.add(serie); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listSerie; } public static ArrayList<Classe> getClasse(Serie serie) { c = Connect.cConnect(); ArrayList<Classe> listeClasse = new ArrayList<>(); // test avec select Statement stm; try { stm = c.createStatement(); String sql = "select * from classe INNER join serie on serie.ID_SERIE = classe.ID_SERIE where serie.ID_SERIE ='" + serie.getIdSerie() + "'"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String nomclasse = new String(rs.getString("NOM_CLASSE")); int idClasse = rs.getInt("ID_CLASSE"); Classe classe = new Classe(serie.getNomSerie(), serie.getIdSerie(), nomclasse, idClasse); listeClasse.add(classe); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listeClasse; } public static void newVoilier(Voilier voilier, Classe classe, Proprietaire proprio) { Connection c = Connect.cConnect(); PreparedStatement stm; try { stm = c.prepareStatement("insert into voilier(ID_CLASSE,ID_PROPRIETAIRE,NO_VOILE,COEFFICIENT) VALUES(?,?,?,?)"); stm.setInt(1, classe.getIdClasse()); stm.setInt(2, proprio.getId()); stm.setString(3, voilier.getNom()); stm.setDouble(4, voilier.getCoef()); stm.executeUpdate(); stm.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } }
package com.wavefront.agent; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.fasterxml.jackson.databind.JsonNode; import com.squareup.tape.FileObjectQueue; import com.squareup.tape.TaskInjector; import com.squareup.tape.TaskQueue; import com.wavefront.agent.api.ForceQueueEnabledAgentAPI; import com.wavefront.api.AgentAPI; import com.wavefront.api.agent.AgentConfiguration; import com.wavefront.api.agent.ShellOutputDTO; import com.wavefront.metrics.ExpectedAgentMetric; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Gauge; import com.yammer.metrics.core.Histogram; import com.yammer.metrics.core.Meter; import com.yammer.metrics.core.MetricsRegistry; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.annotation.Nullable; import javax.ws.rs.core.Response; import static com.google.common.collect.ImmutableList.of; /** * A wrapper for any AgentAPI that queues up any result posting if the backend is not available. Current data * will always be submitted right away (thus prioritizing live data) while background threads will submit * backlogged data. * * @author Clement Pang (clement@wavefront.com) */ public class QueuedAgentService implements ForceQueueEnabledAgentAPI { private static final Logger logger = Logger.getLogger(QueuedAgentService.class.getCanonicalName()); private final Gson resubmissionTaskMarshaller; private final AgentAPI wrapped; private final List<TaskQueue<ResubmissionTask>> taskQueues; private boolean lastKnownQueueSizeIsPositive = true; private MetricsRegistry metricsRegistry = new MetricsRegistry(); private Meter resultPostingMeter = metricsRegistry.newMeter(QueuedAgentService.class, "post-result", "results", TimeUnit.MINUTES); /** * Biases result sizes to the last 5 minutes heavily. This histogram does not see all result sizes. The executor * only ever processes one posting at any given time and drops the rest. {@link #resultPostingMeter} records the * actual rate (i.e. sees all posting calls). */ private Histogram resultPostingSizes = metricsRegistry.newHistogram(QueuedAgentService.class, "result-size", true); /** * A single threaded bounded work queue to update result posting sizes. */ private ExecutorService resultPostingSizerExecutorService = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)); /** * @return bytes per minute for requests submissions. Null if no data is available yet. */ @Nullable public Long getBytesPerMinute() { if (resultPostingMeter.fifteenMinuteRate() == 0 || resultPostingSizes.mean() == 0 || resultPostingSizes.count() < 50) { return null; } return (long) (resultPostingSizes.mean() * resultPostingMeter.fifteenMinuteRate()); } public QueuedAgentService(AgentAPI service, String bufferFile, int retryThreads, ScheduledExecutorService executorService, boolean purge, final UUID agentId) throws IOException { if (retryThreads <= 0) { logger.warning("You have no retry threads set up. Any points that get rejected will be lost.\n Change this by " + "setting retryThreads to a value > 0"); } resubmissionTaskMarshaller = new GsonBuilder(). registerTypeHierarchyAdapter(ResubmissionTask.class, new ResubmissionTaskDeserializer()).create(); this.wrapped = service; this.taskQueues = Lists.newArrayListWithExpectedSize(retryThreads); for (int i = 0; i < retryThreads; i++) { final int threadId = i; File buffer = new File(bufferFile + "." + i); if (purge) { if (buffer.delete()) { logger.warning("Retry buffer has been purged: " + buffer.getAbsolutePath()); } } final TaskQueue<ResubmissionTask> taskQueue = new TaskQueue<>( new FileObjectQueue<>(buffer, new FileObjectQueue.Converter<ResubmissionTask>() { @Override public ResubmissionTask from(byte[] bytes) throws IOException { try { Reader reader = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(bytes))); return resubmissionTaskMarshaller.fromJson(reader, ResubmissionTask.class); } catch (Throwable t) { logger.warning("Failed to read a single retry submission from buffer, ignoring: " + t); return null; } } @Override public void toStream(ResubmissionTask o, OutputStream bytes) throws IOException { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); Writer writer = new OutputStreamWriter(gzipOutputStream); resubmissionTaskMarshaller.toJson(o, writer); writer.close(); gzipOutputStream.finish(); gzipOutputStream.close(); } }), new TaskInjector<ResubmissionTask>() { @Override public void injectMembers(ResubmissionTask task) { task.service = wrapped; task.currentAgentId = agentId; } } ); executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { int failures = 0; while (taskQueue.size() > 0 && taskQueue.size() > failures) { synchronized (taskQueue) { ResubmissionTask task = taskQueue.peek(); boolean removeTask = true; try { if (task != null) { task.execute(null); } } catch (Exception ex) { failures++; //noinspection ThrowableResultOfMethodCallIgnored if (Throwables.getRootCause(ex) instanceof QueuedPushTooLargeException) { logger.warning("[RETRY THREAD " + threadId + "] Wavefront server rejected push (413 response). " + "Split data and attempt later: " + ex); List<? extends ResubmissionTask> splitTasks = task.splitTask(); for (ResubmissionTask smallerTask : splitTasks) { taskQueue.add(smallerTask); } // this should remove the task from the queue break; } else //noinspection ThrowableResultOfMethodCallIgnored if (Throwables.getRootCause(ex) instanceof RejectedExecutionException) { logger.warning("[RETRY THREAD " + threadId + "] Wavefront server quiesced (406 response). Will " + "re-attempt later: " + ex); removeTask = false; break; } else { logger.warning("[RETRY THREAD " + threadId + "] cannot submit data to Wavefront servers. Will " + "re-attempt later: " + ex); } // this can potentially cause a duplicate task to be injected (but since submission is mostly // idempotent it's not really a big deal) task.service = null; task.currentAgentId = null; taskQueue.add(task); if (failures > 10) { logger.warning("[RETRY THREAD " + threadId + "] saw too many submission errors. Will re-attempt " + "in 30s"); break; } } finally { if (removeTask) taskQueue.remove(); } } } } catch (Throwable ex) { logger.log(Level.WARNING, "[RETRY THREAD " + threadId + "] unexpected exception", ex); } } }, (long) (Math.random() * 30), 30, TimeUnit.SECONDS); taskQueues.add(taskQueue); } if (retryThreads > 0) { executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { List<Integer> queueSizes = Lists.newArrayList(Lists.transform(taskQueues, new Function<TaskQueue<ResubmissionTask>, Integer>() { @Override public Integer apply(TaskQueue<ResubmissionTask> input) { return input.size(); } } )); if (Iterables.tryFind(queueSizes, new Predicate<Integer>() { @Override public boolean apply(Integer input) { return input > 0; } }).isPresent()) { lastKnownQueueSizeIsPositive = true; logger.warning("current retry queue sizes: [" + Joiner.on("/").join(queueSizes) + "]"); } else if (lastKnownQueueSizeIsPositive) { lastKnownQueueSizeIsPositive = false; logger.warning("retry queue has been cleared"); } } }, 0, 5, TimeUnit.SECONDS); } Metrics.newGauge(ExpectedAgentMetric.BUFFER_BYTES_PER_MINUTE.metricName, new Gauge<Long>() { @Override public Long value() { return getBytesPerMinute(); } }); Metrics.newGauge(ExpectedAgentMetric.CURRENT_QUEUE_SIZE.metricName, new Gauge<Long>() { @Override public Long value() { return getQueuedTasksCount(); } }); } public long getQueuedTasksCount() { long toReturn = 0; for (TaskQueue<ResubmissionTask> taskQueue : taskQueues) { toReturn += taskQueue.size(); } return toReturn; } private TaskQueue<ResubmissionTask> getSmallestQueue() { int size = Integer.MAX_VALUE; TaskQueue<ResubmissionTask> toReturn = null; for (TaskQueue<ResubmissionTask> queue : taskQueues) { if (queue.size() == 0) { return queue; } else if (queue.size() < size) { toReturn = queue; size = queue.size(); } } return toReturn; } private Runnable getPostingSizerTask(final ResubmissionTask task) { return new Runnable() { @Override public void run() { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); Writer writer = new OutputStreamWriter(gzipOutputStream); resubmissionTaskMarshaller.toJson(task, writer); writer.close(); gzipOutputStream.finish(); gzipOutputStream.close(); resultPostingSizes.update(outputStream.size()); } catch (Throwable t) { // ignored. this is a stats task. } } }; } private void scheduleTaskForSizing(ResubmissionTask task) { try { resultPostingSizerExecutorService.submit(getPostingSizerTask(task)); } catch (RejectedExecutionException ex) { // ignored. } catch (RuntimeException ex) { logger.warning("cannot size a submission task for stats tracking: " + ex); } } @Override public AgentConfiguration getConfig(UUID agentId, String hostname, Long currentMillis, Long bytesLeftForbuffer, Long bytesPerMinuteForBuffer, Long currentQueueSize, String token, String version) { return wrapped.getConfig(agentId, hostname, currentMillis, bytesLeftForbuffer, bytesPerMinuteForBuffer, currentQueueSize, token, version); } @Override public AgentConfiguration checkin(UUID agentId, String hostname, String token, String version, Long currentMillis, Boolean localAgent, JsonNode agentMetrics, Boolean pushAgent) { return wrapped.checkin(agentId, hostname, token, version, currentMillis, localAgent, agentMetrics, pushAgent); } @Override public Response postWorkUnitResult(final UUID agentId, final UUID workUnitId, final UUID targetId, final ShellOutputDTO shellOutputDTO) { return this.postWorkUnitResult(agentId, workUnitId, targetId, shellOutputDTO, false); } @Override public Response postWorkUnitResult(UUID agentId, UUID workUnitId, UUID targetId, ShellOutputDTO shellOutputDTO, boolean forceToQueue) { PostWorkUnitResultTask task = new PostWorkUnitResultTask(agentId, workUnitId, targetId, shellOutputDTO); if (forceToQueue) { addTaskToSmallestQueue(task); return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } else { try { resultPostingMeter.mark(); parsePostingResponse(wrapped.postWorkUnitResult(agentId, workUnitId, targetId, shellOutputDTO)); scheduleTaskForSizing(task); } catch (RuntimeException ex) { logger.warning("Cannot post work unit result to Wavefront servers. Will enqueue and retry later: " + ex); handleTaskRetry(ex, task); return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } return Response.ok().build(); } } @Override public Response postPushData(final UUID agentId, final UUID workUnitId, final Long currentMillis, final String format, final String pushData) { return this.postPushData(agentId, workUnitId, currentMillis, format, pushData, false); } @Override public Response postPushData(UUID agentId, UUID workUnitId, Long currentMillis, String format, String pushData, boolean forceToQueue) { PostPushDataResultTask task = new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, pushData); if (forceToQueue) { // bypass the charade of posting to the wrapped agentAPI. Just go straight to the retry queue addTaskToSmallestQueue(task); return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } else { try { resultPostingMeter.mark(); parsePostingResponse(wrapped.postPushData(agentId, workUnitId, currentMillis, format, pushData)); scheduleTaskForSizing(task); } catch (RuntimeException ex) { List<PostPushDataResultTask> splitTasks = handleTaskRetry(ex, task); for (PostPushDataResultTask splitTask : splitTasks) { // we need to ensure that we use the latest agent id. postPushData(agentId, splitTask.getWorkUnitId(), splitTask.getCurrentMillis(), splitTask.getFormat(), splitTask.getPushData()); } return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } return Response.ok().build(); } } /** * @return list of tasks to immediately retry */ private <T extends ResubmissionTask<T>> List<T> handleTaskRetry(RuntimeException failureException, T taskToRetry) { if (failureException instanceof QueuedPushTooLargeException) { List<T> resubmissionTasks = taskToRetry.splitTask(); // there are split tasks, so go ahead and return them // otherwise, nothing got split, so this should just get queued up if (resubmissionTasks.size() > 1) { return resubmissionTasks; } } logger.warning("Cannot post push data result to Wavefront servers. Will enqueue and retry later: " + failureException); addTaskToSmallestQueue(taskToRetry); return Collections.emptyList(); } private void addTaskToSmallestQueue(ResubmissionTask taskToRetry) { TaskQueue<ResubmissionTask> queue = getSmallestQueue(); if (queue != null) { synchronized (queue) { queue.add(taskToRetry); } } else { logger.warning("CRITICAL: No retry queues found. Losing points!"); } } private static void parsePostingResponse(Response response) { if (response.getStatus() != Response.Status.OK.getStatusCode()) { if (response.getStatus() == Response.Status.NOT_ACCEPTABLE.getStatusCode()) { throw new RejectedExecutionException("Response not accepted by server: " + response.getStatus()); } else if (response.getStatus() == Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode()) { throw new QueuedPushTooLargeException("Request too large: " + response.getStatus()); } else { throw new RuntimeException("Server error: " + response.getStatus()); } } } @Override public void agentError(UUID agentId, String details) { wrapped.agentError(agentId, details); } @Override public void agentConfigProcessed(UUID agentId) { wrapped.agentConfigProcessed(agentId); } @Override public void hostConnectionFailed(UUID agentId, UUID hostId, String details) { wrapped.hostConnectionFailed(agentId, hostId, details); } @Override public void hostConnectionEstablished(UUID agentId, UUID hostId) { wrapped.hostConnectionEstablished(agentId, hostId); } @Override public void hostAuthenticated(UUID agentId, UUID hostId) { wrapped.hostAuthenticated(agentId, hostId); } public static class PostWorkUnitResultTask extends ResubmissionTask { @VisibleForTesting final UUID agentId; @VisibleForTesting final UUID workUnitId; @VisibleForTesting final UUID hostId; @VisibleForTesting final ShellOutputDTO shellOutputDTO; public PostWorkUnitResultTask(UUID agentId, UUID workUnitId, UUID hostId, ShellOutputDTO shellOutputDTO) { this.agentId = agentId; this.workUnitId = workUnitId; this.hostId = hostId; this.shellOutputDTO = shellOutputDTO; } @Override public void execute(Object callback) { parsePostingResponse(service.postWorkUnitResult(currentAgentId, workUnitId, hostId, shellOutputDTO)); } @Override public List<PostWorkUnitResultTask> splitTask() { // doesn't make sense to split this, so just return a new task return of(new PostWorkUnitResultTask(agentId, workUnitId, hostId, shellOutputDTO)); } } public static class PostPushDataResultTask extends ResubmissionTask<PostPushDataResultTask> { private final UUID agentId; private final UUID workUnitId; private final Long currentMillis; private final String format; private final String pushData; public PostPushDataResultTask(UUID agentId, UUID workUnitId, Long currentMillis, String format, String pushData) { this.agentId = agentId; this.workUnitId = workUnitId; this.currentMillis = currentMillis; this.format = format; this.pushData = pushData; } @Override public void execute(Object callback) { parsePostingResponse(service.postPushData(currentAgentId, workUnitId, currentMillis, format, pushData)); } @Override public List<PostPushDataResultTask> splitTask() { // pull the pushdata back apart to split and put back together List<PostPushDataResultTask> splitTasks = Lists.newArrayList(); List<String> pushDatum = ChannelStringHandler.unjoinPushData(pushData); // split data into 2 tasks w/ half the strings if (pushDatum.size() > 1) { int halfPoints = pushDatum.size() / 2; splitTasks.add(new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, ChannelStringHandler.joinPushData(new ArrayList<>(pushDatum.subList(0, halfPoints))))); splitTasks.add(new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, ChannelStringHandler.joinPushData(new ArrayList<>(pushDatum.subList(halfPoints, pushDatum.size()))) )); } else { // 1 or 0 splitTasks.add(new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, pushData)); } return splitTasks; } @VisibleForTesting public UUID getAgentId() { return agentId; } @VisibleForTesting public UUID getWorkUnitId() { return workUnitId; } @VisibleForTesting public Long getCurrentMillis() { return currentMillis; } @VisibleForTesting public String getFormat() { return format; } @VisibleForTesting public String getPushData() { return pushData; } } }
package se.kb.libris.whelks.basic; import java.io.OutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.logging.Logger; import java.util.logging.Level; /* import org.json.simple.JSONArray; import org.json.simple.JSONObject; */ import se.kb.libris.whelks.*; import se.kb.libris.whelks.api.*; import se.kb.libris.whelks.component.*; import se.kb.libris.whelks.exception.WhelkRuntimeException; /* import se.kb.libris.whelks.persistance.JSONInitialisable; import se.kb.libris.whelks.persistance.JSONSerialisable; */ import se.kb.libris.whelks.plugin.*; public class BasicWhelk implements Whelk, Pluggable { //, JSONInitialisable, JSONSerialisable { private Random random = new Random(); private final List<Plugin> plugins = new LinkedList<Plugin>(); private String prefix; public BasicWhelk(String pfx) { this.prefix = ((pfx != null && pfx.startsWith("/")) ? pfx.substring(1) : pfx); } @Override public String getPrefix() { return this.prefix; } @Override public URI store(Document d) { if (d.getIdentifier() == null || !d.getIdentifier().toString().startsWith("/"+prefix)) { d.setIdentifier(mintIdentifier(d)); } List<Document> docs = new ArrayList<Document>(); docs.add(d); store(docs); return d.getIdentifier(); } @Override public void store(Iterable<Document> docs) { // Pre storage operations for (Document doc : docs) { if (doc.getIdentifier() == null || !doc.getIdentifier().toString().startsWith("/"+prefix)) { doc.setIdentifier(mintIdentifier(doc)); } for (Trigger t : getTriggers()) { if (t.isEnabled()) { t.beforeStore(doc); } } } for (FormatConverter fc : getFormatConverters()) { if (((List)docs).size() > 0 && fc.getRequiredFormat().equals(((Document)((List)docs).get(0)).getFormat())) { List<Document> convertedList = new ArrayList<Document>(); for (Document doc : ((List<Document>)docs)) { convertedList.addAll(fc.convert(doc)); } docs = convertedList; } } if (docs != null && ((List)docs).size() > 0) { for (Component c : getComponents()) { if (c instanceof Storage) { ((Storage)c).store(docs, this.prefix); } if (c instanceof Index) { List<Document> idocs = new ArrayList<Document>(); boolean formatConverted = false; for (IndexFormatConverter ifc : getIndexFormatConverters()) { formatConverted = true; for (Document doc : ((List<Document>)docs)) { idocs.addAll(ifc.convert(doc)); } } if (!formatConverted) { idocs.addAll((Collection)docs); } for (Document d : idocs) { ((Index)c).index(d, this.prefix); } } if (c instanceof QuadStore) { for (Document doc : docs) { ((QuadStore)c).update(doc.getIdentifier(), doc); } } } // Post storage operations for (Document doc : docs) { for (Trigger t : getTriggers()) { if (t.isEnabled()) { t.afterStore(doc); } } } } } /** * Post construct init method. */ @Override public void init() { } @Override public Document get(URI uri) { Document d = null; for (Component c: getComponents()) { if (c instanceof Storage) { d = ((Storage)c).get(uri, this.prefix); if (d != null) { Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Document found in storage " + c); return d; } } } return d; } @Override public void delete(URI uri) { // before triggers for (Trigger t: getTriggers()) t.beforeDelete(uri); for (Component c: getComponents()) if (c instanceof Storage) ((Storage)c).delete(uri, this.prefix); else if (c instanceof Index) ((Index)c).delete(uri, this.prefix); else if (c instanceof QuadStore) ((QuadStore)c).delete(uri); // after triggers for (Trigger t: getTriggers()) t.afterDelete(uri); } @Override public SearchResult query(String query) { return query(new Query(query)); } @Override public SearchResult query(Query query) { return query(query, null); } public SearchResult query(Query query, String indexType) { return query(query, this.prefix, indexType); } public SearchResult query(Query query, String prefix, String indexType) { for (Component c: getComponents()) if (c instanceof Index) return ((Index)c).query(query, prefix, indexType); throw new WhelkRuntimeException("Whelk has no index for searching"); } @Override public LookupResult<? extends Document> lookup(Key key) { for (Component c: getComponents()) if (c instanceof Storage) return ((Storage)c).lookup(key); throw new WhelkRuntimeException("Whelk has no storage for searching"); } @Override public SparqlResult sparql(String query) { for (Component c: getComponents()) if (c instanceof QuadStore) return ((QuadStore)c).sparql(query); throw new WhelkRuntimeException("Whelk has no quadstore component."); } @Override public Iterable<Document> log() { for (Component c: getComponents()) if (c instanceof Storage) return ((Storage)c).getAll(this.prefix); throw new WhelkRuntimeException("Whelk has no storage for searching"); } @Override public Iterable<Document> log(int startIndex) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Iterable<Document> log(URI identifier) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Iterable<Document> log(Date since) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void destroy() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Document createDocument() { return new BasicDocument(); } @Override public void reindex() { throw new UnsupportedOperationException("Not supported yet."); } private List<KeyGenerator> getKeyGenerators() { List<KeyGenerator> ret = new LinkedList<KeyGenerator>(); for (Plugin plugin: plugins) if (plugin instanceof KeyGenerator) ret.add((KeyGenerator)plugin); return ret; } private List<DescriptionExtractor> getDescriptionExtractors() { List<DescriptionExtractor> ret = new LinkedList<DescriptionExtractor>(); for (Plugin plugin: plugins) if (plugin instanceof DescriptionExtractor) ret.add((DescriptionExtractor)plugin); return ret; } private List<LinkFinder> getLinkFinders() { List<LinkFinder> ret = new LinkedList<LinkFinder>(); for (Plugin plugin: plugins) if (plugin instanceof LinkFinder) ret.add((LinkFinder)plugin); return ret; } private List<Trigger> getTriggers() { List<Trigger> ret = new LinkedList<Trigger>(); for (Plugin plugin: plugins) if (plugin instanceof Trigger) ret.add((Trigger)plugin); return ret; } protected Iterable<Storage> getStorages() { TreeSet<Storage> ret = new TreeSet<Storage>(); for (Plugin plugin: plugins) if (plugin instanceof Storage) ret.add((Storage)plugin); return ret; } protected Iterable<FormatConverter> getFormatConverters() { TreeSet<FormatConverter> ret = new TreeSet<FormatConverter>(); for (Plugin plugin: plugins) if (plugin instanceof FormatConverter) ret.add((FormatConverter)plugin); return ret; } protected Iterable<IndexFormatConverter> getIndexFormatConverters() { TreeSet<IndexFormatConverter> ret = new TreeSet<IndexFormatConverter>(); for (Plugin plugin: plugins) if (plugin instanceof IndexFormatConverter) ret.add((IndexFormatConverter)plugin); return ret; } protected Iterable<Component> getComponents() { TreeSet<Component> ret = new TreeSet<Component>(); for (Plugin plugin: plugins) if (plugin instanceof Component) ret.add((Component)plugin); return ret; } protected Iterable<API> getAPIs() { List<API> ret = new LinkedList<API>(); for (Plugin plugin: plugins) if (plugin instanceof API) ret.add((API)plugin); return ret; } protected void initializePlugins() { for (Plugin plugin : plugins) plugin.init(this.prefix); } @Override public void addPlugin(Plugin plugin) { synchronized (plugins) { if (plugin instanceof WhelkAware) { ((WhelkAware)plugin).setWhelk(this); } plugins.add(plugin); initializePlugins(); } } @Override public void addPluginIfNotExists(Plugin plugin) { synchronized (plugins) { if (! plugins.contains(plugin)) { addPlugin(plugin); } } } @Override public void removePlugin(String id) { synchronized (plugins) { ListIterator<Plugin> li = plugins.listIterator(); while (li.hasNext()) { Plugin p = li.next(); if (p.getId().equals(id)) li.remove(); } } } @Override public Iterable<? extends Plugin> getPlugins() { return plugins; } private URI mintIdentifier(Document d) { try { return new URI("/"+prefix.toString() +"/"+ UUID.randomUUID()); } catch (URISyntaxException ex) { throw new WhelkRuntimeException("Could not mint URI", ex); } } }
package org.wikipedia.history; import android.app.*; import android.content.*; import android.database.*; import android.net.*; import android.os.*; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.*; import android.text.Editable; import android.text.TextWatcher; import android.view.*; import android.widget.*; import com.squareup.picasso.*; import org.wikipedia.*; import org.wikipedia.page.*; import org.wikipedia.pageimages.*; import java.text.*; import java.util.*; public class HistoryActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<Cursor> { private ListView historyEntryList; private TextView historyEmptyMessage; private HistoryEntryAdapter adapter; private EditText entryFilter; private WikipediaApp app; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (WikipediaApp)getApplicationContext(); setContentView(R.layout.activity_history); historyEntryList = (ListView) findViewById(R.id.history_entry_list); historyEmptyMessage = (TextView) findViewById(R.id.history_empty_message); entryFilter = (EditText) findViewById(R.id.history_search_list); adapter = new HistoryEntryAdapter(this, null, true); historyEntryList.setAdapter(adapter); historyEntryList.setEmptyView(historyEmptyMessage); entryFilter.addTextChangedListener( new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { // Do nothing } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { // Do nothing } @Override public void afterTextChanged(Editable editable) { getSupportLoaderManager().restartLoader(0, null, HistoryActivity.this); if (editable.length() == 0) { historyEmptyMessage.setText(R.string.history_empty_message); } else { historyEmptyMessage.setText(getString(R.string.history_search_empty_message, editable.toString())); } } }); historyEntryList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Utils.hideSoftKeyboard(HistoryActivity.this); HistoryEntry oldEntry = (HistoryEntry) view.getTag(); HistoryEntry newEntry = new HistoryEntry(oldEntry.getTitle(), HistoryEntry.SOURCE_HISTORY); Intent intent = new Intent(); intent.setClass(HistoryActivity.this, PageActivity.class); intent.setAction(PageActivity.ACTION_PAGE_FOR_TITLE); intent.putExtra(PageActivity.EXTRA_PAGETITLE, oldEntry.getTitle()); intent.putExtra(PageActivity.EXTRA_HISTORYENTRY, newEntry); startActivity(intent); } }); getSupportLoaderManager().initLoader(0, null, this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { String selection = null; String[] selectionArgs = null; if (entryFilter.getText().length() != 0) { // FIXME: Find ways to not have to hard code column names selection = "UPPER(history.title) LIKE UPPER(?)"; selectionArgs = new String[]{"%" + entryFilter.getText().toString() + "%"}; } return new CursorLoader( this, Uri.parse(HistoryEntry.PERSISTANCE_HELPER.getBaseContentURI().toString() + "/" + PageImage.PERSISTANCE_HELPER.getTableName()), null, selection, selectionArgs, "timestamp DESC"); } @Override public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { adapter.swapCursor(cursorLoader); supportInvalidateOptionsMenu(); } @Override public void onLoaderReset(Loader<Cursor> cursorLoaderLoader) { adapter.changeCursor(null); } private class HistoryEntryAdapter extends CursorAdapter { public HistoryEntryAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { return getLayoutInflater().inflate(R.layout.item_history_entry, viewGroup, false); } private String getDateString(Date date) { return DateFormat.getDateInstance().format(date); } private int getImageForSource(int source) { switch (source) { case HistoryEntry.SOURCE_INTERNAL_LINK: return R.drawable.link; case HistoryEntry.SOURCE_EXTERNAL_LINK: return R.drawable.external; case HistoryEntry.SOURCE_HISTORY: return R.drawable.external; case HistoryEntry.SOURCE_SEARCH: return R.drawable.search; case HistoryEntry.SOURCE_SAVED_PAGE: return R.drawable.external; case HistoryEntry.SOURCE_LANGUAGE_LINK: return R.drawable.link; case HistoryEntry.SOURCE_RANDOM: return R.drawable.random; case HistoryEntry.SOURCE_MAIN_PAGE: return R.drawable.link; default: throw new RuntimeException("Unknown source id encountered"); } } @Override public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView) view.findViewById(R.id.history_title); ImageView source = (ImageView) view.findViewById(R.id.history_source); ImageView thumbnail = (ImageView) view.findViewById(R.id.history_thumbnail); HistoryEntry entry = HistoryEntry.PERSISTANCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); source.setImageResource(getImageForSource(entry.getSource())); view.setTag(entry); Picasso.with(HistoryActivity.this) .load(cursor.getString(5)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); // Check the previous item, see if the times differe enough // If they do, display the section header. // Always do it this is the first item. String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.PERSISTANCE_HELPER.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.history_section_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_history, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.menu_clear_all_history).setEnabled(historyEntryList.getCount() > 0); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_clear_all_history: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_title_clear_history); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Clear history! app.getPersister(HistoryEntry.class).deleteAll(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Uh, do nothing? } }); builder.create().show(); return true; default: throw new RuntimeException("Unknown menu item clicked!"); } } }
package com.example.moodly; import android.app.Activity; import android.support.design.widget.FloatingActionButton; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.view.KeyEvent; import android.widget.EditText; import android.widget.Spinner; import com.example.moodly.Activities.LoginScreen; import com.example.moodly.Activities.ViewMood; import com.example.moodly.Activities.ViewMoodList; import com.robotium.solo.Solo; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; public class MoodIntentTest extends ActivityInstrumentationTestCase2<LoginScreen> { private Solo solo; public MoodIntentTest() { super(com.example.moodly.Activities.LoginScreen.class); } public void setUp() throws Exception{ solo = new Solo(getInstrumentation(), getActivity()); } public void testStart() throws Exception { Activity activity = getActivity(); } public void actionLogin() { solo.assertCurrentActivity("Wrong Activity", LoginScreen.class); solo.enterText((EditText) solo.getView(R.id.userName), "Minh"); solo.clickOnButton("Login"); solo.assertCurrentActivity("Wrong Activities", ViewMoodList.class); } public void actionLogOut() { solo.sendKey(solo.MENU); solo.clickOnText("Log Out"); solo.assertCurrentActivity("Wrong Activity", LoginScreen.class); } protected String getRDString() { String CHARS = "abcdefghijklmnopqrstuvwxyz1234567890"; StringBuilder stringBuilder = new StringBuilder(); Random rnd = new Random(); while (stringBuilder.length() < 18) { int index = (int) (rnd.nextFloat() * CHARS.length()); stringBuilder.append(CHARS.charAt(index)); } String Str = stringBuilder.toString(); return Str; } public void test1_AddMood() { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.fab)); solo.assertCurrentActivity("Wrong Activities", ViewMood.class); Spinner emoij = (Spinner) solo.getView(R.id.spinner_emotion); solo.clickOnView(emoij); solo.clickOnText("Anger"); solo.clickOnView((EditText) solo.getView(R.id.view_date)); solo.clickOnText("OK"); solo.clickOnText("OK"); solo.enterText((EditText) solo.getView(R.id.view_reason), "test reason"); solo.clickOnText("Save Mood"); solo.assertCurrentActivity("Wrong Activity", ViewMoodList.class); assertEquals(solo.searchText("Anger"), true); actionLogOut(); } public void t2_FilterByMood () { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.filterButton)); solo.clickOnText("Sad"); solo.clickOnText("OK"); solo.clickOnText("No"); solo.clickOnText("Yes"); ArrayList<String> moods = new ArrayList<>(Arrays.asList("Anger","Confusion","Disgust","Fear","Shame","Surprise")); for (String mood: moods) { Log.i("Mood", mood); assertFalse(solo.searchText(mood)); } actionLogOut(); } public void test3_EditMood() { actionLogin(); solo.clickLongInList(0); solo.clickOnText("View/Edit"); solo.assertCurrentActivity("Wrong Activity", ViewMood.class); solo.clickOnView((Spinner) solo.getView(R.id.spinner_emotion)); solo.clickOnText("Sad"); solo.clickOnText("Save Mood"); solo.assertCurrentActivity("Wrong Activity", ViewMoodList.class); assertEquals(solo.searchText("Anger"), false); assertEquals(solo.searchText("Sad"), true); actionLogOut(); } public void test4_DeleteMood() { actionLogin(); solo.clickLongInList(0); solo.clickOnText("Delete"); assertEquals(solo.searchText("Sad"), false); actionLogOut(); } public void test5_AddComment() { actionLogin(); solo.clickOnText("Following"); solo.clickLongOnText("haha"); solo.clickOnText("View"); solo.clickOnText("Add Comment"); String comment = getRDString(); char[] ch_array = comment.toCharArray(); for(int i=0;i<ch_array.length;i++) { solo.sendKey( android_keycode(ch_array[i]) ); } solo.clickOnText("OK"); solo.clickOnText("View Comments"); assertTrue(solo.searchText(comment)); solo.goBack(); solo.goBack(); actionLogOut(); } public int android_keycode(char ch) { int keycode = ch;//String.valueOf(ch).codePointAt(0); Log.v("T","in fun : "+ch+" : "+keycode + ""); if(keycode>=97 && keycode <=122) { Log.v("T","atoz : "+ch+" : "+keycode + " : " + (keycode-68)); return keycode-68; } else if(keycode>=65 && keycode <=90) { Log.v("T","atoz : "+ch+" : "+keycode + " : " + (keycode-36)); return keycode-36; } else if(keycode>=48 && keycode <=57) { Log.v("T","0to9"+ch+" : "+keycode + " : " + (keycode-41)); return keycode-41; } else if(keycode==64) { Log.v("T","@"+ch+" : "+keycode + " : " + "77"); return KeyEvent.KEYCODE_AT; } else if(ch=='.') { Log.v("T","DOT "+ch+" : "+keycode + " : " + "158"); return KeyEvent.KEYCODE_PERIOD; } else if(ch==',') { Log.v("T","comma "+ch+" : "+keycode + " : " + "55"); return KeyEvent.KEYCODE_COMMA; } return 62; } }
package com.a2017hkt15.sortaddr; import android.graphics.Bitmap; import android.util.Log; import com.skp.Tmap.TMapMarkerItem; import com.skp.Tmap.TMapPoint; import com.skp.Tmap.TMapView; import java.util.ArrayList; public class MarkerController { private boolean isStartExist; private boolean isEndExist; private int endIndex = -1; private ArrayList<TMapMarkerItem> markerList; private float markerCenterDx = 0.5f; private float markerCenterDy = 1.0f; private TMapView tmapView; private Bitmap startMarkerIcon; private Bitmap passMarkerIcon; private Bitmap endMarkerIcon; private Bitmap poiIcon; private Bitmap[] numberMarkerIcon; public MarkerController (TMapView tmapView, Bitmap startMarkerIcon, Bitmap passMarkerIcon, Bitmap[] markerNumberIcon, Bitmap endMarkerIcon, Bitmap poiIcon) { this.tmapView = tmapView; this.isStartExist = false; this.isEndExist = false; this.startMarkerIcon = startMarkerIcon; this.passMarkerIcon = passMarkerIcon; this.numberMarkerIcon = markerNumberIcon; this.endMarkerIcon = endMarkerIcon; this.poiIcon = poiIcon; this.markerList = new ArrayList<TMapMarkerItem>(); for (int i = 0; i < 4; i++) { markerList.add(new TMapMarkerItem()); } } public void addMarker(float latitude, float longitude, String placeName) { TMapPoint placePoint = new TMapPoint(latitude, longitude); TMapMarkerItem placeMarker = new TMapMarkerItem(); placeMarker.setTMapPoint(placePoint); placeMarker.setID(placeName); placeMarker.setName(placeName); placeMarker.setVisible(TMapMarkerItem.VISIBLE); placeMarker.setIcon(passMarkerIcon); placeMarker.setPosition(markerCenterDx, markerCenterDy); placeMarker.setCanShowCallout(true); placeMarker.setAutoCalloutVisible(true); placeMarker.setCalloutTitle(placeName); placeMarker.setCalloutLeftImage(passMarkerIcon); placeMarker.setCalloutRightButtonImage(poiIcon); tmapView.addMarkerItem(placeMarker.getID(), placeMarker); markerList.add(placeMarker); } public void setStartMarker(float latitude, float longitude, String placeName) { removeMarker(0); TMapPoint placePoint = new TMapPoint(latitude, longitude); TMapMarkerItem placeMarker = new TMapMarkerItem(); placeMarker.setTMapPoint(placePoint); placeMarker.setID(placeName); placeMarker.setName(placeName); placeMarker.setVisible(TMapMarkerItem.VISIBLE); placeMarker.setIcon(startMarkerIcon); placeMarker.setPosition(markerCenterDx, markerCenterDy); placeMarker.setCanShowCallout(true); placeMarker.setAutoCalloutVisible(true); placeMarker.setCalloutTitle(placeName); placeMarker.setCalloutLeftImage(startMarkerIcon); placeMarker.setCalloutRightButtonImage(poiIcon); tmapView.addMarkerItem(placeMarker.getID(), placeMarker); markerList.add(0, placeMarker); isStartExist = true; } public void setMarkerNumber(int index, int number) { if (number == 0) return; if (isEndExist && endIndex == markerList.size() - 1) return; markerList.get(index).setIcon(numberMarkerIcon[number]); tmapView.removeMarkerItem(markerList.get(index).getID()); tmapView.addMarkerItem(markerList.get(index).getID(), markerList.get(index)); } public void setEndIndex(int index) { if (index == -1) { this.endIndex = index; this.isEndExist = false; return; } if (isEndExist) { markerList.get(endIndex).setIcon(passMarkerIcon); tmapView.removeMarkerItem(markerList.get(endIndex).getID()); tmapView.addMarkerItem(markerList.get(endIndex).getID(), markerList.get(endIndex)); } if (index == 0) { this.endIndex = index; this.isEndExist = true; return; } else { this.endIndex = index; this.isEndExist = true; markerList.get(index).setIcon(endMarkerIcon); tmapView.removeMarkerItem(markerList.get(index).getID()); tmapView.addMarkerItem(markerList.get(index).getID(), markerList.get(index)); } } public int getEndIndex() { return endIndex; } // Parameter : public void removeMarker(int markerIndex) { if (markerList.size() <= markerIndex) return; else if (markerList.get(markerIndex).getID() == null) return; try { tmapView.removeMarkerItem(markerList.get(markerIndex).getID()); } catch (Exception e) { } markerList.remove(markerIndex); } // (true : , false : ) public void removeAllMarker(boolean fromStart) { int isStart; if (fromStart) { isStart = -1; isStartExist = false; } else isStart = 0; for (int index = markerList.size() - 1; index > isStart; index removeMarker(index); } public ArrayList<TMapMarkerItem> getMarkerList() { return markerList; } }
package com.android.infosessions; import android.app.Fragment; import android.app.LoaderManager; import android.app.SearchManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.android.infosessions.data.DbHelper; import com.android.infosessions.data.SessionContract.SessionEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class CurrentFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { public static final String LOG_TAG = MainActivity.class.getName(); private ListView sessionsListView; private static final String UWAPI_REQUEST_URL = "https://api.uwaterloo.ca/v2/resources/infosessions.json?key=123afda14d0a233ecb585591a95e0339"; private static final int LOADER_ID = 0; private SessionCursorAdapter mCursorAdapter; private String mQuery; public CurrentFragment() { } // Required empty public constructor @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.sessions_list, container, false); sessionsListView = (ListView) rootView.findViewById(R.id.list); mCursorAdapter = new SessionCursorAdapter(getContext(), null); sessionsListView.setAdapter(mCursorAdapter); FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab); fab.setVisibility(View.VISIBLE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SessionTask sessionTask = new SessionTask(); sessionTask.execute(UWAPI_REQUEST_URL); } }); sessionsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getContext(), DetailActivity.class); Uri currentPetUri = ContentUris.withAppendedId(SessionEntry.CONTENT_URI, id); // Set the URI on the data field of the intent intent.setData(currentPetUri); // Launch the {@link EditorActivity} to display the data for the current pet. startActivity(intent); } }); getLoaderManager().initLoader(LOADER_ID, null, this); return rootView; } public class SessionTask extends AsyncTask<String, Void, ArrayList<Session>> { @Override protected ArrayList<Session> doInBackground(String... params) { ArrayList<Session> sessions = QueryUtils.fetchInfos(params[0], getContext()); return sessions; } @Override protected void onPostExecute(ArrayList<Session> sessions) { super.onPostExecute(sessions); insertSession(sessions); Toast toast = Toast.makeText(getContext(), "Updated seconds ago", Toast.LENGTH_SHORT); toast.show(); } } private void insertSession(ArrayList<Session> sessions) { for(int i = 0; i < sessions.size(); i++) { Session session = sessions.get(i); String mEmployer = session.getEmployer(); String mStartTime = session.getStartTime(); String mEndTime = session.getEndTime(); String mDate = session.getDate(); String mDay = session.getDay(); long mMinutes = dayToMilliSeconds(mDate); String mWebsite = session.getWebsite(); String mLink = session.getLink(); String mDescription = session.getDescription(); String mLogo = session.getLogoString(); if (mDescription.isEmpty()) { mDescription = "Employer's Description is not provided."; } String mBuildingName = session.getBuildingName(); String mRoom = session.getBuildingRoom(); String mCode = session.getBuildingCode(); String mMapUrl = session.getMapUrl(); String mAudience = session.getAudience(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(SessionEntry.COLUMN_SESSION_EMPLOYER, mEmployer); values.put(SessionEntry.COLUMN_SESSION_START_TIME, mStartTime); values.put(SessionEntry.COLUMN_SESSION_END_TIME, mEndTime); values.put(SessionEntry.COLUMN_SESSION_DATE, mDate); values.put(SessionEntry.COLUMN_SESSION_DAY, mDay); values.put(SessionEntry.COLUMN_SESSION_MILLISECONDS, mMinutes); values.put(SessionEntry.COLUMN_SESSION_WEBSITE, mWebsite); values.put(SessionEntry.COLUMN_SESSION_LINK, mLink); values.put(SessionEntry.COLUMN_SESSION_AUDIENCE, mAudience); values.put(SessionEntry.COLUMN_SESSION_DESCRIPTION, mDescription); values.put(SessionEntry.COLUMN_SESSION_BUILDING_CODE, mCode); values.put(SessionEntry.COLUMN_SESSION_BUILDING_NAME, mBuildingName); values.put(SessionEntry.COLUMN_SESSION_BUILDING_ROOM, mRoom); values.put(SessionEntry.COLUMN_SESSION_MAP_URL, mMapUrl); values.put(SessionEntry.COLUMN_SESSION_LOGO, mLogo); // Insert a new row for pet in the database, returning the ID of that new row. Uri newUri = getActivity().getContentResolver().insert(SessionEntry.CONTENT_URI, values); } } public long dayToMilliSeconds(String data) { String[] mDay = data.split("-"); int day = Integer.parseInt(mDay[2]); int month = Integer.parseInt(mDay[1]); int year = Integer.parseInt(mDay[0]); Date date = new Date(year, month, day); return date.getTime(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Define a projection that specifies the columns from the table we care about. Calendar rightNow = Calendar.getInstance(); int day = rightNow.get(rightNow.DAY_OF_MONTH); int month = rightNow.get(rightNow.MONTH) + 1; int year = rightNow.get(rightNow.YEAR); Date date = new Date(year, month, day); long milliSeconds = date.getTime(); String[] projection = { SessionEntry._ID, SessionEntry.COLUMN_SESSION_EMPLOYER, SessionEntry.COLUMN_SESSION_START_TIME, SessionEntry.COLUMN_SESSION_END_TIME, SessionEntry.COLUMN_SESSION_DATE, SessionEntry.COLUMN_SESSION_DAY, SessionEntry.COLUMN_SESSION_MILLISECONDS, SessionEntry.COLUMN_SESSION_WEBSITE, SessionEntry.COLUMN_SESSION_LINK, SessionEntry.COLUMN_SESSION_DESCRIPTION, SessionEntry.COLUMN_SESSION_BUILDING_CODE, SessionEntry.COLUMN_SESSION_BUILDING_NAME, SessionEntry.COLUMN_SESSION_BUILDING_ROOM, SessionEntry.COLUMN_SESSION_MAP_URL, SessionEntry.COLUMN_SESSION_LOGO, SessionEntry.COLUMN_SESSION_AUDIENCE}; DbHelper mDbHelper = new DbHelper(getContext()); SQLiteDatabase db = mDbHelper.getReadableDatabase(); // Perform a query on the pets table Cursor cursor = db.query( SessionEntry.TABLE_NAME, // The table to query projection, // The columns to return null, // The columns for the WHERE clause null, // The values for the WHERE clause null, // Don't group the rows null, // Don't filter by row groups null); if(cursor.getCount() == 0) { SessionTask sessionTask = new SessionTask(); sessionTask.execute(UWAPI_REQUEST_URL); } String selection = SessionEntry.COLUMN_SESSION_MILLISECONDS + ">?"; String[] selectionArgs = { String.valueOf(milliSeconds) }; // This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(getContext(), SessionEntry.CONTENT_URI, projection, selection, selectionArgs, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Update {@link PetCursorAdapter} with this new cursor containing updated pet data mCursorAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { // Callback called when the data needs to be deleted mCursorAdapter.swapCursor(null); } }
package com.buggycoder.tickmenot.ui; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.ContentResolver; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.buggycoder.tickmenot.R; import com.buggycoder.tickmenot.event.NotifAccessChangedEvent; import com.buggycoder.tickmenot.event.NotifPerstEvent; import com.buggycoder.tickmenot.model.WhatsappNotif; import com.squareup.otto.Subscribe; import java.util.Date; import butterknife.InjectView; import timber.log.Timber; public class MainActivity extends BaseActivity { private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners"; private static final String SETTINGS_NOTIF_LISTENER = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"; private String mPackageName; private NotifListFragment mNotifListFragment; @InjectView(R.id.requestNotifAccess) Button mRequestNotifAccess; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRequestNotifAccess.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestNotifAccess(); } }); FragmentManager fm = getFragmentManager(); mNotifListFragment = (NotifListFragment) fm.findFragmentByTag(NotifListFragment.TAG); if (savedInstanceState == null) { FragmentTransaction transaction = fm.beginTransaction(); mNotifListFragment = new NotifListFragment(); transaction.replace(R.id.contentPane, mNotifListFragment, NotifListFragment.TAG); transaction.commit(); } mPackageName = getPackageName(); } @Override protected void onResume() { super.onResume(); updateUI(); } private void updateUI() { updateNotifAccessView(hasNotifAccessPermission()); } private boolean hasNotifAccessPermission() { ContentResolver contentResolver = getContentResolver(); String listeners = Settings.Secure.getString(contentResolver, ENABLED_NOTIFICATION_LISTENERS); return (listeners != null && listeners.contains(mPackageName)); } private void requestNotifAccess() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, getString(R.string.request_notif_access), Toast.LENGTH_SHORT).show(); startActivity(new Intent(SETTINGS_NOTIF_LISTENER)); } }); } private void updateNotifAccessView(final boolean isAccessEnabled) { runOnUiThread(new Runnable() { @Override public void run() { mRequestNotifAccess.setVisibility(isAccessEnabled ? View.GONE : View.VISIBLE); } }); } @Subscribe public void onNotifAccessChangedEvent(final NotifAccessChangedEvent event) { updateNotifAccessView(event.isAllowed); } @Subscribe public void onNotifPerstEvent(final NotifPerstEvent notifPerst) { runOnUiThread(new Runnable() { @Override public void run() { if (mNotifListFragment != null) { mNotifListFragment.updateNotifs(notifPerst.notifs); } } }); if (notifPerst.notifs.size() > 0) { WhatsappNotif notif = notifPerst.notifs.get(notifPerst.notifs.size() - 1); String status = notifPerst.isSuccess ? "Success" : "Error"; String msg = String.format("%s: %s: %s | %s", status, notif.sender, notif.message, new Date(notif.postTime)); Timber.d(msg); } } }
package com.czbix.v2ex.ui.fragment; import android.animation.ObjectAnimator; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Intent; import android.os.Bundle; import android.support.annotation.StringRes; import android.support.design.widget.AppBarLayout; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.ShareActionProvider; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.ImageButton; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.czbix.v2ex.AppCtx; import com.czbix.v2ex.R; import com.czbix.v2ex.common.PrefStore; import com.czbix.v2ex.common.UserState; import com.czbix.v2ex.common.exception.ConnectionException; import com.czbix.v2ex.common.exception.FatalException; import com.czbix.v2ex.common.exception.RemoteException; import com.czbix.v2ex.common.exception.RequestException; import com.czbix.v2ex.dao.DraftDao; import com.czbix.v2ex.dao.TopicDao; import com.czbix.v2ex.eventbus.TopicEvent; import com.czbix.v2ex.helper.MultiList; import com.czbix.v2ex.model.Comment; import com.czbix.v2ex.model.Ignorable; import com.czbix.v2ex.model.Member; import com.czbix.v2ex.model.Node; import com.czbix.v2ex.model.Thankable; import com.czbix.v2ex.model.Topic; import com.czbix.v2ex.model.TopicWithComments; import com.czbix.v2ex.model.db.Draft; import com.czbix.v2ex.network.HttpStatus; import com.czbix.v2ex.network.RequestHelper; import com.czbix.v2ex.ui.MainActivity; import com.czbix.v2ex.ui.TopicActivity; import com.czbix.v2ex.ui.adapter.CommentAdapter; import com.czbix.v2ex.ui.helper.ReplyFormHelper; import com.czbix.v2ex.ui.loader.AsyncTaskLoader.LoaderResult; import com.czbix.v2ex.ui.loader.TopicLoader; import com.czbix.v2ex.ui.util.Html; import com.czbix.v2ex.ui.widget.AvatarView; import com.czbix.v2ex.ui.widget.CommentView; import com.czbix.v2ex.ui.widget.DividerItemDecoration; import com.czbix.v2ex.ui.widget.HtmlMovementMethod; import com.czbix.v2ex.util.ExceptionUtils; import com.czbix.v2ex.util.ExecutorUtils; import com.czbix.v2ex.util.LogUtils; import com.czbix.v2ex.util.MiscUtils; import com.czbix.v2ex.util.TrackerUtils; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.eventbus.Subscribe; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import static android.support.v7.widget.RecyclerView.NO_POSITION; /** * A simple {@link Fragment} subclass. * Use the {@link TopicFragment#newInstance} factory method to * create an instance of this fragment. */ public class TopicFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks<LoaderResult<TopicWithComments>>, ReplyFormHelper.OnReplyListener, CommentView.OnCommentActionListener, HtmlMovementMethod.OnHtmlActionListener, NodeListFragment.OnNodeActionListener, AvatarView.OnAvatarActionListener { private static final String TAG = TopicFragment.class.getSimpleName(); private static final String ARG_TOPIC = "topic"; private static final int[] MENU_REQUIRED_LOGGED_IN = {R.id.action_ignore, R.id.action_reply, R.id.action_thank, R.id.action_fav}; private Topic mTopic; private SwipeRefreshLayout mLayout; private RecyclerView mCommentsView; private CommentAdapter mCommentAdapter; private ReplyFormHelper mReplyForm; private String mCsrfToken; private String mOnceToken; private Draft mDraft; private ImageButton mJumpBack; private MultiList<Comment> mComments; private boolean mIsLoaded; private int mCurPage; private int mMaxPage; private boolean mIsLoading; private boolean mLastIsFailed; private boolean mFavored; private MenuItem mFavIcon; private int mLastFocusPos; private LinearLayoutManager mCommentsLayoutManager; private AppBarLayout mAppBarLayout; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment TopicFragment. */ public static TopicFragment newInstance(Topic topic) { TopicFragment fragment = new TopicFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_TOPIC, topic); fragment.setArguments(args); return fragment; } public TopicFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mTopic = getArguments().getParcelable(ARG_TOPIC); } mComments = new MultiList<>(); mMaxPage = 1; mCurPage = 1; mIsLoaded = false; mLastFocusPos = NO_POSITION; setHasOptionsMenu(true); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_topic, container, false); initJumpBackButton(rootView); mLayout = ((SwipeRefreshLayout) rootView.findViewById(R.id.comments_layout)); mLayout.setOnRefreshListener(this); mCommentsView = (RecyclerView) mLayout.findViewById(R.id.comments); if (!mTopic.hasInfo()) { mCommentsView.setVisibility(View.INVISIBLE); } return rootView; } private void initCommentsView(TopicActivity activity) { mCommentsLayoutManager = new LinearLayoutManager(activity); mCommentsView.setLayoutManager(mCommentsLayoutManager); mCommentsView.addItemDecoration(new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL_LIST)); mCommentAdapter = new CommentAdapter(this, this, this, this); mCommentAdapter.setTopic(mTopic); mCommentAdapter.setDataSource(mComments); mCommentsView.setAdapter(mCommentAdapter); mCommentsView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(View view) { loadNextPageIfNeed(mCommentAdapter.getItemCount(), mCommentsView.getChildAdapterPosition(view)); } @Override public void onChildViewDetachedFromWindow(View view) { } }); } private void initJumpBackButton(View rootView) { mJumpBack = ((ImageButton) rootView.findViewById(R.id.btn_jump_back)); mJumpBack.setOnClickListener(v -> { Preconditions.checkState(mLastFocusPos != NO_POSITION, "why jump button show without dest"); scrollToPos(NO_POSITION, mLastFocusPos); }); mJumpBack.setOnLongClickListener(v -> { Toast.makeText(getActivity(), R.string.toast_jump_to_last_read_pos, Toast.LENGTH_SHORT).show(); return true; }); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final TopicActivity activity = (TopicActivity) getActivity(); activity.setTitle(null); final ActionBar actionBar = activity.getSupportActionBar(); Preconditions.checkNotNull(actionBar); actionBar.setDisplayHomeAsUpEnabled(true); mAppBarLayout = activity.getAppBarLayout(); initCommentsView(activity); setIsLoading(true); getLoaderManager().initLoader(0, null, this); } private void setIsLoading(boolean isLoading) { mIsLoading = isLoading; mLayout.setRefreshing(isLoading); } @Override public void onStart() { super.onStart(); mDraft = null; final Draft draft = DraftDao.get(mTopic.getId()); if (draft == null) { return; } if (draft.isExpired()) { DraftDao.delete(draft.mId); return; } mDraft = draft; } @Override public void onRefresh() { final TopicLoader loader = getLoader(); if (loader == null) { return; } loader.forceLoad(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (!mIsLoaded) { return; } inflater.inflate(R.menu.menu_topic, menu); if (UserState.getInstance().isLoggedIn()) { mFavIcon = menu.findItem(R.id.action_fav); updateFavIcon(); if (PrefStore.getInstance().isAlwaysShowReplyForm()) { menu.findItem(R.id.action_reply).setVisible(false); } } else { for (int i : MENU_REQUIRED_LOGGED_IN) { menu.findItem(i).setVisible(false); } } setupShareActionMenu(menu); super.onCreateOptionsMenu(menu, inflater); } private void updateFavIcon() { mFavIcon.setIcon(mFavored ? R.drawable.ic_favorite_white_24dp : R.drawable.ic_favorite_border_white_24dp); } private void setupShareActionMenu(Menu menu) { final MenuItem itemShare = menu.findItem(R.id.action_share); final Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, String.format("%s\n%s", mTopic.getTitle(), mTopic.getUrl())); if (MiscUtils.HAS_L) { itemShare.setOnMenuItemClickListener(item -> { startActivity(Intent.createChooser(shareIntent, null)); return true; }); } else { final ShareActionProvider actionProvider = new ShareActionProvider(getContext()); MenuItemCompat.setActionProvider(itemShare, actionProvider); actionProvider.setShareIntent(shareIntent); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_copy_link: MiscUtils.setClipboard(getActivity(), getString(R.string.desc_topic_link), String.format("%s\n%s", mTopic.getTitle(), mTopic.getUrl())); return true; case R.id.action_copy: MiscUtils.setClipboard(getActivity(), ClipData.newHtmlText(mTopic.getTitle(), String.format("%s\n%s", mTopic.getTitle(), Html.fromHtml(mTopic.getContent()).toString()), String.format("<p>%s</p>%s", mTopic.getTitle(), mTopic.getContent()))); return true; case R.id.action_refresh: setIsLoading(true); onRefresh(); return true; case R.id.action_fav: onFavTopic(); return true; case R.id.action_reply: toggleReplyForm(); return true; case R.id.action_thank: onThank(mTopic); return true; case R.id.action_ignore: onIgnore(mTopic, true); return true; } return super.onOptionsItemSelected(item); } private void toggleReplyForm() { boolean isShow; if (mReplyForm == null) { final View rootView = getView(); Preconditions.checkNotNull(rootView); final ViewStub viewStub = (ViewStub) rootView.findViewById(R.id.reply_form); mReplyForm = new ReplyFormHelper(getActivity(), viewStub, this); isShow = true; } else { mReplyForm.toggle(); isShow = mReplyForm.getVisibility(); } if (isShow) { mAppBarLayout.setExpanded(false); } TrackerUtils.onTopicSwitchReply(isShow); } @Override public Loader<LoaderResult<TopicWithComments>> onCreateLoader(int id, Bundle args) { String log = String.format("load topic, id: %d, title: %s", mTopic.getId(), mTopic.getTitle()); Crashlytics.log(log); LogUtils.d(TAG, log); return new TopicLoader(getActivity(), mTopic); } @Override public void onLoadFinished(Loader<LoaderResult<TopicWithComments>> loader, LoaderResult<TopicWithComments> result) { if (result.hasException()) { handleLoadException(result); return; } final TopicWithComments data = result.mResult; if (!mIsLoaded) { if (!mTopic.hasInfo()) { mCommentsView.setVisibility(View.VISIBLE); } if (data.mLastReadPos > 0) { // add one for topic in header mLastFocusPos = data.mLastReadPos + 1; updateJumpBackButton(); } } mIsLoaded = true; mLastIsFailed = false; mCommentAdapter.setTopic(data.mTopic); mTopic = data.mTopic; mCurPage = data.mCurPage; mMaxPage = data.mMaxPage; final int oldSize = mComments.listSize(); if (mCurPage > oldSize) { // new page mComments.addList(data.mComments); } else { mComments.setList(mCurPage - 1, data.mComments); } mCommentAdapter.notifyDataSetChanged(); mFavored = mTopic.isFavored(); mCsrfToken = data.mCsrfToken; mOnceToken = data.mOnceToken; getActivity().invalidateOptionsMenu(); if (mReplyForm == null && UserState.getInstance().isLoggedIn() && PrefStore.getInstance().isAlwaysShowReplyForm()) { toggleReplyForm(); } if (mDraft != null) { if (mReplyForm == null || !mReplyForm.getVisibility()) { toggleReplyForm(); } mReplyForm.setContent(mDraft.mContent); DraftDao.delete(mDraft.mId); mDraft = null; } setIsLoading(false); } private void handleLoadException(LoaderResult<TopicWithComments> result) { mLastIsFailed = true; setIsLoading(false); mCurPage = Math.max(mComments.listSize(), 1); boolean finishActivity; try { finishActivity = ExceptionUtils.handleExceptionNoCatch(this, result.mException); } catch (FatalException e) { if (e.getCause() instanceof RequestException) { final RequestException ex = (RequestException) e.getCause(); @StringRes int strId; switch (ex.getCode()) { case HttpStatus.SC_NOT_FOUND: strId = R.string.toast_topic_not_found; break; default: throw e; } if (getUserVisibleHint()) { Toast.makeText(getActivity(), strId, Toast.LENGTH_SHORT).show(); } finishActivity = true; } else { throw e; } } if (finishActivity) { getActivity().finish(); } } @Override public void onLoaderReset(Loader<LoaderResult<TopicWithComments>> loader) { mCommentAdapter.setDataSource(null); mComments.clear(); mCsrfToken = null; mOnceToken = null; } @Override public void onStop() { super.onStop(); if (mIsLoaded) { TopicDao.updateLastRead(mTopic); if (mReplyForm != null) { // save comment draft final Editable content = mReplyForm.getContent(); if (TextUtils.isEmpty(content)) { return; } DraftDao.update(mTopic.getId(), content.toString()); Toast.makeText(getActivity(), R.string.toast_reply_saved_as_draft, Toast.LENGTH_LONG).show(); } } } @Override public void onReply(final CharSequence content) { TrackerUtils.onTopicReply(); doActionRequest(() -> { try { RequestHelper.reply(mTopic, content.toString(), mOnceToken); } catch (ConnectionException | RemoteException e) { ExecutorUtils.runInUiThread(() -> doActionException(e)); return; } AppCtx.getEventBus().post(new TopicEvent(TopicEvent.TYPE_REPLY)); }, future -> { if (cancelRequest(future)) { mReplyForm.setContent(content); if (!mReplyForm.getVisibility()) { mReplyForm.toggle(); } } return null; }); mReplyForm.setVisibility(false); } private void doActionException(Exception e) { ExceptionUtils.handleExceptionNoCatch(this, e); getActivity().finish(); } @Subscribe public void onTopicEvent(TopicEvent e) { AppCtx.getEventBus().unregister(this); if (e.mType == TopicEvent.TYPE_REPLY) { if (mDraft != null) { DraftDao.delete(mDraft.mId); mDraft = null; } mReplyForm.setContent(null); } else if (e.mType == TopicEvent.TYPE_IGNORE_TOPIC) { Toast.makeText(getActivity(), R.string.toast_topic_ignored, Toast.LENGTH_LONG).show(); getActivity().finish(); return; } else if (e.mType == TopicEvent.TYPE_FAV_TOPIC) { updateFavIcon(); return; } onRefresh(); } private void doActionRequest(final Runnable sendAction, final Function<Future<?>, Void> cancelCallback) { AppCtx.getEventBus().register(this); mLayout.setRefreshing(true); final Snackbar snackbar = Snackbar.make(mLayout, R.string.toast_sending, Snackbar.LENGTH_LONG); if (PrefStore.getInstance().isUndoEnabled()) { final ScheduledFuture<?> future = ExecutorUtils.schedule(sendAction, 3, TimeUnit.SECONDS); snackbar.setAction(R.string.action_cancel, v -> cancelCallback.apply(future)); } else { ExecutorUtils.execute(() -> { sendAction.run(); ExecutorUtils.runInUiThread(snackbar::dismiss); }); } snackbar.show(); } @Override public void onCommentIgnore(final Comment comment) { onIgnore(comment, false); } private void onIgnore(final Ignorable obj, final boolean isTopic) { doActionRequest(() -> { try { RequestHelper.ignore(obj, mOnceToken); } catch (ConnectionException | RemoteException e) { ExecutorUtils.runInUiThread(() -> doActionException(e)); return; } AppCtx.getEventBus().post(new TopicEvent(isTopic ? TopicEvent.TYPE_IGNORE_TOPIC : TopicEvent.TYPE_IGNORE_COMMENT)); }, future -> { cancelRequest(future); return null; }); } private boolean cancelRequest(Future<?> future) { if (future.cancel(false)) { AppCtx.getEventBus().unregister(this); mLayout.setRefreshing(false); return true; } Snackbar.make(mLayout, R.string.toast_cancel_failed, Snackbar.LENGTH_LONG).show(); return false; } @Override public void onCommentThank(final Comment comment) { onThank(comment); } private void onThank(final Thankable obj) { doActionRequest(() -> { try { RequestHelper.thank(obj, mCsrfToken); } catch (ConnectionException | RemoteException e) { ExecutorUtils.runInUiThread(() -> doActionException(e)); return; } AppCtx.getEventBus().post(new TopicEvent(TopicEvent.TYPE_THANK)); }, future -> { cancelRequest(future); return null; }); } @Override public void onCommentReply(Comment comment) { if (mReplyForm == null || !mReplyForm.getVisibility()) { toggleReplyForm(); } mReplyForm.getContent().append("@").append(comment.getMember().getUsername()).append(" "); mReplyForm.requestFocus(); } @Override public void onCommentCopy(Comment comment, String content) { final FragmentActivity context = getActivity(); MiscUtils.setClipboard(context, ClipData.newHtmlText(null, content, comment.getContent())); } @Override public void onCommentUrlClick(String url, int pos) { if (url.startsWith(MiscUtils.PREFIX_MEMBER)) { findComment(Member.getNameFromUrl(url), pos); return; } onUrlClick(url); } private void findComment(String member, int pos) { for (int i = pos - 1; i >= 0; i final Comment comment = mComments.get(i); if (comment.getMember().getUsername().equals(member)) { scrollToPos(pos, i + 1); return; } } if (mTopic.getMember().getUsername().equals(member)) { scrollToPos(pos, 0); return; } Toast.makeText(getActivity(), getString(R.string.toast_can_not_found_comments_of_the_author, member), Toast.LENGTH_SHORT).show(); } private void scrollToPos(int curPos, int destPos) { mLastFocusPos = curPos; updateJumpBackButton(); mCommentsView.scrollToPosition(destPos); mCommentsView.postDelayed(() -> { View view = mCommentsLayoutManager.findViewByPosition(destPos); highlightRow(view); }, 100); } @Override public void onUrlClick(String url) { try { MiscUtils.openUrl(getActivity(), url); } catch (ActivityNotFoundException e) { LogUtils.i(TAG, "can't start activity for: %s", e, url); Toast.makeText(getActivity(), R.string.toast_activity_not_found, Toast.LENGTH_SHORT).show(); } } @Override public void onImageClick(String source) { onUrlClick(source); } @Override public void onNodeOpen(Node node) { final Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra(MainActivity.BUNDLE_NODE, node); startActivity(intent); } @Override public void onMemberClick(Member member) { onUrlClick(member.getUrl()); } private void onFavTopic() { AppCtx.getEventBus().register(this); mFavored = !mFavored; updateFavIcon(); ExecutorUtils.execute(() -> { try { RequestHelper.favor(mTopic, mFavored, mCsrfToken); } catch (ConnectionException | RemoteException e) { LogUtils.w(TAG, "favorite topic failed", e); mFavored = !mFavored; } AppCtx.getEventBus().post(new TopicEvent(TopicEvent.TYPE_FAV_TOPIC)); }); } private TopicLoader getLoader() { return (TopicLoader) getLoaderManager().<LoaderResult<TopicWithComments>>getLoader(0); } private void loadNextPageIfNeed(int totalItemCount, int lastVisibleItem) { if (mIsLoading || mLastIsFailed || (mCurPage >= mMaxPage)) { return; } if ((totalItemCount - lastVisibleItem) > 20) { return; } final TopicLoader loader = getLoader(); setIsLoading(true); loader.setPage(mCurPage + 1); loader.startLoading(); } private void highlightRow(View view) { Preconditions.checkNotNull(view, "view shouldn't be null"); float width = view.getWidth() / 20; ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", 0, -width, width, 0); animator.setInterpolator(null); animator.start(); } private void updateJumpBackButton() { mJumpBack.setVisibility(mLastFocusPos == NO_POSITION ? View.GONE : View.VISIBLE); } }
package com.el1t.iolite.adapter; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.el1t.iolite.R; import com.el1t.iolite.item.EighthActivityItem; import com.el1t.iolite.item.EighthBlockItem; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; public class BlockListAdapter extends ArrayAdapter<EighthBlockItem> { private ArrayList<EighthBlockItem> mItems; private final BIDSortComp mComp; private final LayoutInflater mLayoutInflater; private final int[] mColors; public enum Block { A, B, C, D, E, F } public enum Colors { INDIGO, LIGHT_BLUE, GREY, GREY1, GREY2, RED, DARK_RED, BLACK, TEXT } // View lookup cache private static class ViewHolder { TextView title; TextView sponsors; TextView room; TextView description; ImageView circle; TextView letter; } public BlockListAdapter(Context context, ArrayList<EighthBlockItem> items) { super(context, 0); mComp = new BIDSortComp(); mItems = items; sort(); // Cache colors Resources resources = context.getResources(); mColors = new int[10]; mColors[Colors.INDIGO.ordinal()] = resources.getColor(R.color.primary_400); mColors[Colors.LIGHT_BLUE.ordinal()] = resources.getColor(R.color.accent_400); for (int i = 2; i < 6; i++) { mColors[i] = resources.getColor(R.color.grey); } mColors[Colors.RED.ordinal()] = resources.getColor(R.color.red_400); mColors[Colors.DARK_RED.ordinal()] = resources.getColor(R.color.red_600); mColors[Colors.BLACK.ordinal()] = resources.getColor(R.color.primary_text_default_material_light); mColors[Colors.TEXT.ordinal()] = resources.getColor(R.color.secondary_text_default_material_light); mLayoutInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Cache the views for faster performance ViewHolder viewHolder; final EighthBlockItem blockItem = getItem(position); final EighthActivityItem activityItem = blockItem.getEighth(); if (convertView == null) { // Initialize viewHolder and convertView viewHolder = new ViewHolder(); // Save IDs inside ViewHolder and attach the ViewHolder to convertView if (blockItem.isHeader()) { convertView = mLayoutInflater.inflate(R.layout.row_header, parent, false); viewHolder.title = (TextView) convertView.findViewById(R.id.headerName); } else { convertView = mLayoutInflater.inflate(R.layout.row_block, parent, false); viewHolder.title = (TextView) convertView.findViewById(R.id.title); viewHolder.sponsors = (TextView) convertView.findViewById(R.id.sponsors); viewHolder.room = (TextView) convertView.findViewById(R.id.room); viewHolder.description = (TextView) convertView.findViewById(R.id.description); viewHolder.circle = (ImageView) convertView.findViewById(R.id.circle); viewHolder.letter = (TextView) convertView.findViewById(R.id.letter); } convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } // Set fields if (blockItem.isHeader()) { // Note: superscript does not work in header viewHolder.title.setText(blockItem.getDisp()); } else { viewHolder.title.setText(blockItem.getEighth().getName()); Colors color; final float alpha; if (activityItem.getAID() == 999) { // Hide empty fields viewHolder.sponsors.setVisibility(View.GONE); viewHolder.room.setVisibility(View.GONE); viewHolder.description.setText("Please select an activity."); // Format title viewHolder.title.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD); color = Colors.BLACK; alpha = 1f; } else { // Show fields if (activityItem.getRoom().isEmpty()) { viewHolder.room.setVisibility(View.GONE); } else { viewHolder.room.setVisibility(View.VISIBLE); viewHolder.room.setText(activityItem.getRoom()); } if (activityItem.hasSponsors()) { viewHolder.sponsors.setVisibility(View.VISIBLE); // Show dash only if needed if (viewHolder.room.getVisibility() == View.VISIBLE) { viewHolder.sponsors.setText("—" + activityItem.getSponsors()); } else { viewHolder.sponsors.setText(activityItem.getSponsors()); } } else { viewHolder.sponsors.setVisibility(View.GONE); } if (activityItem.hasDescription()) { viewHolder.description.setText(activityItem.getDescription()); } else { viewHolder.description.setText("No description."); } // Format title if (activityItem.isCancelled()) { viewHolder.title.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD); viewHolder.description.setText("Cancelled!"); color = Colors.DARK_RED; alpha = 1f; } else { viewHolder.title.setTypeface(Typeface.SANS_SERIF); color = Colors.BLACK; alpha = .87f; } } viewHolder.title.setTextColor(mColors[color.ordinal()]); viewHolder.title.setAlpha(alpha); // Set color of circle final String letter = blockItem.getBlock(); if (blockItem.isLocked()) { color = Colors.RED; } else if (activityItem.isCancelled()) { color = Colors.DARK_RED; } else { switch(Block.valueOf(letter)) { case A: color = Colors.INDIGO; break; case B: color = Colors.LIGHT_BLUE; break; default: color = Colors.GREY; } } // Tint icon viewHolder.circle.setColorFilter(mColors[color.ordinal()]); viewHolder.letter.setText(letter); } return convertView; } @Override public int getItemViewType(int position) { return getItem(position).isHeader() ? 1 : 0; } @Override public int getViewTypeCount() { return 2; } @Override public boolean isEnabled(int position) { return !getItem(position).isHeader(); } void sort() { Collections.sort(mItems, mComp); clear(); addAll(mItems); addHeaders(); notifyDataSetChanged(); } private void addHeaders() { // Count will increment every time a header is added int count = getCount(); if (count > 0) { // Dates must be used because blocks can start on any letter Date date = getItem(0).getDate(); Date nextDate; insert(new EighthBlockItem(date), 0); count++; for (int i = 1; i < count; i++) { nextDate = getItem(i).getDate(); if (!nextDate.equals(date)) { date = nextDate; insert(new EighthBlockItem(date), i++); count++; } } } } public void setListItems(ArrayList<EighthBlockItem> items) { mItems = items; sort(); } // Sort by block date and type private class BIDSortComp implements Comparator<EighthBlockItem> { @Override public int compare(EighthBlockItem e1, EighthBlockItem e2) { int cmp = e1.getDate().compareTo(e2.getDate()); if (cmp != 0) { return cmp; } else { return e1.getBlock().compareTo(e2.getBlock()); } } } }
package com.erakk.lnreader.service; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.erakk.lnreader.Constants; import com.erakk.lnreader.LNReaderApplication; import com.erakk.lnreader.R; import com.erakk.lnreader.UI.activity.DisplayLightNovelContentActivity; import com.erakk.lnreader.UI.activity.MainActivity; import com.erakk.lnreader.UI.fragment.UpdateInfoFragment; import com.erakk.lnreader.UIHelper; import com.erakk.lnreader.callback.CallbackEventData; import com.erakk.lnreader.callback.IExtendedCallbackNotifier; import com.erakk.lnreader.dao.NovelsDao; import com.erakk.lnreader.helper.Util; import com.erakk.lnreader.model.PageModel; import com.erakk.lnreader.model.UpdateInfoModel; import com.erakk.lnreader.model.UpdateTypeEnum; import com.erakk.lnreader.task.AsyncTaskResult; import com.erakk.lnreader.task.GetUpdatedChaptersTask; import java.util.ArrayList; import java.util.Date; public class UpdateService extends Service { private final IBinder mBinder = new MyBinder(); public boolean force = false; public final static String TAG = UpdateService.class.toString(); private static boolean isRunning; private IExtendedCallbackNotifier<AsyncTaskResult<?>> notifier; private GetUpdatedChaptersTask task; @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); execute(); return Service.START_NOT_STICKY; } @Override public IBinder onBind(Intent arg0) { Log.d(TAG, "onBind"); return mBinder; } @Override public void onCreate() { // Display a notification about us starting. We put an icon in the status bar. Log.d(TAG, "onCreate"); execute(); } @TargetApi(11) public void execute() { if (!shouldRun(force)) { // Reschedule for next run UpdateScheduleReceiver.reschedule(this); isRunning = false; return; } if (!isRunning) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString(Constants.PREF_RUN_UPDATES, "Running..."); editor.putString(Constants.PREF_RUN_UPDATES_STATUS, ""); editor.commit(); task = new GetUpdatedChaptersTask(this, GetAutoDownloadUpdatedChapterPreferences(), notifier); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); } } private boolean GetAutoDownloadUpdatedChapterPreferences() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREF_AUTO_DOWNLOAD_UPDATED_CHAPTER, false); } public class MyBinder extends Binder { public UpdateService getService() { Log.d(TAG, "getService"); return UpdateService.this; } } public void updateStatus(String status) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPrefs.edit(); String date = new Date().toString(); editor.putString(Constants.PREF_RUN_UPDATES, date); editor.putString(Constants.PREF_RUN_UPDATES_STATUS, status); editor.commit(); if (notifier != null) notifier.onProgressCallback(new CallbackEventData(getString(R.string.svc_update_status, date, status), Constants.PREF_RUN_UPDATES)); } private boolean getConsolidateNotificationPref() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREF_CONSOLIDATE_NOTIFICATION, true); } @SuppressWarnings("deprecation") private boolean shouldRun(boolean forced) { if (forced) { Log.i(TAG, "Forced run"); return true; } else { // check wifi only preferences if (UIHelper.isAutoUpdateOnlyUseWifi(this) && !Util.isWifiConnected()) { Log.i(TAG, "Wifi is not connected!"); return false; } else { Log.i(TAG, "Wifi available."); } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String updatesIntervalStr = preferences.getString(Constants.PREF_UPDATE_INTERVAL, "0"); if (!updatesIntervalStr.equalsIgnoreCase("0")) { long lastUpdate = preferences.getLong(Constants.PREF_LAST_UPDATE, 0); Date nowDate = new Date(); long now = nowDate.getTime(); lastUpdate += GetUpdateInterval(updatesIntervalStr); Date lastUpdateDate = new Date(lastUpdate); if (lastUpdate <= now) { Log.e(TAG, "Updating: " + lastUpdateDate.toLocaleString() + " <= " + nowDate.toLocaleString()); return true; } Log.i(TAG, "Next Update: " + lastUpdateDate.toLocaleString() + ", Now: " + nowDate.toLocaleString()); return false; } else { Log.i(TAG, "Update Interval set to Never."); return false; } } } public static long GetUpdateInterval(String updatesIntervalStr) { long interval = 0; if (updatesIntervalStr.equalsIgnoreCase("1")) { interval = 6 * 60 * 60 * 1000; } else if (updatesIntervalStr.equalsIgnoreCase("2")) { interval = 12 * 60 * 60 * 1000; } else if (updatesIntervalStr.equalsIgnoreCase("3")) { interval = 24 * 60 * 60 * 1000; } else if (updatesIntervalStr.equalsIgnoreCase("4")) { interval = 2 * 24 * 60 * 60 * 1000; } else if (updatesIntervalStr.equalsIgnoreCase("5")) { interval = 7 * 24 * 60 * 60 * 1000; } return interval; } public void cancelUpdate() { if (task != null) { task.cancel(true); } } public void setRunning(boolean isRunning) { UpdateService.isRunning = isRunning; } public void setForce(boolean isForced) { this.force = isForced; } public boolean isForced() { return force; } public void setOnCallbackNotifier(IExtendedCallbackNotifier<AsyncTaskResult<?>> notifier) { this.notifier = notifier; if (task != null) task.setCallbackNotifier(notifier); } public void sendNotification(ArrayList<PageModel> updatedChapters) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (updatedChapters != null && updatedChapters.size() > 0) { Log.d(TAG, "sendNotification"); // create UpdateInfoModel list int updateCount = 0; int newCount = 0; int newNovel = 0; ArrayList<UpdateInfoModel> updatesInfo = new ArrayList<UpdateInfoModel>(); for (PageModel pageModel : updatedChapters) { UpdateInfoModel updateInfo = new UpdateInfoModel(); if (pageModel.getType().equalsIgnoreCase(PageModel.TYPE_NOVEL)) { ++newNovel; updateInfo.setUpdateTitle("New Novel: " + pageModel.getTitle()); updateInfo.setUpdateType(UpdateTypeEnum.NewNovel); } else if (pageModel.getType().equalsIgnoreCase(PageModel.TYPE_TOS)) { updateInfo.setUpdateTitle("Updated TOS"); updateInfo.setUpdateType(UpdateTypeEnum.UpdateTos); } else { if (pageModel.isUpdated()) { updateInfo.setUpdateType(UpdateTypeEnum.Updated); ++updateCount; } else { updateInfo.setUpdateType(UpdateTypeEnum.New); ++newCount; } String novelTitle = ""; try { novelTitle = pageModel.getBook(true).getParent().getPageModel().getTitle() + ": "; } catch (Exception ex) { Log.e(TAG, "Error when getting Novel title", ex); } novelTitle = novelTitle + pageModel.getTitle() + " (" + pageModel.getBook(true).getTitle() + ")"; if (pageModel.isExternal()) { // double check if (pageModel.getPage().startsWith("http: novelTitle += " - EXTERNAL LINK"; updateInfo.setExternal(true); } } updateInfo.setUpdateTitle(novelTitle); } updateInfo.setUpdateDate(pageModel.getLastUpdate()); updateInfo.setUpdatePage(pageModel.getPage()); updateInfo.setUpdatePageModel(pageModel); // insert to db NovelsDao.getInstance().insertUpdateHistory(updateInfo); updatesInfo.add(updateInfo); } if (getConsolidateNotificationPref()) { createConsolidatedNotification(mNotificationManager, updateCount, newCount, newNovel); } else { int id = Constants.NOTIFIER_ID; boolean first = true; for (UpdateInfoModel updateInfoModel : updatesInfo) { final int notifId = ++id; Log.d(TAG, "set Notification for: " + updateInfoModel.getUpdatePage()); NotificationCompat.Builder mBuilder = getNotificationTemplate(first); first = false; prepareNotification(notifId, updateInfoModel, mBuilder); mNotificationManager.notify(notifId, mBuilder.build()); } } } updateStatus("OK"); Toast.makeText(this, "Update Service completed", Toast.LENGTH_SHORT).show(); LNReaderApplication.getInstance().updateDownload(TAG, 100, getString(R.string.svc_update_complete)); if (notifier != null) notifier.onProgressCallback(new CallbackEventData(getString(R.string.svc_update_complete), 100, Constants.PREF_RUN_UPDATES)); } private void prepareNotification(final int notifId, UpdateInfoModel chapter, NotificationCompat.Builder mBuilder) { CharSequence contentTitle = chapter.getUpdateType().toString(); CharSequence contentText = chapter.getUpdateTitle(); Intent notificationIntent = new Intent(this, DisplayLightNovelContentActivity.class); notificationIntent.putExtra(Constants.EXTRA_PAGE, chapter.getUpdatePage()); int pendingFlag = PendingIntent.FLAG_CANCEL_CURRENT; PendingIntent contentIntent = PendingIntent.getActivity(this, notifId, notificationIntent, pendingFlag); mBuilder.setContentTitle(contentTitle) .setContentText(contentText) .setContentIntent(contentIntent); } private void createConsolidatedNotification(NotificationManager mNotificationManager, int updateCount, int newCount, int newNovel) { Log.d(TAG, "set consolidated Notification"); CharSequence contentTitle = "BakaReader EX Updates"; String contentText = "Found"; if (updateCount > 0) { contentText += " " + updateCount + " updated chapter(s)"; } if (newCount > 0) { if (updateCount > 0) contentText += " and "; contentText += " " + newCount + " new chapter(s)"; } if (newNovel > 0) { if (updateCount > 0 || newCount > 0) contentText += " and "; contentText += " " + newNovel + " new novel(s)"; } contentText += "."; Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.putExtra(Constants.EXTRA_INITIAL_FRAGMENT, UpdateInfoFragment.class.toString()); notificationIntent.putExtra(Constants.EXTRA_CALLER_ACTIVITY, UpdateService.class.toString()); int pendingFlag = PendingIntent.FLAG_CANCEL_CURRENT; PendingIntent contentIntent = PendingIntent.getActivity(this, Constants.CONSOLIDATED_NOTIFIER_ID, notificationIntent, pendingFlag); NotificationCompat.Builder mBuilder = getNotificationTemplate(true); mBuilder.setContentTitle(contentTitle) .setContentText(contentText) .setContentIntent(contentIntent); mNotificationManager.notify(Constants.CONSOLIDATED_NOTIFIER_ID, mBuilder.build()); } private NotificationCompat.Builder getNotificationTemplate(boolean firstNotification) { int icon = android.R.drawable.arrow_up_float; // Just a placeholder CharSequence tickerText = "New Chapters Update"; boolean persist = !PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREF_PERSIST_NOTIFICATION, false); int def = 0; if (firstNotification) { if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREF_UPDATE_RING, false)) { def |= Notification.DEFAULT_SOUND; } if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREF_UPDATE_VIBRATE, false)) { def |= Notification.DEFAULT_VIBRATE; } } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(icon) .setWhen(System.currentTimeMillis()) .setTicker(tickerText) .setDefaults(def) .setAutoCancel(persist); return mBuilder; } }
package com.martindisch.chronoscopy; import android.support.design.widget.TabLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Prepare toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the fragment adapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; public PlaceholderFragment() { } /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); TextView textView = (TextView) rootView.findViewById(R.id.section_label); textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))); return rootView; } } public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "ACTIVITIES"; case 1: return "HISTORY"; } return null; } } }
package com.maxiee.heartbeat.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.maxiee.heartbeat.R; import com.maxiee.heartbeat.common.DialogAsyncTask; import com.maxiee.heartbeat.common.FileUtils; import com.maxiee.heartbeat.common.tagview.Tag; import com.maxiee.heartbeat.common.tagview.TagView; import com.maxiee.heartbeat.database.api.AddEventApi; import com.maxiee.heartbeat.database.api.AddEventLabelRelationApi; import com.maxiee.heartbeat.database.api.AddImageApi; import com.maxiee.heartbeat.database.api.AddLabelsApi; import com.maxiee.heartbeat.database.api.AddThoughtApi; import com.maxiee.heartbeat.database.api.GetLabelsAndFreqApi; import com.maxiee.heartbeat.database.api.GetOneLabelApi; import com.maxiee.heartbeat.model.Thoughts; import com.maxiee.heartbeat.ui.dialog.NewLabelDialog; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Map; public class AddEventActivity extends AppCompatActivity{ private final static String TAG = AddEventActivity.class.getSimpleName(); private static final int ADD_IMAGE = 1127; public final static int ADD_EVENT_REQUEST = 100; public final static int ADD_EVENT_RESULT_OK = 101; private EditText mEditEvent; private EditText mEditFirstThought; private String mStrEvent; private String mStrFirstThought; private ArrayList<String> mLabels; private TagView mTagViewRecent; private TagView mTagViewToAdd; private TextView mTvAddImage; private ImageView mImageBackDrop; private Uri mImageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event); final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mEditEvent = (EditText) findViewById(R.id.edit_event); mEditFirstThought = (EditText) findViewById(R.id.first_thought); mTagViewRecent = (TagView) findViewById(R.id.tagview_added); mTagViewToAdd = (TagView) findViewById(R.id.tagview_to_add); mTvAddImage = (TextView) findViewById(R.id.add_imgae); mImageBackDrop = (ImageView) findViewById(R.id.backdrop); mTvAddImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT < 19) { Intent intent = new Intent();
package eu.chargetime.ocpp; import eu.chargetime.ocpp.feature.Feature; import eu.chargetime.ocpp.model.Confirmation; import eu.chargetime.ocpp.model.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; /** * Unites outgoing {@link Request} with incoming {@link Confirmation}s or errors. * Catches errors and responds with error messages. */ public class Session { private static final Logger logger = LoggerFactory.getLogger(Session.class); private Communicator communicator; private Queue queue; private RequestDispatcher dispatcher; private SessionEvents events; /** * Handles required injections. * * @param communicator send and receive messages. * @param queue store and restore requests based on unique ids. * @param handleRequestAsync toggle if requests are handled async or not. */ public Session(Communicator communicator, Queue queue, boolean handleRequestAsync) { this.communicator = communicator; this.queue = queue; PromiseFulfiller fulfiller = new SimplePromiseFulfiller(); if (handleRequestAsync) fulfiller = new AsyncPromiseFulfilerDecorator(fulfiller); dispatcher = new RequestDispatcher(fulfiller); } /** * Send a {@link Request}. * * @param action action name to identify the feature. * @param payload the {@link Request} payload to send * @param uuid unique identification to identify the request */ public void sendRequest(String action, Request payload, String uuid) { communicator.sendCall(uuid, action, payload); } /** * Store a {@link Request} and get the unique id. * * @param payload the {@link Request} payload to send * @return unique identification to identify the request. */ public String storeRequest(Request payload) { return queue.store(payload); } /** * Send a {@link Confirmation} to a {@link Request} * * @param uniqueId the unique identification the receiver expects. * @param confirmation the {@link Confirmation} payload to send. */ public void sendConfirmation(String uniqueId, String action, Confirmation confirmation) { communicator.sendCallResult(uniqueId, action, confirmation); } private Class<? extends Confirmation> getConfirmationType(String uniqueId) throws UnsupportedFeatureException { Request request = queue.restoreRequest(uniqueId); Feature feature = events.findFeatureByRequest(request); if (feature == null) throw new UnsupportedFeatureException(); return feature.getConfirmationType(); } /** * Connect to a specific uri, provided a call back handler for connection related events. * * @param uri url and port of the remote system. * @param eventHandler call back handler for connection related events. */ public void open(String uri, SessionEvents eventHandler) { this.events = eventHandler; dispatcher.setEventHandler(eventHandler); communicator.connect(uri, new CommunicatorEventHandler()); } /** * Close down the connection. */ public void close() { communicator.disconnect(); } public void accept(SessionEvents eventHandler) { this.events = eventHandler; dispatcher.setEventHandler(eventHandler); communicator.accept(new CommunicatorEventHandler()); } private class CommunicatorEventHandler implements CommunicatorEvents { private static final String OCCURENCE_CONSTRAINT_VIOLATION = "Payload for Action is syntactically correct but at least one of the fields violates occurence constraints"; private static final String FIELD_CONSTRAINT_VIOLATION = "Field %s violates constraints with value: \"%s\". %s"; private static final String INTERNAL_ERROR = "An internal error occurred and the receiver was not able to process the requested Action successfully"; private static final String UNABLE_TO_PROCESS = "Unable to process action"; @Override public void onCallResult(String id, String action, Object payload) { try { Confirmation confirmation = communicator.unpackPayload(payload, getConfirmationType(id)); if (confirmation.validate()) { events.handleConfirmation(id, confirmation); } else { communicator.sendCallError(id, action, "OccurenceConstraintViolation", OCCURENCE_CONSTRAINT_VIOLATION); } } catch (PropertyConstraintException ex) { String message = String.format(FIELD_CONSTRAINT_VIOLATION, ex.getFieldKey(), ex.getFieldValue(), ex.getMessage()); logger.warn(message, ex); communicator.sendCallError(id, action, "TypeConstraintViolation", message); } catch (UnsupportedFeatureException ex) { logger.warn(INTERNAL_ERROR, ex); communicator.sendCallError(id, action, "InternalError", INTERNAL_ERROR); } catch (Exception ex) { logger.warn(UNABLE_TO_PROCESS, ex); communicator.sendCallError(id, action, "FormationViolation", UNABLE_TO_PROCESS); } } @Override synchronized public void onCall(String id, String action, Object payload) { Feature feature = events.findFeatureByAction(action); if (feature == null) { communicator.sendCallError(id, action, "NotImplemented", "Requested Action is not known by receiver"); } else { try { Request request = communicator.unpackPayload(payload, feature.getRequestType()); if (request.validate()) { CompletableFuture<Confirmation> promise = dispatcher.handleRequest(request); promise.whenComplete(new ConfirmationHandler(id, action, communicator)); } else { communicator.sendCallError(id, action, "OccurenceConstraintViolation", OCCURENCE_CONSTRAINT_VIOLATION); } } catch (PropertyConstraintException ex) { String message = String.format(FIELD_CONSTRAINT_VIOLATION, ex.getFieldKey(), ex.getFieldValue(), ex.getMessage()); logger.warn(message, ex); communicator.sendCallError(id, action, "TypeConstraintViolation", message); } catch (Exception ex) { logger.warn(UNABLE_TO_PROCESS, ex); communicator.sendCallError(id, action, "FormationViolation", UNABLE_TO_PROCESS); } } } @Override public void onError(String id, String errorCode, String errorDescription, Object payload) { events.handleError(id, errorCode, errorDescription, payload); } @Override public void onDisconnected() { events.handleConnectionClosed(); } @Override public void onConnected() { events.handleConnectionOpened(); } } }
package com.samourai.sentinel.segwit; import org.bitcoinj.core.Address; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Utils; import org.bitcoinj.script.Script; import org.bouncycastle.crypto.digests.RIPEMD160Digest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; public class P2SH_P2WPKH { private ECKey ecKey = null; private List<ECKey> keys = null; private NetworkParameters params = null; private P2SH_P2WPKH() { ; } public P2SH_P2WPKH(NetworkParameters params) { this.params = params; keys = new ArrayList<ECKey>(); } public P2SH_P2WPKH(ECKey ecKey, NetworkParameters params) { this.ecKey = ecKey; this.params = params; keys = new ArrayList<ECKey>(); } // use only compressed public keys for SegWit public P2SH_P2WPKH(byte[] pubkey, NetworkParameters params) { this.ecKey = ECKey.fromPublicOnly(pubkey); this.params = params; keys = new ArrayList<ECKey>(); } public ECKey getECKey() { return ecKey; } public void setECKey(ECKey ecKey) { this.ecKey = ecKey; } public List<ECKey> getECKeys() { return keys; } public void setECKeys(List<ECKey> keys) { this.keys = keys; } public Address segWitAddress() { return Address.fromP2SHScript(params, segWitOutputScript()); } public String getAddressAsString() { return segWitAddress().toString(); } public Script segWitOutputScript() { // OP_HASH160 hash160(redeemScript) OP_EQUAL byte[] hash = Utils.sha256hash160(segWitRedeemScript().getProgram()); byte[] buf = new byte[3 + hash.length]; buf[0] = (byte)0xa9; // HASH160 buf[1] = (byte)0x14; // push 20 bytes System.arraycopy(hash, 0, buf, 2, hash.length); // keyhash buf[22] = (byte)0x87; // OP_EQUAL return new Script(buf); } public Script segWitRedeemScript() { // The P2SH segwit redeemScript is always 22 bytes. It starts with a OP_0, followed by a canonical push of the keyhash (i.e. 0x0014{20-byte keyhash}) byte[] hash = Utils.sha256hash160(ecKey.getPubKey()); byte[] buf = new byte[2 + hash.length]; buf[0] = (byte)0x00; // OP_0 buf[1] = (byte)0x14; // push 20 bytes System.arraycopy(hash, 0, buf, 2, hash.length); // keyhash return new Script(buf); } private boolean hasPrivKey() { if(ecKey != null && ecKey.hasPrivKey()) { return true; } else { return false; } } }
package com.ynov.android.gluciddiab; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import com.ynov.android.gluciddiab.restoUtils.ImageAdapter; public class MenuActivity extends AppCompatActivity { private String[] fakedata = { "Coca Cola", "Deluxe Potatoes", "280 Original", "Cheese Burger", "Evian", "Petite Frites", "Truc au Poulet", "Ketchup", "Muffin myrtille", "280 Emmental", "Petit Hotdog", "Sundae", "Triple cheese" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); GridView gridview = (GridView) findViewById(R.id.gridviewItems); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(MenuActivity.this, "" + fakedata[position], Toast.LENGTH_SHORT).show(); } }); } }
package io.xdevs23.cornowser.browser; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.view.KeyEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.baoyz.widget.PullRefreshLayout; import com.crashlytics.android.Crashlytics; import junit.framework.AssertionFailedError; import org.xdevs23.android.app.XquidCompatActivity; import org.xdevs23.android.widget.XquidRelativeLayout; import org.xdevs23.debugutils.Logging; import org.xdevs23.debugutils.StackTraceParser; import org.xdevs23.net.DownloadUtils; import org.xdevs23.rey.material.widget.ProgressView; import org.xdevs23.threads.Sleeper; import org.xdevs23.ui.utils.BarColors; import org.xdevs23.ui.utils.DpUtil; import org.xdevs23.ui.view.listview.XDListView; import org.xdevs23.ui.widget.TastyOverflowMenu; import org.xwalk.core.XWalkPreferences; import io.fabric.sdk.android.Fabric; import io.xdevs23.cornowser.browser.activity.BgLoadActivity; import io.xdevs23.cornowser.browser.activity.SettingsActivity; import io.xdevs23.cornowser.browser.browser.BrowserStorage; import io.xdevs23.cornowser.browser.browser.modules.ColorUtil; import io.xdevs23.cornowser.browser.browser.modules.WebThemeHelper; import io.xdevs23.cornowser.browser.browser.modules.adblock.AdBlockManager; import io.xdevs23.cornowser.browser.browser.modules.adblock.AdBlockParser; import io.xdevs23.cornowser.browser.browser.modules.tabs.BasicTabSwitcher; import io.xdevs23.cornowser.browser.browser.modules.tabs.BlueListedTabSwitcher; import io.xdevs23.cornowser.browser.browser.modules.tabs.TabStorage; import io.xdevs23.cornowser.browser.browser.modules.tabs.TabSwitcherOpenButton; import io.xdevs23.cornowser.browser.browser.modules.tabs.TabSwitcherWrapper; import io.xdevs23.cornowser.browser.browser.modules.ui.OmniboxAnimations; import io.xdevs23.cornowser.browser.browser.modules.ui.OmniboxControl; import io.xdevs23.cornowser.browser.browser.xwalk.CrunchyWalkView; import io.xdevs23.cornowser.browser.updater.UpdateActivity; import io.xdevs23.cornowser.browser.updater.UpdaterStorage; public class CornBrowser extends XquidCompatActivity { public static final String URL_TO_LOAD_KEY = "urlToLoad" ; public static CrunchyWalkView publicWebRender = null; public static RelativeLayout omnibox, publicWebRenderLayout, omniboxControls, omniboxTinyItemsLayout ; public static EditText browserInputBar; public static ImageButton goForwardImgBtn ; public static TabSwitcherOpenButton openTabswitcherImgBtn; public static TastyOverflowMenu overflowMenuLayout; public static String readyToLoadUrl = ""; public static boolean isBgBoot = false, alreadyCheckedUpdate = false ; private static final int PERMISSION_REQUEST_CODE = 1; private static PullRefreshLayout omniPtrLayout; private static View staticView; private static Context staticContext; private static Activity staticActivity; private static Window staticWindow; @SuppressWarnings("FieldCanBeLocal") private static RelativeLayout staticRootView; private static ProgressView webProgressBar; private static BrowserStorage browserStorage; private static TabSwitcherWrapper tabSwitcher; private static Handler mHandler; private static String newVersionAv = ""; @SuppressWarnings("FieldCanBeLocal") private static String[] optionsMenuItems; private static boolean isBootstrapped = false; private static boolean isInitialized = false; private static boolean isNewIntent = false; private static final int aLeft = RelativeLayout.ALIGN_PARENT_LEFT, aTop = RelativeLayout.ALIGN_PARENT_TOP, aRight = RelativeLayout.ALIGN_PARENT_RIGHT, aBottom = RelativeLayout.ALIGN_PARENT_BOTTOM; private AlertDialog optionsMenuDialog; private boolean isAdWhitelisted; // For options menu @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(!isBootstrapped) bootstrap(); } /** * Whole initialization is done here */ protected void bootstrap() { if(isBgBoot) moveTaskToBack(true); if(!handleStartUp()) return; handleWaitForAdBlock(); if(isUpdateCheckAllowed() && (!alreadyCheckedUpdate)) checkUpdate.start(); // AdBlock hosts update if(getBrowserStorage().isAdBlockEnabled()) AdBlockManager.initAdBlock(); if(!isBgBoot) fastReloadComponents(); } protected boolean handleStartUp() { if(isNormalStartUp()) { if(!isBgBoot) checkMallowPermissions(); applyXWalkPreferences(); initAll(); handleCrashlyticsActivation(); isBootstrapped = true; } else if(isNewIntent) { handleStartupWebLoad(); fastReloadComponents(); return false; } else if(!isInitialized) { initAll(); handleStartupWebLoad(); return false; } return true; } private boolean isNormalStartUp() { return (!isBootstrapped && !isInitialized && staticContext == null && (!isNewIntent)); } private boolean isUpdateCheckAllowed() { return ((!isBgBoot) && (!checkUpdate.isAlive()) || (!isNewIntent)); } public void handleWaitForAdBlock() { if(getBrowserStorage().isWaitForAdBlockEnabled()) { Logging.logd("Waiting for AdBlock is enabled. Blocking."); browserInputBar.clearFocus(); final TextView fTextView = (TextView) findViewById(R.id.omnibox_init_view); final RelativeLayout omniboxInputBarLayout = (RelativeLayout) findViewById(R.id.omnibox_input_bar_layout); assert fTextView != null; assert omniboxInputBarLayout != null; fTextView.setVisibility(View.VISIBLE); browserInputBar.setVisibility(View.INVISIBLE); overflowMenuLayout.setVisibility(View.INVISIBLE); openTabswitcherImgBtn.setVisibility(View.INVISIBLE); AdBlockManager.setOnHostsUpdatedListener(new AdBlockManager.OnHostsUpdatedListener() { @Override public void onUpdateFinished() { Logging.logd("AdBlock init completed. Starting web load."); omniboxInputBarLayout.removeView(fTextView); browserInputBar.setVisibility(View.VISIBLE); overflowMenuLayout.setVisibility(View.VISIBLE); openTabswitcherImgBtn.setVisibility(View.VISIBLE); handleStartupWebLoad(); } }); } else handleStartupWebLoad(); } public void handleCrashlyticsActivation() { if(!getBrowserStorage().isCrashlyticsOptedOut()) { Logging.logd("Crashlytics is enabled."); Fabric.with(Core.applicationCore, new Crashlytics()); } else Logging.logd("Crashlytics is disabled."); } public void applyXWalkPreferences() { try { XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, (!System.getProperty("os.arch", "armv7a").toLowerCase().contains("arm"))); XWalkPreferences.setValue(XWalkPreferences.SUPPORT_MULTIPLE_WINDOWS, true); XWalkPreferences.setValue(XWalkPreferences.JAVASCRIPT_CAN_OPEN_WINDOW, true); XWalkPreferences.setValue(XWalkPreferences.ENABLE_THEME_COLOR, false); } catch(AssertionFailedError ex) { Logging.logd("Error while setting some XWalk preferences. Are you using x86?"); } } public void checkMallowPermissions() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission( getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED && (!isBgBoot)) { Toast.makeText(getApplicationContext(), getString(R.string.permission_hint_write_storage), Toast.LENGTH_LONG).show(); if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } } /** * For start-up web loading */ protected void handleStartupWebLoad() { Logging.logd("Handling start-up load"); if (getIntent().getData() != null && (!getIntent().getDataString().isEmpty())) { Logging.logd(" => Intent url load"); getTabSwitcher().addTab(getIntent().getDataString()); } else if (getIntent().getStringExtra(BgLoadActivity.bgLoadKey) != null && (!getIntent().getStringExtra(BgLoadActivity.bgLoadKey).isEmpty())) { Logging.logd(" => Background load"); getTabSwitcher().addTab(getIntent().getStringExtra(BgLoadActivity.bgLoadKey)); } else if(getIntent().getStringExtra(URL_TO_LOAD_KEY) != null && (!getIntent().getStringExtra(URL_TO_LOAD_KEY).isEmpty())) { Logging.logd(" => Shortcut/requested load"); getTabSwitcher().addTab(getIntent().getStringExtra(URL_TO_LOAD_KEY)); } else if(getBrowserStorage().isLastSessionEnabled() && getBrowserStorage().getLastBrowsingSession() != null) { Logging.logd(" => Restore last session"); Logging.logd(" Restoring last session (" + getBrowserStorage().getLastBrowsingSession().length + " tabs)..."); for (String s : getBrowserStorage().getLastBrowsingSession()) { getTabSwitcher().addTab(s); } getTabSwitcher().switchTab(0); getTabSwitcher().fixWebResumation(); Logging.logd(" Restored!"); } else if (readyToLoadUrl.isEmpty()) { Logging.logd(" => Default load"); getTabSwitcher().addTab(browserStorage.getUserHomePage(), ""); } else { Logging.logd("In-App requested load"); getTabSwitcher().addTab(readyToLoadUrl, null); readyToLoadUrl = ""; } } /** * Initialize everything */ public void initAll() { Logging.logd("Initialization started."); setContentView(R.layout.main_corn); preInit(); init(); isInitialized = true; } /** * Initialize some stuff before getting started */ public void preInit() { mHandler = new Handler(); initStaticFields(); BarColors.enableBarColoring(staticWindow, R.color.omnibox_statusbar_background); staticView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { handleFullscreenMode(); } }); getWindow().getDecorView().setOnSystemUiVisibilityChangeListener( new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if (browserStorage.getIsFullscreenEnabled() && (visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { handleFullscreenMode(); } } }); } // Pre init start /** * Initialize static fields */ public void initStaticFields() { Logging.logd("Initializing static fields"); staticActivity = this; staticContext = this.getApplicationContext(); staticView = findViewById(R.id.corn_root_view); staticWindow = this.getWindow(); staticRootView = (RelativeLayout)staticView; // layout must be initialized before initializing the tab switcher if(!isNewIntent) publicWebRenderLayout = (RelativeLayout) findViewById(R.id.webrender_layout); if(!isNewIntent) initBrowsing(); } // Pre init end /** * Main initialization */ public void init() { Logging.logd("Initializing..."); initOptionsMenu(); initOmnibox(); initWebXWalkEngine(); } // Init start /** * Initialize web rendering stuff */ public void initWebXWalkEngine() { Logging.logd(" Web engine and necessary components"); // web render layout is initialized while initializing static fields initOmniboxPosition(); } /** * Initialize essential browsing components */ public static void initBrowsing() { if(browserStorage == null && tabSwitcher == null) { browserStorage = new BrowserStorage(getContext()); tabSwitcher = new TabSwitcherWrapper( new BlueListedTabSwitcher(getContext(), staticRootView) .setTabStorage(new TabStorage())); } } /** * Initialize the omnibox */ public void initOmnibox() { Logging.logd(" Omnibox"); omnibox = (RelativeLayout) findViewById(R.id.omnibox_layout); omniPtrLayout = (PullRefreshLayout) findViewById(R.id.omnibox_refresh_ptr); browserInputBar = (EditText) findViewById(R.id.omnibox_input_bar); omniboxTinyItemsLayout = (RelativeLayout) findViewById(R.id.omnibox_tiny_items_layout); webProgressBar = (ProgressView) findViewById(R.id.omnibox_progressbar); browserInputBar.clearFocus(); omniPtrLayout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL); omniPtrLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getWebEngine().reload(true); } }); initOmniboxControls(); } /** * Initialize omnibox controls */ public void initOmniboxControls() { Logging.logd(" Controls"); omniboxControls = (RelativeLayout) findViewById(R.id.omnibox_controls); openTabswitcherImgBtn = (TabSwitcherOpenButton) findViewById(R.id.omnibox_control_open_tabswitcher); goForwardImgBtn = (ImageButton) findViewById(R.id.omnibox_control_forward); overflowMenuLayout = (TastyOverflowMenu) findViewById(R.id.omnibox_control_overflowmenu); browserInputBar.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NAVIGATE_NEXT) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getView().getWindowToken(), 0); publicWebRender.load(((EditText) v).getText().toString(), null); } return false; } }); overflowMenuLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openOptionsMenu(); } }); openTabswitcherImgBtn.init(getContext()); openTabswitcherImgBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTabSwitcher().switchSwitcher(); } }); openTabswitcherImgBtn.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { getTabSwitcher().addTab(getBrowserStorage().getUserHomePage()); return true; } }); openTabswitcherImgBtn.setTabCount(0); goForwardImgBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(getWebEngine().currentProgress != 100) getWebEngine().stopLoading(); else getWebEngine().goForward(); } }); goForwardImgBtn.setVisibility(View.INVISIBLE); goForwardImgBtn.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY); } /** * Properly init omnibox position */ public static void initOmniboxPosition() { Logging.logd(" Omnibox position"); RelativeLayout.LayoutParams omniparams = XquidRelativeLayout.LayoutParams.getPredefinedLPFromViewMetrics(omnibox); RelativeLayout.LayoutParams webrparams = XquidRelativeLayout.LayoutParams.getPredefinedLPFromViewMetrics(publicWebRenderLayout); RelativeLayout.LayoutParams otilparams = XquidRelativeLayout.LayoutParams.getPredefinedLPFromViewMetrics(omniboxTinyItemsLayout); XquidRelativeLayout.addRuleLP(aLeft, omniparams, webrparams, otilparams); XquidRelativeLayout.addRuleLP(aRight, omniparams, webrparams, otilparams); if(browserStorage.getOmniboxPosition()) { omniparams.addRule(aBottom); webrparams.addRule(aTop); otilparams.addRule(aTop); } else { omniparams.addRule(aTop); webrparams.addRule(aBottom); otilparams.addRule(aBottom); } omnibox.setLayoutParams(omniparams); publicWebRenderLayout.setLayoutParams(webrparams); omniboxTinyItemsLayout.setLayoutParams(otilparams); ((RelativeLayout.LayoutParams)browserInputBar.getLayoutParams()).setMargins( 0, 0, DpUtil.dp2px(getContext(), 3 * 40 + 4), 0 ); // This is for proper refresh feature when omnibox is at bottom omniPtrLayout.setRotation(OmniboxControl.isBottom() ? 180f : 0f); getActivity().findViewById(R.id.omnibox_layout_inner) .setRotation(OmniboxControl.isBottom() ? 180f : 0); omnibox.bringToFront(); omniboxTinyItemsLayout.bringToFront(); omniboxControls.bringToFront(); getActivity().findViewById(R.id.omnibox_separator).bringToFront(); resetOmniPositionState(); } /** * Init reloadable stuff */ public void reloadComponents() { initOmniboxPosition(); } /** * Show omnibox by resetting the translation values */ public static void resetOmniPositionState() { if(!OmniboxAnimations.isBottom()) publicWebRenderLayout.setTranslationY(omnibox.getHeight()); else publicWebRenderLayout.setTranslationY(0); omnibox.setTranslationY(0); publicWebRenderLayout.setScrollY(0); publicWebRenderLayout.setScrollX(0); } /** * Show omnibox with animation * @param animate Animate it? */ public static void resetOmniPositionState(boolean animate) { if(!animate) { resetOmniPositionState(); return; } OmniboxAnimations.resetOmni(); } /** * Set the text inside the omnibox */ public static void applyOnlyInsideOmniText() { try { String eurl = getWebEngine().getUrl(); eurl = eurl.replaceFirst("^([^ ]*): if(eurl.substring(eurl.length() - 2, eurl.length() - 1).equals("/")) eurl = eurl.substring(0, eurl.length() - 2); browserInputBar.setText(eurl); if(getWebEngine().getUrl().startsWith("https: getActivity().findViewById(R.id.omnibox_separator) .setBackgroundColor(ColorUtil.getColor(R.color.transGreen)); } else getActivity().findViewById(R.id.omnibox_separator) .setBackgroundColor(ColorUtil.getColor(R.color.dark_semi_more_transparent)); } catch(Exception ex) { Logging.logd("Warning: Didn't succeed while applying inside omni text."); } } /** * Set the text of the address bar (and apply it in tab switcher) */ public static void applyInsideOmniText() { if(browserInputBar.hasFocus()) return; try { if (publicWebRender.getUrl() != null && publicWebRender.getUrl().isEmpty()) publicWebRender.load(getTabSwitcher().getCurrentTab().getUrl()); getTabSwitcher().changeCurrentTab(publicWebRender.getUrl(), publicWebRender.getTitle()); getTabSwitcher().updateAllTabs(); } catch(Exception ex) { StackTraceParser.logStackTrace(ex); } applyOnlyInsideOmniText(); } /** * Update the progress bar */ public static void updateWebProgress() { webProgressBar.setProgress( ((float)publicWebRender.currentProgress) / 100); } /** * Items of options menu */ private static class optMenuItems { public static final int UPDATER = 0, SETTINGS = 1, SHARE_PAGE = 2, ADD_HOME_SHCT = 3, ADD_DOMAIN_TO_ADBLOCK_WHITELIST = 4 ; } /** * Initialize the options menu */ public void initOptionsMenu() { optionsMenuItems = new String[] { getString(R.string.cornmenu_item_updater), getString(R.string.cornmenu_item_settings), getString(R.string.optmenu_share), getString(R.string.cornmenu_item_addhomesc), getString(R.string.cornmenu_item_addtoadwl) }; AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogBlueRipple); builder.setAdapter(XDListView.createLittle(getContext(), optionsMenuItems), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case optMenuItems.UPDATER: startActivity(new Intent(getContext(), UpdateActivity.class)); break; case optMenuItems.SETTINGS: startActivity(new Intent(getContext(), SettingsActivity.class)); break; case optMenuItems.SHARE_PAGE: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra (Intent.EXTRA_TEXT, publicWebRender.getUrl()); startActivity(Intent.createChooser(shareIntent, getString(R.string.optmenu_share))); break; case optMenuItems.ADD_HOME_SHCT: final Intent shortcutIntent = new Intent(getActivity(), CornBrowser.class); shortcutIntent.putExtra(URL_TO_LOAD_KEY, getWebEngine().getUrl()); final Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getWebEngine().getTitle()); if(getWebEngine().getFavicon() != null) intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, getWebEngine().getFavicon()); else intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource .fromContext(getContext(), R.mipmap.m_app_icon)); intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); sendBroadcast(intent); break; case optMenuItems.ADD_DOMAIN_TO_ADBLOCK_WHITELIST: getBrowserStorage().saveAdBlockWhitelist( publicWebRender.getUrlDomain(), !isAdWhitelisted ); break; default: break; } dialog.dismiss(); } }); optionsMenuDialog = builder.create(); } // Init end /** * Open the options menu */ @Override public void openOptionsMenu() { if(!publicWebRender.getUrlDomain().isEmpty()) { if (AdBlockParser.isHostListed(publicWebRender.getUrlDomain(), getBrowserStorage().getAdBlockWhitelist())) { optionsMenuItems[optMenuItems.ADD_DOMAIN_TO_ADBLOCK_WHITELIST] = getString(R.string.cornmenu_item_rmfrmadwl); isAdWhitelisted = true; } else { optionsMenuItems[optMenuItems.ADD_DOMAIN_TO_ADBLOCK_WHITELIST] = getString(R.string.cornmenu_item_addtoadwl); isAdWhitelisted = false; } } else isAdWhitelisted = false; optionsMenuDialog.show(); } /** * Hide/show go forward button */ public static void handleGoForwardControlVisibility() { if(publicWebRender.currentProgress != 100) { goForwardImgBtn.setBackgroundResource(WebThemeHelper.isDark ? R.drawable.main_cross_rot_icon_light : R.drawable.main_cross_rot_icon); goForwardImgBtn.setVisibility(View.VISIBLE); } else { if(publicWebRender.canGoForward()) { goForwardImgBtn.setBackgroundResource(WebThemeHelper.isDark ? R.drawable.ic_arrow_forward_white_48dp : R.drawable.ic_arrow_forward_black_48dp); goForwardImgBtn.setVisibility(View.VISIBLE); } else goForwardImgBtn.setVisibility(View.INVISIBLE); } } /** * @return Static root view */ public static View getView() { return staticView; } /** * @return Static context */ public static Context getContext() { return staticContext; } /** * @return Static activity */ public static Activity getActivity() { return staticActivity; } /** * @return Static window */ public static Window getStaticWindow() { return staticWindow; } /** * @return The actual browser storage */ public static BrowserStorage getBrowserStorage() { return browserStorage; } /** * @return Our delicious and crunchy web engine :D */ public static CrunchyWalkView getWebEngine() { return publicWebRender; } /** * @return The requested string */ public static String getRStr(int resId) { return staticContext.getString(resId); } /** * @return Progress bar (shows actual loading progress) */ public static ProgressView getWebProgressBar() { return webProgressBar; } /** * @return Tab switcher */ public static BasicTabSwitcher getTabSwitcher() { return tabSwitcher.getTabSwitcher(); } /** * @return Pull to refresh layout */ public static PullRefreshLayout getOmniPtrLayout() { return omniPtrLayout; } /** * Reset the color of status bar and navigation bar */ public static void resetBarColor() { if (OmniboxControl.isTop()) { // Status bar BarColors.updateBarsColor(getStaticWindow(), R.color.omnibox_statusbar_background, false, false, true); // Navbar BarColors.updateBarsColor(getStaticWindow(), R.color.black, false, true, false); } else { // Navbar BarColors.updateBarsColor(getStaticWindow(), R.color.omnibox_statusbar_background, false, true, false); // Status bar BarColors.updateBarsColor(getStaticWindow(), R.color.omnibox_statusbar_background, false, false, true); } } /** * Quickly reload some components (e. g. after resume) */ private void fastReloadComponents() { onPauseWebRender(true); onResumeWebRender(); } /** * Pause the web rendering engine (reduces memory leaks etc.) */ protected void onPauseWebRender() { onPauseWebRender(false); } /** * Pause the web rendering engine * @param fastPause Choose if it should be a fast pause (no difference in speed) */ protected void onPauseWebRender(boolean fastPause) { if (publicWebRender != null) { publicWebRender.pauseTimers(); publicWebRender.onHide(); if(!fastPause) readyToLoadUrl = ""; } } /** * Resume the web rendering engine after being paused (or reload) */ protected void onResumeWebRender() { if (publicWebRender != null) { publicWebRender.resumeTimers(); publicWebRender.onShow(); WebThemeHelper.tintNow(); if(!browserStorage.getOmniColoringEnabled()) WebThemeHelper.resetWebThemeColor(omnibox); publicWebRender.drawWithColorMode(); if(readyToLoadUrl.length() > 0) { publicWebRender.load(readyToLoadUrl, null); readyToLoadUrl = ""; } if( (publicWebRender.getTitle() == null || publicWebRender.getTitle().isEmpty() || publicWebRender.getUrl() == null || publicWebRender.getUrl().isEmpty()) && publicWebRender.getUIClient().readyForBugfreeBrowsing) publicWebRender.loadWorkingUrl(); } } @Override protected void onPause() { Logging.logd("Activity paused."); onPauseWebRender(); if(getBrowserStorage().isLastSessionEnabled()) { String[] sessionArray = new String[getTabSwitcher().getTabStorage().getTabCount()]; Logging.logd("Session urls:" + sessionArray.length); for (int i = 0; i < getTabSwitcher().getTabStorage().getTabCount(); i++) { Logging.logd("Saving tab " + i); if (getBrowserStorage().isLastSessionEnabled()) sessionArray[i] = getTabSwitcher().getTabStorage().getTab(i).getUrl(); } if(sessionArray != getBrowserStorage().getLastBrowsingSession()) getBrowserStorage().saveLastBrowsingSession(sessionArray); } super.onPause(); } @Override protected void onResume() { Logging.logd("Activity resumed."); super.onResume(); if(this.getWindow().isActive() && isBgBoot) { isBgBoot = false; if( (!checkUpdate.isAlive()) && (!alreadyCheckedUpdate) ) checkUpdate.start(); fastReloadComponents(); } else onResumeWebRender(); reloadComponents(); } @Override protected void onDestroy() { Logging.logd("Destroying activity"); super.onDestroy(); if (publicWebRender != null) { Logging.logd("Saving state and destroying webviews..."); String[] sessionArray = new String[getTabSwitcher().getTabStorage().getTabCount()]; Logging.logd("Session urls:" + sessionArray.length); for (int i = 0; i < getTabSwitcher().getTabStorage().getTabCount(); i++) { Logging.logd("Shutting down tab " + i); if(getBrowserStorage().isLastSessionEnabled()) sessionArray[i] = getTabSwitcher().getTabStorage().getTab(i).getUrl(); getTabSwitcher().getTabStorage().getTab(i).getWebView().onDestroy(); } getBrowserStorage().saveLastBrowsingSession(sessionArray); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Logging.logd("Activity result received."); if (publicWebRender != null) publicWebRender.onActivityResult(requestCode, resultCode, data); } @Override protected void onNewIntent(Intent intent) { Logging.logd("New intent!"); getIntent().setData(intent.getData()); if( (intent.getData() == null || intent.getDataString().isEmpty()) && (intent.getStringExtra(URL_TO_LOAD_KEY) == null || intent.getStringExtra(URL_TO_LOAD_KEY).isEmpty()) && (intent.getStringExtra(BgLoadActivity.bgLoadKey) == null || intent.getStringExtra(BgLoadActivity.bgLoadKey).isEmpty()) ) return; Logging.logd("URL information in intent found"); if(! (intent.getStringExtra(URL_TO_LOAD_KEY) == null || intent.getStringExtra(URL_TO_LOAD_KEY).isEmpty()) ) { getIntent().putExtra(URL_TO_LOAD_KEY, intent.getStringExtra(URL_TO_LOAD_KEY)); handleStartupWebLoad(); return; } if(! (intent.getStringExtra(BgLoadActivity.bgLoadKey) == null || intent.getStringExtra(BgLoadActivity.bgLoadKey).isEmpty()) ) { getIntent().putExtra(BgLoadActivity.bgLoadKey, intent.getStringExtra(BgLoadActivity.bgLoadKey)); isBgBoot = true; } Logging.logd("Bootstrapping with new intent."); isNewIntent = true; bootstrap(); } @Override public void onBackPressed() { if(omnibox != null && browserInputBar != null) { browserInputBar.clearFocus(); applyInsideOmniText(); return; } Logging.logd("Back pressed, web render cannot go back. Exiting application."); if(publicWebRender != null && (!publicWebRender.goBack())) endApplication(); } /** * Handle fullscreen mode */ public void handleFullscreenMode() { if (browserStorage.getIsFullscreenEnabled()) { if(Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { getWindow().getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION ); } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getWindow().getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } } else { getWindow().getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); handleFullscreenMode(); } /* Updater section */ /** * This Thread checks for Updates in the Background */ private Thread checkUpdate = new Thread() { public void run() { try { Logging.logd("Checking for updates..."); alreadyCheckedUpdate = true; Sleeper.sleep(1000); // Give the browser a second to get air xD String newVer = DownloadUtils.downloadString(UpdaterStorage.URL_VERSION_CODE); newVersionAv = DownloadUtils.downloadString(UpdaterStorage.URL_VERSION_NAME); if(Integer.parseInt(newVer) > getContext().getPackageManager().getPackageInfo( getApplicationContext().getPackageName(), 0 ).versionCode) mHandler.post(showUpdate); Logging.logd("Check completed."); } catch (Exception e) { /* Do nothing */ } } }; /** * Show update dialog */ private Runnable showUpdate = new Runnable() { public void run() { Logging.logd("Update available!"); new AlertDialog.Builder(CornBrowser.this) .setTitle(getContext().getString(R.string.update_available_title)) .setMessage(String.format(getContext().getString(R.string.update_available_message), newVersionAv)) .setPositiveButton(getContext().getString(R.string.answer_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { UpdateActivity.startUpdateImmediately(staticActivity, UpdaterStorage.URL_APK); } }) .setNegativeButton(getContext().getString(R.string.answer_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } }; }
package me.devsaki.hentoid.parsers; import android.util.Pair; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import me.devsaki.hentoid.database.domains.Content; import static me.devsaki.hentoid.util.HttpHelper.getOnlineDocument; public class EHentaiParser extends BaseParser { @Override protected List<String> parseImages(Content content) throws IOException { List<String> result = new ArrayList<>(); /* * 1- Detect the number of pages of the gallery * * 2- Browse the gallery and fetch the URL for every page (since all of them have a different temporary key...) * * 3- Open all pages and grab the URL of the displayed image */ // 1- Detect the number of pages of the gallery Element e; List<Pair<String, String>> headers = new ArrayList<>(); headers.add(new Pair<>("cookie", "nw=1")); // nw=1 (always) avoids the Offensive Content popup (equivalent to clicking the "Never warn me again" link) Document doc = getOnlineDocument(content.getGalleryUrl(), headers, true); if (doc != null) { Elements elements = doc.select("table.ptt a"); if (null == elements || 0 == elements.size()) return result; int tabId = (1 == elements.size()) ? 0 : elements.size() - 2; int nbGalleryPages = Integer.parseInt(elements.get(tabId).text()); // 2- Browse the gallery and fetch the URL for every page (since all of them have a different temporary key...) List<String> pageUrls = new ArrayList<>(); fetchPageUrls(doc, pageUrls); if (nbGalleryPages > 1) { for (int i = 1; i < nbGalleryPages; i++) { doc = getOnlineDocument(content.getGalleryUrl() + "/?p=" + i, headers, true); if (doc != null) fetchPageUrls(doc, pageUrls); } } // 3- Open all pages and grab the URL of the displayed image for (String s : pageUrls) { doc = getOnlineDocument(s, headers, true); if (doc != null) { elements = doc.select("img#img"); if (elements != null && elements.size() > 0) { e = elements.first(); result.add(e.attr("src")); } } } } return result; } private void fetchPageUrls(Document doc, List<String> pageUrls) { Elements imageLinks = doc.getElementsByClass("gdtm"); for (Element e : imageLinks) { e = e.select("div").first().select("a").first(); pageUrls.add(e.attr("href")); } } }
package nu.yona.app.ui.settings; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import nu.yona.app.R; import nu.yona.app.YonaApplication; import nu.yona.app.analytics.AnalyticsConstant; import nu.yona.app.analytics.YonaAnalytics; import nu.yona.app.api.manager.APIManager; import nu.yona.app.api.manager.impl.DeviceManagerImpl; import nu.yona.app.api.model.ErrorMessage; import nu.yona.app.customview.CustomAlertDialog; import nu.yona.app.customview.YonaFontTextView; import nu.yona.app.enums.IntentEnum; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.state.EventChangeManager; import nu.yona.app.ui.BaseFragment; import nu.yona.app.ui.LaunchActivity; import nu.yona.app.ui.YonaActivity; import nu.yona.app.ui.pincode.PinActivity; import nu.yona.app.utils.AppConstant; import nu.yona.app.utils.AppUtils; public class SettingsFragment extends BaseFragment { private DeviceManagerImpl deviceManager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.settings_fragment, null); setupToolbar(view); ListView listView = (ListView) view.findViewById(R.id.list_view); deviceManager = new DeviceManagerImpl(getActivity()); listView.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.settings_list_item, new String[]{getString(R.string.changepin), getString(R.string.privacy), getString(R.string.adddevice), getString(R.string.contact_us), getString(R.string.deleteuser)})); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (((YonaFontTextView) view).getText().toString().equals(getString(R.string.changepin))) { YonaAnalytics.createTapEvent(getString(R.string.changepin)); showChangePin(); } else if (((YonaFontTextView) view).getText().toString().equals(getString(R.string.privacy))) { YonaAnalytics.createTapEvent(getString(R.string.privacy)); showPrivacy(); } else if (((YonaFontTextView) view).getText().toString().equals(getString(R.string.adddevice))) { YonaAnalytics.createTapEvent(getString(R.string.adddevice)); YonaActivity.getActivity().showLoadingView(true, null); addDevice(AppUtils.getRandomString(AppConstant.ADD_DEVICE_PASSWORD_CHAR_LIMIT)); } else if (((YonaFontTextView) view).getText().toString().equals(getString(R.string.deleteuser))) { YonaAnalytics.createTapEvent(getString(R.string.deleteuser)); unsubscribeUser(); } else if (((YonaFontTextView) view).getText().toString().equals(getString(R.string.contact_us))) { openEmail(); } } }); try { PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); ((TextView) view.findViewById(R.id.label_version)).setText(getString(R.string.version) + pInfo.versionName + getString(R.string.space) + pInfo.versionCode); } catch (PackageManager.NameNotFoundException e) { AppUtils.throwException(SettingsFragment.class.getSimpleName(), e, Thread.currentThread(), null); } setHook(new YonaAnalytics.BackHook(AnalyticsConstant.BACK_FROM_SCREEN_SETTINGS)); return view; } private void showChangePin() { YonaActivity.getActivity().setSkipVerification(true); APIManager.getInstance().getPasscodeManager().resetWrongCounter(); Intent intent = new Intent(getActivity(), PinActivity.class); Bundle bundle = new Bundle(); bundle.putBoolean(AppConstant.FROM_SETTINGS, true); bundle.putString(AppConstant.SCREEN_TYPE, AppConstant.PIN_RESET_VERIFICATION); bundle.putInt(AppConstant.PROGRESS_DRAWABLE, R.drawable.pin_reset_progress_bar); bundle.putString(AppConstant.SCREEN_TITLE, getString(R.string.changepin)); bundle.putInt(AppConstant.COLOR_CODE, ContextCompat.getColor(YonaActivity.getActivity(), R.color.mango)); bundle.putInt(AppConstant.TITLE_BACKGROUND_RESOURCE, R.drawable.triangle_shadow_mango); bundle.putInt(AppConstant.PASSCODE_TEXT_BACKGROUND, R.drawable.passcode_edit_bg_mango); intent.putExtras(bundle); startActivity(intent); } private void showPrivacy() { Intent friendIntent = new Intent(IntentEnum.ACTION_PRIVACY_POLICY.getActionString()); YonaActivity.getActivity().replaceFragment(friendIntent); } private void unsubscribeUser() { CustomAlertDialog.show(YonaActivity.getActivity(), getString(R.string.deleteuser), getString(R.string.deleteusermessage), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); YonaAnalytics.createTapEvent(getString(R.string.ok)); doUnsubscribe(); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { YonaAnalytics.createTapEvent(getString(R.string.cancel)); dialog.dismiss(); } }); } private void doUnsubscribe() { YonaActivity.getActivity().showLoadingView(true, null); APIManager.getInstance().getAuthenticateManager().deleteUser(new DataLoadListener() { @Override public void onDataLoad(Object result) { YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_CLEAR_ACTIVITY_LIST, null); YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_USER_NOT_EXIST, null); YonaActivity.getActivity().showLoadingView(false, null); startActivity(new Intent(YonaActivity.getActivity(), LaunchActivity.class)); YonaApplication.getEventChangeManager().notifyChange(EventChangeManager.EVENT_CLOSE_ALL_ACTIVITY_EXCEPT_LAUNCH, null); } @Override public void onError(Object errorMessage) { YonaActivity.getActivity().showLoadingView(false, null); Snackbar snackbar = Snackbar.make(YonaActivity.getActivity().findViewById(android.R.id.content), ((ErrorMessage) errorMessage).getMessage(), Snackbar.LENGTH_SHORT); TextView textView = ((TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text)); textView.setMaxLines(5); snackbar.show(); } }); } @Override public void onResume() { super.onResume(); setTitleAndIcon(); YonaActivity.getActivity().setSkipVerification(false); } private void setTitleAndIcon() { toolbarTitle.setText(R.string.settings); } private void addDevice(final String pin) { try { deviceManager.addDevice(pin, new DataLoadListener() { @Override public void onDataLoad(Object result) { showAlert(getString(R.string.yonaadddevicemessage, pin), true); } @Override public void onError(Object errorMessage) { showAlert(((ErrorMessage) errorMessage).getMessage(), false); } }); } catch (Exception e) { AppUtils.throwException(SettingsFragment.class.getSimpleName(), e, Thread.currentThread(), null); showAlert(e.toString(), false); } } private void showAlert(String message, final boolean doDelete) { try { if (YonaActivity.getActivity() != null) { YonaActivity.getActivity().showLoadingView(false, null); Snackbar.make(YonaActivity.getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE) .setAction(getString(R.string.ok), new View.OnClickListener() { @Override public void onClick(View v) { if (doDelete) { doDeleteDeviceRequest(); } } }) .show(); } } catch (Exception e) { Log.e(SettingsFragment.class.getSimpleName(), e.getMessage()); } } private void doDeleteDeviceRequest() { try { deviceManager.deleteDevice(new DataLoadListener() { @Override public void onDataLoad(Object result) { //do nothing if server response success } @Override public void onError(Object errorMessage) { showAlert(((ErrorMessage) errorMessage).getMessage(), false); } }); } catch (Exception e) { AppUtils.throwException(SettingsFragment.class.getSimpleName(), e, Thread.currentThread(), null); showAlert(e.toString(), false); } } private void openEmail() { CustomAlertDialog.show(YonaActivity.getActivity(), getString(R.string.usercredential), getString(R.string.usercredentialmsg), getString(R.string.yes), getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String userCredential = Html.fromHtml("<html> Base URL: " +Uri.encode( YonaApplication.getEventChangeManager().getDataState().getUser().getLinks().getSelf().getHref()) + "<br><br>" + Uri.encode("Password: " + YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword()) + "</html>").toString(); showEmailClient(userCredential); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showEmailClient(""); } }); } private void showEmailClient(String userCredential) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse("mailto:support@yona.nu?subject=Yona" + "&body=" + userCredential); intent.setData(data); startActivity(intent); } @Override public String getAnalyticsCategory() { return AnalyticsConstant.SCREEN_SETTINGS; } }
package org.wikipedia.page; import android.content.Intent; import android.widget.Toast; import androidx.annotation.NonNull; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.bridge.JavaScriptActionHandler; import org.wikipedia.database.contract.PageImageHistoryContract; import org.wikipedia.dataclient.okhttp.OfflineCacheInterceptor; import org.wikipedia.dataclient.page.PageClient; import org.wikipedia.dataclient.page.PageLead; import org.wikipedia.edit.EditHandler; import org.wikipedia.edit.EditSectionActivity; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.leadimages.LeadImagesHandler; import org.wikipedia.page.tabs.Tab; import org.wikipedia.pageimages.PageImage; import org.wikipedia.readinglist.database.ReadingListDbHelper; import org.wikipedia.util.DateUtil; import org.wikipedia.util.log.L; import org.wikipedia.views.ObservableWebView; import java.text.ParseException; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import static org.wikipedia.util.DimenUtil.calculateLeadImageWidth; /** * Our old page load strategy, which uses the JSON MW API directly and loads a page in multiple steps: * First it loads the lead section (sections=0). * Then it loads the remaining sections (sections=1-). * <p/> * This class tracks: * - the states the page loading goes through, * - a backstack of pages and page positions visited, * - and many handlers. */ public class PageFragmentLoadState { private interface ErrorCallback { void call(@NonNull Throwable error); } private boolean loading; @NonNull private Tab currentTab = new Tab(); @NonNull private final SequenceNumber sequenceNumber = new SequenceNumber(); private int sectionTargetFromIntent; private String sectionTargetFromTitle; private ErrorCallback networkErrorCallback; // copied fields private PageViewModel model; private PageFragment fragment; private CommunicationBridge bridge; private ObservableWebView webView; private WikipediaApp app = WikipediaApp.getInstance(); private LeadImagesHandler leadImagesHandler; private EditHandler editHandler; private String revision; private CompositeDisposable disposables = new CompositeDisposable(); @SuppressWarnings("checkstyle:parameternumber") public void setUp(@NonNull PageViewModel model, @NonNull PageFragment fragment, @NonNull ObservableWebView webView, @NonNull CommunicationBridge bridge, @NonNull LeadImagesHandler leadImagesHandler, @NonNull Tab tab) { this.model = model; this.fragment = fragment; this.webView = webView; this.bridge = bridge; this.leadImagesHandler = leadImagesHandler; this.currentTab = tab; } public void load(boolean pushBackStack) { if (pushBackStack) { // update the topmost entry in the backstack, before we start overwriting things. updateCurrentBackStackItem(); currentTab.pushBackStackItem(new PageBackStackItem(model.getTitleOriginal(), model.getCurEntry())); } loading = true; // increment our sequence number, so that any async tasks that depend on the sequence // will invalidate themselves upon completion. sequenceNumber.increase(); pageLoadCheckReadingLists(); } public boolean isLoading() { return loading; } public void onPageFinished() { bridge.onPageFinished(); loading = false; } public void loadFromBackStack() { if (currentTab.getBackStack().isEmpty()) { return; } PageBackStackItem item = currentTab.getBackStack().get(currentTab.getBackStackPosition()); // display the page based on the backstack item, stage the scrollY position based on // the backstack item. fragment.loadPage(item.getTitle(), item.getHistoryEntry(), false, item.getScrollY()); L.d("Loaded page " + item.getTitle().getDisplayText() + " from backstack"); } public void updateCurrentBackStackItem() { if (currentTab.getBackStack().isEmpty()) { return; } PageBackStackItem item = currentTab.getBackStack().get(currentTab.getBackStackPosition()); item.setScrollY(webView.getScrollY()); if (model.getTitle() != null) { // Preserve metadata of the current PageTitle into our backstack, so that // this data would be available immediately upon loading PageFragment, instead // of only after loading the lead section. item.getTitle().setDescription(model.getTitle().getDescription()); item.getTitle().setThumbUrl(model.getTitle().getThumbUrl()); } } public void setTab(@NonNull Tab tab) { this.currentTab = tab; } public boolean goBack() { if (currentTab.canGoBack()) { currentTab.moveBack(); if (!backStackEmpty()) { loadFromBackStack(); return true; } } return false; } public boolean goForward() { if (currentTab.canGoForward()) { currentTab.moveForward(); loadFromBackStack(); return true; } return false; } public boolean backStackEmpty() { return currentTab.getBackStack().isEmpty(); } public void setEditHandler(EditHandler editHandler) { this.editHandler = editHandler; } public void backFromEditing(Intent data) { //Retrieve section ID from intent, and find correct section, so where know where to scroll to sectionTargetFromIntent = data.getIntExtra(EditSectionActivity.EXTRA_SECTION_ID, 0); } public void onConfigurationChanged() { leadImagesHandler.loadLeadImage(); bridge.execute(JavaScriptActionHandler.setTopMargin(leadImagesHandler.getTopMargin())); fragment.setToolbarFadeEnabled(leadImagesHandler.isLeadImageEnabled()); } public boolean isFirstPage() { return currentTab.getBackStack().size() <= 1 && !webView.canGoBack(); } public String getRevision() { return revision; } protected void commonSectionFetchOnCatch(@NonNull Throwable caught) { if (!fragment.isAdded()) { return; } ErrorCallback callback = networkErrorCallback; networkErrorCallback = null; loading = false; fragment.requireActivity().invalidateOptionsMenu(); if (callback != null) { callback.call(caught); } } private void pageLoadCheckReadingLists() { disposables.clear(); disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageInAnyList(model.getTitle())) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate(() -> pageLoadFromNetwork((final Throwable networkError) -> fragment.onPageLoadError(networkError))) .subscribe(page -> model.setReadingListPage(page), throwable -> model.setReadingListPage(null))); } private void pageLoadFromNetwork(final ErrorCallback errorCallback) { if (model.getTitle() == null) { return; } fragment.updateBookmarkAndMenuOptions(); // stage any section-specific link target from the title, since the title may be // replaced (normalized) sectionTargetFromTitle = model.getTitle().getFragment(); networkErrorCallback = errorCallback; if (!fragment.isAdded()) { return; } loading = true; fragment.requireActivity().invalidateOptionsMenu(); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } app.getSessionFunnel().leadSectionFetchStart(); disposables.add(new PageClient() .lead(model.getTitle().getWikiSite(), model.getCacheControl(), model.shouldSaveOffline() ? OfflineCacheInterceptor.SAVE_HEADER_SAVE : null, model.getCurEntry().getReferrer(), model.getTitle().getConvertedText(), calculateLeadImageWidth()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(rsp -> { app.getSessionFunnel().leadSectionFetchEnd(); PageLead lead = rsp.body(); pageLoadLeadSectionComplete(lead); bridge.execute(JavaScriptActionHandler.setFooter(fragment.requireContext(), model)); if ((rsp.raw().cacheResponse() != null && rsp.raw().networkResponse() == null) || OfflineCacheInterceptor.SAVE_HEADER_SAVE.equals(rsp.headers().get(OfflineCacheInterceptor.SAVE_HEADER))) { showPageOfflineMessage(rsp.raw().header("date", "")); } }, t -> { L.e("PageLead error: ", t); commonSectionFetchOnCatch(t); })); // And finally, start blasting the HTML into the WebView. bridge.resetHtml(model.getTitle().getWikiSite().url(), model.getTitle().getPrefixedText()); } private void updateThumbnail(String thumbUrl) { model.getTitle().setThumbUrl(thumbUrl); model.getTitleOriginal().setThumbUrl(thumbUrl); } private void showPageOfflineMessage(@NonNull String dateHeader) { if (!fragment.isAdded()) { return; } try { String dateStr = DateUtil.getShortDateString(DateUtil .getHttpLastModifiedDate(dateHeader)); Toast.makeText(fragment.requireContext().getApplicationContext(), fragment.getString(R.string.page_offline_notice_last_date, dateStr), Toast.LENGTH_LONG).show(); } catch (ParseException e) { // ignore } } private void pageLoadLeadSectionComplete(PageLead pageLead) { if (!fragment.isAdded()) { return; } Page page = pageLead.toPage(model.getTitle()); bridge.execute(JavaScriptActionHandler.setUpEditButtons(true, !page.getPageProperties().canEdit())); model.setPage(page); model.setTitle(page.getTitle()); editHandler.setPage(model.getPage()); if (page.getTitle().getDescription() == null) { app.getSessionFunnel().noDescription(); } leadImagesHandler.loadLeadImage(); fragment.setToolbarFadeEnabled(leadImagesHandler.isLeadImageEnabled()); fragment.requireActivity().invalidateOptionsMenu(); // Update our history entry, in case the Title was changed (i.e. normalized) final HistoryEntry curEntry = model.getCurEntry(); model.setCurEntry(new HistoryEntry(model.getTitle(), curEntry.getTimestamp(), curEntry.getSource())); model.getCurEntry().setReferrer(curEntry.getReferrer()); // Save the thumbnail URL to the DB PageImage pageImage = new PageImage(model.getTitle(), pageLead.getThumbUrl()); Completable.fromAction(() -> app.getDatabaseClient(PageImage.class).upsert(pageImage, PageImageHistoryContract.Image.SELECTION)).subscribeOn(Schedulers.io()).subscribe(); model.getTitle().setThumbUrl(pageImage.getImageName()); model.getTitleOriginal().setThumbUrl(pageImage.getImageName()); bridge.evaluate(JavaScriptActionHandler.getRevision(), revision -> { L.d("Page revision: " + revision); this.revision = revision; }); } /** * Monotonically increasing sequence number to maintain synchronization when loading page * content asynchronously between the Java and JavaScript layers, as well as between synchronous * methods and asynchronous callbacks on the UI thread. */ private static class SequenceNumber { private int sequence; void increase() { ++sequence; } int get() { return sequence; } boolean inSync(int sequence) { return this.sequence == sequence; } } }
package org.y20k.trackbook.helpers; import android.app.Activity; import android.os.Environment; import android.support.v4.os.EnvironmentCompat; import android.widget.Toast; import com.google.gson.Gson; import org.y20k.trackbook.R; import org.y20k.trackbook.core.Track; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; /** * StorageHelper class */ public class StorageHelper implements TrackbookKeys { /* Define log tag */ private static final String LOG_TAG = StorageHelper.class.getSimpleName(); /* Main class variables */ private final Activity mActivity; private File mFolder; /* Constructor */ public StorageHelper(Activity activity) { // store activity mActivity = activity; // set name sub-directory to "tracks" mFolder = mActivity.getExternalFilesDir("tracks"); // mFolder = getTracksDirectory(); // create folder if necessary if (mFolder != null && !mFolder.exists()) { LogHelper.v(LOG_TAG, "Creating new folder: " + mFolder.toString()); mFolder.mkdir(); } } /* Saves track object to file */ public boolean saveTrack(Track track) { Date recordingStart = track.getRecordingStart(); if (mFolder.exists() && mFolder.isDirectory() && mFolder.canWrite() && recordingStart != null) { File lastTrackFile = getLastTrack(); // construct filename from track recording date DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US); String fileName = dateFormat.format(recordingStart) + ".trackbook"; File file = new File(mFolder.toString() + "/" + fileName); // convert to JSON Gson gson = new Gson(); String json = gson.toJson(track); // write track try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { LogHelper.v(LOG_TAG, "Saving track to external storage: " + file.toString()); bw.write(json); } catch (IOException e) { LogHelper.e(LOG_TAG, "Unable to saving track to external storage (IOException): " + file.toString()); return false; } // if write was successful delete last file lastTrackFile.delete(); return true; } else { LogHelper.e(LOG_TAG, "Unable to save track to external storage."); return false; } } /* Loads given file into memory */ public Track loadTrack (File file) { try (BufferedReader br = new BufferedReader(new FileReader(file))) { LogHelper.v(LOG_TAG, "Loading track to external storage: " + file.toString()); String line; StringBuilder sb = new StringBuilder(""); // read until last line reached while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } // get track from JSON Gson gson = new Gson(); return gson.fromJson(sb.toString(), Track.class); } catch (IOException e) { LogHelper.e(LOG_TAG, "Unable to read file from external storage: " + file.toString()); return null; } } /* Gets the last track from directory */ public File getLastTrack() { if (mFolder != null && mFolder.isDirectory()) { List<File> files = new ArrayList<File>(Arrays.asList(mFolder.listFiles())); Collections.sort(files); // TODO return files.get(files.size() - 1); } // TODO return null; } /* Return a write-able sub-directory from external storage */ private File getTracksDirectory() { String subDirectory = "Tracks"; File[] storage = mActivity.getExternalFilesDirs(subDirectory); for (File file : storage) { if (file != null) { String state = EnvironmentCompat.getStorageState(file); if (Environment.MEDIA_MOUNTED.equals(state)) { LogHelper.i(LOG_TAG, "External storage: " + file.toString()); return file; } } } Toast.makeText(mActivity, R.string.toast_message_no_external_storage, Toast.LENGTH_LONG).show(); LogHelper.e(LOG_TAG, "Unable to access external storage."); return null; } }
package tech.akpmakes.android.taskkeeper; import android.app.Application; import android.provider.Settings; import android.support.v7.app.AppCompatDelegate; import com.google.firebase.database.FirebaseDatabase; public class WhenApp extends Application { @Override public void onCreate() { super.onCreate(); String testLabSetting = Settings.System.getString(getContentResolver(), "firebase.test.lab"); if ("true".equals(testLabSetting)) { // Kill the process if we're running in Test Lab. We don't like Test Lab at the moment. android.os.Process.killProcess(android.os.Process.myPid()); } /* Enable disk persistence */ FirebaseDatabase.getInstance().setPersistenceEnabled(true); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } }
package com.turo.pushy.apns; import com.turo.pushy.apns.auth.ApnsSigningKey; import com.turo.pushy.apns.proxy.ProxyHandlerFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http2.Http2FrameLogger; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.resolver.AddressResolverGroup; import io.netty.resolver.NoopAddressResolverGroup; import io.netty.resolver.dns.DefaultDnsServerAddressStreamProvider; import io.netty.resolver.dns.RoundRobinDnsAddressResolverGroup; import io.netty.util.AttributeKey; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.PromiseNotifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * An APNs channel factory creates new channels connected to an APNs server. Channels constructed by this factory are * intended for use in an {@link ApnsChannelPool}. */ class ApnsChannelFactory implements PooledObjectFactory<Channel>, Closeable { private final SslContext sslContext; private final AtomicBoolean hasReleasedSslContext = new AtomicBoolean(false); private final AddressResolverGroup addressResolverGroup; private final Bootstrap bootstrapTemplate; private final AtomicLong currentDelaySeconds = new AtomicLong(0); private static final long MIN_CONNECT_DELAY_SECONDS = 1; private static final long MAX_CONNECT_DELAY_SECONDS = 60; private static final AttributeKey<Promise<Channel>> CHANNEL_READY_PROMISE_ATTRIBUTE_KEY = AttributeKey.valueOf(ApnsChannelFactory.class, "channelReadyPromise"); private static final Logger log = LoggerFactory.getLogger(ApnsChannelFactory.class); @ChannelHandler.Sharable private static class ConnectionNegotiationErrorHandler extends ChannelHandlerAdapter { static final ConnectionNegotiationErrorHandler INSTANCE = new ConnectionNegotiationErrorHandler(); @Override public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { tryFailureAndLogRejectedCause(context.channel().attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(), cause); } } ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey, final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis, final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis, final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress, final EventLoopGroup eventLoopGroup) { this.sslContext = sslContext; if (this.sslContext instanceof ReferenceCounted) { ((ReferenceCounted) this.sslContext).retain(); } this.addressResolverGroup = proxyHandlerFactory == null ? new RoundRobinDnsAddressResolverGroup(ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup), DefaultDnsServerAddressStreamProvider.INSTANCE) : NoopAddressResolverGroup.INSTANCE; this.bootstrapTemplate = new Bootstrap(); this.bootstrapTemplate.group(eventLoopGroup); this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true); this.bootstrapTemplate.remoteAddress(apnsServerAddress); this.bootstrapTemplate.resolver(this.addressResolverGroup); if (connectTimeoutMillis > 0) { this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); if (proxyHandlerFactory != null) { pipeline.addFirst(proxyHandlerFactory.createProxyHandler()); } final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> handshakeFuture) { if (handshakeFuture.isSuccess()) { final String authority = channel.remoteAddress().getHostName(); final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder; if (signingKey != null) { clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder() .signingKey(signingKey) .authority(authority) .idlePingIntervalMillis(idlePingIntervalMillis); } else { clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder() .authority(authority) .idlePingIntervalMillis(idlePingIntervalMillis); } if (frameLogger != null) { clientHandlerBuilder.frameLogger(frameLogger); } final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build(); if (gracefulShutdownTimeoutMillis > 0) { apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis); } pipeline.addLast(new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS)); pipeline.addLast(apnsClientHandler); pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE); channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel); } else { tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(), handshakeFuture.cause()); } } }); pipeline.addLast(sslHandler); pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE); } }); } /** * Creates and connects a new channel. The initial connection attempt may be delayed to accommodate exponential * back-off requirements. * * @param channelReadyPromise the promise to be notified when a channel has been created and connected to the APNs * server * * @return a future that will be notified once a channel has been created and connected to the APNs server */ @Override public Future<Channel> create(final Promise<Channel> channelReadyPromise) { final long delay = this.currentDelaySeconds.get(); channelReadyPromise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) { final long updatedDelay = future.isSuccess() ? 0 : Math.max(Math.min(delay * 2, MAX_CONNECT_DELAY_SECONDS), MIN_CONNECT_DELAY_SECONDS); ApnsChannelFactory.this.currentDelaySeconds.compareAndSet(delay, updatedDelay); } }); this.bootstrapTemplate.config().group().schedule(new Runnable() { @Override public void run() { final Bootstrap bootstrap = ApnsChannelFactory.this.bootstrapTemplate.clone() .channelFactory(new AugmentingReflectiveChannelFactory<>( ClientChannelClassUtil.getSocketChannelClass(ApnsChannelFactory.this.bootstrapTemplate.config().group()), CHANNEL_READY_PROMISE_ATTRIBUTE_KEY, channelReadyPromise)); final ChannelFuture connectFuture = bootstrap.connect(); connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) { if (!future.isSuccess()) { // This may seem spurious, but our goal here is to accurately report the cause of // connection failure; if we just wait for connection closure, we won't be able to // tell callers anything more specific about what went wrong. tryFailureAndLogRejectedCause(channelReadyPromise, future.cause()); } } }); connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture> () { @Override public void operationComplete(final ChannelFuture future) { // We always want to try to fail the "channel ready" promise if the connection closes; if it has // already succeeded, this will have no effect. channelReadyPromise.tryFailure( new IllegalStateException("Channel closed before HTTP/2 preface completed.")); } }); } }, delay, TimeUnit.SECONDS); return channelReadyPromise; } /** * Destroys a channel by closing it. * * @param channel the channel to destroy * @param promise the promise to notify when the channel has been destroyed * * @return a future that will be notified when the channel has been destroyed */ @Override public Future<Void> destroy(final Channel channel, final Promise<Void> promise) { channel.close().addListener(new PromiseNotifier<>(promise)); return promise; } @Override public void close() { this.addressResolverGroup.close(); if (this.sslContext instanceof ReferenceCounted) { if (this.hasReleasedSslContext.compareAndSet(false, true)) { ((ReferenceCounted) this.sslContext).release(); } } } private static void tryFailureAndLogRejectedCause(final Promise<?> promise, final Throwable cause) { if (!promise.tryFailure(cause)) { log.warn("Tried to mark promise as \"failed,\" but it was already done.", cause); } } }
package chapter_6; public class EightQueens { public void arrangeQueens(int[][] chessBoard) { arrange8Queens(0, 0, chessBoard); } private boolean arrange8Queens(int column, int n, int[][] chessBoard) { if (n == chessBoard.length) { return true; } for (int i = 0; i < chessBoard.length; i++) { if (canPlaceQueen(i, column, chessBoard)) { chessBoard[i][column] = 1; if (arrange8Queens(column + 1, n + 1, chessBoard)) { return true; } else { chessBoard[i][column] = 0; } } } return false; } private boolean canPlaceQueen(int row, int column, int[][] chessBoard) { for (int i = 0; i < column; i++) { if (chessBoard[row][i] == 1) { return false; } } for (int i = row - 1, j = column - 1; i >= 0 && j >= 0; i if (chessBoard[i][j] == 1) { return false; } } for (int i = row, j = column; i < chessBoard.length && j >= 0; i++, j if (chessBoard[i][j] == 1) { return false; } } return true; } private void printBoard(int[][] chessBoard) { for (int i = 0; i < chessBoard.length; i++) { for (int j = 0; j < chessBoard[0].length; j++) { System.out.print(chessBoard[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { EightQueens eightQueens = new EightQueens(); int[][] chessBoard = new int[][] { new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0 } }; eightQueens.arrangeQueens(chessBoard); eightQueens.printBoard(chessBoard); } }
package org.dcache.xdr; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.dcache.utils.net.InetSocketAddresses; import org.dcache.xdr.gss.GssProtocolFilter; import org.dcache.xdr.gss.GssSessionManager; import org.dcache.xdr.portmap.GenericPortmapClient; import org.dcache.xdr.portmap.OncPortmapClient; import org.dcache.xdr.portmap.OncRpcPortmap; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.PortRange; import org.glassfish.grizzly.SocketBinder; import org.glassfish.grizzly.Transport; import org.glassfish.grizzly.filterchain.FilterChain; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.filterchain.TransportFilter; import org.glassfish.grizzly.monitoring.jmx.GrizzlyJmxManager; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.nio.transport.UDPNIOTransport; import org.glassfish.grizzly.nio.transport.UDPNIOTransportBuilder; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.dcache.xdr.GrizzlyUtils.*; import org.glassfish.grizzly.*; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; import org.glassfish.grizzly.strategies.WorkerThreadIOStrategy; public class OncRpcSvc { private final static Logger _log = LoggerFactory.getLogger(OncRpcSvc.class); private final static int BACKLOG = 4096; private final boolean _publish; private final PortRange _portRange; private final List<Transport> _transports = new ArrayList<Transport>(); private final Set<Connection<InetSocketAddress>> _boundConnections = new HashSet<Connection<InetSocketAddress>>(); public enum IoStrategy { SAME_THREAD { @Override IOStrategy getStrategy() { return SameThreadIOStrategy.getInstance(); } }, WORKER_THREAD { @Override IOStrategy getStrategy() { return WorkerThreadIOStrategy.getInstance(); } }; abstract IOStrategy getStrategy(); } private final ReplyQueue<Integer, RpcReply> _replyQueue = new ReplyQueue<Integer, RpcReply>(); /** * Handle RPCSEC_GSS */ private GssSessionManager _gssSessionManager; /** * mapping of registered programs. */ private final Map<OncRpcProgram, RpcDispatchable> _programs = new ConcurrentHashMap<OncRpcProgram, RpcDispatchable>(); /** * Create new RPC service with defined configuration. * @param builder to build this service */ OncRpcSvc(OncRpcSvcBuilder builder) { _publish = builder.isAutoPublish(); final int protocol = builder.getProtocol(); if ((protocol & (IpProtocolType.TCP | IpProtocolType.UDP)) == 0) { throw new IllegalArgumentException("TCP or UDP protocol have to be defined"); } IOStrategy grizzlyIoStrategy = builder.getIoStrategy().getStrategy(); if ((protocol & IpProtocolType.TCP) != 0) { final TCPNIOTransport tcpTransport = TCPNIOTransportBuilder .newInstance() .setReuseAddress(true) .setIOStrategy(grizzlyIoStrategy) .build(); _transports.add(tcpTransport); } if ((protocol & IpProtocolType.UDP) != 0) { final UDPNIOTransport udpTransport = UDPNIOTransportBuilder .newInstance() .setReuseAddress(true) .setIOStrategy(grizzlyIoStrategy) .build(); _transports.add(udpTransport); } _portRange = new PortRange(builder.getMinPort(), builder.getMaxPort()); if (builder.isWithJMX()) { final GrizzlyJmxManager jmxManager = GrizzlyJmxManager.instance(); for (Transport t : _transports) { jmxManager.registerAtRoot(t.getMonitoringConfig().createManagementObject(), t.getName() + "-" + _portRange); } } } /** * Register a new PRC service. Existing registration will be overwritten. * * @param prog program number * @param handler RPC requests handler. */ public void register(OncRpcProgram prog, RpcDispatchable handler) { _log.info("Registering new program {} : {}", prog, handler); _programs.put(prog, handler); } /** * Unregister program. * * @param prog */ public void unregister(OncRpcProgram prog) { _log.info("Unregistering program {}", prog); _programs.remove(prog); } /** * Add programs to existing services. * @param services */ public void setPrograms(Map<OncRpcProgram, RpcDispatchable> services) { _programs.putAll(services); } /** * Register services in portmap. * * @throws IOException * @throws UnknownHostException */ private void publishToPortmap(Connection<InetSocketAddress> connection, Set<OncRpcProgram> programs) throws IOException { OncRpcClient rpcClient = new OncRpcClient(InetAddress.getByName(null), IpProtocolType.UDP, OncRpcPortmap.PORTMAP_PORT); XdrTransport transport = rpcClient.connect(); OncPortmapClient portmapClient = new GenericPortmapClient(transport); try { String username = System.getProperty("user.name"); Transport t = connection.getTransport(); String uaddr = InetSocketAddresses.uaddrOf(connection.getLocalAddress()); for (OncRpcProgram program : programs) { try { if (t instanceof TCPNIOTransport) { portmapClient.setPort(program.getNumber(), program.getVersion(), "tcp", uaddr, username); } if (t instanceof UDPNIOTransport) { portmapClient.setPort(program.getNumber(), program.getVersion(), "udp", uaddr, username); } } catch (OncRpcException ex) { _log.error("Failed to register program", ex); } } } finally { rpcClient.close(); } } /** * UnRegister services in portmap. * * @throws IOException * @throws UnknownHostException */ private void clearPortmap(Set<OncRpcProgram> programs) throws IOException { OncRpcClient rpcClient = new OncRpcClient(InetAddress.getByName(null), IpProtocolType.UDP, OncRpcPortmap.PORTMAP_PORT); XdrTransport transport = rpcClient.connect(); OncPortmapClient portmapClient = new GenericPortmapClient(transport); try { String username = System.getProperty("user.name"); for (OncRpcProgram program : programs) { try { portmapClient.unsetPort(program.getNumber(), program.getVersion(), username); } catch (OncRpcException ex) { _log.error("Failed to unregister program", ex); } } } finally { rpcClient.close(); } } /** * Set {@link GssSessionManager} to handle GSS context if RPCSEG_GSS is used. * If {@code gssSessionManager} is <i>null</i> GSS authentication will be * disabled. * @param gssSessionManager */ public void setGssSessionManager(GssSessionManager gssSessionManager) { _gssSessionManager = gssSessionManager; } public void start() throws IOException { if(_publish) { clearPortmap(_programs.keySet()); } for (Transport t : _transports) { FilterChainBuilder filterChain = FilterChainBuilder.stateless(); filterChain.add(new TransportFilter()); filterChain.add(rpcMessageReceiverFor(t)); filterChain.add(new RpcProtocolFilter(_replyQueue)); // use GSS if configures if (_gssSessionManager != null) { filterChain.add(new GssProtocolFilter(_gssSessionManager)); } filterChain.add(new RpcDispatcher(_programs)); final FilterChain filters = filterChain.build(); t.setProcessor(filters); Connection<InetSocketAddress> connection = ((SocketBinder) t).bind("0.0.0.0", _portRange, BACKLOG); t.start(); _boundConnections.add(connection); if (_publish) { publishToPortmap(connection, _programs.keySet()); } } } public void stop() throws IOException { if (_publish) { clearPortmap(_programs.keySet()); } for (Transport t : _transports) { t.stop(); } } /** * Returns the address of the endpoint this service is bound to, * or <code>null<code> if it is not bound yet. * @param protocol * @return a {@link InetSocketAddress} representing the local endpoint of * this service, or <code>null</code> if it is not bound yet. */ public InetSocketAddress getInetSocketAddress(int protocol) { Class< ? extends Transport> transportClass = transportFor(protocol); for (Connection<InetSocketAddress> connection: _boundConnections) { if(connection.getTransport().getClass() == transportClass) return connection.getLocalAddress(); } return null; } }
package railo.runtime.i18n; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import railo.runtime.exp.ExpressionException; import railo.runtime.type.List; /** * Factory to create Locales by Cold Fusion rules */ public final class LocaleFactory { //private static Pattern localePattern = Pattern.compile("^\\s*([^\\s\\(]+)\\s*(\\(\\s*([^\\s\\)]+)\\s*\\))?\\s*$"); private static Pattern localePattern = Pattern.compile("^\\s*([^\\(]+)\\s*(\\(\\s*([^\\)]+)\\s*\\))?\\s*$"); private static Pattern localePattern2 = Pattern.compile("^([a-z]{2})_([a-z]{2,3})$"); private static Pattern localePattern3 = Pattern.compile("^([a-z]{2})_([a-z]{2,3})_([a-z]{2,})$"); private static Map locales=new LinkedHashMap(); private static Map localeAlias=new LinkedHashMap(); private static String list; static { Locale[] ls = Locale.getAvailableLocales(); String key; StringBuffer sb=new StringBuffer(); for(int i=0;i<ls.length;i++) { key=ls[i].getDisplayName(Locale.US).toLowerCase(); locales.put(key, ls[i]); if(key.indexOf(',')!=-1){ key=ls[i].toString(); //print.ln(key); } if(i>0)sb.append(","); sb.append(key); } list=sb.toString(); localeAlias.put("chinese (china)", Locale.CHINA); localeAlias.put("chinese (hong kong)",new Locale("zh","HK")); localeAlias.put("chinese (taiwan)",new Locale("zho","TWN")); localeAlias.put("dutch (belgian)",new Locale("nl","BE")); localeAlias.put("dutch (belgium)",new Locale("nl","BE")); localeAlias.put("dutch (standard)",new Locale("nl","NL")); localeAlias.put("english (australian)",new Locale("en","AU")); localeAlias.put("english (australia)",new Locale("en","AU")); localeAlias.put("english (canadian)",new Locale("en","CA")); localeAlias.put("english (canadia)",new Locale("en","CA")); localeAlias.put("english (new zealand)",new Locale("en","NZ")); localeAlias.put("english (uk)",new Locale("en","GB")); localeAlias.put("english (united kingdom)",new Locale("en","GB")); localeAlias.put("english (us)",new Locale("en","US")); localeAlias.put("french (belgium)",new Locale("fr","BE")); localeAlias.put("french (belgian)",new Locale("fr","BE")); localeAlias.put("french (canadian)",new Locale("fr","CA")); localeAlias.put("french (canadia)",new Locale("fr","CA")); localeAlias.put("french (standard)",new Locale("fr","FRA")); localeAlias.put("french (swiss)",new Locale("fr","CH")); localeAlias.put("german (austrian)",new Locale("de","AT")); localeAlias.put("german (austria)",new Locale("de","AT")); localeAlias.put("german (standard)",new Locale("de","DE")); localeAlias.put("german (swiss)",new Locale("de","CH")); localeAlias.put("italian (standard)",new Locale("it","IT")); localeAlias.put("italian (swiss)",new Locale("it","CH")); localeAlias.put("japanese",new Locale("ja","JP")); localeAlias.put("korean",Locale.KOREAN); localeAlias.put("norwegian (bokmal)",new Locale("no","NO")); localeAlias.put("norwegian (nynorsk)",new Locale("no","NO")); localeAlias.put("portuguese (brazilian)",new Locale("pt","BR")); localeAlias.put("portuguese (brazil)",new Locale("pt","BR")); localeAlias.put("portuguese (standard)",new Locale("pt","PT")); localeAlias.put("rhaeto-romance (swiss)",new Locale("rm","CH")); locales.put("rhaeto-romance (swiss)",new Locale("rm","CH")); localeAlias.put("spanish (modern)",new Locale("es","ES")); localeAlias.put("spanish (standard)",new Locale("es","ES")); localeAlias.put("swedish",new Locale("sv","SE")); } private LocaleFactory(){} /** * @param strLocale * @param defaultValue * @return return locale match to String */ public static Locale getLocale(String strLocale, Locale defaultValue) { try { return getLocale(strLocale); } catch (ExpressionException e) { return defaultValue; } } /** * @param strLocale * @return return locale match to String * @throws ExpressionException */ public static Locale getLocale(String strLocale) throws ExpressionException { String strLocaleLC = strLocale.toLowerCase().trim(); Locale l=(Locale) locales.get(strLocaleLC); if(l!=null) return l; l=(Locale) localeAlias.get(strLocaleLC); if(l!=null) return l; Matcher matcher = localePattern2.matcher(strLocaleLC); if(matcher.find()) { int len=matcher.groupCount(); if(len==2) { String lang=matcher.group(1).trim(); String country=matcher.group(2).trim(); Locale locale=new Locale(lang,country); try { locale.getISO3Language(); localeAlias.put(strLocaleLC, locale); return locale; } catch(Exception e) {} } } matcher = localePattern3.matcher(strLocaleLC); if(matcher.find()) { int len=matcher.groupCount(); if(len==3) { String lang=matcher.group(1).trim(); String country=matcher.group(2).trim(); String variant=matcher.group(3).trim(); Locale locale=new Locale(lang,country,variant); try { locale.getISO3Language(); localeAlias.put(strLocaleLC, locale); return locale; } catch(Exception e) {} } } matcher=localePattern.matcher(strLocaleLC); if(matcher.find()) { int len=matcher.groupCount(); if(len==3) { String lang=matcher.group(1).trim(); String country=matcher.group(3); if(country!=null)country=country.trim(); Object objLocale=null; if(country!=null) objLocale=locales.get(lang.toLowerCase()+" ("+(country.toLowerCase())+")"); else objLocale=locales.get(lang.toLowerCase()); if(objLocale!=null)return (Locale)objLocale; Locale locale; if(country!=null)locale=new Locale(lang.toUpperCase(),country.toLowerCase()); else locale=new Locale(lang); try { locale.getISO3Language(); } catch(Exception e) { if(strLocale.indexOf('-')!=-1) return getLocale(strLocale.replace('-', '_')); throw new ExpressionException("unsupported Locale ["+strLocale+"]","supported Locales are:"+getSupportedLocalesAsString()); } localeAlias.put(strLocaleLC, locale); return locale; } } throw new ExpressionException("can't cast value ("+strLocale+") to a Locale","supported Locales are:"+getSupportedLocalesAsString()); } private static String getSupportedLocalesAsString() { //StringBuffer sb=new StringBuffer(); // TODO chnge from ArryObject to string return List.arrayToList((String[])locales.keySet().toArray(new String[locales.size()]),","); } /** * @param locale * @return cast a Locale to a String */ public static String toString(Locale locale) { String lang=locale.getLanguage(); String country=locale.getCountry(); synchronized(localeAlias){ Iterator it = localeAlias.entrySet().iterator(); Map.Entry entry; while(it.hasNext()) { entry=(Entry) it.next(); //Object qkey=it.next(); Locale curr=(Locale) entry.getValue(); if(lang.equals(curr.getLanguage()) && country.equals(curr.getCountry())) { return entry.getKey().toString(); } } } return locale.getDisplayName(Locale.ENGLISH); } /** * @return Returns the locales. */ public static Map getLocales() { return locales; } public static String getLocaleList() { return list; } }
package yasp; import com.google.protobuf.GeneratedMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skadistats.clarity.decoder.Util; import skadistats.clarity.model.GameEvent; import skadistats.clarity.model.Entity; import skadistats.clarity.model.GameEvent; import skadistats.clarity.model.GameEventDescriptor; import skadistats.clarity.model.s1.GameRulesStateType; import skadistats.clarity.processor.gameevents.OnGameEvent; import skadistats.clarity.processor.gameevents.CombatLog; import skadistats.clarity.processor.gameevents.OnCombatLogEntry; import skadistats.clarity.processor.entities.Entities; import skadistats.clarity.processor.entities.UsesEntities; import skadistats.clarity.processor.entities.OnEntityEntered; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.reader.OnTickStart; import skadistats.clarity.processor.reader.OnTickEnd; import skadistats.clarity.processor.runner.Context; import skadistats.clarity.processor.runner.SimpleRunner; import skadistats.clarity.source.InputStreamSource; import skadistats.clarity.wire.s1.proto.S1UserMessages.CUserMsg_SayText2; import skadistats.clarity.wire.s2.proto.S2UserMessages.CUserMessageSayText2; import skadistats.clarity.wire.common.proto.DotaUserMessages.CDOTAUserMsg_ChatEvent; import skadistats.clarity.wire.common.proto.DotaUserMessages.CDOTAUserMsg_LocationPing; import skadistats.clarity.wire.common.proto.DotaUserMessages.CDOTAUserMsg_SpectatorPlayerClick; import skadistats.clarity.wire.common.proto.DotaUserMessages.DOTA_COMBATLOG_TYPES; import skadistats.clarity.wire.common.proto.Demo.CDemoFileInfo; import skadistats.clarity.wire.common.proto.Demo.CGameInfo.CDotaGameInfo.CPlayerInfo; import skadistats.clarity.model.FieldPath; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.HashMap; import java.util.Iterator; import java.util.Arrays; import com.google.gson.Gson; public class Main { private final Logger log = LoggerFactory.getLogger(Main.class.getPackage().getClass()); float INTERVAL = 1; HashMap<Integer, Integer> slot_to_hero = new HashMap<Integer, Integer>(); HashMap<Long, Integer> steamid_to_slot = new HashMap<Long, Integer>(); float nextInterval = 0; Integer time = 0; int numPlayers = 10; EventStream es = new EventStream(); //Set<Integer> seenEntities = new HashSet<Integer>(); //@OnMessage(GeneratedMessage.class) public void onMessage(Context ctx, GeneratedMessage message) { System.err.println(message.getClass().getName()); System.out.println(message.toString()); } /* //@OnMessage(CDOTAUserMsg_SpectatorPlayerClick.class) public void onPlayerClick(Context ctx, CDOTAUserMsg_SpectatorPlayerClick message){ Entry entry = new Entry(time); entry.type = "clicks"; //TODO need to get the entity by index, and figure out the owner entity, then figure out the player controlling //assumes all clicks are made by the controlling player entry.slot = (Integer)message.getEntindex()-2; entry.key = String.valueOf(message.getOrderType()); //theres also target_index es.output(entry); } */ @OnMessage(CDOTAUserMsg_LocationPing.class) public void onPlayerPing(Context ctx, CDOTAUserMsg_LocationPing message){ Entry entry = new Entry(time); entry.type = "pings"; Integer player1=(Integer)message.getPlayerId(); entry.slot = player1; /* System.err.println(message); player_id: 7 location_ping { x: 5871 y: 6508 target: -1 direct_ping: false type: 0 } */ //we could get the ping coordinates/type if we cared //entry.key = String.valueOf(message.getOrderType()); es.output(entry); } @OnMessage(CDOTAUserMsg_ChatEvent.class) public void onChatEvent(Context ctx, CDOTAUserMsg_ChatEvent message) { CDOTAUserMsg_ChatEvent u = message; Integer player1=(Integer)u.getPlayerid1(); Integer player2=(Integer)u.getPlayerid2(); Integer value = (Integer)u.getValue(); String type = String.valueOf(u.getType()); Entry entry = new Entry(time); entry.type = "chat_event"; entry.subtype = type; entry.player1 = player1; entry.player2 = player2; entry.value = value; es.output(entry); } @OnMessage(CUserMsg_SayText2.class) public void onAllChatS1(Context ctx, CUserMsg_SayText2 message) { Entry entry = new Entry(time); entry.unit = String.valueOf(message.getPrefix()); entry.key = String.valueOf(message.getText()); //TODO this message has a client field, likely based on connection order. If we can figure out how the ids are assigned we can use this to match chat messages to players //entry.slot = message.getClient(); entry.type = "chat"; es.output(entry); } @OnMessage(CUserMessageSayText2.class) public void onAllChatS2(Context ctx, CUserMessageSayText2 message) { Entry entry = new Entry(time); entry.unit = String.valueOf(message.getParam1()); entry.key = String.valueOf(message.getParam2()); //TODO this message has a client field, likely based on connection order. If we can figure out how the ids are assigned we can use this to match chat messages to players //entry.slot = message.getClient(); entry.type = "chat"; es.output(entry); } @OnMessage(CDemoFileInfo.class) public void onFileInfo(Context ctx, CDemoFileInfo message){ //test dump entity /* int ind = 0; while(ind<1000){ try{ System.err.println(ctx.getProcessor(Entities.class).getByIndex(ind).getDtClass().getDtName()); } catch(Exception e){ System.err.println(e); } ind++; } */ //load epilogue CDemoFileInfo info = message; List<CPlayerInfo> players = info.getGameInfo().getDota().getPlayerInfoList(); for (int i = 0;i<players.size();i++) { Entry entry = new Entry(); entry.type="name"; entry.key = players.get(i).getPlayerName(); entry.slot = steamid_to_slot.get(players.get(i).getSteamid()); es.output(entry); } for (int i = 0;i<players.size();i++) { Entry entry = new Entry(); entry.type="steam_id"; entry.key = String.valueOf(players.get(i).getSteamid()); entry.slot = steamid_to_slot.get(players.get(i).getSteamid()); es.output(entry); } if (true){ Entry entry = new Entry(); entry.type="match_id"; entry.value = info.getGameInfo().getDota().getMatchId(); es.output(entry); } if (true){ //emit epilogue event Entry entry = new Entry(); entry.type="epilogue"; entry.key = new Gson().toJson(info); es.output(entry); } } @OnCombatLogEntry public void onCombatLogEntry(Context ctx, CombatLog.Entry cle) { //System.err.format("stun: %s, slow: %s\n", cle.getStunDuration(), cle.getSlowDuration()); //System.err.format("x: %s, y: %s\n", cle.getLocationX(), cle.getLocationY()); //System.err.format("modifier_duration: %s, last_hits: %s, att_team: %s, target_team: %s, obs_placed: %s\n",cle.getModifierDuration(), cle.getAttackerTeam(), cle.getTargetTeam(), cle.getObsWardsPlaced()); time = Math.round(cle.getTimestamp()); String type = DOTA_COMBATLOG_TYPES.valueOf(cle.getType()).name(); if (true){ //create a new entry Entry entry = new Entry(time); entry.type="combat_log"; //entry.subtype=String.valueOf(cle.getType()); entry.subtype = type; //translate the fields using string tables if necessary (get*Name methods) entry.attackername=cle.getAttackerName(); entry.targetname=cle.getTargetName(); entry.sourcename=cle.getSourceName(); entry.targetsourcename=cle.getTargetSourceName(); entry.inflictor=cle.getInflictorName(); entry.gold_reason=cle.getGoldReason(); entry.xp_reason=cle.getXpReason(); entry.attackerhero=cle.isAttackerHero(); entry.targethero=cle.isTargetHero(); entry.attackerillusion=cle.isAttackerIllusion(); entry.targetillusion=cle.isTargetIllusion(); entry.value=cle.getValue(); //value may be out of bounds in string table, we can only get valuename if a purchase (type 11) if (type=="DOTA_COMBATLOG_PURCHASE"){ entry.valuename=cle.getValueName(); } //TODO re-enable combat log when entities are debugged //es.output(entry); } if (type == "DOTA_COMBATLOG_GAME_STATE") { //emit game state change ("PLAYING, POST_GAME, etc.") (type 9) //used to compute game zero time so we can display accurate timestamps Entry entry = new Entry(time); //if the value is out of bounds, just make it the value itself String state = GameRulesStateType.values().length >= cle.getValue() ? GameRulesStateType.values()[cle.getValue() - 1].toString() : String.valueOf(cle.getValue() - 1); entry.key = state; entry.type = "state"; es.output(entry); } } @OnEntityEntered public void onEntityEntered(Context ctx, Entity e) { //CDOTA_NPC_Observer_Ward //CDOTA_NPC_Observer_Ward_TrueSight //s1 "DT_DOTA_NPC_Observer_Ward" //s1 "DT_DOTA_NPC_Observer_Ward_TrueSight" boolean isObserver = e.getDtClass().getDtName().equals("CDOTA_NPC_Observer_Ward"); boolean isSentry = e.getDtClass().getDtName().equals("CDOTA_NPC_Observer_Ward_TrueSight"); if (isObserver || isSentry) { //System.err.println(e); Entry entry = new Entry(time); Integer[] pos = {(Integer)getEntityProperty(e, "m_cellX", null),(Integer)getEntityProperty(e, "m_cellY", null)}; entry.type = isObserver ? "obs" : "sen"; entry.key = Arrays.toString(pos); Integer owner = (Integer)getEntityProperty(e, "m_hOwnerEntity", null); Entity ownerEntity = ctx.getProcessor(Entities.class).getByHandle(owner); entry.slot = ownerEntity!=null ? (Integer)getEntityProperty(ownerEntity, "m_iPlayerID", null) : null; //2/3 radiant/dire //entry.team = e.getProperty("m_iTeamNum"); es.output(entry); } } @UsesEntities @OnTickStart public void onTickStart(Context ctx, boolean synthetic){ //s1 DT_DOTAGameRulesProxy Entity grp = ctx.getProcessor(Entities.class).getByDtName("CDOTAGamerules"); if (grp!=null){ System.err.println(grp); //dota_gamerules_data.m_iGameMode = 22 //dota_gamerules_data.m_unMatchID64 = 1193091757 time = Math.round((float)getEntityProperty(grp, "dota_gamerules_data.m_fGameTime", null)); } if (time >= nextInterval){ Entity pr = ctx.getProcessor(Entities.class).getByDtName("CDOTA_PlayerResource"); Entity dData = ctx.getProcessor(Entities.class).getByDtName("CDOTA_DataDire"); Entity rData = ctx.getProcessor(Entities.class).getByDtName("CDOTA_DataRadiant"); if (pr!=null){ //System.err.println(pr); int half = numPlayers / 2; for (int i = 0; i < numPlayers; i++) { Entry entry = new Entry(time); entry.type = "interval"; entry.slot = i; Entity e = i < half ? dData : rData; entry.gold = (Integer) getEntityProperty(e, "m_vecDataTeam.%i.m_iTotalEarnedGold", i % half); entry.lh = (Integer) getEntityProperty(e, "m_vecDataTeam.%i.m_iLastHitCount", i % half); entry.xp = (Integer) getEntityProperty(e, "m_vecDataData.%i.m_iTotalEarnedXP", i % half); entry.stuns=(Float)getEntityProperty(e, "m_vecDataTeam.%i.m_fStuns", i % half); Integer hero = (Integer)getEntityProperty(pr, "m_vecPlayerTeamData.%i.m_nSelectedHeroID", i); Long steamid = (Long)getEntityProperty(pr, "m_vecPlayerData.%i.m_iPlayerSteamID", i); int handle = (Integer)getEntityProperty(pr, "m_vecPlayerTeamData.%i.m_hSelectedHero", i); //booleans to check at endgame //m_bHasPredictedVictory.0000 //m_bVoiceChatBanned.0000 //m_bHasRandomed.0000 //m_bHasRepicked.0000 //can do all these stats with each playerresource interval for graphs? //m_iKills.0000 //m_iAssists.0000 //m_iDeaths.0000 //gem, rapier time? //need to dump inventory items for each player and possibly keep track of item entity handles //time dead, count number of intervals where this value is >0? //m_iRespawnSeconds.0000 if (hero>0 && (!slot_to_hero.containsKey(i) || !slot_to_hero.get(i).equals(hero))){ //hero_to_slot.put(hero, i); slot_to_hero.put(i, hero); Entry entry2 = new Entry(time); entry2.type="hero_log"; entry2.slot=i; entry2.key=String.valueOf(hero); es.output(entry2); } steamid_to_slot.put(steamid, i); //get the player's controlled hero's coordinates Entity e = ctx.getProcessor(Entities.class).getByHandle(handle); if (e!=null){ entry.x=(Integer)getEntityProperty(e, "m_cellX", null); entry.y=(Integer)getEntityProperty(e, "m_cellY", null); } es.output(entry); } nextInterval += INTERVAL; } } } public <T> T getEntityProperty(Entity e, String property, Integer idx){ if (idx!=null){ property = property.replace("%i", Util.arrayIdxToString(idx)); } System.err.println(property); FieldPath fp = e.getDtClass().getFieldPathForName(property); //fp.path[0] += (index == null) ? 0 : index; return e.getPropertyForFieldPath(fp); } public void run(String[] args) throws Exception { long tStart = System.currentTimeMillis(); new SimpleRunner(new InputStreamSource(System.in)).runWith(this); long tMatch = System.currentTimeMillis() - tStart; System.err.format("total time taken: %s\n", (tMatch) / 1000.0); } public static void main(String[] args) throws Exception { new Main().run(args); } }
// Decompiler options: packimports(3) package raptor.connector.ics.timeseal; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import raptor.util.RaptorLogger; public class TimesealingSocket extends Socket { private class CryptOutputStream extends OutputStream { private byte buffer[]; private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); private final OutputStream outputStreamToDecorate; private final byte timesealKey[] = "Timestamp (FICS) v1.0 - programmed by Henrik Gram." .getBytes(); public CryptOutputStream(OutputStream outputstream) { buffer = new byte[10000]; outputStreamToDecorate = outputstream; } @Override public void write(int i) throws IOException { if (i == 10) { synchronized (TimesealingSocket.this) { int resultLength = crypt( byteArrayOutputStream.toByteArray(), System.currentTimeMillis() - initialTime); outputStreamToDecorate.write(buffer, 0, resultLength); outputStreamToDecorate.flush(); byteArrayOutputStream.reset(); } } else { byteArrayOutputStream.write(i); } } private int crypt(byte stringToWriteBytes[], long timestamp) { int bytesInLength = stringToWriteBytes.length; System.arraycopy(stringToWriteBytes, 0, buffer, 0, stringToWriteBytes.length); buffer[bytesInLength++] = 24; byte abyte1[] = Long.toString(timestamp).getBytes(); System.arraycopy(abyte1, 0, buffer, bytesInLength, abyte1.length); bytesInLength += abyte1.length; buffer[bytesInLength++] = 25; int j = bytesInLength; for (bytesInLength += 12 - bytesInLength % 12; j < bytesInLength;) { buffer[j++] = 49; } for (int k = 0; k < bytesInLength; k++) { buffer[k] = (byte) (buffer[k] | 0x80); } for (int i1 = 0; i1 < bytesInLength; i1 += 12) { byte byte0 = buffer[i1 + 11]; buffer[i1 + 11] = buffer[i1]; buffer[i1] = byte0; byte0 = buffer[i1 + 9]; buffer[i1 + 9] = buffer[i1 + 2]; buffer[i1 + 2] = byte0; byte0 = buffer[i1 + 7]; buffer[i1 + 7] = buffer[i1 + 4]; buffer[i1 + 4] = byte0; } int l1 = 0; for (int j1 = 0; j1 < bytesInLength; j1++) { buffer[j1] = (byte) (buffer[j1] ^ timesealKey[l1]); l1 = (l1 + 1) % timesealKey.length; } for (int k1 = 0; k1 < bytesInLength; k1++) { buffer[k1] = (byte) (buffer[k1] - 32); } buffer[bytesInLength++] = -128; buffer[bytesInLength++] = 10; return bytesInLength; } } private static final RaptorLogger LOG = RaptorLogger .getLog(TimesealingSocket.class); private CryptOutputStream cryptedOutputStream; private volatile long initialTime; private String initialTimesealString = null; private volatile Thread thread; // private final TimesealPipe timesealPipe; public TimesealingSocket(InetAddress inetaddress, int i, String intialTimestampString) throws IOException { super(inetaddress, i); initialTimesealString = intialTimestampString; // timesealPipe = new TimesealPipe(10000); init(); } public TimesealingSocket(String s, int i, String intialTimestampString) throws IOException { super(s, i); // timesealPipe = new TimesealPipe(10000); initialTimesealString = intialTimestampString; init(); } @Override public void close() throws IOException { super.close(); thread = null; } @Override public InputStream getInputStream() throws IOException { return super.getInputStream(); // return timesealPipe.getTimesealInputStream(); } @Override public CryptOutputStream getOutputStream() throws IOException { return cryptedOutputStream; } private void init() throws IOException { initialTime = System.currentTimeMillis(); cryptedOutputStream = new CryptOutputStream(super.getOutputStream()); writeInitialTimesealString(); } private void writeInitialTimesealString() throws IOException { // BICS can't handle speedy connections so this slows it down a bit. try { Thread.sleep(100); } catch (InterruptedException ie) { } OutputStream outputstream = getOutputStream(); synchronized (outputstream) { outputstream.write(initialTimesealString.getBytes()); outputstream.write(10); } } }
package org.aesh.readline; import org.aesh.readline.cursor.Line; import org.aesh.readline.cursor.CursorListener; import org.aesh.readline.history.InMemoryHistory; import org.aesh.readline.paste.PasteManager; import org.aesh.readline.undo.UndoAction; import org.aesh.readline.undo.UndoManager; import org.aesh.utils.ANSI; import org.aesh.utils.Config; import org.aesh.readline.completion.CompletionHandler; import org.aesh.readline.editing.EditMode; import org.aesh.readline.history.History; import org.aesh.terminal.Connection; import org.aesh.readline.util.LoggerUtil; import java.util.logging.Logger; import org.aesh.terminal.tty.Size; public class AeshConsoleBuffer implements ConsoleBuffer { private EditMode editMode; private final Buffer buffer; private final Connection connection; private final UndoManager undoManager; private final PasteManager pasteManager; private final History history; private final CompletionHandler completionHandler; private Size size; private final boolean ansiMode; private static final Logger LOGGER = LoggerUtil.getLogger(AeshConsoleBuffer.class.getName()); private final CursorListener cursorListener; public AeshConsoleBuffer(Connection connection, Prompt prompt, EditMode editMode, History history, CompletionHandler completionHandler, boolean ansi, CursorListener listener) { this.connection = connection; this.ansiMode = ansi; this.buffer = new Buffer(prompt); pasteManager = new PasteManager(); undoManager = new UndoManager(); if(history == null) { this.history = new InMemoryHistory(); this.history.enable(); } else { //do not enable an history object if its given this.history = history; } this.completionHandler = completionHandler; this.size = connection.size(); this.editMode = editMode; this.cursorListener = listener; } @Override public History history() { return history; } @Override public CompletionHandler completer() { return completionHandler; } @Override public void setSize(Size size) { this.size = size; } @Override public Size size() { return size; } @Override public Buffer buffer() { return this.buffer; } @Override public UndoManager undoManager() { return undoManager; } @Override public void addActionToUndoStack() { undoManager.addUndo(new UndoAction( buffer().cursor(), buffer().multiLine())); } @Override public PasteManager pasteManager() { return pasteManager; } @Override public void moveCursor(int where) { buffer.move(connection.stdoutHandler(), where, size().getWidth(), isViMode()); if (cursorListener != null) { cursorListener.moved(new Line(buffer, connection, size.getWidth())); } } @Override public void drawLine() { buffer.print(connection.stdoutHandler(), size().getWidth()); } @Override public void drawLineForceDisplay() { buffer.setIsPromptDisplayed(false); buffer.print(connection.stdoutHandler(), size().getWidth()); } @Override public void writeChar(char input) { buffer.insert(connection.stdoutHandler(), input, size().getWidth()); } @Override public void writeOut(String out) { connection.write(out); } @Override public void writeOut(int[] out) { connection.stdoutHandler().accept(out); } @Override public void writeChars(int[] input) { buffer.insert(connection.stdoutHandler(), input, size().getWidth()); } @Override public void writeString(String input) { if(input != null && input.length() > 0) buffer.insert(connection.stdoutHandler(), input, size().getWidth()); } @Override public void setPrompt(Prompt prompt) { buffer.setPrompt(prompt, connection.stdoutHandler(), size().getWidth()); } @Override public void insert(String insert, int position) { buffer.insert(connection.stdoutHandler(), insert, size().getWidth()); } @Override public void insert(int[] insert) { buffer.insert(connection.stdoutHandler(), insert, size().getWidth()); } @Override public void delete(int delta) { buffer.delete(connection.stdoutHandler(), delta, size().getWidth(), isViMode()); } @Override public void upCase() { buffer.upCase(connection.stdoutHandler()); } @Override public void downCase() { buffer.downCase(connection.stdoutHandler()); } @Override public void changeCase() { buffer.changeCase(connection.stdoutHandler()); } @Override public void replace(int[] line) { buffer.replace(connection.stdoutHandler(), line, size().getWidth()); } @Override public void replace(String line) { buffer.replace(connection.stdoutHandler(), line, size().getWidth()); } @Override public void reset() { buffer.reset(); } @Override public void clear(boolean includeBuffer) { //(windows fix) if(!Config.isOSPOSIXCompatible()) connection.stdoutHandler().accept(Config.CR); //first clear console connection.stdoutHandler().accept(ANSI.CLEAR_SCREEN); int cursorPosition = -1; if(buffer.cursor() < buffer.length()) { cursorPosition = buffer.cursor(); buffer.move(connection.stdoutHandler(), buffer.length() - cursorPosition, size().getWidth()); } //move cursor to correct position connection.stdoutHandler().accept(new int[] {27, '[', '1', ';', '1', 'H'}); //then write prompt if(!includeBuffer) buffer().reset(); //redraw drawLineForceDisplay(); if(cursorPosition > -1) buffer.move(connection.stdoutHandler(), cursorPosition-buffer.length(), size().getWidth()); } private boolean isViMode() { return editMode.mode() == EditMode.Mode.VI && editMode.status() != EditMode.Status.EDIT; } }
package com.openxc; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.test.ServiceTestCase; import android.test.suitebuilder.annotation.MediumTest; import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.*; import com.openxc.measurements.Latitude; import com.openxc.measurements.Longitude; import com.openxc.measurements.VehicleSpeed; import com.openxc.messages.SimpleVehicleMessage; import com.openxc.remote.VehicleService; import com.openxc.VehicleManager; import com.openxc.sources.BaseVehicleDataSource; import com.openxc.sources.SourceCallback; import com.openxc.sources.TestSource; public class VehicleLocationProviderTest extends ServiceTestCase<VehicleManager> { VehicleManager manager; VehicleLocationProvider locationProvider; TestSource source; LocationManager mLocationManager; Double latitude = 42.1; Double longitude = 100.1; Double speed = 23.2; public VehicleLocationProviderTest() { super(VehicleManager.class); } @Override protected void setUp() throws Exception { super.setUp(); source = new TestSource(); // if the service is already running (and thus may have old data // cached), kill it. getContext().stopService(new Intent(getContext(), VehicleService.class)); mLocationManager = (LocationManager) getContext().getSystemService( Context.LOCATION_SERVICE); try { // Remove it so that the VehicleLocationProvider re-adds it with fresh // location history mLocationManager.removeTestProvider( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER); } catch(IllegalArgumentException e) { } try { // Remove it so that the VehicleLocationProvider re-adds it with fresh // location history mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER); } catch(IllegalArgumentException e) { } } // Due to bugs and or general crappiness in the ServiceTestCase, you will // run into many unexpected problems if you start the service in setUp - see // this blog post for more details: private void prepareServices() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), VehicleManager.class); manager = ((VehicleManager.VehicleBinder) bindService(startIntent)).getService(); manager.waitUntilBound(); manager.addSource(source); locationProvider = new VehicleLocationProvider(getContext(), manager); locationProvider.setOverwritingStatus(true); } @Override protected void tearDown() throws Exception { if(locationProvider != null) { locationProvider.stop(); } super.tearDown(); } @MediumTest public void testNoLocationMessages() { prepareServices(); assertThat(mLocationManager.getLastKnownLocation( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER), nullValue()); } @MediumTest public void testNoLocationWithOnlyLatitude() { prepareServices(); source.inject(Latitude.ID, latitude); TestUtils.pause(200); assertThat(mLocationManager.getLastKnownLocation( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER), nullValue()); } @MediumTest public void testNoLocationWithOnlyLongitude() { prepareServices(); source.inject(Longitude.ID, longitude); TestUtils.pause(100); assertThat(mLocationManager.getLastKnownLocation( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER), nullValue()); } @MediumTest public void testNoLocationWithOnlySpeed() { prepareServices(); source.inject(VehicleSpeed.ID, speed); TestUtils.pause(100); assertThat(mLocationManager.getLastKnownLocation( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER), nullValue()); } @MediumTest public void testLocationWhenAllPresent() { prepareServices(); source.inject(Latitude.ID, latitude); source.inject(Longitude.ID, longitude); source.inject(VehicleSpeed.ID, speed); TestUtils.pause(200); Location location = mLocationManager.getLastKnownLocation( VehicleLocationProvider.VEHICLE_LOCATION_PROVIDER); assertThat(location, notNullValue()); assertThat(location.getLatitude(), equalTo(latitude)); assertThat(location.getLongitude(), equalTo(longitude)); assertThat(location.getSpeed(), equalTo(speed.floatValue())); } @MediumTest public void testOverwritesNativeGps() { prepareServices(); source.inject(Latitude.ID, latitude); source.inject(Longitude.ID, longitude); source.inject(VehicleSpeed.ID, speed); TestUtils.pause(100); Location location = mLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER); assertThat(location, notNullValue()); assertThat(location.getLatitude(), equalTo(latitude)); assertThat(location.getLongitude(), equalTo(longitude)); assertThat(location.getSpeed(), equalTo(speed.floatValue())); } @MediumTest public void testNotOverwrittenWhenDisabled() { prepareServices(); locationProvider.setOverwritingStatus(false); source.inject(Latitude.ID, latitude); source.inject(Longitude.ID, longitude); source.inject(VehicleSpeed.ID, speed); TestUtils.pause(200); Location location = mLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER); assertThat(location, nullValue()); } }
package org.jgrapes.portal; import freemarker.template.Configuration; import freemarker.template.SimpleScalar; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.nio.CharBuffer; import java.security.Principal; import java.text.Collator; import java.text.ParseException; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Optional; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.StreamSupport; import javax.json.Json; import javax.json.JsonReader; import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; import org.jdrupes.httpcodec.protocols.http.HttpField; import org.jdrupes.httpcodec.protocols.http.HttpRequest; import org.jdrupes.httpcodec.protocols.http.HttpResponse; import org.jdrupes.httpcodec.types.Converters; import org.jdrupes.httpcodec.types.Directive; import org.jdrupes.httpcodec.types.MediaType; import org.jdrupes.json.JsonDecodeException; import org.jgrapes.core.Channel; import org.jgrapes.core.CompletionLock; import org.jgrapes.core.Component; import org.jgrapes.core.annotation.Handler; import org.jgrapes.core.events.Error; import org.jgrapes.http.LanguageSelector.Selection; import org.jgrapes.http.Session; import org.jgrapes.http.annotation.RequestHandler; import org.jgrapes.http.events.GetRequest; import org.jgrapes.http.events.Response; import org.jgrapes.http.events.WebSocketAccepted; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.events.Closed; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.ByteBufferOutputStream; import org.jgrapes.io.util.CharBufferWriter; import org.jgrapes.io.util.InputStreamPipeline; import org.jgrapes.io.util.LinkedIOSubchannel; import org.jgrapes.io.util.ManagedCharBuffer; import org.jgrapes.portal.events.JsonInput; import org.jgrapes.portal.events.JsonOutput; import org.jgrapes.portal.events.PortalReady; import org.jgrapes.portal.events.PortletResourceRequest; import org.jgrapes.portal.events.PortletResourceResponse; import org.jgrapes.portal.events.SetLocale; import org.jgrapes.portal.events.SetTheme; import org.jgrapes.portal.themes.base.Provider; import org.jgrapes.util.events.KeyValueStoreData; import org.jgrapes.util.events.KeyValueStoreQuery; import org.jgrapes.util.events.KeyValueStoreUpdate; public class PortalView extends Component { private Portal portal; private ServiceLoader<ThemeProvider> themeLoader; private static Configuration fmConfig = null; private Function<Locale,ResourceBundle> resourceBundleSupplier; private BiFunction<ThemeProvider,String,InputStream> fallbackResourceSupplier = (themeProvider, resource) -> { return null; }; private Set<Locale> supportedLocales; private ThemeProvider baseTheme; private Map<String,Object> portalBaseModel = new HashMap<>(); private RenderSupport renderSupport = new RenderSupportImpl(); /** * @param componentChannel */ public PortalView(Portal portal, Channel componentChannel) { super(componentChannel); this.portal = portal; if (fmConfig == null) { fmConfig = new Configuration(Configuration.VERSION_2_3_26); fmConfig.setClassLoaderForTemplateLoading( getClass().getClassLoader(), "org/jgrapes/portal"); fmConfig.setDefaultEncoding("utf-8"); fmConfig.setTemplateExceptionHandler( TemplateExceptionHandler.RETHROW_HANDLER); fmConfig.setLogTemplateExceptions(false); } baseTheme = new Provider(); supportedLocales = new HashSet<>(); for (Locale locale: Locale.getAvailableLocales()) { if (locale.getLanguage().equals("")) { continue; } if (resourceBundleSupplier != null) { ResourceBundle rb = resourceBundleSupplier.apply(locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } ResourceBundle rb = ResourceBundle.getBundle(getClass() .getPackage().getName() + ".l10n", locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } RequestHandler.Evaluator.add(this, "onGet", portal.prefix() + "**"); RequestHandler.Evaluator.add(this, "onGetRedirect", portal.prefix().getPath().substring( 0, portal.prefix().getPath().length() - 1)); // Create portal model portalBaseModel.put("resourceUrl", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } return portal.prefix().resolve( ((SimpleScalar)args.get(0)).getAsString()).getRawPath(); } }); portalBaseModel = Collections.unmodifiableMap(portalBaseModel); // Handlers attached to the portal side channel Handler.Evaluator.add(this, "onPortalReady", portal.channel()); Handler.Evaluator.add(this, "onKeyValueStoreData", portal.channel()); Handler.Evaluator.add( this, "onPortletResourceResponse", portal.channel()); Handler.Evaluator.add(this, "onJsonOutput", portal.channel()); Handler.Evaluator.add(this, "onSetLocale", portal.channel()); Handler.Evaluator.add(this, "onSetTheme", portal.channel()); } /** * The service loader must be created lazily, else the OSGi * service mediator doesn't work properly. * * @return */ private ServiceLoader<ThemeProvider> themeLoader() { if (themeLoader != null) { return themeLoader; } return themeLoader = ServiceLoader.load(ThemeProvider.class); } void setResourceBundleSupplier( Function<Locale,ResourceBundle> supplier) { this.resourceBundleSupplier = supplier; } void setFallbackResourceSupplier( BiFunction<ThemeProvider,String,InputStream> supplier) { this.fallbackResourceSupplier = supplier; } RenderSupport renderSupport() { return renderSupport; } private LinkedIOSubchannel portalChannel(IOSubchannel channel) { @SuppressWarnings("unchecked") Optional<LinkedIOSubchannel> portalChannel = (Optional<LinkedIOSubchannel>)LinkedIOSubchannel .downstreamChannel(portal, channel); return portalChannel.orElseGet( () -> new LinkedIOSubchannel(portal, channel)); } @RequestHandler(dynamic=true) public void onGetRedirect(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException, ParseException { HttpResponse response = event.httpRequest().response().get(); response.setStatus(HttpStatus.MOVED_PERMANENTLY) .setContentType("text", "plain", "utf-8") .setField(HttpField.LOCATION, portal.prefix()); fire(new Response(response), channel); try { fire(Output.wrap(portal.prefix().toString() .getBytes("utf-8"), true), channel); } catch (UnsupportedEncodingException e) { // Supported by definition } event.stop(); } @RequestHandler(dynamic=true) public void onGet(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException { URI requestUri = event.requestUri(); // Append trailing slash, if missing if ((requestUri.getRawPath() + "/").equals( portal.prefix().getRawPath())) { requestUri = portal.prefix(); } // Request for portal? if (!requestUri.getRawPath().startsWith(portal.prefix().getRawPath())) { return; } // Normalize and evaluate requestUri = portal.prefix().relativize( URI.create(requestUri.getRawPath())); if (requestUri.getRawPath().isEmpty()) { if (event.httpRequest().findField( HttpField.UPGRADE, Converters.STRING_LIST) .map(f -> f.value().containsIgnoreCase("websocket")) .orElse(false)) { channel.setAssociated(this, new PortalInfo()); channel.respond(new WebSocketAccepted(event)); event.stop(); return; } renderPortal(event, channel); return; } URI subUri = uriFromPath("portal-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendPortalResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("theme-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendThemeResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("portlet-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { requestPortletResource(event, channel, subUri); return; } } private void renderPortal(GetRequest event, IOSubchannel channel) throws IOException, InterruptedException { event.stop(); // Because language is changed via websocket, locale cookie // may be out-dated event.associated(Selection.class) .ifPresent(s -> s.prefer(s.get()[0])); // Prepare response HttpResponse response = event.httpRequest().response().get(); MediaType mediaType = MediaType.builder().setType("text", "html") .setParameter("charset", "utf-8").build(); response.setField(HttpField.CONTENT_TYPE, mediaType); response.setStatus(HttpStatus.OK); response.setHasPayload(true); channel.respond(new Response(response)); try (Writer out = new OutputStreamWriter(new ByteBufferOutputStream( channel, channel.responsePipeline()), "utf-8")) { Map<String,Object> portalModel = new HashMap<>(portalBaseModel); // Add locale final Locale locale = event.associated(Selection.class).map( s -> s.get()[0]).orElse(Locale.getDefault()); portalModel.put("locale", locale); // Add supported locales final Collator coll = Collator.getInstance(locale); final Comparator<LanguageInfo> comp = new Comparator<PortalView.LanguageInfo>() { @Override public int compare(LanguageInfo o1, LanguageInfo o2) { return coll.compare(o1.getLabel(), o2.getLabel()); } }; LanguageInfo[] languages = supportedLocales.stream() .map(l -> new LanguageInfo(l)) .sorted(comp).toArray(size -> new LanguageInfo[size]); portalModel.put("supportedLanguages", languages); // Add localization final ResourceBundle additionalResources = resourceBundleSupplier == null ? null : resourceBundleSupplier.apply(locale); final ResourceBundle baseResources = ResourceBundle.getBundle( getClass().getPackage().getName() + ".l10n", locale, ResourceBundle.Control.getNoFallbackControl( ResourceBundle.Control.FORMAT_DEFAULT)); portalModel.put("_", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } String key = ((SimpleScalar)args.get(0)).getAsString(); try { return additionalResources.getString(key); } catch (MissingResourceException e) { // try base resources } try { return baseResources.getString(key); } catch (MissingResourceException e) { // no luck } return key; } }); // Add themes. Doing this on every reload allows themes // to be added dynamically. Note that we must load again // (not reload) in order for this to work in an OSGi environment. themeLoader = ServiceLoader.load(ThemeProvider.class); portalModel.put("themeInfos", StreamSupport.stream(themeLoader().spliterator(), false) .map(t -> new ThemeInfo(t.themeId(), t.themeName())) .sorted().toArray(size -> new ThemeInfo[size])); Template tpl = fmConfig.getTemplate("portal.ftlh"); tpl.process(portalModel, out); } catch (TemplateException e) { throw new IOException(e); } } private void sendPortalResource(GetRequest event, IOSubchannel channel, String resource) { // Look for content InputStream in = this.getClass().getResourceAsStream(resource); if (in == null) { return; } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(in, channel)); // Done event.stop(); } private void sendThemeResource(GetRequest event, IOSubchannel channel, String resource) { // Get resource ThemeProvider themeProvider = event.associated(Session.class) .map(session -> (ThemeProvider) session.get("themeProvider")) .orElse(baseTheme); InputStream resIn; try { resIn = themeProvider.getResourceAsStream(resource); } catch (ResourceNotFoundException e) { try { resIn = baseTheme.getResourceAsStream(resource); } catch (ResourceNotFoundException e1) { resIn = fallbackResourceSupplier.apply(themeProvider, resource); if (resIn == null) { return; } } } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(resIn, channel)); // Done event.stop(); } public static void prepareResourceResponse( HttpResponse response, URI request) { response.setContentType(request); // Set max age in cache-control header List<Directive> directives = new ArrayList<>(); directives.add(new Directive("max-age", 600)); response.setField(HttpField.CACHE_CONTROL, directives); response.setField(HttpField.LAST_MODIFIED, Instant.now()); response.setStatus(HttpStatus.OK); } private void requestPortletResource(GetRequest event, IOSubchannel channel, URI resource) throws InterruptedException { String resPath = resource.getPath(); int sep = resPath.indexOf('/'); // Send events to portlets on portal's channel if (Boolean.TRUE.equals(newEventPipeline().fire( new PortletResourceRequest(resPath.substring(0, sep), uriFromPath(resPath.substring(sep + 1)), event.httpRequest(), channel), portalChannel(channel)) .get())) { event.stop(); } } @Handler public void onInput(Input<ManagedCharBuffer> event, IOSubchannel channel) throws IOException { Optional<PortalInfo> optPortalInfo = channel.associated(this, PortalInfo.class); if (!optPortalInfo.isPresent()) { return; } optPortalInfo.get().toEvent(portalChannel(channel), event.buffer().backingBuffer(), event.isEndOfRecord()); } /** * Forward the {@link Closed} event to the portal channel. * * @param event the event * @param channel the channel */ @Handler public void onClosed(Closed event, IOSubchannel channel) { fire(new Closed(), portalChannel(channel)); } @Handler(dynamic=true) public void onPortalReady(PortalReady event, IOSubchannel channel) { KeyValueStoreQuery query = new KeyValueStoreQuery( "/themeProvider", true); channel.setAssociated(this, new CompletionLock(event, 3000)); fire(query, channel); } @Handler(dynamic=true) public void onKeyValueStoreData( KeyValueStoreData event, IOSubchannel channel) throws JsonDecodeException { if (!event.event().query().equals("/themeProvider")) { return; } channel.associated(this, CompletionLock.class) .ifPresent(lock -> lock.remove()); if (!event.data().values().iterator().hasNext()) { return; } String themeId = event.data().values().iterator().next(); ThemeProvider themeProvider = channel.associated(Session.class) .map(session -> (ThemeProvider)session.get("themeProvider")) .orElse(baseTheme); if (!themeProvider.themeId().equals(themeId)) { fire(new SetTheme(themeId), channel); } } @Handler(dynamic=true) public void onPortletResourceResponse(PortletResourceResponse event, LinkedIOSubchannel channel) { HttpRequest request = event.request().httpRequest(); // Send header HttpResponse response = request.response().get(); prepareResourceResponse(response, request.requestUri()); channel.upstreamChannel().respond(new Response(response)); // Send content activeEventPipeline().executorService().submit( new InputStreamPipeline( event.stream(), channel.upstreamChannel())); } @Handler(dynamic=true) public void onSetLocale(SetLocale event, LinkedIOSubchannel channel) throws InterruptedException, IOException { supportedLocales.stream() .filter(l -> l.equals(event.locale())).findFirst() .ifPresent(l -> channel.associated(Selection.class) .map(s -> s.prefer(l))); fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onSetTheme(SetTheme event, LinkedIOSubchannel channel) throws InterruptedException, IOException { ThemeProvider themeProvider = StreamSupport .stream(themeLoader().spliterator(), false) .filter(t -> t.themeId().equals(event.theme())).findFirst() .orElse(baseTheme); Optional<Session> optSession = channel.associated(Session.class); if (optSession.isPresent()) { Session session = optSession.get(); session.put("themeProvider", themeProvider); channel.respond(new KeyValueStoreUpdate().update( "/" + session.getOrDefault(Principal.class, "").toString() + "/themeProvider", themeProvider.themeId())).get(); } fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onJsonOutput(JsonOutput event, LinkedIOSubchannel channel) throws InterruptedException, IOException { IOSubchannel upstream = channel.upstreamChannel(); @SuppressWarnings("resource") CharBufferWriter out = new CharBufferWriter(upstream, upstream.responsePipeline()).suppressClose(); event.toJson(out); out.close(); } private class PortalInfo { private PipedWriter decodeWriter; public void toEvent(IOSubchannel channel, CharBuffer buffer, boolean last) throws IOException { if (decodeWriter == null) { decodeWriter = new PipedWriter(); PipedReader reader = new PipedReader( decodeWriter, buffer.capacity()); activeEventPipeline().executorService() .submit(new DecodeTask(reader, channel)); } decodeWriter.append(buffer); if (last) { decodeWriter.close(); decodeWriter = null; } } private class DecodeTask implements Runnable { IOSubchannel channel; private Reader reader; public DecodeTask(Reader reader, IOSubchannel channel) { this.reader = reader; this.channel = channel; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { try (Reader in = reader) { JsonReader reader = Json.createReader(in); fire(new JsonInput(reader.readObject()), channel); } catch (Throwable e) { fire(new Error(null, e)); } } } } public static class LanguageInfo { private Locale locale; /** * @param locale */ public LanguageInfo(Locale locale) { this.locale = locale; } /** * @return the locale */ public Locale getLocale() { return locale; } public String getLabel() { String str = locale.getDisplayName(locale); return Character.toUpperCase(str.charAt(0)) + str.substring(1); } } public static class ThemeInfo implements Comparable<ThemeInfo> { private String id; private String name; /** * @param id * @param name */ public ThemeInfo(String id, String name) { super(); this.id = id; this.name = name; } /** * @return the id */ public String id() { return id; } /** * @return the name */ public String name() { return name; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(ThemeInfo other) { return name().compareToIgnoreCase(other.name()); } } public static URI uriFromPath(String path) throws IllegalArgumentException { try { return new URI(null, null, path, null); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private class RenderSupportImpl implements RenderSupport { /* (non-Javadoc) * @see org.jgrapes.portal.RenderSupport#portletResource(java.lang.String, java.net.URI) */ @Override public URI portletResource(String portletType, URI uri) { return portal.prefix().resolve(uriFromPath( "portlet-resource/" + portletType + "/")).resolve(uri); } } }