repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
diokey/ums | JavaSource/org/gs/model/Role.java | 1735 | package org.gs.model;
import java.io.Serializable;
public class Role implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public Role() {
}
public Role(Role copy) {
this.roleId = copy.roleId;
this.roleName = copy.roleName;
this.roleDescription = copy.roleDescription;
this.buildIn = copy.buildIn;
this.canDelete = copy.canDelete;
this.deleted = copy.deleted;
this.loginDestination = copy.loginDestination;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDescription() {
return roleDescription;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
}
public boolean isBuildIn() {
return buildIn;
}
public void setBuildIn(boolean buildIn) {
this.buildIn = buildIn;
}
public boolean isCanDelete() {
return canDelete;
}
public void setCanDelete(boolean canDelete) {
this.canDelete = canDelete;
}
public String getLoginDestination() {
return loginDestination;
}
public void setLoginDestination(String loginDestination) {
this.loginDestination = loginDestination;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
private int roleId;
private String roleName;
private String roleDescription;
private boolean buildIn = false;
private boolean canDelete = true;
private String loginDestination = "/";
private boolean deleted;
}
| gpl-2.0 |
Bombe/fred | src/freenet/client/filter/GIFFilter.java | 2194 | /* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package freenet.client.filter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import freenet.l10n.NodeL10n;
import freenet.support.io.FileUtil;
/**
* Content filter for GIF's.
* This one just verifies that a GIF is valid, and throws if it isn't.
*/
public class GIFFilter implements ContentDataFilter {
static final int HEADER_SIZE = 6;
static final byte[] gif87aHeader =
{ (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'7', (byte)'a' };
static final byte[] gif89aHeader =
{ (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a' };
@Override
public void readFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams,
FilterCallback cb) throws DataFilterException, IOException {
DataInputStream dis = new DataInputStream(input);
// Check the header
byte[] headerCheck = new byte[HEADER_SIZE];
dis.readFully(headerCheck);
if ((!Arrays.equals(headerCheck, gif87aHeader)) && (!Arrays.equals(headerCheck, gif89aHeader))) {
throwHeaderError(l10n("invalidHeaderTitle"), l10n("invalidHeader"));
}
output.write(headerCheck);
FileUtil.copy(dis, output, -1);
output.flush();
}
private static String l10n(String key) {
return NodeL10n.getBase().getString("GIFFilter."+key);
}
private void throwHeaderError(String shortReason, String reason) throws DataFilterException {
// Throw an exception
String message = l10n("notGif");
if (reason != null) {
message += ' ' + reason;
}
if (shortReason != null) {
message += " - (" + shortReason + ')';
}
throw new DataFilterException(shortReason, shortReason, message);
}
@Override
public void writeFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams,
FilterCallback cb) throws DataFilterException, IOException {
output.write(input.read());
}
}
| gpl-2.0 |
mzmine/mzmine3 | src/main/java/io/github/mzmine/modules/dataprocessing/filter_blanksubtraction/FeatureListBlankSubtractionTask.java | 8697 | /*
* Copyright 2006-2021 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package io.github.mzmine.modules.dataprocessing.filter_blanksubtraction;
import io.github.mzmine.datamodel.FeatureStatus;
import io.github.mzmine.datamodel.MZmineProject;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.datamodel.features.FeatureList;
import io.github.mzmine.datamodel.features.ModularFeature;
import io.github.mzmine.datamodel.features.ModularFeatureList;
import io.github.mzmine.datamodel.features.ModularFeatureListRow;
import io.github.mzmine.datamodel.features.SimpleFeatureListAppliedMethod;
import io.github.mzmine.parameters.parametertypes.selectors.RawDataFilesSelection;
import io.github.mzmine.taskcontrol.AbstractTask;
import io.github.mzmine.taskcontrol.TaskStatus;
import io.github.mzmine.util.MemoryMapStorage;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author SteffenHeu steffen.heuckeroth@gmx.de / s_heuc03@uni-muenster.de
*/
public class FeatureListBlankSubtractionTask extends AbstractTask {
private static Logger logger = Logger
.getLogger(FeatureListBlankSubtractionTask.class.getName());
private final int totalRows;
private final int minBlankDetections;
private final String suffix;
private final boolean checkFoldChange;
private final double foldChange;
private final BlankIntensityType intensityType;
private AtomicInteger processedRows = new AtomicInteger(0);
private MZmineProject project;
private FeatureListBlankSubtractionParameters parameters;
private RawDataFilesSelection blankSelection;
private List<RawDataFile> blankRaws;
private ModularFeatureList alignedFeatureList;
public FeatureListBlankSubtractionTask(MZmineProject project,
FeatureListBlankSubtractionParameters parameters, @Nullable MemoryMapStorage storage, @NotNull Instant moduleCallDate) {
super(storage, moduleCallDate);
this.project = project;
this.parameters = parameters;
this.blankSelection =
parameters.getParameter(FeatureListBlankSubtractionParameters.blankRawDataFiles).getValue();
this.blankRaws = List.of(blankSelection.getMatchingRawDataFiles().clone());
this.alignedFeatureList =
parameters.getParameter(FeatureListBlankSubtractionParameters.alignedPeakList).getValue()
.getMatchingFeatureLists()[0];
this.minBlankDetections =
parameters.getParameter(FeatureListBlankSubtractionParameters.minBlanks).getValue();
this.suffix = parameters.getParameter(FeatureListBlankSubtractionParameters.suffix).getValue();
checkFoldChange = parameters.getParameter(FeatureListBlankSubtractionParameters.foldChange)
.getValue();
foldChange = parameters.getParameter(FeatureListBlankSubtractionParameters.foldChange)
.getEmbeddedParameter().getValue();
intensityType = BlankIntensityType.Maximum;
totalRows = alignedFeatureList.getNumberOfRows();
setStatus(TaskStatus.WAITING);
logger.setLevel(Level.FINEST);
}
@Override
public String getTaskDescription() {
return "Blank subtraction task on " + alignedFeatureList.getName();
}
@Override
public double getFinishedPercentage() {
return processedRows.get() / (double)totalRows;
}
@Override
public void run() {
setStatus(TaskStatus.PROCESSING);
if (!checkBlankSelection(alignedFeatureList, blankRaws)) {
setErrorMessage("Feature list " + alignedFeatureList.getName()
+ " does no contain all selected blank raw data files.");
setStatus(TaskStatus.ERROR);
return;
}
// get the files that are not considered as blank
final List<RawDataFile> nonBlankFiles = new ArrayList<>();
for (RawDataFile file : alignedFeatureList.getRawDataFiles()) {
if (!blankRaws.contains(file)) {
nonBlankFiles.add(file);
}
}
logger.finest(() -> alignedFeatureList.getName() + " contains " + nonBlankFiles.size() + " raw data files not classified as blank.");
final ModularFeatureList result = new ModularFeatureList(
alignedFeatureList.getName() + " " + suffix, getMemoryMapStorage(), nonBlankFiles);
alignedFeatureList.getRowTypes().values().forEach(result::addRowType);
nonBlankFiles.forEach(f -> result.setSelectedScans(f, alignedFeatureList.getSeletedScans(f)));
Set<ModularFeatureListRow> filteredRows = ConcurrentHashMap.newKeySet();
alignedFeatureList.modularStream()/*.parallel()*/.forEach(row -> {
int numBlankDetections = 0;
for (RawDataFile blankRaw : blankRaws) {
if (row.hasFeature(blankRaw)) {
numBlankDetections++;
}
}
if (numBlankDetections < minBlankDetections || checkFoldChange) {
final ModularFeatureListRow filteredRow = new ModularFeatureListRow(result, row.getID());
final double blankIntensity =
checkFoldChange ? getBlankIntensity(row, blankRaws, intensityType) : 1d;
int numFeatures = 0;
for (RawDataFile file : nonBlankFiles) {
final ModularFeature f = row.getFeature(file);
// check if there's actually a feature
if (f != null && f.getFeatureStatus() != FeatureStatus.UNKNOWN) {
// check validity
if (!checkFoldChange || f.getHeight() / blankIntensity >= foldChange) {
filteredRow.addFeature(file, new ModularFeature(result, f));
numFeatures++;
}
}
}
// copy row types
if(numFeatures > 0) {
// row.stream().filter(e -> !(e.getKey() instanceof FeaturesType))
// .forEach(entry -> filteredRow.set(entry.getKey(), entry.getValue()));
filteredRows.add(filteredRow);
}
}
processedRows.getAndIncrement();
});
filteredRows.forEach(result::addRow);
result.getAppliedMethods().addAll(alignedFeatureList.getAppliedMethods());
result.getAppliedMethods().add(
new SimpleFeatureListAppliedMethod(FeatureListBlankSubtractionModule.class, parameters, getModuleCallDate()));
project.addFeatureList(result);
setStatus(TaskStatus.FINISHED);
}
private double getBlankIntensity(ModularFeatureListRow row, Collection<RawDataFile> blankRaws,
BlankIntensityType intensityType) {
double intensity = 0d;
int numDetections = 0;
for (RawDataFile file : blankRaws) {
final ModularFeature f = row.getFeature(file);
if (f != null && f.getFeatureStatus() != FeatureStatus.UNKNOWN) {
if (intensityType == BlankIntensityType.Average) {
intensity += f.getHeight();
numDetections++;
} else if (intensityType == BlankIntensityType.Maximum) {
intensity = Math.max(f.getHeight(), intensity);
}
}
}
return intensityType == BlankIntensityType.Average && numDetections != 0 ? intensity
/ numDetections : intensity;
}
private boolean checkBlankSelection(FeatureList aligned, List<RawDataFile> blankRaws) {
List<RawDataFile> flRaws = aligned.getRawDataFiles();
for (int i = 0; i < blankRaws.size(); i++) {
boolean contained = false;
for (RawDataFile flRaw : flRaws) {
if (blankRaws.get(i) == flRaw) {
contained = true;
}
}
if (!contained) {
final int i1 = i;
logger.info(() -> "Feature list " + aligned.getName() + " does not contain raw data files "
+ blankRaws.get(i1).getName());
return false;
}
}
logger.finest(
() -> "Feature list " + aligned.getName() + " contains all selected blank raw data files.");
return true;
}
enum BlankIntensityType {
Average, Maximum
}
}
| gpl-2.0 |
petersalomonsen/frinika | src/com/frinika/sequencer/gui/LoopPanel.java | 7314 | /*
* Created on Apr 24, 2005
*
* Copyright (c) 2005 Peter Johan Salomonsen (http://www.petersalomonsen.com)
*
* http://www.frinika.com
*
* This file is part of Frinika.
*
* Frinika is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Frinika is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Frinika; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.frinika.sequencer.gui;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.sound.midi.Sequencer;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.frinika.project.ProjectContainer;
import com.frinika.sequencer.FrinikaSequencer;
import com.frinika.sequencer.SongPositionListener;
import com.frinika.sequencer.SwingSongPositionListenerWrapper;
import com.frinika.sequencer.model.util.TimeUtils;
import static com.frinika.localization.CurrentLocale.getMessage;
/**
* Panel for setting edit/playing section range, and control looping
*
* @author Peter Johan Salomonsen
* @author Jens Gulden
*
*/
/*
public class LoopPanel extends JPanel {
private static final long serialVersionUID = 1L;
FrinikaSequencer sequencer;
JTextField sectionStartTextField;
JTextField sectionEndTextField;
TimeUtils timeUtil;
public LoopPanel(ProjectContainer project) {
this.sequencer = project.getSequencer();
timeUtil=new TimeUtils(project);
initComponents();
setText();
sequencer.addSongPositionListener(new SongPositionListener() {
public void notifyTickPosition(long tick) {
// TODO Auto-generated method stub
setText();
}
public boolean requiresNotificationOnEachTick() {
// TODO Auto-generated method stub
return false;
}
});
}
void setText() {
sectionStartTextField.setText(timeUtil.tickToBarBeatTick(sequencer.getLoopStartPoint()));
sectionEndTextField.setText(timeUtil.tickToBarBeatTick(sequencer.getLoopEndPoint()));
}
void initComponents() {
add(new JLabel(" Start "));
sectionStartTextField = new JTextField(" ");
sectionStartTextField.setColumns(6);
add(sectionStartTextField);
sectionStartTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
try {
sequencer.setLoopStartPoint(timeUtil.barBeatTickToTick(sectionStartTextField
.getText()));
} catch (Exception ex) {
}
}
});
sectionStartTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
sequencer.setLoopStartPoint(timeUtil.barBeatTickToTick(sectionStartTextField
.getText()));
} catch (Exception ex) {
}
}
});
add(new JLabel(" End "));
sectionEndTextField = new JTextField(" ");
sectionEndTextField.setColumns(6);
sectionEndTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
try {
sequencer.setLoopEndPoint(timeUtil.barBeatTickToTick(sectionEndTextField
.getText()));
} catch (Exception ex) {
}
}
});
sectionEndTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
sequencer.setLoopEndPoint(timeUtil.barBeatTickToTick(sectionEndTextField
.getText()));
} catch (Exception ex) {
}
}
});
add(sectionEndTextField);
final JToggleButton loopButton = new JToggleButton(new ImageIcon(
ClassLoader.getSystemResource("icons/loop.png")));
loopButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// tracker.updateLoopPoints();
// sequencer.setLoopStartPoint(sectionStart * ticksPerBeat);
// sequencer.setLoopEndPoint((sectionStart+sectionLength) * ticksPerBeat);
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
} else {
sequencer.setLoopCount(0);
}
}
});
add(loopButton);
}
*/
/**
* @return Returns the sectionLength.
*/
/*public int getSectionLength() {
return sectionLength;
}
*/
/**
* @return Returns the sectionStart.
*/
/* public int getSectionStart() {
return sectionStart;
}
*/
/* public void previousPage() {
sectionStart -= sectionLength;
if (sectionStart < 0)
sectionStart = 0;
sectionStartTextField.setText(sectionStart + "");
// tracker.refreshTrackView();
}
public void nextPage() {
sectionStart += sectionLength;
sectionStartTextField.setText(sectionStart + "");
// tracker.refreshTrackView();
}*/
/*
}
*/
// Alternative implementation using 2 TimeSelectors, Jens:
public class LoopPanel extends JPanel {
private static final long serialVersionUID = 1L;
ProjectContainer project;
FrinikaSequencer sequencer;
TimeSelector sectionStartTimeSelector;
TimeSelector sectionEndTimeSelector;
TimeUtils timeUtil;
public LoopPanel(ProjectContainer project) {
this.project = project;
this.sequencer = project.getSequencer();
timeUtil=new TimeUtils(project);
initComponents();
setText();
sequencer.addSongPositionListener(new SwingSongPositionListenerWrapper(new SongPositionListener() {
public void notifyTickPosition(long tick) {
setText();
}
public boolean requiresNotificationOnEachTick() {
return false;
}
}));
}
void setText() {
sectionStartTimeSelector.setTicks(sequencer.getLoopStartPoint());
sectionEndTimeSelector.setTicks(sequencer.getLoopEndPoint());
}
void initComponents() {
sectionStartTimeSelector = new TimeSelector(getMessage("globaltoolbar.loop.start"), 0l, project, TimeFormat.BAR_BEAT_TICK);
sectionStartTimeSelector.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
sequencer.setLoopStartPoint(sectionStartTimeSelector.getTicks());
}
});
add(sectionStartTimeSelector);
sectionEndTimeSelector = new TimeSelector(getMessage("globaltoolbar.loop.end"), 0l, project, TimeFormat.BAR_BEAT_TICK);
sectionEndTimeSelector.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
sequencer.setLoopEndPoint(sectionEndTimeSelector.getTicks());
}
});
add(sectionEndTimeSelector);
final JToggleButton loopButton = new JToggleButton(new ImageIcon(
ClassLoader.getSystemResource("icons/loop.png")));
loopButton.setSelected(sequencer.getLoopCount() != 0);
loopButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
} else {
sequencer.setLoopCount(0);
}
}
});
add(loopButton);
}
}
| gpl-2.0 |
clusterwork/ClusterWork | src/com/intel/fangpei/terminal/Client.java | 440 | package com.intel.fangpei.terminal;
import java.nio.channels.SocketChannel;
import com.intel.fangpei.network.NIOHandler;
import com.intel.fangpei.util.CommandPhraser;
public abstract class Client implements Runnable {
NIOHandler connect = null;
SocketChannel client = null;
int connectType = -1;
CommandPhraser cp = null;
public Client() {
cp = new CommandPhraser();
}
@Override
public void run() {
}
}
| gpl-2.0 |
ebraminio/Kaspar | src/mediawiki/task/NormdatenTask2.java | 21065 | package mediawiki.task;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mediawiki.ContinuingRequest;
import mediawiki.MediaWikiConnection;
import mediawiki.MediaWikiException;
import mediawiki.MediaWikiUtil;
import mediawiki.info.Article;
import mediawiki.info.Project;
import mediawiki.info.wikibase.Claim;
import mediawiki.info.wikibase.Property;
import mediawiki.info.wikibase.Statement;
import mediawiki.info.wikibase.snaks.StringSnak;
import mediawiki.info.wikibase.snaks.URLSnak;
import mediawiki.request.CategoryMemberRequest;
import mediawiki.request.ContentRequest;
import mediawiki.request.EditRequest;
import mediawiki.request.GetTemplatesValuesRequest;
import mediawiki.request.TemplateEmbeddedInRequest;
import mediawiki.request.TranscludedTemplatesRequest;
import mediawiki.request.WikiBaseItemRequest;
import mediawiki.request.wikibase.CreateClaimRequest;
import mediawiki.request.wikibase.GetSpecificStatementRequest;
import mediawiki.request.wikibase.SetReferenceRequest;
import mediawiki.task.config.NormdatenTask2Configuration;
import mediawiki.task.config.NormdatenTask2ErrorHandler;
import org.json.JSONObject;
import util.GetRequest;
import datasets.in.GND;
import datasets.in.VIAF;
public class NormdatenTask2 extends WikipediaWikidataTask {
private NormdatenTask2Configuration config;
private HashSet<NormdatenTask2ErrorHandler> handlers = new HashSet<>();
public NormdatenTask2(MediaWikiConnection wikidata, MediaWikiConnection wikipedia, NormdatenTask2Configuration c){
super(wikidata, wikipedia);
config = c;
}
@Override
public void run() {
List<Article> articles;
try {
InputStream in = NormdatenTask2Configuration.class.getResourceAsStream("authoritycontrol.json");
StringBuffer b = new StringBuffer();
while(in.available() > 0){
byte[] buffer = new byte[1024];
in.read(buffer);
b.append(new String(buffer));
}
in.close();
final JSONObject ac = new JSONObject(b.toString());
if(config.getRequest() instanceof CategoryMemberRequest){
config.getRequest().setProperty("cmdir", "newer");
}else if(config.getRequest() instanceof TemplateEmbeddedInRequest){
config.getRequest().setProperty("eidir", "descending");
}
/* if(config.getRequest() instanceof ContinuingRequest)
((ContinuingRequest) config.getRequest()).setLimit(10); */
articles = getWikipediaConnection().request(config.getRequest());
System.out.println(articles.size()+" Artikel geladen");
for(Article a : articles){
System.out.println("* [["+a.getTitle()+"]] "+new Date().toGMTString());
try{
String base = (String) getWikipediaConnection().request(new WikiBaseItemRequest(a));
if(base == null){
throwWarning(new NormdatenTask2Exception(a, "no wikidata item", NormdatenTask2ExceptionLevel.PROBLEM));
continue;
}
List<Map<String,String>> t2 = null;
for(String template : config.getTemplates()){
GetTemplatesValuesRequest gtvr = new GetTemplatesValuesRequest(a.getTitle(), template);
gtvr.setUppercaseMode(true);
t2 = getWikipediaConnection().request(gtvr);
if(! t2.isEmpty())
break;
}
if(t2 == null || t2.size() == 0){
throwWarning(new NormdatenTask2Exception(a, "unknown alias embedded or recursive transclusion", NormdatenTask2ExceptionLevel.PROBLEM));
continue;
}
if(t2.size() > 1){
throwWarning(new NormdatenTask2Exception(a, "more than one template embedded", NormdatenTask2ExceptionLevel.PROBLEM));
continue;
}
Map<String, String> t = t2.get(0);
if(t.size() == 0){
throwWarning(new NormdatenTask2Exception(a, "already moved to wikidata", NormdatenTask2ExceptionLevel.INFO));
continue;
}
boolean removable = true;
HashMap<String,String> newParameters = new HashMap<>();
if(t.containsKey("WORLDCAT") && ! t.containsKey("WORLDCATID")) {
t.put("WORLDCATID", t.get("WORLDCAT"));
t.remove("WORLDCAT");
}
for(Entry<String, String> e : t.entrySet()){
if( e.getKey().equalsIgnoreCase("TYP") ||
e.getKey().equalsIgnoreCase("TYPE") ||
e.getKey().equalsIgnoreCase("GNDCheck") ||
e.getKey().equalsIgnoreCase("GNDfehlt") ||
e.getKey().equalsIgnoreCase("GNDName") ||
e.getKey().equalsIgnoreCase("TIMESTAMP") ||
e.getKey().equalsIgnoreCase("TSURL") ||
e.getKey().equalsIgnoreCase("NOTES") ||
e.getKey().equalsIgnoreCase("REMARK") ||
e.getKey().equalsIgnoreCase("BARE") ||
e.getKey().equalsIgnoreCase("PREFIX") ||
e.getKey().equalsIgnoreCase("TESTCASE")
)
continue;
if(e.getKey().equalsIgnoreCase("1") && e.getValue().trim().length() == 0)
continue;
if(MediaWikiUtil.containsPersianDigits(e.getValue()))
e.setValue(MediaWikiUtil.parsePersianNumber(e.getValue()));
if(e.getKey().equalsIgnoreCase("WORLDCATID") && e.getValue().trim().length() > 0) {
if(! reachable(new URL("http://www.worldcat.org/identities/"+URLEncoder.encode(e.getValue().replaceAll("\\/",""),"UTF-8")))) {
newParameters.remove(e.getKey());
System.out.println("** 404 Error for "+e.getKey()+" value "+e.getValue()+". ready for removal");
continue;
}
if(e.getValue().matches("^lccn-.*")){
String lccn = null;
if(t.containsKey("LCCN"))
lccn = t.get("LCCN");
else{
List<Statement> l = getWikidataConnection().request(new GetSpecificStatementRequest(base, new Property(ac.getJSONObject("LCCN").getInt("property"))));
if(l.size() > 0)
lccn = (String) l.get(0).getClaim().getSnak().getValue();
}
if(lccn == null && e.getValue().matches("^lccn-.*$")){
String value = e.getValue().replaceAll("^lccn-", "");
if(! value.matches(ac.getJSONObject("LCCN").getString("pattern"))){
value = value.replaceAll("\\-", "/");
value = value.replaceAll("^(|n|nb|nr|no|ns|sh|sj|sn)(.*)$", "$1/$2");
value = MediaWikiUtil.formatLCCN(value);
}
if(value != null && value.matches(ac.getJSONObject("LCCN").getString("pattern")) ) {
Statement s = getConnection().request(new CreateClaimRequest(base, new Claim(ac.getJSONObject("LCCN").getInt("property"), new StringSnak(value))));
if(s == null){
throwWarning(new NormdatenTask2Exception(a, "unable to add claim",e.getKey(), NormdatenTask2ExceptionLevel.INTERNAL));
removable = false;
newParameters.put(e.getKey(),e.getValue());
continue;
}else{
getConnection().request(new SetReferenceRequest(s, config.getReference()));
System.out.println("** added claim for "+e.getKey());
continue;
}
}else{
newParameters.put(e.getKey(),e.getValue());
continue;
}
}else{
String[] lccns = MediaWikiUtil.splitLCCN(lccn);
if(! reachable(new URL("http://www.worldcat.org/identities/lccn-"+URLEncoder.encode(lccns[0]+"-"+lccns[1]+"-"+lccns[2], "UTF-8")))) {
newParameters.remove(e.getKey());
System.out.println("** 404 Error for "+e.getKey()+" value "+lccns[0]+"-"+lccns[1]+"-"+lccns[2]+". ready for removal");
continue;
}
for(int i = 0; i < lccns.length; i++)
lccns[i] = lccns[i].replaceAll("^0+(\\d+)$", "$1");
if(e.getValue().matches("^lccn-"+Matcher.quoteReplacement(lccns[0])+"\\-?0*"+Matcher.quoteReplacement(lccns[1])+"\\-?0*"+Matcher.quoteReplacement(lccns[2])+"$" )) {
newParameters.remove(e.getKey());
System.out.println("** WORLDCATID equals suggested value. ready for removal");
continue;
}else{
throwWarning(new NormdatenTask2Exception(a, "different value on wikidata", e.getKey()+": "+e.getValue()+"!=lccn-"+lccns[0]+"-"+lccns[1]+"-"+lccns[2], NormdatenTask2ExceptionLevel.PROBLEM));
newParameters.put(e.getKey(),e.getValue());
continue;
}
}
}else{
throwWarning(new NormdatenTask2Exception(a, "WORLDCATID not based on LCCN", NormdatenTask2ExceptionLevel.PROBLEM));
newParameters.put(e.getKey(),e.getValue());
removable = false;
continue;
}
}
if(! ac.has(e.getKey()) && (e.getValue().trim().length() > 0 || (config.isKeepEmpty() && e.getValue().trim().length() == 0) ) ){
throwWarning(new NormdatenTask2Exception(a, "unknown template property", e.getKey(), NormdatenTask2ExceptionLevel.PROBLEM));
newParameters.put(e.getKey(),e.getValue());
removable = false;
}else{
if(e.getValue().trim().length() == 0){
if(config.isKeepEmpty()){
newParameters.put(e.getKey(),"");
removable = false;
throwWarning(new NormdatenTask2Exception(a, "keep-empty-mode. empty template property: "+e.getKey(), NormdatenTask2ExceptionLevel.INFO));
}
continue;
}
String value = e.getKey().equals("LCCN") && ! e.getValue().matches(ac.getJSONObject(e.getKey()).getString("pattern")) ? MediaWikiUtil.formatLCCN(e.getValue()) : e.getValue();
if(e.getKey().equals("LCCN") && value == null)
value = e.getValue();
if(e.getKey().equalsIgnoreCase("ISNI")){
value = value.replaceAll("(\\d{4})(\\d{4})(\\d{4})(\\d{3}[\\dX])", "$1 $2 $3 $4");
value = value.replaceAll("(\\d{4})\\s{2,}(\\d{4})\\s{2,}(\\d{4})\\s{2,}(\\d{3}[\\dX])", "$1 $2 $3 $4");
} else
if(e.getKey().equalsIgnoreCase("BNF")){
value = value.replaceAll("cb(\\d{8}[0-9bcdfghjkmnpqrstvwxz])", "$1");
} else
if(e.getKey().equalsIgnoreCase("NLA")){
value = value.replaceAll("0000([1-9][0-9]{0,11})", "$1");
} else
if(e.getKey().equalsIgnoreCase("PLANTLIST") && e.getValue().matches("\\d+")){
value = t.get("PREFIX")+"-"+e.getValue();
} else
if(e.getKey().equalsIgnoreCase("CANTIC")){
value = value.replaceAll("(a\\d{7}[0-9x])\\/\\d+", "$1");
} else
if(e.getKey().equalsIgnoreCase("ORCID") && ! e.getValue().matches("0000-000(1-[5-9]|2-[0-9]|3-[0-4])\\d\\d\\d-\\d\\d\\d[\\dX]")){
value = value.replaceAll("\\s+", "-");
}
try{
if(value != null && value.matches(ac.getJSONObject(e.getKey()).getString("pattern"))){
String formatter = (String) getWikidataConnection().request(new GetSpecificStatementRequest("P"+ac.getJSONObject(e.getKey()).getInt("property"), new Property(1630))).get(0).getClaim().getSnak().getValue();
String u = formatter.replaceAll("\\$1", URLEncoder.encode(value, "UTF-8"));
if(! reachable(new URL(u))){
newParameters.remove(e.getKey());
System.out.println("** 404 Error for "+e.getKey()+" value "+value+". ready for removal");
continue;
}
}
}catch(Exception e2){
throwWarning(new NormdatenTask2Exception(a, "unknown error while checking external databases", e.getKey()+": "+e2.getClass().getCanonicalName()+" "+e2.getMessage(), NormdatenTask2ExceptionLevel.EXTERNAL));
}
if(value == null || ! value.matches(ac.getJSONObject(e.getKey()).getString("pattern"))){
throwWarning(new NormdatenTask2Exception(a, "malformed value", e.getKey()+": "+value, NormdatenTask2ExceptionLevel.PROBLEM));
newParameters.put(e.getKey(),e.getValue());
if(e.getKey().equalsIgnoreCase("PLANTLIST") && t.containsKey("PREFIX")){newParameters.put("PREFIX", t.get("PREFIX"));}
removable = false;
}else{
List<Statement> l = getConnection().request(new GetSpecificStatementRequest(base, new Property(ac.getJSONObject(e.getKey()).getInt("property"))));
if(l.size() == 0){
Statement s = getConnection().request(new CreateClaimRequest(base, new Claim(ac.getJSONObject(e.getKey()).getInt("property"), new StringSnak(value))));
if(s == null){
throwWarning(new NormdatenTask2Exception(a, "unable to add claim", e.getKey(), NormdatenTask2ExceptionLevel.INTERNAL));
removable = false;
newParameters.put(e.getKey(),e.getValue());
if(e.getKey().equalsIgnoreCase("PLANTLIST") && t.containsKey("PREFIX")){newParameters.put("PREFIX", t.get("PREFIX"));}
}else{
getConnection().request(new SetReferenceRequest(s, config.getReference()));
System.out.println("** added claim for "+e.getKey());
}
}else{
boolean flag2 = false;
String ss = "";
HashSet<String> wikidatavalues = new HashSet<>();
for(Statement s : l){
ss += ","+s.getClaim().getSnak().getValue();
wikidatavalues.add(s.getClaim().getSnak().getValue().toString());
if(s.getClaim().getSnak().getValue().equals(value)){
flag2 = true;
}
}
ss = ss.substring(1);
if(!flag2) {
try{
String formatter = (String) getWikidataConnection().request(new GetSpecificStatementRequest("P"+ac.getJSONObject(e.getKey()).getInt("property"), new Property(1630))).get(0).getClaim().getSnak().getValue();
String newu = detectRedirect(formatter, value);
if(newu != null && newu.matches(ac.getJSONObject(e.getKey()).getString("pattern")) ){
throwWarning(new NormdatenTask2Exception(a, "redirect for "+e.getKey()+" detected", "new value: "+value+"", NormdatenTask2ExceptionLevel.INFO));
if(wikidatavalues.contains(newu)){
flag2 = true;
}
}
}catch(Exception e2){
throwWarning(new NormdatenTask2Exception(a, "unknown error while checking external databases", e.getKey()+": "+e2.getClass().getCanonicalName()+" "+e2.getMessage(), NormdatenTask2ExceptionLevel.EXTERNAL));
}
}
if(!flag2){
throwWarning(new NormdatenTask2Exception(a, "different value on wikidata", e.getKey()+": "+value+"!="+ss, NormdatenTask2ExceptionLevel.PROBLEM));
newParameters.put(e.getKey(),e.getValue());
if(e.getKey().equalsIgnoreCase("PLANTLIST") && t.containsKey("PREFIX")){newParameters.put("PREFIX", t.get("PREFIX"));}
}
removable = flag2 ? removable : false;
}
}
}
}
if(getWikipediaConnection().request(new TranscludedTemplatesRequest(a, "Template:bots")).size() != 0 ){
throwWarning(new NormdatenTask2Exception(a, "bot-template found", NormdatenTask2ExceptionLevel.PROBLEM));
continue;
}
removable = (newParameters.size() > 0 && newParameters.size() < t.size()) || removable;
if(newParameters.size() >= t.size()){
throwWarning(new NormdatenTask2Exception(a, "no effective reduction possible", NormdatenTask2ExceptionLevel.FINAL));
removable = false;
}
if(config.isLowerCaseMode()){
HashMap<String,String> np2 = new HashMap<>();
for(Entry<String,String> entry : newParameters.entrySet())
np2.put(entry.getKey().toLowerCase(), entry.getValue());
newParameters = np2;
}
if(removable){
String old = getWikipediaConnection().request(new ContentRequest(a));
String regex = "(?iu)\\{\\{\\ {0,1}(";
for(String template : config.getTemplates()){
regex += "("+Pattern.quote(template)+")|"; //
}
regex = regex.substring(0, regex.length()-1);
regex+= ")[^\\{\\}\\<\\>]+\\}\\}";
String nw = old.replaceAll(regex, "{{"+config.getTemplate()+(newParameters.size() > 0 ? "|"+convertToTemplateProperties(newParameters) : "")+"}}");
if(nw.equals(old)){
throwWarning(new NormdatenTask2Exception(a, "regex doesn't match", NormdatenTask2ExceptionLevel.PROBLEM));
removable = false;
}
if(nw.length() == 0){
throwWarning(new NormdatenTask2Exception(a, "error while calculating", NormdatenTask2ExceptionLevel.INTERNAL));
removable = false;
}
if(removable){
if(getWikipediaConnection().isTestState()){
throwWarning(new NormdatenTask2Exception(a, "template can only be replaced manually", NormdatenTask2ExceptionLevel.PROBLEM));
}
try{
getWikipediaConnection().request(new EditRequest(a, nw, config.getSummary()));
throwWarning(new NormdatenTask2Exception(a, "template replaced", NormdatenTask2ExceptionLevel.FINAL));
System.out.println("** template replaced");
}catch(MediaWikiException e3){
throwWarning(new NormdatenTask2Exception(a, "edit request rejected", NormdatenTask2ExceptionLevel.PROBLEM));
}
}
}
}catch(Exception e){
e.printStackTrace();
throwWarning(new NormdatenTask2Exception(a, "unknown error", e.getClass().getCanonicalName()+" "+e.getMessage(), NormdatenTask2ExceptionLevel.INTERNAL));
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private HashMap<NormdatenTask2Exception, Integer> stat = new HashMap<>();
private void throwWarning(NormdatenTask2Exception e) throws Exception{
System.out.println("** "+e.getMessage());
if(stat.containsKey(e))
stat.put(e, stat.get(e)+1);
else
stat.put(e, 1);
handleError(e);
}
private void throwException(NormdatenTask2Exception e) throws Exception{
throwWarning(e);
throw e;
}
public Map<NormdatenTask2Exception, Integer> getStatistic() {
return stat;
}
private static String convertToTemplateProperties(Map<String,String> m){
String result = "";
for(Entry<String, String> e : m.entrySet()){
result +="|"+e.getKey()+"="+e.getValue()+" ";
}
if(result.length() > 0)
result = result.substring(1).trim();
return result;
}
private static boolean reachable(URL u) throws IOException{
try{
new GetRequest(u).request();
}catch(FileNotFoundException e){
return false;
}
return true;
}
private static String detectRedirect(String formatter, String identifier) throws MalformedURLException, UnsupportedEncodingException, IOException{
String newidentifier = new GetRequest(formatter.replaceAll("\\$1", URLEncoder.encode(identifier, "UTF-8"))).detectRedirect().toExternalForm();
formatter = formatter.replaceAll("\\$1", "(.+)")
.replaceAll("https\\:\\/\\/","http[s]?://")
.replaceAll("http\\:\\/\\/","http[s]?://");
newidentifier = newidentifier.replaceAll(formatter, "$1");
if(identifier.equals(newidentifier))
return null;
return newidentifier;
}
public class NormdatenTask2Exception extends MediaWikiException {
private Article article;
private String type;
private NormdatenTask2ExceptionLevel level;
private String message = null;
public NormdatenTask2Exception(Article a, String type, String message, NormdatenTask2ExceptionLevel level) {
super(type+ " ("+ message+") at "+a.getTitle());
setArticle(a);
this.type = type;
this.level = level;
this.message = message;
}
public NormdatenTask2Exception(Article a, String type, NormdatenTask2ExceptionLevel level) {
super(type+ " at "+a.getTitle());
setArticle(a);
this.type = type;
this.level = level;
}
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(! (obj instanceof NormdatenTask2Exception))
return false;
NormdatenTask2Exception e = (NormdatenTask2Exception) obj;
return this.type.equals(e.type);
}
@Override
public int hashCode() {
return type.hashCode();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Project getProject() throws MalformedURLException {
return NormdatenTask2.this.getWikipediaConnection().getProject();
}
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
public NormdatenTask2ExceptionLevel getLevel() {
return level;
}
public void setLevel(NormdatenTask2ExceptionLevel level) {
this.level = level;
}
public String getSimpleMessage(){
return message;
}
}
public enum NormdatenTask2ExceptionLevel {
INFO, PROBLEM, INTERNAL, EXTERNAL, FINAL
}
public void registerErrorHandler(NormdatenTask2ErrorHandler e){
handlers.add(e);
}
protected void handleError(NormdatenTask2Exception e) throws Exception{
for(NormdatenTask2ErrorHandler eh : handlers)
if(eh.accept(e))
eh.handle(e);
}
public void removeErrorHandler(NormdatenTask2ErrorHandler e){
handlers.remove(e);
}
}
| gpl-2.0 |
shushanxingzhe/LouisJava | first.java | 79 | class first{
public void main(){
printf('hello world');
}
}
| gpl-2.0 |
Stasmo/rpgtables-server | src/main/java/com/dhaselhan/rpgtables/services/SessionService.java | 1202 | package com.dhaselhan.rpgtables.services;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.dhaselhan.rpgtables.data.User;
import com.dhaselhan.rpgtables.data.UserSession;
public class SessionService {
private EntityManagerFactory factory;
public SessionService() {
factory = Persistence.createEntityManagerFactory(AppConstants.TABLE_NAME);
}
public boolean registerSession(String token, User user, Date expiryDate) {
UserSession session = new UserSession();
session.setToken(token);
session.setUserName(user.getUsername());
session.setExpiryDate(expiryDate);
EntityManager em = factory.createEntityManager();
EntityTransaction trans = em.getTransaction();
trans.begin();
em.merge(session);
trans.commit();
em.close();
return true;
}
public UserSession isTokenValid(String token) {
EntityManager em = factory.createEntityManager();
UserSession result = em.find(UserSession.class, token);
if (result != null && result.getExpiryDate().before(new Date())) {
return result;
}
return null;
}
}
| gpl-2.0 |
baratine/baratine | web/src/main/java/com/caucho/v5/network/NetworkSystem.java | 9420 | /*
* Copyright (c) 1998-2015 Caucho Technology -- all rights reserved
*
* This file is part of Baratine(TM)
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Baratine is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Baratine is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Baratine; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.v5.network;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.caucho.v5.amp.AmpSystem;
import com.caucho.v5.amp.ServicesAmp;
import com.caucho.v5.amp.spi.ShutdownModeAmp;
import com.caucho.v5.bartender.ServerBartender;
import com.caucho.v5.config.ConfigException;
import com.caucho.v5.http.protocol.ProtocolHttp;
import com.caucho.v5.io.ServerSocketBar;
import com.caucho.v5.io.SocketSystem;
import com.caucho.v5.jni.SelectManagerJni;
import com.caucho.v5.network.port.ConnectionTcp;
import com.caucho.v5.network.port.PollTcpManagerBase;
import com.caucho.v5.network.port.PortTcp;
import com.caucho.v5.network.port.PortTcpBuilder;
import com.caucho.v5.subsystem.SubSystemBase;
import com.caucho.v5.subsystem.SystemManager;
import com.caucho.v5.util.Alarm;
import com.caucho.v5.util.AlarmListener;
import com.caucho.v5.util.L10N;
import io.baratine.config.Config;
/**
* NetworkClusterService manages the cluster network code, the communication
* between Resin servers in a cluster.
*/
public class NetworkSystem extends SubSystemBase
{
private static final String UID = "/network-address";
private static final Logger log
= Logger.getLogger(NetworkSystem.class.getName());
public static final int START_PRIORITY = START_PRIORITY_NETWORK;
private static final long ALARM_TIMEOUT = 120 * 1000L;
private static final L10N L = new L10N(NetworkSystem.class);
private final ServerBartender _selfServer;
private final ArrayList<PortTcp> _ports
= new ArrayList<>();
private SelectManagerJni _pollManager;
private Alarm _alarm;
private Config _config;
public NetworkSystem(SystemManager systemManager,
ServerBartender selfServer,
Config config)
{
Objects.requireNonNull(selfServer);
Objects.requireNonNull(config);
_selfServer = selfServer;
_config = config;
ServicesAmp manager = AmpSystem.currentManager();
}
/**
* Creates a new network cluster service.
*/
public static NetworkSystem
createAndAddSystem(SystemManager systemManager,
ServerBartender selfServer,
Config config)
{
NetworkSystem clusterSystem
= new NetworkSystem(systemManager, selfServer, config);
createAndAddSystem(clusterSystem);
return clusterSystem;
}
public static void
createAndAddSystem(NetworkSystem clusterSystem)
{
SystemManager resinSystem = preCreate(NetworkSystem.class);
resinSystem.addSystem(NetworkSystem.class, clusterSystem);
}
/**
* Returns the current network service.
*/
public static NetworkSystem current()
{
return SystemManager.getCurrentSystem(NetworkSystem.class);
}
/**
* Returns the current network service.
*/
public static ServerBartender currentSelfServer()
{
NetworkSystem clusterService = current();
if (clusterService == null)
throw new IllegalStateException(L.l("{0} is not available in this context",
NetworkSystem.class.getSimpleName()));
return clusterService.selfServer();
}
/**
* Returns the self server for the network.
*/
public ServerBartender selfServer()
{
return _selfServer;
}
/**
* Returns the active server id.
*/
public String serverId()
{
return selfServer().getId();
}
//
// lifecycle
//
@Override
public int getStartPriority()
{
return START_PRIORITY;
}
@Override
public void start()
throws Exception
{
super.start();
boolean isFirst = true;
_pollManager = SelectManagerJni.create();
initPorts();
for (PortTcp port : _ports) {
if (isFirst) {
//log.info("");
}
isFirst = false;
port.bind();
// XXX: delay start until after kraken
port.start();
}
if (! isFirst) {
//log.info("");
}
_alarm = new Alarm(new NetworkAlarmListener());
_alarm.runAfter(ALARM_TIMEOUT);
}
private void initPorts()
{
ProtocolHttp httpProtocol = new ProtocolHttp();
/*
if (_serverConfig.getPortBartender() < 0) {
protocolPublic = _httpProtocolBartender;
}
*/
Config config = _config;
PortTcpBuilder portBuilder = new PortTcpBuilder(config);
portBuilder.portName("server");
//portBuilder.serverSocket(_serverConfig.getServerSocket());
portBuilder.protocol(httpProtocol);
portBuilder.ampManager(AmpSystem.currentManager());
portBuilder.portDefault(8080);
// XXX: config timing issues, see network/0330,
// NetworkServerConfig.getClusterIdleTime()
PortTcp portPublic = portBuilder.get();
_ports.add(portPublic);
}
/**
* Closes the server.
*/
@Override
public void stop(ShutdownModeAmp mode)
throws Exception
{
super.stop(mode);
Alarm alarm = _alarm;
_alarm = null;
if (alarm != null) {
alarm.dequeue();
}
for (PortTcp port : _ports) {
try {
port.close();
} catch (Throwable e) {
log.log(Level.WARNING, e.toString(), e);
}
}
}
public static ArrayList<InetAddress> getLocalAddresses()
{
return SocketSystem.current().getLocalAddresses();
}
public void addPort(PortTcp port)
{
try {
if (! _ports.contains(port)) {
_ports.add(port);
}
else {
System.err.println("Duplicate port: " + _ports + " " + port);
return;
// throw new ConfigException(L.l("duplicate port {0}", port));
}
if (isActive()) {
// server/1e00
port.bind();
port.start();
}
} catch (Exception e) {
throw ConfigException.wrap(e);
}
}
/**
* Returns the {@link PortTcp}s for this server.
*/
public Collection<PortTcp> getPorts()
{
return Collections.unmodifiableList(_ports);
}
public void bind(String address, int port, ServerSocketBar ss)
throws IOException
{
if ("null".equals(address)) {
address = null;
}
for (int i = 0; i < _ports.size(); i++) {
PortTcp serverPort = _ports.get(i);
if (port != serverPort.port()) {
continue;
}
if ((address == null) != (serverPort.address() == null)) {
continue;
}
else if (address == null || address.equals(serverPort.address())) {
serverPort.bind(ss);
return;
}
}
throw new IllegalStateException(L.l("No matching port for {0}:{1}",
address, port));
}
/**
* Finds the TcpConnection given the threadId
*/
public ConnectionTcp findConnectionByThreadId(long threadId)
{
for (PortTcp listener : getPorts()) {
ConnectionTcp conn = listener.findConnectionByThreadId(threadId);
if (conn != null)
return conn;
}
return null;
}
//
// lifecycle
//
public static PollTcpManagerBase currentPollManager()
{
NetworkSystem system = current();
if (system != null) {
return system.getPollManager();
}
else {
return null;
}
}
public PollTcpManagerBase getPollManager()
{
if (_pollManager == null) {
_pollManager = SelectManagerJni.create();
}
return _pollManager;
}
/**
* Handles the alarm.
*/
private class NetworkAlarmListener implements AlarmListener {
@Override
public void handleAlarm(Alarm alarm)
{
try {
for (PortTcp listener : _ports) {
if (listener.isClosed()) {
log.severe("Restarting due to closed listener: " + listener);
// destroy();
//_controller.restart();
}
}
} catch (Throwable e) {
log.log(Level.WARNING, e.toString(), e);
// destroy();
//_controller.restart();
} finally {
alarm = _alarm;
if (alarm != null)
alarm.runAfter(ALARM_TIMEOUT);
}
}
}
/**
* Closes the server.
*/
/*
@Override
public void stop(ShutdownMode mode)
{
}
*/
@Override
public String toString()
{
return (getClass().getSimpleName() + "[]");
}
}
| gpl-2.0 |
liquid36/TreAvisoAndroid | app/src/main/java/com/samsoft/treaviso/app/AlarmFrame.java | 6707 | package com.samsoft.treaviso.app;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import com.mburman.fileexplore.FileExplore;
import com.samsoft.treaviso.background.data.Alarm;
import com.samsoft.treaviso.background.data.DAOFactory;
import com.samsoft.treaviso.background.data.LocationDAO;
import android.util.Log;
import android.widget.Toast;
public class AlarmFrame extends ActionBarActivity {
private long editID;
private Alarm editA;
private LocationDAO db;
EditText name;
EditText metros;
EditText path;
EditText lat;
EditText lon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_frame);
name = (EditText) findViewById(R.id.txtName);
metros = (EditText) findViewById(R.id.txtMetros);
path = (EditText) findViewById(R.id.txtPath);
lat = (EditText) findViewById(R.id.txtLat);
lon = (EditText) findViewById(R.id.txtLong);
Bundle i = getIntent().getExtras();
editID = i.getLong("accion", 0);
db = DAOFactory.createLocationDAO(getApplicationContext());
editA = db.getAlarm(editID);
if (editA != null) {
name.setText(editA.getName());
metros.setText(Integer.toString(editA.getMetros()));
path.setText(editA.getPath());
lat.setText(editA.getLatitude());
lon.setText(editA.getLongitude());
setTitle("Editar Alarma");
} else {
setTitle("Nueva Alarma");
editA = new Alarm();
editA.setActive(1);
}
path.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent i = new Intent(AlarmFrame.this, FileExplore.class);
startActivityForResult(i, 2);
return true;
}
});
path.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus) makeToast("Long press for file explorer");
}
});
path.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makeToast("Long press for file explorer");
}
});
}
public void setTitle(String t)
{
if (android.os.Build.VERSION.SDK_INT >= 11)
getActionBar().setTitle(t);
else
getSupportActionBar().setTitle(t);
}
public void makeToast(String s) {
Context context = getApplicationContext();
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
public boolean checkData()
{
if (lon.getText().toString().trim().isEmpty() || lat.getText().toString().trim().isEmpty() ) {
makeToast("Falta elegir coordenadas");
return false;
}
return true;
}
public void saveClick()
{
if (name.getText().toString().trim().isEmpty()) editA.setName("[unNamed]");
else editA.setName(name.getText().toString());
editA.setPath(path.getText().toString());
editA.setLongitude(lon.getText().toString());
editA.setLatitude(lat.getText().toString());
try {
editA.setMetros(Integer.parseInt(metros.getText().toString()));
} catch (Exception e){ editA.setMetros(400); }
if (editA.getId() > 0)
db.updateAlarm(editA);
else
db.persistAlarm(editA);
Intent resultIntent = new Intent( AlarmFrame.this , AlarmFrame.class);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
lat = (EditText) findViewById(R.id.txtLat);
lon = (EditText) findViewById(R.id.txtLong);
double dlat = data.getDoubleExtra("lat", 0);
double dlon = data.getDoubleExtra("lon", 0);
lat.setText(Double.toString(dlat));
lon.setText(Double.toString(dlon));
}
break;
}
case 2: {
if (resultCode == Activity.RESULT_OK) {
path.setText(data.getStringExtra("path"));
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.alarm_frame, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.act_back:
Intent resultIntent = new Intent( AlarmFrame.this , AlarmFrame.class);
setResult(Activity.RESULT_CANCELED, resultIntent);
finish();
case R.id.act_do:
if (checkData())
saveClick();
return true;
case R.id.act_search:
Intent i = new Intent(AlarmFrame.this, MapViewer.class);
try {
i.putExtra("Metros", Integer.parseInt(metros.getText().toString()));
} catch (Exception e) { i.putExtra("Metros",400); }
startActivityForResult(i, 1);
}
return super.onOptionsItemSelected(item);
}
public void startMap(View m)
{
Intent i = new Intent(AlarmFrame.this, MapViewer.class);
try {
i.putExtra("Metros", Integer.parseInt(metros.getText().toString()));
} catch (Exception e) { i.putExtra("Metros",400); }
startActivityForResult(i, 1);
}
}
| gpl-2.0 |
smarr/Truffle | tools/src/org.graalvm.tools.lsp/src/org/graalvm/tools/lsp/server/types/DocumentLink.java | 4664 | /*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.tools.lsp.server.types;
import com.oracle.truffle.tools.utils.json.JSONObject;
import java.util.Objects;
/**
* A document link is a range in a text document that links to an internal or external resource,
* like another text document or a web site.
*/
public class DocumentLink extends JSONBase {
DocumentLink(JSONObject jsonData) {
super(jsonData);
}
/**
* The range this link applies to.
*/
public Range getRange() {
return new Range(jsonData.getJSONObject("range"));
}
public DocumentLink setRange(Range range) {
jsonData.put("range", range.jsonData);
return this;
}
/**
* The uri this link points to.
*/
public String getTarget() {
return jsonData.optString("target", null);
}
public DocumentLink setTarget(String target) {
jsonData.putOpt("target", target);
return this;
}
/**
* The tooltip text when you hover over this link.
*
* If a tooltip is provided, is will be displayed in a string that includes instructions on how
* to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending
* on OS, user settings, and localization.
*
* @since 3.15.0
*/
public String getTooltip() {
return jsonData.optString("tooltip", null);
}
public DocumentLink setTooltip(String tooltip) {
jsonData.putOpt("tooltip", tooltip);
return this;
}
/**
* A data entry field that is preserved on a document link between a DocumentLinkRequest and a
* DocumentLinkResolveRequest.
*/
public Object getData() {
return jsonData.opt("data");
}
public DocumentLink setData(Object data) {
jsonData.putOpt("data", data);
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
DocumentLink other = (DocumentLink) obj;
if (!Objects.equals(this.getRange(), other.getRange())) {
return false;
}
if (!Objects.equals(this.getTarget(), other.getTarget())) {
return false;
}
if (!Objects.equals(this.getTooltip(), other.getTooltip())) {
return false;
}
if (!Objects.equals(this.getData(), other.getData())) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash + Objects.hashCode(this.getRange());
if (this.getTarget() != null) {
hash = 37 * hash + Objects.hashCode(this.getTarget());
}
if (this.getTooltip() != null) {
hash = 37 * hash + Objects.hashCode(this.getTooltip());
}
if (this.getData() != null) {
hash = 37 * hash + Objects.hashCode(this.getData());
}
return hash;
}
/**
* Creates a new DocumentLink literal.
*/
public static DocumentLink create(Range range, String target, Object data) {
final JSONObject json = new JSONObject();
json.put("range", range.jsonData);
json.putOpt("target", target);
json.putOpt("data", data);
return new DocumentLink(json);
}
}
| gpl-2.0 |
abollaert/freedomotic | framework/freedomotic-core/src/main/java/com/freedomotic/rules/GreaterEqualThan.java | 1704 | /**
*
* Copyright (c) 2009-2016 Freedomotic team http://freedomotic.com
*
* This file is part of Freedomotic
*
* This Program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2, or (at your option) any later version.
*
* This Program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.freedomotic.rules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Enrico Nicoletti
*/
public class GreaterEqualThan extends BinaryExpression {
private static final String OPERATOR = Statement.GREATER_EQUAL_THAN;
private static final Logger LOG = LoggerFactory.getLogger(GreaterEqualThan.class.getName());
@Override
public String getOperand() {
return OPERATOR;
}
public GreaterEqualThan(String left, String right) {
super(left, right);
}
@Override
public Boolean evaluate() {
try {
Integer intRightValue = new Integer(getRight());
Integer intLeftValue = new Integer(getLeft());
return intLeftValue >= intRightValue;
} catch (NumberFormatException nfe) {
LOG.warn(OPERATOR + " operator can be applied only to integer values");
return false;
}
}
}
| gpl-2.0 |
ninuxorg/OBAMPxP | src/it/radiolabs/obampxp/pktHelloConf.java | 4253 | package it.radiolabs.obampxp;
/*
Copyright (C) 2007 Andrea Detti, Remo Pomposini, Roberto Zanetti
This file is part of "Obamp Proxy",
"Obamp Proxy" is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"Obamp Proxy" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with "Obamp Proxy"; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
public class pktHelloConf {
//packet variables: 4 Bytes
protected byte MessageID;
protected byte SourceIP;
protected byte CoreAddress;
protected byte SequenceNumber;
protected byte TTL;
//complementary variables
protected InetAddress SourceIPAddress;
protected InetAddress DestinationIPAddress;
protected InetAddress IPCoreAddress;
protected byte[] address;
protected int sourcePort;
protected byte[] data;
protected int destPort;
public pktHelloConf(InetAddress address_) {
MessageID = 12;
address = address_.getAddress();
}
public pktHelloConf(byte sn, InetAddress SourceIPAddress_, InetAddress DestinationIPAddress_, InetAddress IPCoreAddress_, byte TTL_, Signalling agent) {
synchronized(agent.signalling_use){
MessageID = 12;
SequenceNumber = sn;
SourceIPAddress = SourceIPAddress_;
IPCoreAddress = IPCoreAddress_;
DestinationIPAddress = DestinationIPAddress_;
TTL = TTL_;
//byte ind [] = SourceIPAddress.getAddress();
this.SourceIP = agent.getIAddresspkt(SourceIPAddress);
//byte indC [] = IPCoreAddress.getAddress();
this.CoreAddress = agent.getIAddresspkt(IPCoreAddress);
}
}
//it sets the packet by an input stream
public void SetpktHelloConf(DataInputStream qI, Signalling agent){
synchronized(agent.signalling_use){
try{
//settings variables
MessageID = qI.readByte();//12;
SourceIP = qI.readByte();
CoreAddress = qI.readByte();
SequenceNumber = qI.readByte();
TTL = qI.readByte();
//byte ind [] = new byte[4];
//ind[0] = address[0];
//ind[1] = address[1];
//ind[2] = address[2];
//ind[3] = SourceIP;
this.SourceIPAddress = agent.getAddresspkt(SourceIP);
//byte indC [] = new byte[4];
//indC[0] = address[0];
//indC[1] = address[1];
//indC[2] = address[2];
//indC[3] = CoreAddress;
this.IPCoreAddress = agent.getAddresspkt(CoreAddress);
} catch (IOException ex) {
}
return;
}
}
public byte[] GetpktHelloConf(){
try {
ByteArrayOutputStream boStream = new ByteArrayOutputStream ();
DataOutputStream doStream = new DataOutputStream (boStream);
doStream.writeByte(MessageID);
doStream.writeByte(SourceIP);
doStream.writeByte(CoreAddress);
doStream.writeByte(SequenceNumber);
doStream.writeByte(TTL);
data = boStream.toByteArray ();
} catch (IOException ex) {
ex.printStackTrace ();
}
return data;
}
} | gpl-2.0 |
Norkart/NK-VirtualGlobe | Xj3D/src/java/org/web3d/vrml/scripting/sai/SAIFieldEvent.java | 1433 | /*****************************************************************************
* Web3d.org Copyright (c) 2001
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.web3d.vrml.scripting.sai;
// Standard imports
// None
// Application specific imports
import org.web3d.x3d.sai.X3DFieldEvent;
/**
* Local variant of the field event that allows data to be reset.
*
* @author Justin Couch
* @version $Revision: 1.2 $
*/
class SAIFieldEvent extends X3DFieldEvent {
/**
* Construct a new default event instance.
*
* @param src Anything non-null. Gets overwritten anyway
*/
SAIFieldEvent(Object src) {
super(src, 0, null);
}
/**
* Construct a new event instance.
*
* @param src The source field that generated this event
* @param ts The timestamp of the event, In VRML time.
* @param data Any user associated data with this event
*/
void update(Object src, double ts, Object data) {
source = src;
timestamp = ts;
userData = data;
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20431.java | 3270 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest20431")
public class BenchmarkTest20431 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("foo");
String bar = doSomething(param);
java.security.Provider[] provider = java.security.Security.getProviders();
javax.crypto.Cipher c;
try {
if (provider.length > 1) {
c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
} else {
c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
return bar;
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest13169.java | 3564 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest13169")
public class BenchmarkTest13169 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = new Test().doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
ProcessBuilder pb = new ProcessBuilder();
pb.command(args);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a5896 = param; //assign
StringBuilder b5896 = new StringBuilder(a5896); // stick in stringbuilder
b5896.append(" SafeStuff"); // append some safe content
b5896.replace(b5896.length()-"Chars".length(),b5896.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map5896 = new java.util.HashMap<String,Object>();
map5896.put("key5896", b5896.toString()); // put in a collection
String c5896 = (String)map5896.get("key5896"); // get it back out
String d5896 = c5896.substring(0,c5896.length()-1); // extract most of it
String e5896 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d5896.getBytes() ) )); // B64 encode and decode it
String f5896 = e5896.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g5896 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g5896); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
FauxFaux/jdk9-langtools | test/tools/javac/MethodParameters/MemberClassTest.java | 2839 | /*
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8006582 8008658
* @summary javac should generate method parameters correctly.
* @modules jdk.jdeps/com.sun.tools.classfile
* @build MethodParametersTester
* @compile -parameters MemberClassTest.java
* @run main MethodParametersTester MemberClassTest MemberClassTest.out
*/
class MemberClassTest {
interface I {
Long m();
Long m(Long x, Long yx);
}
public class Member implements I {
public class Member_Member {
public Member_Member() {}
public Member_Member(String x, String yx) {}
}
public Member() { }
public Member(Long a, Long ba) { }
public Long m() { return 0L; }
public Long m(Long s, Long ts) { return 0L; }
}
static class Static_Member implements I {
public class Static_Member_Member {
public Static_Member_Member() {}
public Static_Member_Member(String x, String yx) {}
}
public static class Static_Member_Static_Member {
public Static_Member_Static_Member() {}
public Static_Member_Static_Member(String x, String yx) {}
}
public Static_Member() { }
public Static_Member(Long arg, Long barg) { }
public Long m() { return 0L; }
public Long m(Long s, Long ts) { return s + ts; }
}
public MemberClassTest() {
}
public MemberClassTest(final Long a, Long ba) {
}
public void foo() {
new I() {
class Anonymous_Member {
public Anonymous_Member() {}
public Anonymous_Member(String x, String yx) {}
}
public Long m() { return 0L; }
public Long m(Long s, Long ts) { return s + ts; }
}.m();
}
}
| gpl-2.0 |
strnbrg59/stuff | cardation/src/net/trhj/cardation/BackupVersion.java | 2897 | package net.trhj.cardation;
import java.io.*;
import android.os.Environment;
class BackupVersion {
public static int newestBackupVersion(final String language)
{
String[] dirlist = listDbbk(language);
int result = -1;
for (int i=0; i<dirlist.length; ++i) {
String[] parts1 = dirlist[i].split("\\.");
String base = parts1[0];
String[] parts2 = base.split("_");
String str_suffix = parts2[4];
int int_suffix = Integer.parseInt(str_suffix);
if (int_suffix > result) {
result = int_suffix;
}
}
return result;
}
/* The one with the highest numerical suffix. */
public static String newestBackupFile(final String language)
{
int highest_version = newestBackupVersion(language);
if (highest_version == -1) {
return "";
} else {
return Environment.getExternalStorageDirectory() + "/"
+ CardDb.pkg_underbars_ + "_" + language + "_"
+ highest_version
+ ".dbbk";
}
}
public static String nextBackupFile(final String language)
{
int highest_version = newestBackupVersion(language);
return Environment.getExternalStorageDirectory() + "/"
+ CardDb.pkg_underbars_ + "_" + language + "_"
+ (highest_version+1)
+ ".dbbk";
}
public static String[] listDbbk(final String language)
{
File dir = new File(Environment.getExternalStorageDirectory() + "/");
String[] dirlist = dir.list(
new FilenameFilter() {
public boolean accept(File dir, String name) {
// E.g. net_trhj_cardation_Italian_2.dbbk
String[] parts = name.split("\\.");
if (parts.length != 2) {
return false;
} else {
String base = parts[0];
String extension = parts[1];
if (!extension.equals("dbbk")) {
return false;
} else {
String[] base_tokens = base.split("_");
if (base_tokens.length != 5) {
return false;
} else {
if (!base_tokens[3].equals(language)) {
return false;
}
}
}
}
return true;
}
});
String[] result = new String[dirlist.length];
for (int i=0;i<dirlist.length;++i) {
result[i] = dirlist[i];
}
return result;
}
}
| gpl-2.0 |
smarr/GraalCompiler | graal/com.oracle.graal.truffle.test/src/com/oracle/graal/truffle/test/builtins/SLSetOptionBuiltin.java | 2454 | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.truffle.test.builtins;
import jdk.internal.jvmci.options.OptionDescriptor;
import com.oracle.graal.truffle.TruffleCompilerOptions;
import com.oracle.graal.truffle.TruffleCompilerOptions_OptionDescriptors;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.NodeInfo;
/**
* Sets an option value in {@link TruffleCompilerOptions}. In the future this builtin might be
* extend to lookup other options as well.
*/
@NodeInfo(shortName = "setOption")
public abstract class SLSetOptionBuiltin extends SLGraalRuntimeBuiltin {
@Specialization
@TruffleBoundary
public Object setOption(String name, Object value) {
TruffleCompilerOptions_OptionDescriptors options = new TruffleCompilerOptions_OptionDescriptors();
for (OptionDescriptor option : options) {
if (option.getName().equals(name)) {
option.getOptionValue().setValue(convertValue(value));
}
}
return value;
}
private static Object convertValue(Object value) {
// Improve this method as you need it.
if (value instanceof Long) {
long longValue = (long) value;
if (longValue == (int) longValue) {
return (int) longValue;
}
}
return value;
}
}
| gpl-2.0 |
MineDoubleSpace/hunger-games | main/java/com/skitscape/sg/util/StringUtil.java | 286 | package com.skitscape.sg.util;
import org.bukkit.ChatColor;
import com.skitscape.sg.Core;
public class StringUtil {
public static String format (String str, Object... args) {
return ChatColor.translateAlternateColorCodes('&', String.format(Core.getPrefix() + str, args));
}
}
| gpl-2.0 |
jeffgdotorg/opennms | features/timeseries/src/main/java/org/opennms/netmgt/timeseries/samplewrite/TimeseriesWriter.java | 10911 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2016 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.timeseries.samplewrite;
import java.sql.SQLException;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import org.opennms.core.logging.Logging;
import org.opennms.integration.api.v1.timeseries.IntrinsicTagNames;
import org.opennms.integration.api.v1.timeseries.Metric;
import org.opennms.integration.api.v1.timeseries.Sample;
import org.opennms.netmgt.timeseries.TimeseriesStorageManager;
import org.opennms.netmgt.timeseries.sampleread.SampleBatchEvent;
import org.opennms.netmgt.timeseries.meta.MetaData;
import org.opennms.netmgt.timeseries.meta.TimeSeriesMetaDataDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
import com.google.common.math.DoubleMath;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.FatalExceptionHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.WorkerPool;
import com.swrve.ratelimitedlogger.RateLimitedLog;
/**
* Used to write samples to the {@link org.opennms.integration.api.v1.timeseries.TimeSeriesStorage}.
*
* Calls to publish the samples to a ring buffer so
* that they don't block while the data is being persisted.
*
* @author jwhite
*/
public class TimeseriesWriter implements WorkHandler<SampleBatchEvent>, DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(TimeseriesWriter.class);
private static final RateLimitedLog RATE_LIMITED_LOGGER = RateLimitedLog
.withRateLimit(LOG)
.maxRate(5).every(Duration.ofSeconds(30))
.build();
private WorkerPool<SampleBatchEvent> workerPool;
private RingBuffer<SampleBatchEvent> ringBuffer;
private final int ringBufferSize;
private final int numWriterThreads;
private final Meter droppedSamples;
private final Timer sampleWriteTsTimer;
@Autowired
private TimeseriesStorageManager storage;
@Autowired
private TimeSeriesMetaDataDao timeSeriesMetaDataDao;
/**
* The {@link RingBuffer} doesn't appear to expose any methods that indicate the number
* of elements that are currently "queued", so we keep track of them with this atomic counter.
*/
private final AtomicLong numEntriesOnRingBuffer = new AtomicLong();
@Inject
public TimeseriesWriter(@Named("timeseries.ring_buffer_size") Integer ringBufferSize,
@Named("timeseries.writer_threads") Integer numWriterThreads, @Named("timeseriesMetricRegistry") MetricRegistry registry) {
Preconditions.checkArgument(ringBufferSize > 0, "ringBufferSize must be positive");
Preconditions.checkArgument(DoubleMath.isMathematicalInteger(Math.log(ringBufferSize) / Math.log(2)), "ringBufferSize must be a power of two");
Preconditions.checkArgument(numWriterThreads > 0, "numWriterThreads must be positive");
Preconditions.checkNotNull(registry, "metric registry");
this.ringBufferSize = ringBufferSize;
this.numWriterThreads = numWriterThreads;
numEntriesOnRingBuffer.set(0L);
registry.register(MetricRegistry.name("ring-buffer", "size"),
new Gauge<Long>() {
@Override
public Long getValue() {
return numEntriesOnRingBuffer.get();
}
});
registry.register(MetricRegistry.name("ring-buffer", "max-size"),
new Gauge<Long>() {
@Override
public Long getValue() {
return Long.valueOf(TimeseriesWriter.this.ringBufferSize);
}
});
droppedSamples = registry.meter(MetricRegistry.name("ring-buffer", "dropped-samples"));
sampleWriteTsTimer = registry.timer("samples.write.ts");
LOG.debug("Using ring_buffer_size: {}", this.ringBufferSize);
setUpWorkerPool();
}
private void setUpWorkerPool() {
// Executor that will be used to construct new threads for consumers
final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("TimeseriesWriter-Consumer-%d").build();
final Executor executor = Executors.newCachedThreadPool(namedThreadFactory);
@SuppressWarnings("unchecked")
final WorkHandler<SampleBatchEvent>[] handlers = new WorkHandler[numWriterThreads];
for (int i = 0; i < numWriterThreads; i++) {
handlers[i] = this;
}
ringBuffer = RingBuffer.createMultiProducer(SampleBatchEvent::new, ringBufferSize);
workerPool = new WorkerPool<SampleBatchEvent>(
ringBuffer,
ringBuffer.newBarrier(),
new FatalExceptionHandler(),
handlers);
ringBuffer.addGatingSequences(workerPool.getWorkerSequences());
workerPool.start(executor);
}
@Override
public void destroy() {
if (workerPool != null) {
workerPool.drainAndHalt();
}
}
public void insert(List<Sample> samples) {
pushToRingBuffer(samples, TRANSLATOR);
}
public void index(List<Sample> samples) {
pushToRingBuffer(samples, INDEX_ONLY_TRANSLATOR);
}
private void pushToRingBuffer(List<Sample> samples, EventTranslatorOneArg<SampleBatchEvent, List<Sample>> translator) {
// Add the samples to the ring buffer
if (!ringBuffer.tryPublishEvent(translator, samples)) {
RATE_LIMITED_LOGGER.error("The ring buffer is full. {} samples associated with resource ids {} will be dropped.",
samples.size(), new Object() {
@Override
public String toString() {
// We wrap this in a toString() method to avoid build the string
// unless the log message is actually printed
return samples.stream()
.map(s -> s.getMetric().getFirstTagByKey(IntrinsicTagNames.resourceId).getValue())
.distinct()
.collect(Collectors.joining(", "));
}
});
droppedSamples.mark(samples.size());
return;
}
// Increase our entry counter
numEntriesOnRingBuffer.incrementAndGet();
}
@Override
public void onEvent(SampleBatchEvent event) throws Exception {
// We'd expect the logs from this thread to be in collectd.log
Logging.putPrefix("collectd");
// Decrement our entry counter
numEntriesOnRingBuffer.decrementAndGet();
try {
if (event.isMetadata()) {
storeMetadata(event); // Sample represents metadata, no "real" Samples. Metadata is stored in table.
} else {
try(Timer.Context context = this.sampleWriteTsTimer.time()) {
this.storage.get().store(event.getSamples());
}
}
} catch (Throwable t) {
RATE_LIMITED_LOGGER.error("An error occurred while inserting samples. Some sample may be lost.", t);
}
}
private void storeMetadata(SampleBatchEvent event) throws SQLException, ExecutionException {
// dedouble attributes
Set<MetaData> metaData = new HashSet<>();
for(Sample sample : event.getSamples()) {
Metric metric = sample.getMetric();
String resourceId = metric.getFirstTagByKey(IntrinsicTagNames.resourceId).getValue();
metric.getMetaTags().forEach(tag -> metaData.add(new MetaData(resourceId, tag.getKey(), tag.getValue())));
}
this.timeSeriesMetaDataDao.store(metaData);
}
private static final EventTranslatorOneArg<SampleBatchEvent, List<Sample>> TRANSLATOR =
new EventTranslatorOneArg<SampleBatchEvent, List<Sample>>() {
public void translateTo(SampleBatchEvent event, long sequence, List<Sample> samples) {
event.setMetadata(false); // we are a "real" Sample
event.setSamples(samples);
}
};
private static final EventTranslatorOneArg<SampleBatchEvent, List<Sample>> INDEX_ONLY_TRANSLATOR =
new EventTranslatorOneArg<SampleBatchEvent, List<Sample>>() {
public void translateTo(SampleBatchEvent event, long sequence, List<Sample> samples) {
event.setMetadata(true); // we are a "fake" Sample carrying meta data
event.setSamples(samples);
}
};
public void setTimeSeriesStorage(final TimeseriesStorageManager timeseriesStorage) {
this.storage = timeseriesStorage;
}
public void setTimeSeriesMetaDataDao(final TimeSeriesMetaDataDao timeSeriesMetaDataDao) {
this.timeSeriesMetaDataDao = timeSeriesMetaDataDao;
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/mov_rCXr9_Iw.java | 1802 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.vm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class mov_rCXr9_Iw extends Executable
{
final int immw;
public mov_rCXr9_Iw(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
immw = Modrm.Iw(input);
}
public Branch execute(Processor cpu)
{
cpu.r_ecx.set16((short)immw);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
emmanuelJd/HEBook | HEBookingClient/src/java/org/client/jersey/ChambreClient.java | 9012 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.client.jersey;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
/**
* Jersey REST client generated for REST resource:ChambreFacadeREST
* [org.hebook.model.chambre]<br>
* USAGE:
* <pre>
* ChambreClient client = new ChambreClient();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author Emmanuel
*/
public class ChambreClient {
private WebResource webResource;
private Client client;
private static final String BASE_URI = "http://localhost:8080/HEBookProjet/webresources";
/**
*
*/
public ChambreClient() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
client = Client.create(config);
webResource = client.resource(BASE_URI).path("org.hebook.model.chambre");
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotel_XML(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotel");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotel_JSON(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotel");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
* @param id
* @throws UniformInterfaceException
*/
public void remove(String id) throws UniformInterfaceException {
webResource.path(java.text.MessageFormat.format("{0}", new Object[]{id})).delete();
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotelNoDisponible_XML(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotelNoDispo");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotelNoDisponible_JSON(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotelNoDispo");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
* @return
* @throws UniformInterfaceException
*/
public String countREST() throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path("count");
return resource.accept(javax.ws.rs.core.MediaType.TEXT_PLAIN).get(String.class);
}
/**
*
* @param <T>
* @param responseType
* @return
* @throws UniformInterfaceException
*/
public <T> T findAll_XML(Class<T> responseType) throws UniformInterfaceException {
WebResource resource = webResource;
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @return
* @throws UniformInterfaceException
*/
public <T> T findAll_JSON(Class<T> responseType) throws UniformInterfaceException {
WebResource resource = webResource;
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
* @param requestEntity
* @throws UniformInterfaceException
*/
public void edit_XML(Object requestEntity) throws UniformInterfaceException {
webResource.type(javax.ws.rs.core.MediaType.APPLICATION_XML).put(requestEntity);
}
/**
*
* @param requestEntity
* @throws UniformInterfaceException
*/
public void edit_JSON(Object requestEntity) throws UniformInterfaceException {
webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(requestEntity);
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotelDisponible_XML(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotelDispo");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param idHotel
* @return
* @throws UniformInterfaceException
*/
public <T> T findChambreByHotelDisponible_JSON(Class<T> responseType, String idHotel) throws UniformInterfaceException {
WebResource resource = webResource;
if (idHotel != null) {
resource = resource.queryParam("idHotel", idHotel);
}
resource = resource.path("getChambreByHotelDispo");
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
* @param requestEntity
* @throws UniformInterfaceException
*/
public void create_XML(Object requestEntity) throws UniformInterfaceException {
webResource.type(javax.ws.rs.core.MediaType.APPLICATION_XML).post(requestEntity);
}
/**
*
* @param requestEntity
* @throws UniformInterfaceException
*/
public void create_JSON(Object requestEntity) throws UniformInterfaceException {
webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(requestEntity);
}
/**
*
* @param <T>
* @param responseType
* @param from
* @param to
* @return
* @throws UniformInterfaceException
*/
public <T> T findRange_XML(Class<T> responseType, String from, String to) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{from, to}));
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param from
* @param to
* @return
* @throws UniformInterfaceException
*/
public <T> T findRange_JSON(Class<T> responseType, String from, String to) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{from, to}));
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param id
* @return
* @throws UniformInterfaceException
*/
public <T> T find_XML(Class<T> responseType, String id) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
/**
*
* @param <T>
* @param responseType
* @param id
* @return
* @throws UniformInterfaceException
*/
public <T> T find_JSON(Class<T> responseType, String id) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
/**
*
*/
public void close() {
client.destroy();
}
}
| gpl-2.0 |
scroniser/cis-498 | PFUCourseSchedulerV2/src/java/model/Schedule.java | 2138 | package model;
import java.sql.Time;
public class Schedule {
private Long callnumber;
private Long coursenumber;
private String department;
private String days;
private Time startime;
private Time endtime;
private String instructor;
private Short room;
private String building;
public Long getCallnumber() {
return callnumber;
}
public void setCallnumber(Long callnumber) {
this.callnumber = callnumber;
}
public Long getCoursenumber() {
return coursenumber;
}
public void setCoursenumber(Long coursenumber) {
this.coursenumber = coursenumber;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public Time getStartime() {
return startime;
}
public void setStartime(Time startime){
this.startime = startime;
}
public Time getEndtime() {
return endtime;
}
public void setEndtime(Time endtime){
this.endtime = endtime;
}
public String getInstructor() {
return instructor;
}
public void setInstructor(String instructor) {
this.instructor = instructor;
}
public Short getRoom() {
return room;
}
public void setRoom(Short room){
this.room = room;
}
public String getBuilding(){
return building;
}
public void setBuilding(String building){
this.building = building;
}
@Override
public String toString() {
return "Schedule [callnumber=" + callnumber + ", coursenumber=" + coursenumber
+ ", department=" + department + ", days="
+ days + ", startime="
+ startime + ", endtime="
+ endtime + ", instructor="
+ instructor + ", room="
+ room + ", building="
+ building + "]";
}
}
| gpl-2.0 |
kompics/kola | src/main/java/se/sics/kola/node/AAssertStatementStatementWithoutTrailingSubstatement.java | 2262 | /* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
import se.sics.kola.analysis.*;
@SuppressWarnings("nls")
public final class AAssertStatementStatementWithoutTrailingSubstatement extends PStatementWithoutTrailingSubstatement
{
private PAssertStatement _assertStatement_;
public AAssertStatementStatementWithoutTrailingSubstatement()
{
// Constructor
}
public AAssertStatementStatementWithoutTrailingSubstatement(
@SuppressWarnings("hiding") PAssertStatement _assertStatement_)
{
// Constructor
setAssertStatement(_assertStatement_);
}
@Override
public Object clone()
{
return new AAssertStatementStatementWithoutTrailingSubstatement(
cloneNode(this._assertStatement_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseAAssertStatementStatementWithoutTrailingSubstatement(this);
}
public PAssertStatement getAssertStatement()
{
return this._assertStatement_;
}
public void setAssertStatement(PAssertStatement node)
{
if(this._assertStatement_ != null)
{
this._assertStatement_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._assertStatement_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._assertStatement_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._assertStatement_ == child)
{
this._assertStatement_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._assertStatement_ == oldChild)
{
setAssertStatement((PAssertStatement) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| gpl-2.0 |
cobexer/fullsync | fullsync-core/src/main/java/net/sourceforge/fullsync/impl/PublishActionDecider.java | 5860 | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* For information about the authors of this project Have a look
* at the AUTHORS file in the root of this project.
*/
package net.sourceforge.fullsync.impl;
import static net.sourceforge.fullsync.Location.DESTINATION;
import static net.sourceforge.fullsync.Location.NONE;
import static net.sourceforge.fullsync.Location.SOURCE;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.fullsync.Action;
import net.sourceforge.fullsync.ActionDecider;
import net.sourceforge.fullsync.ActionType;
import net.sourceforge.fullsync.BufferStateDecider;
import net.sourceforge.fullsync.BufferUpdate;
import net.sourceforge.fullsync.DataParseException;
import net.sourceforge.fullsync.State;
import net.sourceforge.fullsync.StateDecider;
import net.sourceforge.fullsync.Task;
import net.sourceforge.fullsync.fs.File;
/**
* An ActionDecider for destination buffered Publish/Update.
*/
public class PublishActionDecider implements ActionDecider {
private static final Action addDestination = new Action(ActionType.ADD, DESTINATION, BufferUpdate.DESTINATION, "Add");
private static final Action ignoreDestinationExists = new Action(ActionType.UNEXPECTED_CHANGE_ERROR, DESTINATION, BufferUpdate.NONE,
"will not add, destination already exists");
private static final Action overwriteSource = new Action(ActionType.UPDATE, SOURCE, BufferUpdate.DESTINATION, "overwrite source");
private static final Action overwriteDestination = new Action(ActionType.UPDATE, DESTINATION, BufferUpdate.DESTINATION,
"overwrite destination");
private static final Action updateDestination = new Action(ActionType.UPDATE, DESTINATION, BufferUpdate.DESTINATION, "Source changed");
private static final Action unexpectedDestinationChanged = new Action(ActionType.UNEXPECTED_CHANGE_ERROR, DESTINATION,
BufferUpdate.NONE, "Destination changed");
private static final Action unexpectedBothChanged = new Action(ActionType.UNEXPECTED_CHANGE_ERROR, DESTINATION, BufferUpdate.NONE,
"Source changed, but changed remotely too");
private static final Action inSync = new Action(ActionType.NOTHING, NONE, BufferUpdate.NONE, "In Sync");
private static final Action ignore = new Action(ActionType.NOTHING, NONE, BufferUpdate.NONE, "Ignore");
@Override
public Task getTask(final File src, final File dst, final StateDecider sd, final BufferStateDecider bsd)
throws DataParseException, IOException {
List<Action> actions = new ArrayList<>(3);
var state = sd.getState(src, dst);
switch (state) {
case ORPHAN_SOURCE:
if (!bsd.getState(dst).equals(State.ORPHAN_SOURCE)) {
actions.add(addDestination);
}
else {
actions.add(ignoreDestinationExists);
actions.add(overwriteDestination);
}
break;
case DIR_SOURCE_FILE_DESTINATION:
var buff = bsd.getState(dst);
if (buff.equals(State.ORPHAN_SOURCE)) {
actions.add(new Action(ActionType.ADD, DESTINATION, BufferUpdate.DESTINATION,
"There was a node in buff, but its orphan, so add"));
}
else if (buff.equals(State.DIR_SOURCE_FILE_DESTINATION)) {
actions.add(new Action(ActionType.NOTHING, NONE, BufferUpdate.NONE,
"dirherefilethere, but there is a dir instead of file, so its in sync"));
}
else {
actions.add(new Action(ActionType.DIR_HERE_FILE_THERE_ERROR, SOURCE, BufferUpdate.NONE,
"cant update, dir here file there error occured"));
}
break;
case FILE_SOURCE_DIR_DESTINATION:
var buff1 = bsd.getState(dst);
if (buff1.equals(State.ORPHAN_SOURCE)) {
actions.add(
new Action(ActionType.ADD, SOURCE, BufferUpdate.DESTINATION, "There was a node in buff, but its orphan, so add"));
}
else if (buff1.equals(State.FILE_SOURCE_DIR_DESTINATION)) {
actions.add(new Action(ActionType.UNEXPECTED_CHANGE_ERROR, DESTINATION, BufferUpdate.NONE,
"dirherefilethere, but there is a file instead of dir, so unexpected change"));
// TODO ^ recompare here
}
else {
actions.add(new Action(ActionType.DIR_HERE_FILE_THERE_ERROR, DESTINATION, BufferUpdate.NONE,
"cant update, dir here file there error occured"));
}
break;
case FILE_CHANGE_SOURCE:
if (bsd.getState(dst).equals(State.IN_SYNC)) {
actions.add(updateDestination);
}
else {
actions.add(unexpectedBothChanged);
actions.add(overwriteDestination);
}
break;
case FILE_CHANGE_DESTINATION:
if (bsd.getState(dst).equals(State.IN_SYNC)) {
actions.add(unexpectedDestinationChanged);
}
else {
actions.add(unexpectedBothChanged);
}
actions.add(overwriteDestination);
break;
case IN_SYNC:
// TODO this check is not neccessary, check rules whether to do or not
// if( bsd.getState( dst ).equals( State.NodeInSync, Both ) || bsd.getState( dst ).equals( State.NodeInSync,
// None ) )
actions.add(inSync);
actions.add(overwriteDestination);
actions.add(overwriteSource);
break;
case ORPHAN_DESTINATION:
break;
}
actions.add(ignore);
var as = new Action[actions.size()];
actions.toArray(as);
return new Task(src, dst, state, as);
}
}
| gpl-2.0 |
bakaschwarz/EnderOres | src/main/java/de/geratheon/enderores/item/ItemEnderAthame.java | 5934 | package de.geratheon.enderores.item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import de.geratheon.enderores.achievement.ModAchievements;
import de.geratheon.enderores.init.ModItems;
import de.geratheon.enderores.reference.Reference;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import java.util.List;
public class ItemEnderAthame extends ItemEnderOres {
private static final int MAX_PEARLS = 100;
private static IIcon iconEmpty;
private static IIcon iconPartiallyFilled;
private static IIcon iconFull;
public ItemEnderAthame() {
super();
this.setUnlocalizedName("enderAthame");
this.setMaxStackSize(1);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
iconEmpty = iconRegister.registerIcon(Reference.RESOURCE_PREFIX + "enderAthameEmpty");
iconPartiallyFilled = iconRegister.registerIcon(Reference.RESOURCE_PREFIX + "enderAthamePartially");
iconFull = iconRegister.registerIcon(Reference.RESOURCE_PREFIX + "enderAthameFull");
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(ItemStack itemStack, int pass)
{
if (itemStack.stackTagCompound != null) {
int pearls = itemStack.stackTagCompound.getInteger("pearls");
if (pearls == 0) {
return iconEmpty;
} else if (pearls > 0 && pearls < 5) {
return iconPartiallyFilled;
} else {
return iconFull;
}
} else {
return iconEmpty;
}
}
@Override
public boolean requiresMultipleRenderPasses() {
return true;
}
@Override
public int getRenderPasses(int meta) {
return 1;
}
@Override
public void onCreated(ItemStack itemStack, World world, EntityPlayer player) {
initNBT(itemStack);
}
private void initNBT(ItemStack itemStack) {
itemStack.stackTagCompound = new NBTTagCompound();
itemStack.stackTagCompound.setInteger("pearls", 0);
itemStack.stackTagCompound.setInteger("kills", 0);
}
@Override
public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4) {
list.add(EnumChatFormatting.GRAY + "Onehits Endermen for each mini pearl");
list.add(EnumChatFormatting.GRAY + "Sneak + Use to refill from inventory");
if (itemStack.stackTagCompound != null) {
int pearls = itemStack.stackTagCompound.getInteger("pearls");
int kills = itemStack.stackTagCompound.getInteger("kills");
if (pearls == 0) {
list.add(EnumChatFormatting.RED + "Pearls: " + pearls);
} else if (pearls > 0 && pearls < 5) {
list.add(EnumChatFormatting.YELLOW + "Pearls: " + pearls);
} else {
list.add(EnumChatFormatting.GREEN + "Pearls: " + pearls);
}
list.add(EnumChatFormatting.BLUE + "Endermen killed: " + kills);
} else {
list.add(EnumChatFormatting.RED + "Pearls: 0");
}
}
// consumes mini ender pearl in inventory
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
{
if (itemStack.stackTagCompound != null) {
int pearls = itemStack.stackTagCompound.getInteger("pearls");
if (pearls < MAX_PEARLS) {
if (player.inventory.hasItem(ModItems.enderPearlNugget)) {
player.inventory.consumeInventoryItem(ModItems.enderPearlNugget);
itemStack.stackTagCompound.setInteger("pearls", pearls + 1);
}
}
} else {
initNBT(itemStack);
onItemRightClick(itemStack, world, player);
}
return itemStack;
}
// consumes mini ender pearl in athame, kills an ender man, guarantees ender pearl
@Override
public boolean onLeftClickEntity(ItemStack itemStack, EntityPlayer player, Entity entity)
{
entity.attackEntityFrom(DamageSource.causePlayerDamage(player), 1);
if (itemStack.stackTagCompound != null) {
int pearls = itemStack.stackTagCompound.getInteger("pearls");
int kills = itemStack.stackTagCompound.getInteger("kills");
if (pearls > 0) {
if (entity instanceof EntityEnderman) {
entity.playSound("mob.endermen.death", 1F, 1F);
if (!entity.worldObj.isRemote) {
entity.worldObj.spawnEntityInWorld(new EntityItem(entity.worldObj, entity.posX, entity.posY, entity.posZ, new ItemStack(Items.ender_pearl)));
}
entity.setDead();
// todo: find a better way to guarantee an ender pearl drop
//entity.attackEntityFrom(DamageSource.causePlayerDamage(player), 9001);
itemStack.stackTagCompound.setInteger("pearls", pearls - 1);
itemStack.stackTagCompound.setInteger("kills", kills + 1);
if (kills + 1 >= 1000) {
player.addStat(ModAchievements.enderAthameKills, 1);
}
}
}
} else {
initNBT(itemStack);
onLeftClickEntity(itemStack, player, entity);
}
return true;
}
} | gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/bind/v2/runtime/unmarshaller/ChildLoader.java | 1656 | /*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.xml.internal.bind.v2.runtime.unmarshaller;
/**
* Pair of {@link Loader} and {@link Receiver}.
*
* Used by {@link StructureLoader}.
*
* @author Kohsuke Kawaguchi
*/
public final class ChildLoader {
public final Loader loader;
public final Receiver receiver;
public ChildLoader(Loader loader, Receiver receiver) {
assert loader!=null;
this.loader = loader;
this.receiver = receiver;
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/asm/x86/FloatGRPDecoder.java | 4525 | /*
* Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package sun.jvm.hotspot.asm.x86;
import sun.jvm.hotspot.asm.*;
public class FloatGRPDecoder extends FPInstructionDecoder {
final private int number;
//Please refer to IA-32 Intel Architecture Software Developer's Manual Volume 2
//APPENDIX A - Escape opcodes
private static final FPInstructionDecoder floatGRPMap[][] = {
/* d9_2 */
{
new FPInstructionDecoder("fnop"),
null,
null,
null,
null,
null,
null,
null
},
/* d9_4 */
{
new FPInstructionDecoder("fchs"),
new FPInstructionDecoder("fabs"),
null,
null,
new FPInstructionDecoder("ftst"),
new FPInstructionDecoder("fxam"),
null,
null
},
/* d9_5 */
{
new FPInstructionDecoder("fld1"),
new FPInstructionDecoder("fldl2t"),
new FPInstructionDecoder("fldl2e"),
new FPInstructionDecoder("fldpi"),
new FPInstructionDecoder("fldlg2"),
new FPInstructionDecoder("fldln2"),
new FPInstructionDecoder("fldz"),
null
},
/* d9_6 */
{
new FPInstructionDecoder("f2xm1"),
new FPInstructionDecoder("fyl2x"),
new FPInstructionDecoder("fptan"),
new FPInstructionDecoder("fpatan"),
new FPInstructionDecoder("fxtract"),
new FPInstructionDecoder("fprem1"),
new FPInstructionDecoder("fdecstp"),
new FPInstructionDecoder("fincstp")
},
/* d9_7 */
{
new FPInstructionDecoder("fprem"),
new FPInstructionDecoder("fyl2xp1"),
new FPInstructionDecoder("fsqrt"),
new FPInstructionDecoder("fsincos"),
new FPInstructionDecoder("frndint"),
new FPInstructionDecoder("fscale"),
new FPInstructionDecoder("fsin"),
new FPInstructionDecoder("fcos")
},
/* da_5 */
{
null,
new FPInstructionDecoder("fucompp"),
null,
null,
null,
null,
null,
null
},
/* db_4 */
{
new FPInstructionDecoder("feni(287 only)"),
new FPInstructionDecoder("fdisi(287 only)"),
new FPInstructionDecoder("fNclex"),
new FPInstructionDecoder("fNinit"),
new FPInstructionDecoder("fNsetpm(287 only)"),
null,
null,
null
},
/* de_3 */
{
null,
new FPInstructionDecoder("fcompp"),
null,
null,
null,
null,
null,
null
},
/* df_4 */
{
new FPInstructionDecoder("fNstsw"),
null,
null,
null,
null,
null,
null,
null
}
};
public FloatGRPDecoder(String name, int number) {
super(name);
this.number = number;
}
public Instruction decode(byte[] bytesArray, int index, int instrStartIndex, int segmentOverride, int prefixes, X86InstructionFactory factory) {
this.byteIndex = index;
this.instrStartIndex = instrStartIndex;
this.prefixes = prefixes;
int ModRM = readByte(bytesArray, byteIndex);
int rm = ModRM & 7;
FPInstructionDecoder instrDecoder = null;
instrDecoder = floatGRPMap[number][rm];
Instruction instr = null;
if(instrDecoder != null) {
instr = instrDecoder.decode(bytesArray, byteIndex, instrStartIndex, segmentOverride, prefixes, factory);
byteIndex = instrDecoder.getCurrentIndex();
} else {
instr = factory.newIllegalInstruction();
}
return instr;
}
}
| gpl-2.0 |
freenet/Thingamablog-Freenet | src/net/sf/thingamablog/util/string/ASCIIconv.java | 1636 | /*
* ASCIIconv.java
*
* Created on 20 février 2008, 14:48
*/
package net.sf.thingamablog.util.string;
/**
*
* @author dieppe
*/
public class ASCIIconv {
private static final String PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaEeIiOoUuYy" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
;
private static final String UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+"\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+"\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+"\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+"\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+"\u00C5\u00E5"
+"\u00C7\u00E7"
;
// private constructor, can't be instanciated!
private ASCIIconv() { }
// remove accentued from a string and replace with ascii equivalent
public static String convertNonAscii(String s) {
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int pos = UNICODE.indexOf(c);
if (pos > -1){
sb.append(PLAIN_ASCII.charAt(pos));
}
else {
sb.append(c);
}
}
return sb.toString();
}
}
| gpl-2.0 |
cnavaropalos/CUCEI-Helpdesk | CTAHelpdesk/src/java/mx/udg/helpdesk/entities/controllers/DepartmentJpaController.java | 11038 | package mx.udg.helpdesk.entities.controllers;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import mx.udg.helpdesk.entities.DepartmentsByModule;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import mx.udg.helpdesk.entities.Department;
import mx.udg.helpdesk.errorHandlers.exceptions.IllegalOrphanException;
import mx.udg.helpdesk.errorHandlers.exceptions.NonexistentEntityException;
import mx.udg.helpdesk.errorHandlers.exceptions.RollbackFailureException;
/**
*
* @author Carlos Navapa
*/
public class DepartmentJpaController implements Serializable {
public DepartmentJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Department department) throws RollbackFailureException, Exception {
if (department.getDepartmentsByModuleList() == null) {
department.setDepartmentsByModuleList(new ArrayList<DepartmentsByModule>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<DepartmentsByModule> attachedDepartmentsByModuleList = new ArrayList<DepartmentsByModule>();
for (DepartmentsByModule departmentsByModuleListDepartmentsByModuleToAttach : department.getDepartmentsByModuleList()) {
departmentsByModuleListDepartmentsByModuleToAttach = em.getReference(departmentsByModuleListDepartmentsByModuleToAttach.getClass(), departmentsByModuleListDepartmentsByModuleToAttach.getDepartmentsByModulePK());
attachedDepartmentsByModuleList.add(departmentsByModuleListDepartmentsByModuleToAttach);
}
department.setDepartmentsByModuleList(attachedDepartmentsByModuleList);
em.persist(department);
for (DepartmentsByModule departmentsByModuleListDepartmentsByModule : department.getDepartmentsByModuleList()) {
Department oldDepartmentOfDepartmentsByModuleListDepartmentsByModule = departmentsByModuleListDepartmentsByModule.getDepartment();
departmentsByModuleListDepartmentsByModule.setDepartment(department);
departmentsByModuleListDepartmentsByModule = em.merge(departmentsByModuleListDepartmentsByModule);
if (oldDepartmentOfDepartmentsByModuleListDepartmentsByModule != null) {
oldDepartmentOfDepartmentsByModuleListDepartmentsByModule.getDepartmentsByModuleList().remove(departmentsByModuleListDepartmentsByModule);
oldDepartmentOfDepartmentsByModuleListDepartmentsByModule = em.merge(oldDepartmentOfDepartmentsByModuleListDepartmentsByModule);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Department department) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Department persistentDepartment = em.find(Department.class, department.getDepartmentID());
List<DepartmentsByModule> departmentsByModuleListOld = persistentDepartment.getDepartmentsByModuleList();
List<DepartmentsByModule> departmentsByModuleListNew = department.getDepartmentsByModuleList();
List<String> illegalOrphanMessages = null;
for (DepartmentsByModule departmentsByModuleListOldDepartmentsByModule : departmentsByModuleListOld) {
if (!departmentsByModuleListNew.contains(departmentsByModuleListOldDepartmentsByModule)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain DepartmentsByModule " + departmentsByModuleListOldDepartmentsByModule + " since its department field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
List<DepartmentsByModule> attachedDepartmentsByModuleListNew = new ArrayList<DepartmentsByModule>();
for (DepartmentsByModule departmentsByModuleListNewDepartmentsByModuleToAttach : departmentsByModuleListNew) {
departmentsByModuleListNewDepartmentsByModuleToAttach = em.getReference(departmentsByModuleListNewDepartmentsByModuleToAttach.getClass(), departmentsByModuleListNewDepartmentsByModuleToAttach.getDepartmentsByModulePK());
attachedDepartmentsByModuleListNew.add(departmentsByModuleListNewDepartmentsByModuleToAttach);
}
departmentsByModuleListNew = attachedDepartmentsByModuleListNew;
department.setDepartmentsByModuleList(departmentsByModuleListNew);
department = em.merge(department);
for (DepartmentsByModule departmentsByModuleListNewDepartmentsByModule : departmentsByModuleListNew) {
if (!departmentsByModuleListOld.contains(departmentsByModuleListNewDepartmentsByModule)) {
Department oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule = departmentsByModuleListNewDepartmentsByModule.getDepartment();
departmentsByModuleListNewDepartmentsByModule.setDepartment(department);
departmentsByModuleListNewDepartmentsByModule = em.merge(departmentsByModuleListNewDepartmentsByModule);
if (oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule != null && !oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule.equals(department)) {
oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule.getDepartmentsByModuleList().remove(departmentsByModuleListNewDepartmentsByModule);
oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule = em.merge(oldDepartmentOfDepartmentsByModuleListNewDepartmentsByModule);
}
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = department.getDepartmentID();
if (findDepartment(id) == null) {
throw new NonexistentEntityException("The department with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Department department;
try {
department = em.getReference(Department.class, id);
department.getDepartmentID();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The department with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<DepartmentsByModule> departmentsByModuleListOrphanCheck = department.getDepartmentsByModuleList();
for (DepartmentsByModule departmentsByModuleListOrphanCheckDepartmentsByModule : departmentsByModuleListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Department (" + department + ") cannot be destroyed since the DepartmentsByModule " + departmentsByModuleListOrphanCheckDepartmentsByModule + " in its departmentsByModuleList field has a non-nullable department field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(department);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Department> findDepartmentEntities() {
return findDepartmentEntities(true, -1, -1);
}
public List<Department> findDepartmentEntities(int maxResults, int firstResult) {
return findDepartmentEntities(false, maxResults, firstResult);
}
private List<Department> findDepartmentEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Department.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Department findDepartment(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Department.class, id);
} finally {
em.close();
}
}
public int getDepartmentCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Department> rt = cq.from(Department.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| gpl-2.0 |
Sw4T/GrooveBerry | GrooveBerry_Serveur/src/network/ClientTestMulti.java | 6541 | package network;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.Scanner;
import protocol.Protocol;
import files.AudioFile;
import files.ReadingQueue;
public class ClientTestMulti {
static Scanner scannerDL = new Scanner(System.in);
static ObjectOutputStream objectOut = null;
static ObjectInputStream objectIn = null;
static ObjectOutputStream fileOut = null;
static ObjectInputStream fileIn = null;
//Main du client Android ici simulé
public static void main (String [] args) throws InterruptedException {
Socket socketSimple = null, socketFile = null;
int entreeUser = 0; String treatment = null;
ReadingQueue listReading;
try {
//Connexion au serveur socket simple
socketSimple = new Socket("localhost", Server.SERVER_PORT_SIMPLE);
socketFile = new Socket("localhost", Server.SERVER_PORT_OBJECT);
if (socketSimple.isConnected() && socketSimple.isBound()) {
System.out.println("CLIENT : Je me suis bien connect� au serveur !");
objectOut = new ObjectOutputStream(socketSimple.getOutputStream());
objectIn = new ObjectInputStream(socketSimple.getInputStream());
System.out.println("Flux d'objets initialis� !");
} else {
System.out.println("CLIENT : Socket simple cliente non connect�e");
System.exit(1);
}
//Authentification cliente
String messageRecu = (String) objectIn.readObject();
if (messageRecu.equals("#AUTH")) {
objectOut.writeObject("mdp"); //D�fini en dur dans auth.txt pour l'instant
System.out.println("Mot de passe envoy� !");
} else
System.out.println("Echec lors de la phase d'authentification ! Recu : " + messageRecu);
//Connexion au serveur socket objet
if (socketFile.isConnected() && socketFile.isBound()) {
fileOut = new ObjectOutputStream(socketFile.getOutputStream());
fileIn = new ObjectInputStream(socketFile.getInputStream());
} else {
System.out.println("CLIENT : Socket objet cliente non connect�e");
System.exit(2);
}
messageRecu = (String) objectIn.readObject();
//Reception du fil de lecture depuis le serveur
if (messageRecu.equals("#RQ")) {
objectOut.writeObject("#OK");
objectOut.flush();
listReading = (ReadingQueue) objectIn.readObject();
if (listReading != null)
showReadingQueue(listReading);
} else {
System.out.println("Erreurs de synchronisation serveur ! Recu : " + messageRecu);
System.exit(3);
}
threadReceive(objectIn);
//Envoi de chaines définissant des constantes au serveur
Scanner scan = new Scanner(System.in);
do {
showMenu();
try {
entreeUser = scan.nextInt();
treatment = convertIntToMusicConst(entreeUser);
System.out.println("traitement envoy� : " + treatment);
} catch (InputMismatchException inputFail) {
treatment = "";
}
if (!treatment.equals("")) {
objectOut.writeObject(treatment);
objectOut.flush();
}
} while (entreeUser != 7);
//Fermeture de la connexion avec le serveur
if (socketSimple != null) {
objectIn.close();
objectOut.close();
socketSimple.close();
socketFile.close();
scan.close();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static synchronized void threadReceive(final ObjectInputStream is) {
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true)
receiveRQ(is);
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public static void receiveRQ(ObjectInputStream is) throws ClassNotFoundException, IOException {
//Reception de la nouvelle liste
synchronized (is) {
Protocol prot = (Protocol) is.readObject();
System.out.println("********RECEIVED*******\nprotocole : " + prot);
if (prot == Protocol.MODIFY_READING_QUEUE) {
ReadingQueue rq = (ReadingQueue) is.readObject();
System.out.println("Current track : " + rq.getCurrentTrack().getName());
} else if (prot == Protocol.MODIFY_VOLUME) {
Integer volume = (Integer) is.readObject();
System.out.println("Le volume a �t� modifi� de�" + volume + "%");
}
}
}
public static void downloadTest() throws IOException, ClassNotFoundException, InterruptedException {
System.out.println("Entrez le nom du fichier à t�l�charger sur le serveur");
String file = scannerDL.nextLine();
objectOut.writeObject("download$" + file);
objectOut.flush();
fileIn.readObject();
new Thread(new FileDownload(fileIn)).start();
}
public static void uploadTest() throws IOException, ClassNotFoundException, InterruptedException {
System.out.println("Entrez le nom du fichier à mettre sur le serveur");
String file = scannerDL.nextLine();
objectOut.writeObject("upload$" + file);
objectOut.flush();
fileIn.readObject();
new Thread(new FileUpload(fileOut, file)).start();
}
public static String convertIntToMusicConst(int input) throws ClassNotFoundException, IOException, InterruptedException
{
String toReturn = "";
switch (input) {
case 1 : toReturn = "play"; break;
case 2 : toReturn = "pause"; break;
case 3 : toReturn = "mute"; break;
case 4 : toReturn = "restart"; break;
case 5 : toReturn = "stop"; break;
case 6 : toReturn = "loop"; break;
case 7 : toReturn = "exit"; break;
case 8 : toReturn = "next"; break;
case 9 : toReturn = "prev"; break;
case 10 : toReturn = "random"; break;
case 11 : toReturn = "+"; break;
case 12 : toReturn = "-"; break;
case 13 : downloadTest(); break;
case 14 : uploadTest(); break;
default : toReturn = "";
}
return toReturn;
}
public static void showMenu()
{
System.out.println("1. Play");
System.out.println("2. Pause/Unpause");
System.out.println("3. Mute/Unmute");
System.out.println("4. Restart");
System.out.println("5. Stop");
System.out.println("6. Loop");
System.out.println("7. Exit");
System.out.println("8. Next");
System.out.println("9. Prev");
System.out.println("10. Random");
System.out.println("13. Download");
System.out.println("14. Upload");
}
public static void showReadingQueue(ReadingQueue list)
{
System.out.println("Liste de lecture du serveur : ");
for (AudioFile file : list.getAudioFileList()) {
System.out.println("\t" + file.getName());
}
}
}
| gpl-2.0 |
elitak/peertrust | src/org/protune/core/ProtuneService.java | 5527 | package org.protune.core;
import java.text.ParseException;
import org.protune.api.PrologEngine;
import org.protune.api.QueryException;
import org.protune.net.EndNegotiationMessage;
import org.protune.net.NegotiationMessage;
import org.protune.net.OngoingNegotiationMessage;
import org.protune.net.Service;
import org.protune.net.SuccessfulNegotiationResult;
import org.protune.net.UnsuccessfulNegotiationResult;
import org.protune.net.WrongMessageTypeException;
/**
* The class <tt>ProtuneService</tt> could be described as the most important class of the <i>Protune</i>
* system, indeed it implements the algorithm the whole negotiation bases on. The main steps of this
* algorithm are sketched in an informal way in Fig. 1, a closer sight is of course provided by the
* code.
* <table border="1" cellspacing="0"><tbody><tr><td><pre>
* {@link org.protune.net.NegotiationMessage NegotiationMessage} eval({@link org.protune.core.FilteredPolicy FilteredPolicy}[] fpa, {@link org.protune.core.Notification Notification}[] na){
* {@link org.protune.core.Status status}.add(fpa);
* staus.add(na);
* status.add({@link org.protune.core.Checker checker}.checkNotification(na))
*
* status.increaseNegotiationStepNumber();
*
* if({@link org.protune.core.FilterEngine filter}.isNegotiationSatisfied(status))
* return new {@link org.protune.net.EndNegotiationMessage EndNegotiationMessage}(new {@link org.protune.net.SuccessfulNegotiationResult SuccessfulNegotiationResult}());
* if({@link org.protune.core.TerminationAlgorithm terminationAlgorithm}.terminate(mapper, status))
* return new EndNegotiationMessage(new {@link org.protune.net.UnsuccessfulNegotiationResult UnsuccessfulNegotiationResult}());
*
* {@link org.protune.core.Action Action}[] aa = filter.extractActions(fpa);
* FilteredPolicy[] fp = filter.filter(policy, status, aa));
*
* Action[] unlocked;
* FilteredPolicy[] fpToSend;
* for(int i=0; aa.length; i++)
* if(filter.isUnlocked(aa[i])) unlocked.add(aa[i]);
* else fpToSend.add(fp[i]);
*
* Action[] toPerform = {@link org.protune.core.ActionSelectionFunction actionSelectionFunction}.selectActions(toPerform, status);
* Notification[] naToSend = Action.perform(toPerform);
*
* status.addNegotiationElement(fpToSend);
* status.addNegotiationElement(naToSend);
*
* status.increaseNegotiationStepNumber();
*
* return new {@link org.protune.core.ProtuneMessage ProtuneMessage}(fpToSend, naToSend);
* }
* </pre></td></tr></tbody></table>
* <b>Fig. 1</b> - Main step of the algorithm implemented by <tt>ProtuneService</tt>.<br/>
* Basically the algorithm works out the message received from the other peer and sends it a new one.
* During the computation the negotiation status (most likely) changes.
* @author jldecoi
*/
public abstract class ProtuneService extends Service {
protected PrologEngine engine;
protected Checker checker;
/* For some reason this constructor must be commented.
public ProtuneService(Pointer p){
super(p);
}*/
public NegotiationMessage eval(OngoingNegotiationMessage onm) throws WrongMessageTypeException{
if(!(onm instanceof ProtuneMessage)) throw new WrongMessageTypeException();
ProtuneMessage pm = (ProtuneMessage) onm;
Goal g = pm.getGoal();
FilteredPolicy fp = pm.getFilteredPolicy();
Notification[] na = pm.getNotifications();
engine.addReceived(fp);
for(int i=0; i<na.length; i++) engine.addReceived(na[i]);
for(int i=0; i<na.length; i++) try{
engine.add(checker.checkNotification(na[i]));
} catch(UnknownNotificationException une){
// If the checker is not able to check the notification, a further check is simply not
// added.
}
engine.increaseNegotiationStepNumber();
Action[] laa;
try {//System.out.println("B internalA");
laa = engine.extractLocalActions(g);
while(laa.length!=0){
Notification[] lna = new Notification[laa.length];
for(int i=0; i<lna.length; i++){
lna[i] = laa[i].perform();
engine.addLocal(lna[i]);
}
laa = engine.extractLocalActions(g);
}//System.out.println("E internalA");
} catch (QueryException e1) {
// Should not happen.
} catch (ParseException e1) {
// Should not happen.
}
try {
if(engine.isNegotiationSatisfied(g))
return new EndNegotiationMessage(new SuccessfulNegotiationResult());
if(engine.terminate())
return new EndNegotiationMessage(new UnsuccessfulNegotiationResult());
} catch (QueryException e) {
// Should not happen.
}
Action[] eaa = new Action[0];
try {//System.out.println("B externalA");
eaa = engine.extractExternalActions(g);
//String s = "a ";
//for(int i=0; i<eaa.length; i++) s += eaa[i] + " ";
//System.out.println(s);
} catch (QueryException e1) {
// Should not happen.
} catch (ParseException e1) {
// Should not happen.
}
Notification[] ena = new Notification[eaa.length];
for(int i=0; i<eaa.length; i++) ena[i] = eaa[i].perform();
try {//System.out.println("B filter");
fp = engine.filter(g);//System.out.println("E filter");
} catch (QueryException e1) {
// Should not happen.
} catch (ParseException e1) {
// Should not happen.
}
engine.addSent(fp);
//System.out.println(engine + ": " + ((TuPrologWrapper)engine).p.getTheory());
for(int i=0; i<ena.length; i++) engine.addSent(ena[i]);
engine.increaseNegotiationStepNumber();
return new ProtuneMessage(g, fp, ena);
}
}
| gpl-2.0 |
AncientKemet/Ancient-Kemet-Utility | akclient/AKClient.java | 1468 | package akclient;
import akserver.*;
import aku.AncientKemetNET;
import aku.com.net.CommunicationHandler;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.*;
/**
* @author Robert Kollar
*/
public class AKClient {
private static AKClient instance;
public static AKClient getInstance() {
if (instance == null) {
instance = new AKClient();
}
return instance;
}
private Socket masterServerSocket;
private CommunicationHandler masterServerComHandler;
private AKClient() {
try {
masterServerSocket = new Socket("89.177.126.149", AncientKemetNET.GAME_SERVER_PORT);
masterServerComHandler = new CommunicationHandler(masterServerSocket, new AKClientPacketExecutor());
} catch (IOException ex) {
Logger.getLogger(AKClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thread serverThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
masterServerComHandler.readAndExecute();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(MasterServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
public CommunicationHandler getComHandler() {
return masterServerComHandler;
}
}
| gpl-2.0 |
dmlloyd/openjdk-modules | langtools/test/tools/javac/modules/AutomaticModules.java | 23316 | /*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8155026 8178011
* @summary Test automatic modules
* @library /tools/lib
* @modules
* java.desktop
* jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* @build toolbox.ToolBox toolbox.JavacTask toolbox.JarTask ModuleTestBase
* @run main AutomaticModules
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import toolbox.JarTask;
import toolbox.JavacTask;
import toolbox.Task;
public class AutomaticModules extends ModuleTestBase {
public static void main(String... args) throws Exception {
AutomaticModules t = new AutomaticModules();
t.runTests();
}
@Test
public void testSimple(Path base) throws Exception {
Path legacySrc = base.resolve("legacy-src");
tb.writeJavaFiles(legacySrc,
"package api; import java.awt.event.ActionListener; public abstract class Api implements ActionListener {}");
Path legacyClasses = base.resolve("legacy-classes");
Files.createDirectories(legacyClasses);
String log = new JavacTask(tb)
.options()
.outdir(legacyClasses)
.files(findJavaFiles(legacySrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!log.isEmpty()) {
throw new Exception("unexpected output: " + log);
}
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
Path jar = modulePath.resolve("test-api-1.0.jar");
new JarTask(tb, jar)
.baseDir(legacyClasses)
.files("api/Api.class")
.run();
Path moduleSrc = base.resolve("module-src");
Path m1 = moduleSrc.resolve("m1x");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
tb.writeJavaFiles(m1,
"module m1x { requires test.api; requires java.desktop; }",
"package impl; public class Impl { public void e(api.Api api) { api.actionPerformed(null); } }");
new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString(), "--module-path", modulePath.toString())
.outdir(classes)
.files(findJavaFiles(moduleSrc))
.run()
.writeAll();
}
@Test
public void testUnnamedModule(Path base) throws Exception {
Path legacySrc = base.resolve("legacy-src");
tb.writeJavaFiles(legacySrc,
"package api; public abstract class Api { public void run(CharSequence str) { } private void run(base.Base base) { } }",
"package base; public interface Base { public void run(); }");
Path legacyClasses = base.resolve("legacy-classes");
Files.createDirectories(legacyClasses);
String log = new JavacTask(tb)
.options()
.outdir(legacyClasses)
.files(findJavaFiles(legacySrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!log.isEmpty()) {
throw new Exception("unexpected output: " + log);
}
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
Path apiJar = modulePath.resolve("test-api-1.0.jar");
new JarTask(tb, apiJar)
.baseDir(legacyClasses)
.files("api/Api.class")
.run();
Path baseJar = base.resolve("base.jar");
new JarTask(tb, baseJar)
.baseDir(legacyClasses)
.files("base/Base.class")
.run();
Path moduleSrc = base.resolve("module-src");
Path m1 = moduleSrc.resolve("m1x");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
tb.writeJavaFiles(m1,
"module m1x { requires test.api; }",
"package impl; public class Impl { public void e(api.Api api) { api.run(\"\"); } }");
new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString(), "--module-path", modulePath.toString(), "--class-path", baseJar.toString())
.outdir(classes)
.files(findJavaFiles(moduleSrc))
.run()
.writeAll();
}
@Test
public void testModuleInfoFromClassFileDependsOnAutomatic(Path base) throws Exception {
Path automaticSrc = base.resolve("automaticSrc");
tb.writeJavaFiles(automaticSrc, "package api; public class Api {}");
Path automaticClasses = base.resolve("automaticClasses");
tb.createDirectories(automaticClasses);
String automaticLog = new JavacTask(tb)
.outdir(automaticClasses)
.files(findJavaFiles(automaticSrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!automaticLog.isEmpty())
throw new Exception("expected output not found: " + automaticLog);
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
Path automaticJar = modulePath.resolve("automatic-1.0.jar");
new JarTask(tb, automaticJar)
.baseDir(automaticClasses)
.files("api/Api.class")
.run();
Path depSrc = base.resolve("depSrc");
Path depClasses = base.resolve("depClasses");
Files.createDirectories(depSrc);
Files.createDirectories(depClasses);
tb.writeJavaFiles(depSrc,
"module m1x { requires transitive automatic; }",
"package dep; public class Dep { api.Api api; }");
new JavacTask(tb)
.options("--module-path", modulePath.toString())
.outdir(depClasses)
.files(findJavaFiles(depSrc))
.run()
.writeAll();
Path moduleJar = modulePath.resolve("m1x.jar");
new JarTask(tb, moduleJar)
.baseDir(depClasses)
.files("module-info.class", "dep/Dep.class")
.run();
Path testSrc = base.resolve("testSrc");
Path testClasses = base.resolve("testClasses");
Files.createDirectories(testSrc);
Files.createDirectories(testClasses);
tb.writeJavaFiles(testSrc,
"module m2x { requires automatic; }",
"package test; public class Test { }");
new JavacTask(tb)
.options("--module-path", modulePath.toString())
.outdir(testClasses)
.files(findJavaFiles(testSrc))
.run()
.writeAll();
}
@Test
public void testAutomaticAndNamedModules(Path base) throws Exception {
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
for (char c : new char[] {'A', 'B'}) {
Path automaticSrc = base.resolve("automaticSrc" + c);
tb.writeJavaFiles(automaticSrc, "package api" + c + "; public class Api {}");
Path automaticClasses = base.resolve("automaticClasses" + c);
tb.createDirectories(automaticClasses);
String automaticLog = new JavacTask(tb)
.outdir(automaticClasses)
.files(findJavaFiles(automaticSrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!automaticLog.isEmpty())
throw new Exception("expected output not found: " + automaticLog);
Path automaticJar = modulePath.resolve("automatic" + c + "-1.0.jar");
new JarTask(tb, automaticJar)
.baseDir(automaticClasses)
.files("api" + c + "/Api.class")
.run();
}
Path moduleSrc = base.resolve("module-src");
tb.writeJavaFiles(moduleSrc.resolve("m1x"),
"module m1x { requires static automaticA; }",
"package impl; public class Impl { apiA.Api a; apiB.Api b; m2x.M2 m;}");
tb.writeJavaFiles(moduleSrc.resolve("m2x"),
"module m2x { exports m2x; }",
"package m2x; public class M2 { }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
List<String> log = new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString(),
"--module-path", modulePath.toString(),
"--add-modules", "automaticB",
"-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(moduleSrc))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList("Impl.java:1:59: compiler.err.package.not.visible: m2x, (compiler.misc.not.def.access.does.not.read: m1x, m2x, m2x)",
"1 error");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
log = new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString(),
"--module-path", modulePath.toString(),
"-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(moduleSrc))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("Impl.java:1:59: compiler.err.package.not.visible: m2x, (compiler.misc.not.def.access.does.not.read: m1x, m2x, m2x)",
"1 error");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
}
@Test
public void testWithTrailingVersion(Path base) throws Exception {
Path legacySrc = base.resolve("legacy-src");
tb.writeJavaFiles(legacySrc,
"package api; public class Api {}");
Path legacyClasses = base.resolve("legacy-classes");
Files.createDirectories(legacyClasses);
String log = new JavacTask(tb)
.options()
.outdir(legacyClasses)
.files(findJavaFiles(legacySrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!log.isEmpty()) {
throw new Exception("unexpected output: " + log);
}
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
Path jar = modulePath.resolve("test1.jar");
new JarTask(tb, jar)
.baseDir(legacyClasses)
.files("api/Api.class")
.run();
Path moduleSrc = base.resolve("module-src");
Path m = moduleSrc.resolve("m");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
tb.writeJavaFiles(m,
"module m { requires test1; }",
"package impl; public class Impl { public void e(api.Api api) { } }");
new JavacTask(tb)
.options("--module-source-path", moduleSrc.toString(), "--module-path", modulePath.toString())
.outdir(classes)
.files(findJavaFiles(moduleSrc))
.run()
.writeAll();
}
@Test
public void testMultipleAutomatic(Path base) throws Exception {
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
for (char c : new char[] {'A', 'B'}) {
Path automaticSrc = base.resolve("automaticSrc" + c);
tb.writeJavaFiles(automaticSrc, "package api" + c + "; public class Api {}");
Path automaticClasses = base.resolve("automaticClasses" + c);
tb.createDirectories(automaticClasses);
String automaticLog = new JavacTask(tb)
.outdir(automaticClasses)
.files(findJavaFiles(automaticSrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!automaticLog.isEmpty())
throw new Exception("expected output not found: " + automaticLog);
Path automaticJar = modulePath.resolve("automatic" + c + "-1.0.jar");
new JarTask(tb, automaticJar)
.baseDir(automaticClasses)
.files("api" + c + "/Api.class")
.run();
}
Path src = base.resolve("src");
tb.writeJavaFiles(src.resolve("m1x"),
"package impl; public class Impl { apiA.Api a; apiB.Api b; }");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
List<String> log = new JavacTask(tb)
.options("--module-path", modulePath.toString(),
"-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
List<String> expected = Arrays.asList("Impl.java:1:35: compiler.err.package.not.visible: apiA, (compiler.misc.not.def.access.does.not.read.from.unnamed: apiA, automaticA)",
"Impl.java:1:47: compiler.err.package.not.visible: apiB, (compiler.misc.not.def.access.does.not.read.from.unnamed: apiB, automaticB)",
"2 errors");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
new JavacTask(tb)
.options("--module-path", modulePath.toString(),
"--add-modules", "automaticA",
"-XDrawDiagnostics")
.outdir(classes)
.files(findJavaFiles(src))
.run()
.writeAll();
}
@Test
public void testLintRequireAutomatic(Path base) throws Exception {
Path modulePath = base.resolve("module-path");
Files.createDirectories(modulePath);
for (char c : new char[] {'A', 'B'}) {
Path automaticSrc = base.resolve("automaticSrc" + c);
tb.writeJavaFiles(automaticSrc, "package api" + c + "; public class Api {}");
Path automaticClasses = base.resolve("automaticClasses" + c);
tb.createDirectories(automaticClasses);
String automaticLog = new JavacTask(tb)
.outdir(automaticClasses)
.files(findJavaFiles(automaticSrc))
.run()
.writeAll()
.getOutput(Task.OutputKind.DIRECT);
if (!automaticLog.isEmpty())
throw new Exception("expected output not found: " + automaticLog);
Path automaticJar = modulePath.resolve("automatic" + c + "-1.0.jar");
new JarTask(tb, automaticJar)
.baseDir(automaticClasses)
.files("api" + c + "/Api.class")
.run();
}
Path src = base.resolve("src");
tb.writeJavaFiles(src,
"module m1x {\n" +
" requires transitive automaticA;\n" +
" requires automaticB;\n" +
"}");
Path classes = base.resolve("classes");
Files.createDirectories(classes);
List<String> expected;
List<String> log;
log = new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:2:25: compiler.warn.requires.transitive.automatic",
"- compiler.err.warnings.and.werror",
"1 error",
"1 warning");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
log = new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-Xlint:requires-automatic",
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:2:25: compiler.warn.requires.transitive.automatic",
"module-info.java:3:14: compiler.warn.requires.automatic",
"- compiler.err.warnings.and.werror",
"1 error",
"2 warnings");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
log = new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-Xlint:-requires-transitive-automatic,requires-automatic",
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:2:25: compiler.warn.requires.automatic",
"module-info.java:3:14: compiler.warn.requires.automatic",
"- compiler.err.warnings.and.werror",
"1 error",
"2 warnings");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-Xlint:-requires-transitive-automatic",
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
tb.writeJavaFiles(src,
"@SuppressWarnings(\"requires-transitive-automatic\")\n" +
"module m1x {\n" +
" requires transitive automaticA;\n" +
" requires automaticB;\n" +
"}");
new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.SUCCESS)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
log = new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-Xlint:requires-automatic",
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:3:25: compiler.warn.requires.automatic",
"module-info.java:4:14: compiler.warn.requires.automatic",
"- compiler.err.warnings.and.werror",
"1 error",
"2 warnings");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
tb.writeJavaFiles(src,
"@SuppressWarnings(\"requires-automatic\")\n" +
"module m1x {\n" +
" requires transitive automaticA;\n" +
" requires automaticB;\n" +
"}");
log = new JavacTask(tb)
.options("--source-path", src.toString(),
"--module-path", modulePath.toString(),
"-Xlint:requires-automatic",
"-XDrawDiagnostics",
"-Werror")
.outdir(classes)
.files(findJavaFiles(src))
.run(Task.Expect.FAIL)
.writeAll()
.getOutputLines(Task.OutputKind.DIRECT);
expected = Arrays.asList("module-info.java:3:25: compiler.warn.requires.transitive.automatic",
"- compiler.err.warnings.and.werror",
"1 error",
"1 warning");
if (!expected.equals(log)) {
throw new Exception("expected output not found: " + log);
}
}
}
| gpl-2.0 |
louis20150702/mytestgit | Settings/src/com/android/settings/wifi/AccessPoint.java | 16075 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wifi;
import com.android.settings.R;
import android.content.Context;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.Preference;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
class AccessPoint extends Preference {
static final String TAG = "Settings.AccessPoint";
private static final String KEY_DETAILEDSTATE = "key_detailedstate";
private static final String KEY_WIFIINFO = "key_wifiinfo";
private static final String KEY_SCANRESULT = "key_scanresult";
private static final String KEY_CONFIG = "key_config";
private static final int[] STATE_SECURED = {
R.attr.state_encrypted
};
private static final int[] STATE_NONE = {};
/** These values are matched in string arrays -- changes must be kept in sync */
static final int SECURITY_NONE = 0;
static final int SECURITY_WEP = 1;
static final int SECURITY_PSK = 2;
static final int SECURITY_EAP = 3;
// Broadcom, WAPI
static final int SECURITY_WAPI_PSK = 4;
static final int SECURITY_WAPI_CERT = 5;
// Broadcom, WAPI
enum PskType {
UNKNOWN,
WPA,
WPA2,
WPA_WPA2
}
String ssid;
String bssid;
int security;
int networkId;
boolean wpsAvailable = false;
PskType pskType = PskType.UNKNOWN;
private WifiConfiguration mConfig;
/* package */ScanResult mScanResult;
private int mRssi;
private WifiInfo mInfo;
private DetailedState mState;
static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
// Broadcom, WAPI
if (config.allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
return SECURITY_WAPI_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
return SECURITY_WAPI_CERT;
}
// Broadcom, WAPI
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
private static int getSecurity(ScanResult result) {
// Broadcom, WAPI
if (result.capabilities.contains("WAPI-PSK")) {
return SECURITY_WAPI_PSK;
} else if (result.capabilities.contains("WAPI-CERT")) {
return SECURITY_WAPI_CERT;
} else
// Broadcom, WAPI
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
public String getSecurityString(boolean concise) {
Context context = getContext();
switch(security) {
case SECURITY_EAP:
return concise ? context.getString(R.string.wifi_security_short_eap) :
context.getString(R.string.wifi_security_eap);
case SECURITY_PSK:
switch (pskType) {
case WPA:
return concise ? context.getString(R.string.wifi_security_short_wpa) :
context.getString(R.string.wifi_security_wpa);
case WPA2:
return concise ? context.getString(R.string.wifi_security_short_wpa2) :
context.getString(R.string.wifi_security_wpa2);
case WPA_WPA2:
return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
context.getString(R.string.wifi_security_wpa_wpa2);
case UNKNOWN:
default:
return concise ? context.getString(R.string.wifi_security_short_psk_generic)
: context.getString(R.string.wifi_security_psk_generic);
}
case SECURITY_WEP:
return concise ? context.getString(R.string.wifi_security_short_wep) :
context.getString(R.string.wifi_security_wep);
// Broadcom, WAPI
case SECURITY_WAPI_PSK:
return context.getString(R.string.wifi_security_wapi_psk);
case SECURITY_WAPI_CERT:
return context.getString(R.string.wifi_security_wapi_cert);
// Broadcom, WAPI
case SECURITY_NONE:
default:
return concise ? "" : context.getString(R.string.wifi_security_none);
}
}
private static PskType getPskType(ScanResult result) {
boolean wpa = result.capabilities.contains("WPA-PSK");
boolean wpa2 = result.capabilities.contains("WPA2-PSK");
if (wpa2 && wpa) {
return PskType.WPA_WPA2;
} else if (wpa2) {
return PskType.WPA2;
} else if (wpa) {
return PskType.WPA;
} else {
Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
return PskType.UNKNOWN;
}
}
AccessPoint(Context context, WifiConfiguration config) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
loadConfig(config);
refresh();
}
AccessPoint(Context context, ScanResult result) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
loadResult(result);
refresh();
}
AccessPoint(Context context, Bundle savedState) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
mConfig = savedState.getParcelable(KEY_CONFIG);
if (mConfig != null) {
loadConfig(mConfig);
}
mScanResult = (ScanResult) savedState.getParcelable(KEY_SCANRESULT);
if (mScanResult != null) {
loadResult(mScanResult);
}
mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
if (savedState.containsKey(KEY_DETAILEDSTATE)) {
mState = DetailedState.valueOf(savedState.getString(KEY_DETAILEDSTATE));
}
update(mInfo, mState);
}
public void saveWifiState(Bundle savedState) {
savedState.putParcelable(KEY_CONFIG, mConfig);
savedState.putParcelable(KEY_SCANRESULT, mScanResult);
savedState.putParcelable(KEY_WIFIINFO, mInfo);
if (mState != null) {
savedState.putString(KEY_DETAILEDSTATE, mState.toString());
}
}
private void loadConfig(WifiConfiguration config) {
ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
bssid = config.BSSID;
security = getSecurity(config);
networkId = config.networkId;
mRssi = Integer.MAX_VALUE;
mConfig = config;
}
private void loadResult(ScanResult result) {
ssid = result.SSID;
bssid = result.BSSID;
security = getSecurity(result);
wpsAvailable = security != SECURITY_EAP && result.capabilities.contains("WPS");
if (security == SECURITY_PSK)
pskType = getPskType(result);
networkId = -1;
mRssi = result.level;
mScanResult = result;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
ImageView signal = (ImageView) view.findViewById(R.id.signal);
if (mRssi == Integer.MAX_VALUE) {
signal.setImageDrawable(null);
} else {
signal.setImageLevel(getLevel());
signal.setImageDrawable(getContext().getTheme().obtainStyledAttributes(
new int[] {R.attr.wifi_signal}).getDrawable(0));
signal.setImageState((security != SECURITY_NONE) ?
STATE_SECURED : STATE_NONE, true);
}
}
@Override
public int compareTo(Preference preference) {
if (!(preference instanceof AccessPoint)) {
return 1;
}
AccessPoint other = (AccessPoint) preference;
// Active one goes first.
if (mInfo != null && other.mInfo == null) return -1;
if (mInfo == null && other.mInfo != null) return 1;
// Reachable one goes before unreachable one.
if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1;
if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1;
// Configured one goes before unconfigured one.
if (networkId != WifiConfiguration.INVALID_NETWORK_ID
&& other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1;
if (networkId == WifiConfiguration.INVALID_NETWORK_ID
&& other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1;
// Sort by signal strength.
int difference = WifiManager.compareSignalLevel(other.mRssi, mRssi);
if (difference != 0) {
return difference;
}
// Sort by ssid.
return ssid.compareToIgnoreCase(other.ssid);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof AccessPoint)) return false;
/* SPRD: Modify Bug 309533 for not update correct ap because ignore it @{ */
if (((AccessPoint) other).networkId != networkId) {
return false;
}
/* @} */
return (this.compareTo((AccessPoint) other) == 0);
}
@Override
public int hashCode() {
int result = 0;
if (mInfo != null) result += 13 * mInfo.hashCode();
result += 19 * mRssi;
result += 23 * networkId;
result += 29 * ssid.hashCode();
return result;
}
boolean update(ScanResult result) {
if (ssid.equals(result.SSID) && security == getSecurity(result)) {
if (WifiManager.compareSignalLevel(result.level, mRssi) > 0) {
int oldLevel = getLevel();
mRssi = result.level;
if (getLevel() != oldLevel) {
notifyChanged();
}
}
// This flag only comes from scans, is not easily saved in config
if (security == SECURITY_PSK) {
pskType = getPskType(result);
}
refresh();
return true;
}
return false;
}
void update(WifiInfo info, DetailedState state) {
boolean reorder = false;
if (info != null && networkId != WifiConfiguration.INVALID_NETWORK_ID
&& networkId == info.getNetworkId()) {
reorder = (mInfo == null);
int oldLevel = getLevel();
mRssi = info.getRssi();
if (getLevel() != oldLevel) {
notifyChanged();
}
mInfo = info;
mState = state;
refresh();
} else if (mInfo != null) {
reorder = true;
mInfo = null;
mState = null;
refresh();
}
if (reorder) {
notifyHierarchyChanged();
}
}
int getLevel() {
if (mRssi == Integer.MAX_VALUE) {
return -1;
}
return WifiManager.calculateSignalLevel(mRssi, 4);
}
WifiConfiguration getConfig() {
return mConfig;
}
WifiInfo getInfo() {
return mInfo;
}
DetailedState getState() {
return mState;
}
static String removeDoubleQuotes(String string) {
int length = string.length();
if ((length > 1) && (string.charAt(0) == '"')
&& (string.charAt(length - 1) == '"')) {
return string.substring(1, length - 1);
}
return string;
}
static String convertToQuotedString(String string) {
return "\"" + string + "\"";
}
/** Updates the title and summary; may indirectly call notifyChanged() */
private void refresh() {
setTitle(ssid);
Context context = getContext();
/* SPRD: Modify Bug 309540 for ap info display error @{ */
if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
setSummary(context.getString(R.string.wifi_not_in_range));
} else if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) {
/* @} */
switch (mConfig.disableReason) {
// Sprd: disableReason is set to be WifiConfiguration.DISABLED_AUTH_FAILURE after AP reject 16 times.
// So We can set the same summary for the state to WifiConfiguration.DISABLED_AUTH_FAILURE.
case WifiConfiguration.DISABLED_ASSOCIATION_REJECT:
case WifiConfiguration.DISABLED_AUTH_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_password_failure));
break;
case WifiConfiguration.DISABLED_DHCP_FAILURE:
case WifiConfiguration.DISABLED_DNS_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_network_failure));
break;
case WifiConfiguration.DISABLED_UNKNOWN_REASON:
setSummary(context.getString(R.string.wifi_disabled_generic));
}
} else if (mState != null) { // This is the active connection
setSummary(Summary.get(context, mState));
} else { // In range, not disabled.
StringBuilder summary = new StringBuilder();
if (mConfig != null) { // Is saved network
summary.append(context.getString(R.string.wifi_remembered));
}
if (security != SECURITY_NONE) {
String securityStrFormat;
if (summary.length() == 0) {
securityStrFormat = context.getString(R.string.wifi_secured_first_item);
} else {
securityStrFormat = context.getString(R.string.wifi_secured_second_item);
}
summary.append(String.format(securityStrFormat, getSecurityString(true)));
}
if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks
if (summary.length() == 0) {
summary.append(context.getString(R.string.wifi_wps_available_first_item));
} else {
summary.append(context.getString(R.string.wifi_wps_available_second_item));
}
}
setSummary(summary.toString());
}
}
/**
* Generate and save a default wifiConfiguration with common values.
* Can only be called for unsecured networks.
* @hide
*/
protected void generateOpenNetworkConfig() {
if (security != SECURITY_NONE)
throw new IllegalStateException();
if (mConfig != null)
return;
mConfig = new WifiConfiguration();
mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
}
}
| gpl-2.0 |
KouChengjian/PIForAndroid | easyutils/src/com/easyutils/db/assit/WhereBuilder.java | 7461 | package com.easyutils.db.assit;
import com.easyutils.db.TableManager;
/**
* @author MaTianyu
* @date 2015-03-18
*/
public class WhereBuilder {
public static final String NOTHING = "";
public static final String WHERE = " WHERE ";
public static final String EQUAL_HOLDER = "=?";
public static final String NOT_EQUAL_HOLDER = "!=?";
public static final String GREATER_THAN_HOLDER = ">?";
public static final String LESS_THAN_HOLDER = "<?";
public static final String COMMA_HOLDER = ",?";
public static final String HOLDER = "?";
public static final String AND = " AND ";
public static final String OR = " OR ";
public static final String NOT = " NOT ";
public static final String DELETE = "DELETE FROM ";
private static final String PARENTHESES_LEFT = "(";
private static final String PARENTHESES_RIGHT = ")";
private static final String IN = " IN ";
protected String where;
protected Object[] whereArgs;
protected Class tableClass;
public WhereBuilder(Class tableClass) {
this.tableClass = tableClass;
}
public static WhereBuilder create(Class tableClass) {
return new WhereBuilder(tableClass);
}
public static WhereBuilder create(Class tableClass, String where, Object[] whereArgs) {
return new WhereBuilder(tableClass, where, whereArgs);
}
public WhereBuilder(Class tableClass, String where, Object[] whereArgs) {
this.where = where;
this.whereArgs = whereArgs;
this.tableClass = tableClass;
}
public Class getTableClass() {
return tableClass;
}
/**
* @param where "id = ?";
* "id in(?,?,?)";
* "id LIKE %?"
* @param whereArgs new String[]{"",""};
* new Integer[]{1,2}
*/
public WhereBuilder where(String where, Object... whereArgs) {
this.where = where;
this.whereArgs = whereArgs;
return this;
}
/**
* @param where "id = ?";
* "id in(?,?,?)";
* "id LIKE %?"
* @param whereArgs new String[]{"",""};
* new Integer[]{1,2}
*/
public WhereBuilder and(String where, Object... whereArgs) {
return append(AND, where, whereArgs);
}
/**
* @param where "id = ?";
* "id in(?,?,?)";
* "id LIKE %?"
* @param whereArgs new String[]{"",""};
* new Integer[]{1,2}
*/
public WhereBuilder or(String where, Object... whereArgs) {
return append(OR, where, whereArgs);
}
/**
* build as " AND "
*/
public WhereBuilder and() {
if (where != null) {
where += AND;
}
return this;
}
/**
* build as " OR "
*/
public WhereBuilder or() {
if (where != null) {
where += OR;
}
return this;
}
/**
* build as " NOT "
*/
public WhereBuilder not() {
if (where != null) {
where += NOT;
}
return this;
}
/**
* build as " column != ? "
*/
public WhereBuilder noEquals(String column, Object value) {
return append(null, column + NOT_EQUAL_HOLDER, value);
}
/**
* build as " column > ? "
*/
public WhereBuilder greaterThan(String column, Object value) {
return append(null, column + GREATER_THAN_HOLDER, value);
}
/**
* build as " column < ? "
*/
public WhereBuilder lessThan(String column, Object value) {
return append(null, column + LESS_THAN_HOLDER, value);
}
/**
* build as " column = ? "
*/
public WhereBuilder equals(String column, Object value) {
return append(null, column + EQUAL_HOLDER, value);
}
/**
* build as " or column = ? "
*/
public WhereBuilder orEquals(String column, Object value) {
return append(OR, column + EQUAL_HOLDER, value);
}
/**
* build as " and column = ? "
*/
public WhereBuilder andEquals(String column, Object value) {
return append(AND, column + EQUAL_HOLDER, value);
}
/**
* build as " column in(?,?...) "
*/
public WhereBuilder in(String column, Object... values) {
return append(null, buildWhereIn(column, values.length), values);
}
/**
* build as " or column in(?,?...) "
*/
public WhereBuilder orIn(String column, Object... values) {
return append(OR, buildWhereIn(column, values.length), values);
}
/**
* build as " and column in(?,?...) "
*/
public WhereBuilder andIn(String column, Object... values) {
return append(AND, buildWhereIn(column, values.length), values);
}
/**
* @param whereString "id = ?";
* or "id in(?,?,?)";
* or "id LIKE %?";
* ...
* @param value new String[]{"",""};
* or new Integer[]{1,2};
* ...
* @param connect NULL or " AND " or " OR " or " NOT "
* @return this
*/
public WhereBuilder append(String connect, String whereString, Object... value) {
if (where == null) {
where = whereString;
whereArgs = value;
} else {
if (connect != null) {
where += connect;
}
where += whereString;
if (whereArgs == null) {
this.whereArgs = value;
} else {
Object[] newWhere = new Object[whereArgs.length + value.length];
System.arraycopy(whereArgs, 0, newWhere, 0, whereArgs.length);
System.arraycopy(value, 0, newWhere, whereArgs.length, value.length);
this.whereArgs = newWhere;
}
}
return this;
}
public String[] transToStringArray() {
if (whereArgs != null && whereArgs.length > 0) {
if (whereArgs instanceof String[]) {
return (String[]) whereArgs;
}
String[] arr = new String[whereArgs.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = String.valueOf(whereArgs[i]);
}
return arr;
}
return null;
}
public String createWhereString() {
if (where != null) {
return WHERE + where;
} else {
return NOTHING;
}
}
public SQLStatement createStatementDelete() {
SQLStatement stmt = new SQLStatement();
stmt.sql = DELETE + TableManager.getTableName(tableClass) + createWhereString();
stmt.bindArgs = transToStringArray();
return stmt;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
public Object[] getWhereArgs() {
return whereArgs;
}
public void setWhereArgs(Object[] whereArgs) {
this.whereArgs = whereArgs;
}
private String buildWhereIn(String column, int num) {
StringBuilder sb = new StringBuilder(column).append(IN).append(PARENTHESES_LEFT).append(HOLDER);
for (int i = 1; i < num; i++) {
sb.append(COMMA_HOLDER);
}
return sb.append(PARENTHESES_RIGHT).toString();
}
}
| gpl-2.0 |
RandoApp/Rando-android | src/main/java/com/github/randoapp/view/UnwantedRandoView.java | 1423 | package com.github.randoapp.view;
import android.content.Context;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import com.github.randoapp.R;
import com.makeramen.roundedimageview.RoundedImageView;
public class UnwantedRandoView extends RelativeLayout {
private final Animation animation;
private boolean stopAnimation = false;
public UnwantedRandoView(Context context) {
super(context);
RoundedImageView roundedImageView = new RoundedImageView(context);
roundedImageView.setImageResource(R.drawable.ic_boring);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
roundedImageView.setLayoutParams(layoutParams);
roundedImageView.setOval(true);
addView(roundedImageView);
animation = AnimationUtils.loadAnimation(context, R.anim.show_hide_infinity);
startAnimation(animation);
}
@Override
protected void onDetachedFromWindow() {
clearAnimation();
stopAnimation = true;
super.onDetachedFromWindow();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (stopAnimation) {
stopAnimation = false;
startAnimation(animation);
}
}
}
| gpl-2.0 |
ankon/gatormail | src/main/java/edu/ufl/osg/webmail/wrappers/MessageWrapper.java | 3588 | /*
* This file is part of GatorMail, a servlet based webmail.
* Copyright (C) 2002, 2003 William A. McArthur, Jr.
* Copyright (C) 2003 The Open Systems Group / University of Florida
*
* GatorMail is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GatorMail is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GatorMail; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.ufl.osg.webmail.wrappers;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
/**
* Wrapper for a JavaMail Message so that the properties follow the actuall
* JavaBean pattern.
*
* @author sandymac
* @version $Revision: 1.2 $
*/
public class MessageWrapper {
/**
* Holds value of property javaMailMessage.
*/
private Message javaMailMessage;
/**
* Creates a new instance of MessageWrapper
*/
public MessageWrapper(final Message message) {
setJavaMailMessage(message);
}
/**
* Getter for property javaMailMessage.
*
* @return Value of property javaMailMessage.
*/
public Message getJavaMailMessage() {
return this.javaMailMessage;
}
/**
* Setter for property javaMailMessage.
*
* @param javaMailMessage New value of property javaMailMessage.
*/
protected void setJavaMailMessage(final Message javaMailMessage) {
this.javaMailMessage = javaMailMessage;
}
/**
* Getter for property subject.
*
* @return Value of property subject.
*/
public String getSubject() throws MessagingException {
return javaMailMessage.getSubject();
}
/**
* Getter for property to.
*
* @return {@link java.util.List} of "to" recipients,
* empty list if no recipients.
*/
public List getTo() throws MessagingException {
final List list;
final Address[] addresses = javaMailMessage.getRecipients(RecipientType.TO);
if (addresses != null) {
list = Arrays.asList(addresses);
} else {
list = Collections.EMPTY_LIST;
}
return list;
}
/**
* Getter for property from.
*
* @return {@link java.util.List} of senders, empty list
* if no senders.
*/
public List getFrom() throws MessagingException {
final List list;
final Address[] addresses = getJavaMailMessage().getFrom();
if (addresses != null) {
list = Arrays.asList(addresses);
} else {
list = Collections.EMPTY_LIST;
}
return list;
}
/**
* Getter for property size.
*
* @return Value of property size.
*/
public int getSize() throws MessagingException {
return getJavaMailMessage().getSize();
}
}
| gpl-2.0 |
ebraminio/Kaspar | src/mediawiki/info/wikibase/snaks/CoordinateSnak.java | 2459 | package mediawiki.info.wikibase.snaks;
import javat.xml.Element;
import org.json.JSONException;
import org.json.JSONObject;
import mediawiki.info.wikibase.Snak;
import mediawiki.info.wikibase.WikibaseCoordinate;
public class CoordinateSnak extends Snak<WikibaseCoordinate> {
public CoordinateSnak(WikibaseCoordinate value) {
super(value);
}
public CoordinateSnak(Double lat, Double lon,int precision){
this(new WikibaseCoordinate(lat, lon, precision));
}
@Override
public JSONObject toJSONObject() throws JSONException {
JSONObject o = new JSONObject();
o.put("latitude", getValue().getLatitude());
o.put("longitude", getValue().getLongitude());
o.put("altitude", getValue().getAltitude());
o.put("precision", getValue().getPrecision());
o.put("globe", getValue().getGlobe());
return o;
}
@Override
public boolean equalsXML(Element e) {
if(! e.getAttribute("type").getValue().equals("globecoordinate"))
return false;
e = e.getChildren("value").get(0);
if(! e.getAttribute("latitude").getValue().equals(getValue().getLatitude()+""))
return false;
if(! e.getAttribute("longitude").getValue().equals(getValue().getLongitude()+""))
return false;
if(! e.getAttribute("altitude").getValue().equals(getValue().getAltitude()+""))
return false;
if(! e.getAttribute("precision").getValue().equals(getValue().getPrecision()+""))
return false;
if(! e.getAttribute("globe").getValue().equals(getValue().getGlobe()))
return false;
return true;
}
@Override
public JSONObject toReferenceRepresentation() throws JSONException {
JSONObject o = new JSONObject();
o.put("type", "globecoordinate");
o.put("value", toJSONObject());
return o;
}
@Override
public JSONObject toClaimRepresentation() throws JSONException {
return toJSONObject();
}
@Override
public void convert(Element element) throws Exception {
Element e = element.getChildren("value").get(0);
double latitude = Double.parseDouble(e.getAttribute("latitude").getValue());
double longitude = Double.parseDouble(e.getAttribute("longitude").getValue());
Double altitude = e.getAttribute("altitude").getValue().equals("") ? null : Double.parseDouble(e.getAttribute("altitude").getValue());
double precision = Double.parseDouble(e.getAttribute("precision").getValue());
String globe = e.getAttribute("globe").getValue();
setValue(new WikibaseCoordinate(latitude, longitude, altitude, precision, globe));
}
}
| gpl-2.0 |
giancar70/AppBembos | AppBembos/src/com/example/appbembos/model/bean/UsuarioDao.java | 4807 | package com.example.appbembos.model.bean;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import com.example.appbembos.model.bean.Usuario;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table USUARIO.
*/
public class UsuarioDao extends AbstractDao<Usuario, Long> {
public static final String TABLENAME = "USUARIO";
/**
* Properties of entity Usuario.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Nombre = new Property(1, String.class, "nombre", false, "NOMBRE");
public final static Property Apellido = new Property(2, String.class, "apellido", false, "APELLIDO");
public final static Property Password = new Property(3, String.class, "password", false, "PASSWORD");
public final static Property Email = new Property(4, String.class, "email", false, "EMAIL");
};
public UsuarioDao(DaoConfig config) {
super(config);
}
public UsuarioDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "'USUARIO' (" + //
"'_id' INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"'NOMBRE' TEXT," + // 1: nombre
"'APELLIDO' TEXT," + // 2: apellido
"'PASSWORD' TEXT," + // 3: password
"'EMAIL' TEXT);"); // 4: email
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'USUARIO'";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, Usuario entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String nombre = entity.getNombre();
if (nombre != null) {
stmt.bindString(2, nombre);
}
String apellido = entity.getApellido();
if (apellido != null) {
stmt.bindString(3, apellido);
}
String password = entity.getPassword();
if (password != null) {
stmt.bindString(4, password);
}
String email = entity.getEmail();
if (email != null) {
stmt.bindString(5, email);
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/** @inheritdoc */
@Override
public Usuario readEntity(Cursor cursor, int offset) {
Usuario entity = new Usuario( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // nombre
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // apellido
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // password
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4) // email
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, Usuario entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setNombre(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setApellido(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setPassword(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setEmail(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(Usuario entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(Usuario entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
| gpl-2.0 |
heroichornet/jass | src/main/java/ch/game/jass/rules/CorrectSuitMustBePlayedRule.java | 1725 | package ch.game.jass.rules;
import ch.game.jass.JassCard;
import ch.game.jass.JassTable;
import ch.game.jass.impartial.JassGameModerator;
import ch.game.jass.player.JassHand;
import ch.game.jass.player.JassMove;
import ch.game.jass.player.JassPlayer;
public class CorrectSuitMustBePlayedRule implements JassRule {
@Override
public boolean followsRule(JassMove move, JassTable.GameMode mode) {
if (move.getTrick().isEmtpy()) {
return true;
}
JassPlayer player = move.getPlayer();
JassCard card = move.getCard();
JassHand hand = player.getHand();
int suitOfTrick = move.getSuitOfTrick();
if(!player.canPlaySuit(suitOfTrick)) return true;
if (JassTable.isTrumpfGame(mode)) {
if(move.getCard().getSuit() == suitOfTrick) return true;
int suitOfTrump = JassTable.getTrumpfSuit(mode);
if(move.getCard().getSuit()== suitOfTrump) return true;
JassCard bestTrump = new JassCard(suitOfTrump, JassCard.Rank.UNTER.ordinal());
int numberOfTrumps = (int) hand.stream().filter(c -> c.getRank() == suitOfTrick).count();
if(suitOfTrick == suitOfTrump){
if(numberOfTrumps == 0){
return true;
}else if (numberOfTrumps == 1){
if(hand.containsCard(bestTrump)){
return true;
};
}else{
return (card.getSuit() == suitOfTrump);
}
}
}
if (player.canPlaySuit(suitOfTrick)) {
return card.getSuit() == suitOfTrick;
} else {
return true;
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/sun/management/HotspotClassLoadingMBean.java | 3586 | /*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.management;
import java.lang.management.ClassLoadingMXBean;
import sun.management.counter.Counter;
/**
* Hotspot internal management interface for the class loading system.
*
* This management interface is internal and uncommitted
* and subject to change without notice.
*/
public interface HotspotClassLoadingMBean {
/**
* Returns the amount of memory in bytes occupied by loaded classes
* in the Java virtual machine.
*
* @return the amount of memory in bytes occupied by loaded classes
* in the Java virtual machine.
*/
public long getLoadedClassSize();
/**
* Returns the number of bytes that the Java virtual machine
* collected due to class unloading.
*
* @return the number of bytes that the VM collected due to
* class unloading.
*/
public long getUnloadedClassSize();
/**
* Returns the accumulated elapsed time spent by class loading
* in milliseconds.
*
* @return the accumulated elapsed time spent by class loading
* in milliseconds.
*/
public long getClassLoadingTime();
/**
* Returns the amount of memory in bytes occupied by the method
* data.
*
* @return the amount of memory in bytes occupied by the method
* data.
*/
public long getMethodDataSize();
/**
* Returns the number of classes for which initializers were run.
*
* @return the number of classes for which initializers were run.
*/
public long getInitializedClassCount();
/**
* Returns the accumulated elapsed time spent in class initializers
* in milliseconds.
*
* @return the accumulated elapsed time spent in class initializers
* in milliseconds.
*/
public long getClassInitializationTime();
/**
* Returns the accumulated elapsed time spent in class verifier
* in milliseconds.
*
* @return the accumulated elapsed time spent in class verifier
* in milliseconds.
*/
public long getClassVerificationTime();
/**
* Returns a list of internal counters maintained in the Java
* virtual machine for the class loading system.
*
* @return a list of internal counters maintained in the VM
* for the class loading system.
*/
public java.util.List<Counter> getInternalClassLoadingCounters();
}
| gpl-2.0 |
dlitz/resin | modules/resin/src/com/caucho/rewrite/WelcomeFile.java | 6403 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.rewrite;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.DispatcherType;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import com.caucho.config.Configurable;
import com.caucho.server.dispatch.ForwardFilterChain;
import com.caucho.server.dispatch.RewriteDispatchFilterChain;
import com.caucho.server.dispatch.RewriteIncludeFilterChain;
import com.caucho.server.webapp.WebApp;
import com.caucho.util.L10N;
import com.caucho.vfs.Path;
/**
* Manages the welcome-file as a rewrite-dispatch.
*
* <pre>
* <web-app xmlns:resin="urn:java:com.caucho.resin">
*
* <resin:WelcomeFile welcome-file="index.jsp"/>
*
* </web-app>
* </pre>
*/
@Configurable
public class WelcomeFile extends AbstractDispatchRule
{
private static final Logger log
= Logger.getLogger(WelcomeFile.class.getName());
private static final L10N L = new L10N(WelcomeFile.class);
private static final HashSet<String> _welcomeFileResourceMap
= new HashSet<String>();
private final WebApp _webApp;
private ArrayList<String> _welcomeFileList = new ArrayList<String>();
public WelcomeFile()
{
WebApp webApp = WebApp.getCurrent();
if (webApp == null)
throw new IllegalStateException(L.l("{0} must have an active {1}.",
WelcomeFile.class.getSimpleName(),
WebApp.class.getSimpleName()));
_webApp = webApp;
}
public WelcomeFile(ArrayList<String> welcomeFile)
{
this();
_welcomeFileList.addAll(welcomeFile);
}
@Override
public boolean isInclude()
{
return true;
}
@Override
public boolean isForward()
{
return true;
}
public void addWelcomeFile(String welcomeFile)
{
_welcomeFileList.add(welcomeFile);
}
@Override
public String rewriteUri(String uri, String queryString)
{
return uri;
}
@Override
public FilterChain map(DispatcherType type,
String uri,
String queryString,
FilterChain next,
FilterChain tail)
throws ServletException
{
String welcomeUri = matchWelcomeFileResource(type, uri, null);
if (welcomeUri == null) {
return next;
}
// server/1u24
/*
if (queryString != null) {
welcomeUri = welcomeUri + '?' + queryString;
}
*/
if (DispatcherType.INCLUDE.equals(type))
return new RewriteIncludeFilterChain(next, welcomeUri);
else if (DispatcherType.FORWARD.equals(type))
return new ForwardFilterChain(welcomeUri);
else
return new RewriteDispatchFilterChain(welcomeUri);
}
private String matchWelcomeFileResource(DispatcherType type,
String uri,
ArrayList<String> vars)
{
if (matchWelcomeUri(uri) != Match.NONE) {
return null;
}
// String contextUri = invocation.getContextURI();
try {
Path path = _webApp.getCauchoPath(uri);
if (! path.exists())
return null;
} catch (Exception e) {
if (log.isLoggable(Level.FINER))
log.log(Level.FINER, L.l(
"can't match a welcome file path {0}",
uri), e);
return null;
}
// String servletName = null;
ArrayList<String> welcomeFileList = _welcomeFileList;
int size = welcomeFileList.size();
String bestWelcomeUri = null;
Match bestMatch = Match.NONE;
for (int i = 0; i < size; i++) {
String file = welcomeFileList.get(i);
String welcomeUri;
if (uri.endsWith("/"))
welcomeUri = uri + file;
else if (! DispatcherType.REQUEST.equals(type)) {
welcomeUri = uri + '/' + file;
}
else {
continue;
}
Match match = matchWelcomeUri(welcomeUri);
if (bestMatch.ordinal() < match.ordinal()) {
bestMatch = Match.FILE;
bestWelcomeUri = welcomeUri;
}
}
return bestWelcomeUri;
}
private Match matchWelcomeUri(String welcomeUri)
{
try {
InputStream is;
is = _webApp.getResourceAsStream(welcomeUri);
if (is != null)
is.close();
if (is != null)
return Match.FILE;
} catch (Exception e) {
log.fine("welcome-file lookup failed: " + welcomeUri);
log.log(Level.ALL, e.toString(), e);
}
String servletClassName
= _webApp.getServletMapper().getServletClassByUri(welcomeUri);
if (servletClassName != null
&& ! _welcomeFileResourceMap.contains(servletClassName)) {
return Match.SERVLET;
}
return Match.NONE;
}
enum Match {
NONE,
SERVLET,
FILE;
}
static {
_welcomeFileResourceMap.add("com.caucho.servlets.FileServlet");
_welcomeFileResourceMap.add("com.caucho.jsp.JspServlet");
_welcomeFileResourceMap.add("com.caucho.jsp.JspXmlServlet");
_welcomeFileResourceMap.add("com.caucho.quercus.servlet.QuercusServlet");
_welcomeFileResourceMap.add("com.caucho.jsp.XtpServlet");
_welcomeFileResourceMap.add("com.caucho.xtpdoc.ResinDocServlet");
}
}
| gpl-2.0 |
kainagel/teach-oop | src/main/java/ffCollections/bb_ListTest/Agent.java | 163 | package ffCollections.bb_ListTest;
class Agent {
private int id ;
public int getId() {
return this.id ;
}
public Agent ( int ii ) {
this.id = ii ;
}
} | gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/service/capability/CapabilityError.java | 1566 | /*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.orangelabs.rcs.core.ims.service.capability;
import com.orangelabs.rcs.core.ims.service.ImsServiceError;
/**
* Capability error
*
* @author jexa7410
*/
public class CapabilityError extends ImsServiceError {
static final long serialVersionUID = 1L;
/**
* Unexpected exception occurs in the module (e.g. internal exception)
*/
public final static int UNEXPECTED_EXCEPTION = 0x01;
/**
* Options has failed
*/
public final static int OPTIONS_FAILED = 0x02;
/**
* Constructor
*
* @param code Error code
*/
public CapabilityError(int code) {
super(code);
}
/**
* Constructor
*
* @param code Error code
* @param msg Detail message
*/
public CapabilityError(int code, String msg) {
super(code, msg);
}
}
| gpl-2.0 |
dlitz/resin | modules/quercus/src/com/caucho/quercus/env/CopyArrayValue.java | 7685 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.env;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.logging.Logger;
import com.caucho.quercus.Location;
/**
* Represents a PHP array value.
*/
public class CopyArrayValue extends ArrayValue {
private static final Logger log
= Logger.getLogger(CopyArrayValue.class.getName());
private final ConstArrayValue _constArray;
private ArrayValue _copyArray;
public CopyArrayValue(ConstArrayValue constArray)
{
_constArray = constArray;
}
/**
* Converts to a boolean.
*/
public boolean toBoolean()
{
if (_copyArray != null)
return _copyArray.toBoolean();
else
return _constArray.toBoolean();
}
/**
* Copy for assignment.
*/
public Value copy()
{
if (_copyArray != null)
return _copyArray.copy();
else
return _constArray.copy();
}
/**
* Copy for serialization
*/
public Value copy(Env env, IdentityHashMap<Value,Value> map)
{
if (_copyArray != null)
return _copyArray.copy(env, map);
else
return _constArray.copy(env, map);
}
/**
* Copy for saving a function arguments.
*/
public Value copySaveFunArg()
{
if (_copyArray != null)
return _copyArray.copySaveFunArg();
else
return _constArray.copySaveFunArg();
}
/**
* Returns the size.
*/
public int getSize()
{
if (_copyArray != null)
return _copyArray.getSize();
else
return _constArray.getSize();
}
/**
* Clears the array
*/
public void clear()
{
getCopyArray().clear();
}
/**
* Adds a new value.
*/
@Override
public Value put(Value key, Value value)
{
return getCopyArray().put(key, value);
}
/**
* Add
*/
public Value put(Value value)
{
return getCopyArray().put(value);
}
/**
* Add
*/
public ArrayValue unshift(Value value)
{
return getCopyArray().unshift(value);
}
/**
* Splices.
*/
public ArrayValue splice(int start, int end, ArrayValue replace)
{
return getCopyArray().splice(start, end, replace);
}
/**
* Slices.
*/
public ArrayValue slice(Env env, int start, int end, boolean isPreserveKeys)
{
return getCopyArray().slice(env, start, end, isPreserveKeys);
}
/**
* Returns the value as an array.
*/
public Value getArray(Value fieldName)
{
return getCopyArray().getArray(fieldName);
}
/**
* Returns the value as an argument which may be a reference.
*/
@Override
public Value getArg(Value index, boolean isTop)
{
return getCopyArray().getArg(index, isTop);
}
/**
* Convert to an argument value.
*/
@Override
public Value toLocalValue()
{
return getCopyArray().toLocalValue();
}
/**
* Returns the field value, creating an object if it's unset.
*/
@Override
public Value getObject(Env env, Value fieldName)
{
return getCopyArray().getObject(env, fieldName);
}
/**
* Sets the array ref.
*/
public Var putVar()
{
return getCopyArray().putVar();
}
/**
* Add
*/
public ArrayValue append(Value key, Value value)
{
return getCopyArray().append(key, value);
}
/**
* Add
*/
public ArrayValue append(Value value)
{
return getCopyArray().append(value);
}
/**
* Gets a new value.
*/
public Value get(Value key)
{
if (_copyArray != null)
return _copyArray.get(key);
else
return _constArray.get(key);
}
/**
* Returns the corresponding key if this array contains the given value
*
* @param value to search for in the array
*
* @return the key if it is found in the array, NULL otherwise
*/
public Value contains(Value value)
{
if (_copyArray != null)
return _copyArray.contains(value);
else
return _constArray.contains(value);
}
/**
* Returns the corresponding key if this array contains the given value
*
* @param value to search for in the array
*
* @return the key if it is found in the array, NULL otherwise
*/
public Value containsStrict(Value value)
{
if (_copyArray != null)
return _copyArray.containsStrict(value);
else
return _constArray.containsStrict(value);
}
/**
* Returns the corresponding value if this array contains the given key
*
* @param key to search for in the array
*
* @return the value if it is found in the array, NULL otherwise
*/
public Value containsKey(Value key)
{
if (_copyArray != null)
return _copyArray.containsKey(key);
else
return _constArray.containsKey(key);
}
/**
* Removes a value.
*/
public Value remove(Value key)
{
return getCopyArray().remove(key);
}
/**
* Returns the array ref.
*/
public Var getVar(Value index)
{
return getCopyArray().getVar(index);
}
/**
* Pops the top value.
*/
@Override
public Value pop(Env env)
{
return getCopyArray().pop(env);
}
/**
* Pops the top value.
*/
public Value createTailKey()
{
return getCopyArray().createTailKey();
}
/**
* Shuffles the array
*/
public Value shuffle()
{
return getCopyArray().shuffle();
}
public Entry getHead()
{
if (_copyArray != null)
return _copyArray.getHead();
else
return _constArray.getHead();
}
protected Entry getTail()
{
if (_copyArray != null)
return _copyArray.getTail();
else
return _constArray.getTail();
}
private ArrayValue getCopyArray()
{
if (_copyArray == null)
_copyArray = new ArrayValueImpl(_constArray);
return _copyArray;
}
@Override
public int cmp(Value rValue)
{
if (_copyArray != null)
return _copyArray.cmp(rValue);
else
return _constArray.cmp(rValue);
}
@Override
public boolean eq(Value rValue)
{
if (_copyArray != null)
return _copyArray.eq(rValue);
else
return _constArray.eq(rValue);
}
@Override
public boolean eql(Value rValue)
{
if (_copyArray != null)
return _copyArray.eql(rValue);
else
return _constArray.eql(rValue);
}
@Override
public int hashCode()
{
if (_copyArray != null)
return _copyArray.hashCode();
else
return _constArray.hashCode();
}
@Override
public Value toValue()
{
/*
if (_copyArray != null)
return _copyArray;
else
return _constArray;
*/
return this;
}
@Override
public boolean equals(Object o)
{
if (_copyArray != null)
return _copyArray.equals(o);
else
return _constArray.equals(o);
}
}
| gpl-2.0 |
zet-evacuation/evacuation-cellular-automaton | src/main/java/org/zet/cellularautomaton/DoorCell.java | 6886 | /* zet evacuation tool copyright (c) 2007-20 zet evacuation team
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.zet.cellularautomaton;
import java.util.List;
/**
* A Door-EvacCell is special type of cell and therefore inherits properties and methods from the abstract class
* EvacCell. Door-Cells are portals to move between two roomes. Because of that they keep a reference to another
* Door-EvacCell, which belongs to the room you can enter by using this Door-EvacCell of the current room.
*
* @author Jan-Philipp Kappmeier
* @author Marcel Preuß
*
*/
public class DoorCell extends BaseTeleportCell<DoorCell> {
/** Constant defining the standard Speed-Factor of a Door-EvacCell, which may be < 1. */
public static final double STANDARD_DOORCELL_SPEEDFACTOR = 0.8d;
/**
* Constructs an empty DoorCell which is NOT connected with any other DoorCell and has the standard Speed-Factor
* "STANDARD_DOORCELL_SPEEDFACTOR".
*
* @param x x-coordinate of the cell in the room, 0 <= x <= width-1
* @param y y-coordinate of the cell in the room, 0 <= y <= height-1
*/
public DoorCell(int x, int y) {
this(new EvacuationCellState(null), DoorCell.STANDARD_DOORCELL_SPEEDFACTOR, x, y);
}
/**
* Constructs an empty DoorCell which is NOT connected with any other DoorCell and has a speed-factor of
* {@code speedfactor}
*
* @param speedFactor The speedfactor for this cell
* @param x x-coordinate of the cell in the room, 0 <= x <= width-1
* @param y y-coordinate of the cell in the room, 0 <= y <= height-1
*/
public DoorCell(double speedFactor, int x, int y) {
this(speedFactor, x, y, null);
}
public DoorCell(double speedFactor, int x, int y, Room room) {
super(speedFactor, x, y, room);
}
/**
* Constructs a DoorCell with the defined values.
*
* @param individual Defines the individual that occupies the cell. If the cell is not occupied, the value is set to
* "null".
* @param speedFactor Defines how fast the cell can be crossed. The value should be a rational number greater than
* or equal to 0 and smaller or equal to 1. Otherwise the standard value "STANDARD_DOORCELL_SPEEDFACTOR" is set.
* @param x x-coordinate of the cell in the room, 0 <= x <= width-1
* @param y y-coordinate of the cell in the room, 0 <= y <= height-1
*/
public DoorCell(EvacuationCellState individual, double speedFactor, int x, int y) {
super(individual, speedFactor, x, y);
}
/**
* Adds a DoorCell which is connected to this DoorCell and registers itself as a connected DoorCell in "door".
*
* @param door Defines the reference to the Door-EvacCell of the room you can enter by using this Door-EvacCell of
* the current room.
* @throws IllegalArgumentException if the parameter "Door" is null or if "Door" has already been added to the list
* of doors.
*/
@Override
public void addTarget(DoorCell door) throws IllegalArgumentException {
internalAddNextDoor(door);
door.internalAddNextDoor(this);
}
/**
* Removes the specified door.
*
* @param door The door which shall be removed.
*/
@Override
public void removeTarget(DoorCell door) {
this.internalRemoveNextDoor(door);
door.internalRemoveNextDoor(this);
}
/**
* <p>
* Removes all next doors from this door cell but does <b>not</b> notify the next doors about the removal.</p>
* <p>
* <b>Warning!</b> Use this method only if you know what you do. It may destroy the cosistency of the CA. This
* method is basically useful if a {@link ds.ca.CellularAutomaton} should be clonded. In that case the next doors
* have to be set to the new cloned instances and the old instances should be deleted without disturbing the
* original automaton.
* </p>
*/
public void removeAllNextDoorsWithoutNotify() {
while (this.targetCount() > 0) {
internalRemoveNextDoor(this.getTarget(0));
}
}
/**
* Returns a copy of itself as a new Object.
* @return the cloned copy
*/
@Override
public DoorCell clone() {
return clone(false);
}
@Override
public DoorCell clone(boolean cloneIndividual) {
DoorCell aClone = new DoorCell(this.getX(), this.getY());
basicClone(aClone, cloneIndividual);
for (DoorCell cell : teleportTargets) {
aClone.addTarget(cell);
}
return aClone;
}
@Override
public String toString() {
return "D;" + super.toString();
}
@Override
protected List<EvacCellInterface> getNeighbours(boolean passableOnly, boolean freeOnly) {
List<EvacCellInterface> neighbours = super.getNeighbours(passableOnly, freeOnly);
for (DoorCell door : this.teleportTargets) {
if (!freeOnly || door.getState().getIndividual() == null) {
neighbours.add(door);
}
}
return neighbours;
}
/**
* This is a helper method for internal synchronisation. Call this to add a nextDoor without being called back.
*
* @param door a door you want to add to the teleportTargets list.
*/
private void internalAddNextDoor(DoorCell door) {
if (door == null) {
throw new IllegalArgumentException("Parameter Door must not be \"null\"");
}
if (teleportTargets.contains(door)) {
if (!door.containsTarget(this)) {
throw new IllegalArgumentException("\"Door\" has already been added!");
}
} else {
teleportTargets.add(door);
}
}
/**
* This is a helper method for internal synchronisation. Call this to remove a nextDoor without being called back.
*
* @param door a door you want to remove from the teleportTargets list.
*/
private void internalRemoveNextDoor(DoorCell door) {
if (this.teleportTargets.remove(door) == false) {
throw new IllegalArgumentException("The door you tried to remove is not connected to this cell.");
}
}
}
| gpl-2.0 |
tousyourin/Volvox | src/cu/volvox/app/Background.java | 2094 | package cu.volvox.app;
import java.nio.FloatBuffer;
import cu.volvox.app.R;
import cu.smartphone.library.Shader;
import cu.smartphone.library.Sizeof;
import cu.smartphone.library.Texture;
import cu.smartphone.library.VertexBuffer;
import android.content.Context;
import android.opengl.GLES20;
public class Background{
private final static int DEMENSION_POSITION = 3;
private final static int DEMENSION_TEXCOORD = 2;
private final static int STRIDE = Sizeof.FLOAT * (DEMENSION_POSITION + DEMENSION_TEXCOORD);
private final static String vertexShader = "shader/background.gvs";
private final static String fragmentShader = "shader/background.gfs";
private Texture texture;
private Shader shader;
private VertexBuffer buffer = new VertexBuffer();
private float[] color = {1, 0, 0, 1};
/*
* コンストラクタ
*/
public Background(Context context){
texture = new Texture(context, R.drawable.back);
shader = new Shader(context, vertexShader, fragmentShader);
float[] vertices = {
1, 1, 0, 1, 0,
-1, 1, 0, 0, 0,
1, -1, 0, 1, 1,
-1, -1, 0, 0, 1
};
FloatBuffer vertex;
int size = vertices.length * Sizeof.FLOAT;
vertex = VertexBuffer.createBuffer(size, vertices);
buffer.setData(GLES20.GL_ARRAY_BUFFER, size, vertex, GLES20.GL_STATIC_DRAW);
}
/*
* 描画
*/
public void draw(){
shader.use();
texture.bind();
buffer.bind();
buffer.attachAttribute(shader, "aPosition", DEMENSION_POSITION, STRIDE, 0);
buffer.attachAttribute(shader, "aTexCoord", DEMENSION_TEXCOORD, STRIDE, DEMENSION_POSITION * Sizeof.FLOAT);
shader.attachUniformf("uColor", 1, color, 0, 3);
buffer.drawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
buffer.detachAttribute(shader, "aPosition");
}
/*
* 色を設定する
*/
public void setColor(float[] _color){
for(int i = 0; i < 3; ++i){
color[i] = _color[i];
}
}
/*
* 開放
*/
public void release(){
buffer.release();
buffer = null;
if(texture != null){
texture.release();
texture = null;
}
if(shader != null){
shader.release();
shader = null;
}
}
} | gpl-2.0 |
nguyenti/MISTdroid | app/src/main/java/edu/grinnell/glimmer/nguyenti/mistdroid/dagmaking/DAG.java | 4047 | package edu.grinnell.glimmer.nguyenti.mistdroid.dagmaking;
import java.io.PrintWriter;
import java.util.HashMap;
import edu.grinnell.glimmer.nguyenti.mistdroid.parsing.Parser;
import edu.grinnell.glimmer.nguyenti.mistdroid.parsing.TreeNode;
/**
* Creates a directed acyclic graph with all unique nodes from
* an n-ary tree with potentially repeated nodes.
* @author Albert Owusu-Asare<br>
* Vasilisa Bashlovkina<br>
* Jason Liu<br>
* @since 1.0
*
*/
public class DAG
{
/**
* Creates a new DAG.
* @param root
* the root of the tree
* @return
* the root of a corresponding DAG
*/
public static TreeNode makeDAG(TreeNode root)
{
HashMap<HashNode, Integer> map = new HashMap<>();
HashMap<Integer, HashNode> reverseMap = new HashMap<>();
Table table = new Table(map);
HashNode rootNode = makeTable(root, table, reverseMap);
HashMap<HashNode, TreeNode> auxMap = new HashMap<>();
return makeDAGHelper(rootNode, reverseMap, auxMap);
}// makeDAG(TreeNode)
/**
* Populate two maps that are inverses of each other
* with (hash)nodes from the tree starting at root
* @param root
* the original tree
* @param table
* forward map encapsulated with a counter
* @param reverseMap
* reverse of the table map
* @post the two maps are populated
* @return the hashnode representing the root
*/
private static HashNode makeTable(TreeNode root, Table table,
HashMap<Integer, HashNode> reverseMap)
{
HashNode key = new HashNode(root);
//if root is not a leaf : process all its children
if (!root.isLeaf())
{
for (TreeNode child : root.getChildren())
{
HashNode childNode = makeTable(child, table, reverseMap);
//update parent key with child Number
key.addChildNumber(childNode.getNodeNumber());
}//for
}//if
//for a leaf, check if it exists in the table
if (!table.map.containsKey(key))
{
// if not, set the key's number
key.setNodeNumber(table.getAvailableNumber());
// put it in the map and the reverse map
table.map.put(key, key.getNodeNumber());
reverseMap.put(key.getNodeNumber(), key);
// increment the counter in the table
table.incrementAvailableNum();
}//if
else
// if it's already in the table, retrieve its number
key.setNodeNumber(table.map.get(key));
return key;
}//makeDAG(Treenode, Table, HashMap<Integer, HashNode>)
/**
* A helper method that builds a DAG given the
* populated map of hashnodes
* @param hashRoot
* the root of the tree represented in the map
* @param reverseMap
* @return
*/
private static TreeNode makeDAGHelper(HashNode hashRoot,
HashMap<Integer, HashNode> reverseMap,
HashMap<HashNode, TreeNode> auxMap)
{
// if the corresponding TreeNode was already made, pass a reference to it
if (auxMap.containsKey(hashRoot))
return auxMap.get(hashRoot);
// otherwise, make a new TreeNode
TreeNode dagRoot = new TreeNode(hashRoot.getNodeVal());
// recurse on its children, if there are any
for (Integer kid : hashRoot.getChildrenNumbers())
{
HashNode temp = reverseMap.get(kid);
dagRoot.addChild(makeDAGHelper(temp, reverseMap, auxMap));
}
auxMap.put(hashRoot, dagRoot);
return dagRoot;
}// makeDAGHelper(HashNode, HashMap<Integer, HashNode>)
/**
* A simple experiment
*
*/
// public static void main(String[] args)
// throws Exception
// {
// PrintWriter pen = new PrintWriter(System.out, true);
// String code = "sum(neg(x), neg(x), x, y)";
// TreeNode root = Parser.parse(code);
// pen.println("After parsing, the tree is:\n " + root);
// TreeNode dagRoot = makeDAG(root);
// pen.println("After making a DAG, the tree is:\n " + dagRoot);
// }// main
}//DAG class
| gpl-2.0 |
quhfus/DoSeR | doser-experiments/src/main/java/table/imdb/MusicBrainzConverter.java | 7982 | package table.imdb;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import experiments.table.limaye.corrected.Table;
import experiments.table.limaye.corrected.Table.Column;
import experiments.table.limaye.corrected.Table.Column.Cell;
public class MusicBrainzConverter {
public static String RAWDIRECTORY = "/home/quh/Arbeitsfläche/Table Disambiguation Data sets/musicBrainz_raw/";
public static String TRIPPLEFILE = "/home/quh/Arbeitsfläche/Table Disambiguation Data sets/freebase_links_en.nt";
public static String GTDIRECTORY = "/home/quh/Arbeitsfläche/Table Disambiguation Data sets/musicbrainz_entity_keys/";
public static final String OUTPUTFILE = "/home/quh/Arbeitsfläche/Table Disambiguation Data sets/musicbrainz_columns.txt";
private HashMap<String, String> uriconversion;
private HashMap<String, String> groundtruth;
private PrintWriter writer;
private String filename;
public MusicBrainzConverter() {
super();
this.filename = "";
this.uriconversion = new HashMap<String, String>();
try {
writer = new PrintWriter(new File(OUTPUTFILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void readFile(File file) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
this.filename = files[i].getName();
File gtfile = new File(GTDIRECTORY + files[i].getName() + ".keys");
readGroundtruthFile(gtfile);
processFile(files[i]);
}
}
public void processFile(File input) {
String c = "";
try {
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(input));
while ((line = reader.readLine()) != null) {
c += line;
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
convert(c);
}
public void convert(String html) {
Converter parser = new Converter(groundtruth);
Reader in = new StringReader(html);
try {
// the HTML to convert
parser.parse(in);
} catch (Exception e) {
} finally {
try {
in.close();
} catch (IOException ioe) {
// this should never happen
}
}
parser.integrateGT();
Table t = parser.getTable();
int colnr = t.getNumberofColumns();
int max = 2;
if (colnr < max) {
max = colnr;
}
for (int i = 0; i < max; i++) {
writer.append(filename);
writer.append(System.lineSeparator());
Column c = t.getColumn(i);
List<Cell> cellList = c.getCellList();
for (Cell cell : cellList) {
writer.append(cell.getCellContent().replaceAll("\\n\\r", "") + "\t" + cell.getGt());
writer.append(System.lineSeparator());
}
writer.append(System.lineSeparator());
}
}
public void readTripples() {
File nfile = new File(TRIPPLEFILE);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(nfile));
String line = null;
reader.readLine();
while ((line = reader.readLine()) != null) {
String[] splitter = line.split(" ");
String freebaseOrig = splitter[splitter.length - 2];
// Freebase uri
freebaseOrig = freebaseOrig.replaceAll("<http://rdf.freebase.com/ns", "").replaceAll(">", "")
.replaceAll("\\.", "/");
String dbpediaUri = splitter[0];
dbpediaUri = dbpediaUri.replaceAll("<|>", "");
if (uriconversion.containsKey(freebaseOrig)) {
String uris = uriconversion.get(freebaseOrig);
uris += "," + dbpediaUri;
uriconversion.put(freebaseOrig, uris);
} else {
uriconversion.put(freebaseOrig, dbpediaUri);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void readGroundtruthFile(File gt) {
BufferedReader reader = null;
this.groundtruth = new HashMap<String, String>();
try {
reader = new BufferedReader(new FileReader(gt));
String line = null;
while ((line = reader.readLine()) != null) {
String row = line.split("=")[0];
String freebaseGT = line.replaceAll(".*=", "");
freebaseGT = freebaseGT.substring(0, freebaseGT.length() - 1);
groundtruth.put(row, freebaseGT);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Converter extends HTMLEditorKit.ParserCallback {
private boolean isCorrectTable = false;
private boolean checkText = false;
private boolean isCorrectCell = false;
private int columnCounter = 0;
private Table table;
Map<String, String> groundtruth;
Converter(HashMap<String, String> groundtruth) {
super();
this.groundtruth = groundtruth;
this.table = new Table();
}
public void parse(Reader in) throws IOException {
ParserDelegator delegator = new ParserDelegator();
// the third parameter is TRUE to ignore charset directive
delegator.parse(in, this, Boolean.TRUE);
}
public Table getTable() {
return table;
}
public void integrateGT() {
for (Map.Entry<String, String> entry : groundtruth.entrySet()) {
String pos = entry.getKey();
String[] splitter = pos.split(",");
int columnNr = Integer.valueOf(splitter[1]);
int cellNr = Integer.valueOf(splitter[0]);
Column col = table.getColumn(columnNr);
if (col != null) {
List<Cell> cellList = col.getCellList();
if (uriconversion.containsKey(entry.getValue())) {
String wikigt = uriconversion.get(entry.getValue());
cellList.get(cellNr).setGt(wikigt);
} else {
cellList.get(cellNr).setGt("NULL");
}
}
}
}
private boolean isRelevantTable(String table) {
return table.contains("tbl");
}
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
if (t.toString().equals("table") && isRelevantTable(a.toString())) {
isCorrectTable = true;
} else if (isCorrectTable && t.toString().equals("tr")) {
} else if (isCorrectTable && t.toString().equals("td")) {
isCorrectCell = true;
} else if (isCorrectTable && t.toString().equals("a") && isCorrectCell) {
int tablecols = table.getNumberofColumns();
if (tablecols < (columnCounter + 1)) {
System.out.println("ALSO BEIM ADDEN SIND WIR");
table.addColumn("");
}
columnCounter++;
checkText = true;
}
}
public void handleEndTag(HTML.Tag t, int pos) {
if (t.toString().equals("table") && isCorrectTable) {
isCorrectTable = false;
} else if (t.toString().equals("a") && isCorrectTable && checkText && isCorrectCell) {
checkText = false;
} else if (t.toString().equals("td") && isCorrectTable) {
isCorrectCell = false;
} else if (t.toString().equals("tr") && isCorrectTable) {
System.out.println("ICH REETTTTTTEEEE");
columnCounter = 0;
}
}
public void handleText(char[] text, int pos) {
String s = new String(text);
if (checkText) {
Column c = table.getColumn(columnCounter - 1);
System.out.println(columnCounter - 1);
System.out.println(s);
c.addCell(s);
}
}
}
public static void main(String args[]) {
MusicBrainzConverter imdbConverter = new MusicBrainzConverter();
imdbConverter.readTripples();
System.out.println("Finished Tripple Reading");
imdbConverter.readFile(new File(RAWDIRECTORY));
}
}
| gpl-2.0 |
calimero-project/calimero-core | src/tuwien/auto/calimero/dptxlator/DPTXlator1BitControlled.java | 11380 | /*
Calimero 2 - A library for KNX network access
Copyright (c) 2010, 2021 B. Malinowsky
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under terms
of your choice, provided that you also meet, for each linked independent
module, the terms and conditions of the license of that module. An
independent module is a module which is not derived from or based on
this library. If you modify this library, you may extend this exception
to your version of the library, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from your
version.
*/
package tuwien.auto.calimero.dptxlator;
import java.util.Map;
import tuwien.auto.calimero.KNXFormatException;
import tuwien.auto.calimero.KNXIllegalArgumentException;
/**
* Translator for KNX DPTs with main number 2, type <b>1 Bit controlled</b>.
* <p>
* The KNX data type width is 1 Bit, using the lowest Bit of 1 byte, with an additional 1 bit
* boolean control field.<br>
* The type structure is [1 Bit control field][1 Bit value field]. The default return value after
* creation is control flag and boolean value field set to false (0). The value field is according
* to DPT 1.x {@link DPTXlatorBoolean}.
* <p>
* In value methods expecting string types, the item is composed of the control field
* representation, followed by whitespace and the corresponding DPT 1.x value.<br>
* This translator requires {@link DPTXlatorBoolean}.
*
* @see DPTXlatorBoolean
*/
public class DPTXlator1BitControlled extends DPTXlator
{
/**
* A DPT for 1 Bit controlled, describing 1 control field and 1 value field.
* <p>
* This DPT references the corresponding 1.x DPTs, with the value field of a DPT 2.x being
* interpreted by the 1.x DPT of the same DPT sub number. For example, the value part of DPT
* 2.001 is formatted according to DPT 1.001.
*
* @author B. Malinowsky
*/
public static class DPT1BitControlled extends DPT
{
private final DPT value;
/**
* Creates a new datapoint type information structure for the 1 Bit controlled DPT.
*
* @param typeID datapoint type identifier
* @param description short textual description
* @param value the DPT of the control information
*/
public DPT1BitControlled(final String typeID, final String description, final DPT value)
{
super(typeID, description, "0 " + value.getLowerValue(), "1 " + value.getUpperValue());
this.value = value;
}
/**
* Returns the DPT used to represent the value information of this DPT.
* <p>
*
* @return the DPT for the value information
*/
public final DPT getValueDPT()
{
return value;
}
}
/**
* DPT ID 2.001, Switch Controlled; values are {@link DPTXlatorBoolean#DPT_SWITCH}.
*/
public static final DPT DPT_SWITCH_CONTROL = new DPT1BitControlled("2.001",
"Switch Controlled", DPTXlatorBoolean.DPT_SWITCH);
/**
* DPT ID 2.002, Bool Controlled; values are {@link DPTXlatorBoolean#DPT_BOOL}.
*/
public static final DPT DPT_BOOL_CONTROL = new DPT1BitControlled("2.002", "Boolean Controlled",
DPTXlatorBoolean.DPT_BOOL);
/**
* DPT ID 2.003, Enable Controlled; values are {@link DPTXlatorBoolean#DPT_ENABLE}.
*/
public static final DPT DPT_ENABLE_CONTROL = new DPT1BitControlled("2.003",
"Enable Controlled", DPTXlatorBoolean.DPT_ENABLE);
/**
* DPT ID 2.004, Ramp Controlled; values are {@link DPTXlatorBoolean#DPT_RAMP}.
*/
public static final DPT DPT_RAMP_CONTROL = new DPT1BitControlled("2.004", "Ramp Controlled",
DPTXlatorBoolean.DPT_RAMP);
/**
* DPT ID 2.005, Alarm Controlled; values are {@link DPTXlatorBoolean#DPT_ALARM}.
*/
public static final DPT DPT_ALARM_CONTROL = new DPT1BitControlled("2.005", "Alarm Controlled",
DPTXlatorBoolean.DPT_ALARM);
/**
* DPT ID 2.006, Binary Controlled; values are {@link DPTXlatorBoolean#DPT_BINARYVALUE}.
*/
public static final DPT DPT_BINARY_CONTROL = new DPT1BitControlled("2.006",
"Binary Controlled", DPTXlatorBoolean.DPT_BINARYVALUE);
/**
* DPT ID 2.007, Step Controlled; values are {@link DPTXlatorBoolean#DPT_STEP}.
*/
public static final DPT DPT_STEP_CONTROL = new DPT1BitControlled("2.007", "Step Controlled",
DPTXlatorBoolean.DPT_STEP);
/**
* DPT ID 2.008, Up/Down Controlled; values are {@link DPTXlatorBoolean#DPT_UPDOWN}.
*/
public static final DPT DPT_UPDOWN_CONTROL = new DPT1BitControlled("2.008",
"Up/Down Controlled", DPTXlatorBoolean.DPT_UPDOWN);
/**
* DPT ID 2.009, Open/Close Controlled; values are {@link DPTXlatorBoolean#DPT_OPENCLOSE}.
*/
public static final DPT DPT_OPENCLOSE_CONTROL = new DPT1BitControlled("2.009",
"Open/Close Controlled", DPTXlatorBoolean.DPT_OPENCLOSE);
/**
* DPT ID 2.010, Start Controlled; values are {@link DPTXlatorBoolean#DPT_START}.
*/
public static final DPT DPT_START_CONTROL = new DPT1BitControlled("2.010", "Start Controlled",
DPTXlatorBoolean.DPT_START);
/**
* DPT ID 2.011, State Controlled; values are {@link DPTXlatorBoolean#DPT_STATE}.
*/
public static final DPT DPT_STATE_CONTROL = new DPT1BitControlled("2.011", "State Controlled",
DPTXlatorBoolean.DPT_STATE);
/**
* DPT ID 2.012, Invert Controlled; values are {@link DPTXlatorBoolean#DPT_INVERT}.
*/
public static final DPT DPT_INVERT_CONTROL = new DPT1BitControlled("2.012",
"Invert Controlled", DPTXlatorBoolean.DPT_INVERT);
private static final Map<String, DPT> types = loadDatapointTypes(DPTXlator1BitControlled.class);
/**
* Creates a translator for the given datapoint type.
*
* @param dpt the requested datapoint type
* @throws KNXFormatException on not supported or not available DPT
*/
public DPTXlator1BitControlled(final DPT dpt) throws KNXFormatException
{
this(dpt.getID());
}
/**
* Creates a translator for the given datapoint type ID.
*
* @param dptId available implemented datapoint type ID
* @throws KNXFormatException on wrong formatted or not expected (available)
* <code>dptID</code>
*/
public DPTXlator1BitControlled(final String dptId) throws KNXFormatException
{
super(false, 2);
setTypeID(types, dptId);
data = new short[1];
}
@Override
public void setValue(final double value) {
if (value < 0 || value > 3)
throw new KNXIllegalArgumentException("value " + value + " out of range [0..3]");
final int i = (int) value;
final boolean control = (i & 0x02) != 0;
final boolean v = (i & 0x01) != 0;
setValue(control, v);
}
/**
* Sets one new translation item, replacing any old items.
*
* @param control control field, <code>false</code> is <i>no control</i>, <code>true</code> is <i>control</i>
* @param value value field
* @see #setControlBit(boolean)
*/
public final void setValue(final boolean control, final boolean value)
{
data = new short[1];
setControlBit(control);
setValueBit(value);
}
@Override
public String[] getAllValues()
{
final String[] buf = new String[data.length];
for (int i = 0; i < data.length; ++i)
buf[i] = fromDPT(i);
return buf;
}
/**
* Sets the control field for the first translation item.
* <p>
* A value of <code>false</code> stands for <i>no control</i>, <code>true</code> for
* <i>control</i>.<br>
* This method does not reset other item data or discard other translation items.
*
* @param control control direction
*/
public final void setControlBit(final boolean control)
{
if (control)
data[0] |= 0x02;
else
data[0] &= ~0x02;
}
/**
* Returns the control field of the first translation item.
* <p>
* A value of <code>false</code> stands for decrease / up, <code>true</code> for
* increase / down.
*
* @return control bit as boolean
*/
public final boolean getControlBit()
{
return control(0);
}
/**
* Sets the value field for the first translation item.
* <p>
* This method does not reset other item data or discard other translation items.
*
* @param value the value interpreted according to DPT 1.x
*/
public final void setValueBit(final boolean value)
{
if (value)
data[0] |= 0x01;
else
data[0] &= ~0x01;
}
/**
* Returns the value field of the first translation item.
*
* @return value field
*/
public final boolean getValueBit()
{
return value(0);
}
/**
* Returns the numeric representation of both control and value bit.
*
* @return one of the values 0, 1, 2, or 3
*/
@Override
public double getNumericValue() {
return data[0] & 0x03;
}
@Override
public void setData(final byte[] data, final int offset)
{
super.setData(data, offset);
// only keep the lower two bits
for (int i = 0; i < this.data.length; ++i)
this.data[i] = (short) (this.data[i] & 0x03);
}
@Override
public byte[] getData(final byte[] dst, final int offset)
{
final int end = Math.min(data.length, dst.length - offset);
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) (dst[offset + i] & 0xFC | data[i]);
return dst;
}
@Override
public final Map<String, DPT> getSubTypes()
{
return types;
}
/**
* @return the subtypes of the 3 Bit controlled translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map<String, DPT> getSubTypesStatic()
{
return types;
}
private boolean value(final int index)
{
return (data[index] & 0x01) == 0x01;
}
private boolean control(final int index)
{
return (data[index] & 0x02) != 0 ? true : false;
}
private String fromDPT(final int index)
{
final String ctrl = control(index) ? "1 " : "0 ";
final DPT val = ((DPT1BitControlled) dpt).getValueDPT();
return ctrl + (value(index) ? val.getUpperValue() : val.getLowerValue());
}
@Override
protected void toDPT(final String value, final short[] dst, final int index)
throws KNXFormatException
{
if (value.length() < 3)
throw newException("wrong value format", value);
final DPT val = ((DPT1BitControlled) dpt).getValueDPT();
final DPTXlatorBoolean x = new DPTXlatorBoolean(val);
x.setValue(value.substring(2));
int c = 0x0;
if (value.startsWith("1 "))
c = 0x2;
else if (!value.startsWith("0 "))
throw newException("invalid control bit", value);
dst[index] = (short) (c + (x.getValueBoolean() ? 1 : 0));
}
}
| gpl-2.0 |
meer1992/Tannoy-Ahoy | TannoyAhoy/app/src/main/java/com/uow/tannoyahoy/App.java | 331 | package com.uow.tannoyahoy;
import android.app.Application;
import android.content.Context;
/**
* Created by Pwnbot on 9/05/2015.
*/
public class App extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
} | gpl-2.0 |
diamonddevgroup/CodenameOne | Ports/JavaSE/src/com/codename1/impl/javase/fx/JavaFXSEPort.java | 52933 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.codename1.impl.javase.fx;
import com.codename1.impl.javase.AbstractBrowserWindowSE;
import com.codename1.impl.javase.BrowserWindowFactory;
import com.codename1.impl.javase.IBrowserComponent;
import com.codename1.impl.javase.JavaSEPort;
import static com.codename1.impl.javase.JavaSEPort.checkForPermission;
import static com.codename1.impl.javase.JavaSEPort.retinaScale;
import com.codename1.io.Log;
import com.codename1.media.AbstractMedia;
import com.codename1.media.AsyncMedia;
import com.codename1.media.Media;
import com.codename1.ui.Accessor;
import com.codename1.ui.BrowserComponent;
import com.codename1.ui.CN;
import com.codename1.ui.Component;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Graphics;
import com.codename1.ui.Label;
import com.codename1.ui.PeerComponent;
import com.codename1.util.AsyncResource;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.scene.web.WebView;
import javafx.util.Duration;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* @author shannah
*/
public class JavaFXSEPort extends JavaSEPort {
@Override
public void init(Object m) {
super.init(m);
try {
Class.forName("javafx.embed.swing.JFXPanel");
Platform.setImplicitExit(false);
fxExists = true;
} catch (Throwable ex) {
}
}
private static boolean isPlayable(String filename) {
try {
javafx.scene.media.Media media = new javafx.scene.media.Media(filename);
} catch (javafx.scene.media.MediaException e) {
if (e.getType() == javafx.scene.media.MediaException.Type.MEDIA_UNSUPPORTED) {
return false;
}
}
return true;
}
@Override
public AsyncResource<Media> createMediaAsync(String uriAddress, final boolean isVideo, final Runnable onCompletion) {
final AsyncResource<Media> out = new AsyncResource<Media>();
if(!checkForPermission("android.permission.READ_PHONE_STATE", "This is required to play media")){
out.error(new IOException("android.permission.READ_PHONE_STATE is required to play media"));
return out;
}
if(!checkForPermission("android.permission.WRITE_EXTERNAL_STORAGE", "This is required to play media")){
out.error(new IOException("android.permission.WRITE_EXTERNAL_STORAGE is required to play media"));
return out;
}
if(uriAddress.startsWith("file:")) {
uriAddress = unfile(uriAddress);
}
final String uri = uriAddress;
if (!fxExists) {
String msg = "This fetaure is supported from Java version 1.7.0_06, update your Java to enable this feature. This might fail on OpenJDK as well in which case you will need to install the Oracle JDK. ";
System.out.println(msg);
out.error(new IOException(msg));
return out;
}
java.awt.Container cnt = canvas.getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
out.error(new RuntimeException("Could not find canvas. Cannot create media"));
return out;
}
}
final java.awt.Container c = cnt;
//final Media[] media = new Media[1];
final Exception[] err = new Exception[1];
final javafx.embed.swing.JFXPanel m = new CN1JFXPanel();
//mediaContainer = m;
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
if (uri.indexOf(':') < 0 && uri.lastIndexOf('/') == 0) {
String mimeType = "video/mp4";
new CodenameOneMediaPlayer(getResourceAsStream(getClass(), uri), mimeType, (JFrame) c, m, onCompletion, out);
return;
}
new CodenameOneMediaPlayer(uri, isVideo, (JFrame) c, m, onCompletion, out);
} catch (Exception ex) {
out.error(ex);
}
}
});
return out;
}
/**
* Plays the sound in the given stream
*
* @param stream the stream containing the media data
* @param mimeType the type of the data in the stream
* @param onCompletion invoked when the audio file finishes playing, may be
* null
* @return a handle that can be used to control the playback of the audio
* @throws java.io.IOException if the URI access fails
*/
@Override
public AsyncResource<Media> createMediaAsync(final InputStream stream, final String mimeType, final Runnable onCompletion) {
final AsyncResource<Media> out = new AsyncResource<Media>();
if(!checkForPermission("android.permission.READ_PHONE_STATE", "This is required to play media")){
out.error(new IOException("android.permission.READ_PHONE_STATE is required to play media"));
return out;
}
if(!checkForPermission("android.permission.WRITE_EXTERNAL_STORAGE", "This is required to play media")){
out.error(new IOException("android.permission.WRITE_EXTERNAL_STORAGE is required to play media"));
return out;
}
if (!fxExists) {
String msg = "This fetaure is supported from Java version 1.7.0_06, update your Java to enable this feature. This might fail on OpenJDK as well in which case you will need to install the Oracle JDK. ";
//System.out.println(msg);
out.error(new IOException(msg));
return out;
}
java.awt.Container cnt = canvas.getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
return null;
}
}
final java.awt.Container c = cnt;
//final Media[] media = new Media[1];
//final Exception[] err = new Exception[1];
final javafx.embed.swing.JFXPanel m = new CN1JFXPanel();
//mediaContainer = m;
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
new CodenameOneMediaPlayer(stream, mimeType, (JFrame) c, m, onCompletion, out);
} catch (Exception ex) {
out.error(ex);
}
}
});
return out;
}
class CodenameOneMediaPlayer extends AbstractMedia {
private java.util.Timer endMediaPoller;
private Runnable onCompletion;
private List<Runnable> completionHandlers;
private javafx.scene.media.MediaPlayer player;
// private MediaPlayer player;
private boolean realized = false;
private boolean isVideo;
private javafx.embed.swing.JFXPanel videoPanel;
private JFrame frm;
private boolean playing = false;
private boolean nativePlayerMode;
private AsyncResource<Media> _callback;
/**
* This is a callback for the JavaFX media player that is supposed to fire
* when the media is paused. Unfortunately this is unreliable as the status
* events seem to stop working after the first time it is paused.
* We use a poller (the endMediaPoller timer) to track the status of the video
* so that the change listeners are fired. This really sucks!
*/
private Runnable onPaused = new Runnable() {
public void run() {
if (endMediaPoller != null) {
endMediaPoller.cancel();
endMediaPoller = null;
}
stopEndMediaPoller();
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
}
};
/**
* This is a callback for the JavaFX media player that is supposed to fire
* when the media is paused. Unfortunately this is unreliable as the status
* events seem to stop working after the first time it is paused.
* We use a poller (the endMediaPoller timer) to track the status of the video
* so that the change listeners are fired. This really sucks!
*/
private Runnable onPlaying = new Runnable() {
@Override
public void run() {
playing = true;
startEndMediaPoller();
fireMediaStateChange(AsyncMedia.State.Playing);
}
};
/**
* This is a callback for the JavaFX media player that is supposed to fire
* when the media is paused. Unfortunately this is unreliable as the status
* events seem to stop working after the first time it is paused.
* We use a poller (the endMediaPoller timer) to track the status of the video
* so that the change listeners are fired. This really sucks!
*/
private Runnable onError = new Runnable() {
public void run() {
if (_callback != null && !_callback.isDone()) {
_callback.error(player.errorProperty().get());
return;
} else {
Log.e(player.errorProperty().get());
}
fireMediaError(createMediaException(player.errorProperty().get()));
if (!playing) {
stopEndMediaPoller();
fireMediaStateChange(AsyncMedia.State.Playing);
fireMediaStateChange(AsyncMedia.State.Paused);
}
}
};
public CodenameOneMediaPlayer(String uri, boolean isVideo, JFrame f, javafx.embed.swing.JFXPanel fx, final Runnable onCompletion, final AsyncResource<Media> callback) throws IOException {
_callback = callback;
if (onCompletion != null) {
addCompletionHandler(onCompletion);
}
this.onCompletion = new Runnable() {
@Override
public void run() {
if (callback != null && !callback.isDone()) {
callback.complete(CodenameOneMediaPlayer.this);
}
stopEndMediaPoller();
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
fireCompletionHandlers();
}
};
this.isVideo = isVideo;
this.frm = f;
try {
if (uri.startsWith("file:")) {
uri = unfile(uri);
}
File fff = new File(uri);
if(fff.exists()) {
uri = fff.toURI().toURL().toExternalForm();
}
if (isVideo && !isPlayable(uri)) {
// JavaFX doesn't seem to support .mov files. But if you simply rename it
// to .mp4, then it will play it (if it is mpeg4).
// So this will improve .mov files from failing to 100% of the time
// to only half of the time (when it isn't an mp4)
File temp = File.createTempFile("mtmp", ".mp4");
temp.deleteOnExit();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[1024];
int len = 0;
InputStream stream = new URL(uri).openStream();
while ((len = stream.read(buf, 0, buf.length)) > -1) {
out.write(buf, 0, len);
}
stream.close();
uri = temp.toURI().toURL().toExternalForm();
}
player = new MediaPlayer(new javafx.scene.media.Media(uri));
player.setOnReady(new Runnable() {
public void run() {
if (callback != null && !callback.isDone()) {
callback.complete(CodenameOneMediaPlayer.this);
}
}
});
installFxCallbacks();
if (isVideo) {
videoPanel = fx;
}
} catch (Exception ex) {
if (callback != null && !callback.isDone()) {
callback.error(ex);
} else {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
private com.codename1.media.AsyncMedia.MediaException createMediaException(javafx.scene.media.MediaException ex) {
AsyncMedia.MediaErrorType type;
switch (ex.getType()) {
case MEDIA_CORRUPTED:
type = AsyncMedia.MediaErrorType.Decode;
break;
case MEDIA_INACCESSIBLE:
case MEDIA_UNAVAILABLE:
type = AsyncMedia.MediaErrorType.Network;
break;
case MEDIA_UNSUPPORTED:
type = AsyncMedia.MediaErrorType.SrcNotSupported;
break;
case MEDIA_UNSPECIFIED:
type = AsyncMedia.MediaErrorType.Unknown;
break;
case OPERATION_UNSUPPORTED:
type = AsyncMedia.MediaErrorType.SrcNotSupported;
break;
case PLAYBACK_ERROR:
type = AsyncMedia.MediaErrorType.Decode;
break;
case PLAYBACK_HALTED:
type = AsyncMedia.MediaErrorType.Aborted;
break;
//case UNKNOWN:
default:
type = AsyncMedia.MediaErrorType.Unknown;
break;
}
return new com.codename1.media.AsyncMedia.MediaException(type, ex);
}
/**
* This starts a timer which checks the status of media every Xms so that it can fire
* status change events and on completion events. The JavaFX media player has onPlaying,
* onPaused, etc.. status events of its own that seem to not work in many cases, so we
* need to use this timer to poll for the status. That really sucks!!
*/
private void startEndMediaPoller() {
stopEndMediaPoller();
endMediaPoller = new java.util.Timer();
endMediaPoller.schedule(new TimerTask() {
@Override
public void run() {
// Check if the media is playing but we haven't updated our status.
// If so, we change our status to playing, and fire a state change event.
if (!playing && player.getStatus() == MediaPlayer.Status.PLAYING) {
Platform.runLater(new Runnable() {
// State tracking on the fx thread to avoid race conditions.
public void run() {
if (!playing && player.getStatus() == MediaPlayer.Status.PLAYING) {
playing = true;
fireMediaStateChange(AsyncMedia.State.Playing);
}
}
});
} else if (playing && player.getStatus() != MediaPlayer.Status.PLAYING) {
stopEndMediaPoller();
Platform.runLater(new Runnable() {
public void run() {
if (playing && player.getStatus() != MediaPlayer.Status.PLAYING) {
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
}
}
});
}
double diff = player.getTotalDuration().toMillis() - player.getCurrentTime().toMillis();
if (playing && diff < 0.01) {
Platform.runLater(new Runnable() {
public void run() {
double diff = player.getTotalDuration().toMillis() - player.getCurrentTime().toMillis();
if (playing && diff < 0.01) {
Runnable completionCallback = CodenameOneMediaPlayer.this.onCompletion;
if (completionCallback != null) {
completionCallback.run();
}
}
}
});
}
}
}, 100, 100);
}
/**
* Stop the media state poller. This is called when the media is paused.
*/
private void stopEndMediaPoller() {
if (endMediaPoller != null) {
endMediaPoller.cancel();
endMediaPoller = null;
}
}
public CodenameOneMediaPlayer(InputStream stream, String mimeType, JFrame f, javafx.embed.swing.JFXPanel fx, final Runnable onCompletion, final AsyncResource<Media> callback) throws IOException {
String suffix = guessSuffixForMimetype(mimeType);
File temp = File.createTempFile("mtmp", suffix);
temp.deleteOnExit();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[1024];
int len = 0;
while ((len = stream.read(buf, 0, buf.length)) > -1) {
out.write(buf, 0, len);
}
stream.close();
if (onCompletion != null) {
addCompletionHandler(onCompletion);
}
this.onCompletion = new Runnable() {
@Override
public void run() {
if (callback != null && !callback.isDone()) {
callback.complete(CodenameOneMediaPlayer.this);
}
stopEndMediaPoller();
playing = false;
fireMediaStateChange(AsyncMedia.State.Paused);
fireCompletionHandlers();
}
};
this.isVideo = mimeType.contains("video");
this.frm = f;
try {
player = new MediaPlayer(new javafx.scene.media.Media(temp.toURI().toString()));
player.setOnReady(new Runnable() {
public void run() {
if (callback != null) {
callback.complete(CodenameOneMediaPlayer.this);
}
}
});
installFxCallbacks();
if (isVideo) {
videoPanel = fx;
}
} catch (Exception ex) {
if (callback != null) {
callback.error(ex);
} else {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
private void fireCompletionHandlers() {
if (completionHandlers != null && !completionHandlers.isEmpty()) {
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
if (completionHandlers != null && !completionHandlers.isEmpty()) {
List<Runnable> toRun;
synchronized(CodenameOneMediaPlayer.this) {
toRun = new ArrayList<Runnable>(completionHandlers);
}
for (Runnable r : toRun) {
r.run();
}
}
}
});
}
}
public void addCompletionHandler(Runnable onCompletion) {
synchronized(this) {
if (completionHandlers == null) {
completionHandlers = new ArrayList<Runnable>();
}
completionHandlers.add(onCompletion);
}
}
public void removeCompletionHandler(Runnable onCompletion) {
if (completionHandlers != null) {
synchronized(this) {
completionHandlers.remove(onCompletion);
}
}
}
public void cleanup() {
pause();
}
public void prepare() {
}
@Override
protected void playImpl() {
if (isVideo && nativePlayerMode) {
// To simulate native player mode, we will show a form with the player.
final Form currForm = Display.getInstance().getCurrent();
Form playerForm = new Form("Video Player", new com.codename1.ui.layouts.BorderLayout()) {
@Override
protected void onShow() {
Platform.runLater(new Runnable() {
public void run() {
playInternal();
}
});
}
};
com.codename1.ui.Toolbar tb = new com.codename1.ui.Toolbar();
playerForm.setToolbar(tb);
tb.setBackCommand("Back", new com.codename1.ui.events.ActionListener<com.codename1.ui.events.ActionEvent>() {
public void actionPerformed(com.codename1.ui.events.ActionEvent e) {
pauseInternal();
currForm.showBack();
}
});
Component videoComponent = getVideoComponent();
if (videoComponent.getComponentForm() != null) {
videoComponent.remove();
}
playerForm.addComponent(com.codename1.ui.layouts.BorderLayout.CENTER, videoComponent);
playerForm.show();
return;
}
playInternal();
}
private void playInternal() {
installFxCallbacks();
player.play();
startEndMediaPoller();
}
private void pauseInternal() {
player.pause();
}
/**
* Installs listeners for the javafx media player. Unfortunately these are
* incredibly unreliable. onPlaying only first the first time it plays. OnPaused
* also stops firing after the first pause. onEndOfMedia sometimes fires but not
* other times. We use the endOfMediaPoller timer as a backup to test for status
* changes.
*/
private void installFxCallbacks() {
player.setOnPlaying(onPlaying);
player.setOnPaused(onPaused);
player.setOnError(onError);
player.setOnEndOfMedia(onCompletion);
}
@Override
protected void pauseImpl() {
if(player.getStatus() == Status.PLAYING) {
pauseInternal();
}
//playing = false;
}
public int getTime() {
return (int) player.getCurrentTime().toMillis();
}
public void setTime(final int time) {
player.seek(new Duration(time));
}
public int getDuration() {
int d = (int) player.getStopTime().toMillis();
if(d == 0){
return -1;
}
return d;
}
public void setVolume(int vol) {
player.setVolume(((double) vol / 100d));
}
public int getVolume() {
return (int) player.getVolume() * 100;
}
@Override
public Component getVideoComponent() {
if (!isVideo) {
return new Label();
}
if (videoPanel != null) {
final Component[] retVal = new Component[1];
Platform.runLater(new Runnable() {
@Override
public void run() {
retVal[0] = new VideoComponent(frm, videoPanel, player);
}
});
Display.getInstance().invokeAndBlock(new Runnable() {
@Override
public void run() {
while (retVal[0] == null) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
return retVal[0];
}
System.out.println("Video Playing is not supported on this platform");
Label l = new Label("Video");
l.getStyle().setAlignment(Component.CENTER);
return l;
}
public boolean isVideo() {
return isVideo;
}
public boolean isFullScreen() {
return false;
}
public void setFullScreen(boolean fullScreen) {
}
@Override
public boolean isPlaying() {
return playing;
}
@Override
public void setNativePlayerMode(boolean nativePlayer) {
nativePlayerMode = nativePlayer;
}
@Override
public boolean isNativePlayerMode() {
return nativePlayerMode;
}
public void setVariable(String key, Object value) {
}
public Object getVariable(String key) {
return null;
}
}
@Override
public void addCompletionHandler(Media media, Runnable onCompletion) {
super.addCompletionHandler(media, onCompletion);
if (media instanceof CodenameOneMediaPlayer) {
((CodenameOneMediaPlayer)media).addCompletionHandler(onCompletion);
}
}
@Override
public void removeCompletionHandler(Media media, Runnable onCompletion) {
super.removeCompletionHandler(media, onCompletion);
if (media instanceof CodenameOneMediaPlayer) {
((CodenameOneMediaPlayer)media).removeCompletionHandler(onCompletion);
}
}
/**
* Video peer component.
*
* In contrast to the BrowserComponent and Peer (other peer components),
* the native peer supports hi-resolution retina displays. This was possible
* on this component, but no browser component, or other components in general
* because videos don't need to respond to pointer events. Thus the rendered
* dimensions and location (on the CN1 pipeline) may be different the size and
* position of the actual component on the screen (even though in all cases
* we hide the actual component).
*/
class VideoComponent extends PeerComponent {
private javafx.embed.swing.JFXPanel vid;
private JFrame frm;
// Container that holds the video
private JPanel cnt = new JPanel();
private MediaView v;
private boolean init = false;
private Rectangle bounds = new Rectangle();
// AWT paints to this buffered image
// CN1 reads from the buffered image to paint in its own pipeline.
BufferedImage buf;
// Gets the buffered image that AWT paints to and CN1 reads from
private BufferedImage getBuffer() {
if (buf == null || buf.getWidth() != cnt.getWidth() || buf.getHeight() != cnt.getHeight()) {
buf = new BufferedImage((int)(cnt.getWidth()), (int)(cnt.getHeight()), BufferedImage.TYPE_INT_ARGB);
}
return buf;
}
/**
* Paints the native component to the buffer
*/
private void paintOnBuffer() {
// We need to synchronize on the peer component
// drawNativePeer will also synchronize on this
// This prevents simulataneous reads and writes to/from the
// buffered image.
if (EventQueue.isDispatchThread()) {
// Only run this on the AWT event dispatch thread
// to avoid deadlocks
synchronized(VideoComponent.this) {
paintOnBufferImpl();
}
} else if (!Display.getInstance().isEdt()){
// I can only imagine bad things
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
paintOnBuffer();
}
});
} catch (Throwable t) {
t.printStackTrace();
}
}
}
private void paintOnBufferImpl() {
final BufferedImage buf = getBuffer();
Graphics2D g2d = buf.createGraphics();
AffineTransform t = g2d.getTransform();
double tx = t.getTranslateX();
double ty = t.getTranslateY();
vid.paint(g2d);
g2d.dispose();
VideoComponent.this.putClientProperty("__buffer", buf);
}
public VideoComponent(JFrame frm, final javafx.embed.swing.JFXPanel vid, javafx.scene.media.MediaPlayer player) {
super(null);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cnt = new JPanel() {
@Override
public void paint(java.awt.Graphics g) {
paintOnBuffer();
// After we paint to the buffer we need to
// tell CN1 to paint the buffer to its pipeline.
Display.getInstance().callSerially(new Runnable() {
public void run() {
VideoComponent.this.repaint();
}
});
}
@Override
protected void paintChildren(java.awt.Graphics g) {
// Not sure if this is necessary
// but we don't want any painting to occur
// on regular pipeline
}
@Override
protected void paintBorder(java.awt.Graphics g) {
// Not sure if this is necessary but we don't
// want any painting to occur on regular pipeline
}
};
cnt.setOpaque(false);
vid.setOpaque(false);
cnt.setLayout(new BorderLayout());
cnt.add(BorderLayout.CENTER, vid);
cnt.setVisible(false);
}
});
Group root = new Group();
v = new MediaView(player);
final Runnable oldOnReady = player.getOnPlaying();
player.setOnPlaying(new Runnable() {
public void run() {
if (oldOnReady != null) oldOnReady.run();
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (VideoComponent.this.getParent() != null) {
VideoComponent.this.getParent().revalidate();
}
}
});
}
});
root.getChildren().add(v);
vid.setScene(new Scene(root));
this.vid = vid;
this.frm = frm;
}
@Override
protected void initComponent() {
bounds.setBounds(0,0,0,0);
super.initComponent();
}
@Override
protected void deinitialize() {
super.deinitialize();
if (testRecorder != null) {
testRecorder.dispose();
testRecorder = null;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
vid.setScene(null);
vid.removeAll();
cnt.remove(vid);
frm.remove(cnt);
frm.repaint();
//mediaContainer = null;
}
});
}
protected void setLightweightMode(final boolean l) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!l) {
if (!init) {
init = true;
cnt.setVisible(true);
frm.add(cnt, 0);
frm.repaint();
} else {
cnt.setVisible(false);
}
} else {
if (init) {
cnt.setVisible(false);
}
}
}
});
}
@Override
protected com.codename1.ui.geom.Dimension calcPreferredSize() {
com.codename1.ui.geom.Dimension out = new com.codename1.ui.geom.Dimension((int)(vid.getPreferredSize().width), (int)(vid.getPreferredSize().height));
return out;
}
@Override
public void paint(final Graphics g) {
if (init) {
onPositionSizeChange();
drawNativePeer(Accessor.getNativeGraphics(g), this, cnt);
EventQueue.invokeLater(new Runnable() {
public void run() {
paintOnBuffer();
}
});
}else{
if(getComponentForm() != null && getComponentForm() == getCurrentForm()){
setLightweightMode(false);
}
}
}
@Override
protected void onPositionSizeChange() {
final int x = getAbsoluteX();
final int y = getAbsoluteY();
final int w = getWidth();
final int h = getHeight();
int screenX = 0;
int screenY = 0;
if(getScreenCoordinates() != null) {
screenX = getScreenCoordinates().x;
screenY = getScreenCoordinates().y;
}
// NOTE: For the VideoComponent we make the size the actual
// pixel size of the light-weight peer even though, on retina,
// this means that the native component is twice the height and
// width of the native peer. We can do this here because
// the video component doesn't have any interactivity
// that constrains us to keep the same real position on the screen
// as our render position is. THis is not the case for WebBrowser
//
bounds.setBounds((int) ((x + screenX + canvas.x)),
(int) ((y + screenY + canvas.y)),
(int) (w),
(int) (h));
if(!bounds.equals(cnt.getBounds())){
Platform.runLater(new Runnable() {
@Override
public void run() {
v.setFitWidth(w );
v.setFitHeight(h);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cnt.setBounds(bounds);
cnt.doLayout();
paintOnBuffer();
}
});
}
});
}
}
}
public PeerComponent createFXBrowserComponent(final Object parent) {
java.awt.Container cnt = canvas.getParent();
while (!(cnt instanceof JFrame)) {
cnt = cnt.getParent();
if (cnt == null) {
return null;
}
}
final java.awt.Container c = cnt;
final Exception[] err = new Exception[1];
final javafx.embed.swing.JFXPanel webContainer = new CN1JFXPanel();
final SEBrowserComponent[] bc = new SEBrowserComponent[1];
final SEBrowserComponent bcc = new SEBrowserComponent();
Platform.setImplicitExit(false);
Platform.runLater(new Runnable() {
@Override
public void run() {
StackPane root = new StackPane();
final WebView webView = new WebView();
root.getChildren().add(webView);
webContainer.setScene(new Scene(root));
// now wait for the Swing side to finish initializing f'ing JavaFX is so broken its unbeliveable
JPanel parentPanel = ((JPanel)canvas.getParent());
bcc.SEBrowserComponent_init(
JavaFXSEPort.this,
parentPanel,
webContainer,
webView,
(BrowserComponent) parent,
hSelector,
vSelector
);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bc[0] = bcc;
synchronized (bc) {
bc.notify();
}
}
});
}
});
if (bc[0] == null && err[0] == null) {
Display.getInstance().invokeAndBlock(new Runnable() {
@Override
public void run() {
synchronized (bc) {
while (bc[0] == null && err[0] == null) {
try {
bc.wait(20);
} catch (InterruptedException ex) {
}
}
}
}
});
}
return bc[0];
}private void browserExposeInJavaScriptImpl(final PeerComponent browserPeer, final Object o, final String name) {
((IBrowserComponent) browserPeer).exposeInJavaScript(o, name);
}
public void browserExposeInJavaScript(final PeerComponent browserPeer, final Object o, final String name) {
if (!(browserPeer instanceof SEBrowserComponent)) {
return;
}
if (Platform.isFxApplicationThread()) {
browserExposeInJavaScriptImpl(browserPeer, o, name);
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
browserExposeInJavaScriptImpl(browserPeer, o, name);
}
});
}
public PeerComponent createBrowserComponent(final Object parent) {
boolean useWKWebView = "true".equals(Display.getInstance().getProperty("BrowserComponent.useWKWebView", "false"));
if (useWKWebView) {
if (!useWKWebViewChecked) {
useWKWebViewChecked = true;
Map<String, String> m = Display.getInstance().getProjectBuildHints();
if(m != null) {
if(!m.containsKey("ios.useWKWebView")) {
Display.getInstance().setProjectBuildHint("ios.useWKWebView", "true");
}
}
}
}
return createFXBrowserComponent(parent);
}
public boolean isNativeBrowserComponentSupported() {
return fxExists && !blockNativeBrowser;
//return false;
}
class CN1JFXPanel extends javafx.embed.swing.JFXPanel {
@Override
public void revalidate() {
// We need to override this with an empty implementation to workaround
// Deadlock bug http://bugs.java.com/view_bug.do?bug_id=8058870
// If we allow the default implementation, then it will periodically deadlock
// when displaying a browser component
}
@Override
protected void processMouseEvent(MouseEvent e) {
//super.processMouseEvent(e); //To change body of generated methods, choose Tools | Templates.
if (!sendToCn1(e)) {
super.processMouseEvent(e);
}
}
@Override
protected void processMouseMotionEvent(MouseEvent e) {
if (!sendToCn1(e)) {
super.processMouseMotionEvent(e); //To change body of generated methods, choose Tools | Templates.
}
}
@Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (!sendToCn1(e)) {
super.processMouseWheelEvent(e); //To change body of generated methods, choose Tools | Templates.
}
}
private boolean peerGrabbedDrag=false;
private boolean sendToCn1(MouseEvent e) {
int cn1X = getCN1X(e);
int cn1Y = getCN1Y(e);
if ((!peerGrabbedDrag || true) && Display.isInitialized()) {
Form f = Display.getInstance().getCurrent();
if (f != null) {
Component cmp = f.getComponentAt(cn1X, cn1Y);
//if (!(cmp instanceof PeerComponent) || cn1GrabbedDrag) {
// It's not a peer component, so we should pass the event to the canvas
e = SwingUtilities.convertMouseEvent(this, e, canvas);
switch (e.getID()) {
case MouseEvent.MOUSE_CLICKED:
canvas.mouseClicked(e);
break;
case MouseEvent.MOUSE_DRAGGED:
canvas.mouseDragged(e);
break;
case MouseEvent.MOUSE_MOVED:
canvas.mouseMoved(e);
break;
case MouseEvent.MOUSE_PRESSED:
// Mouse pressed in native component - passed to lightweight cmp
if (!(cmp instanceof PeerComponent)) {
cn1GrabbedDrag = true;
}
canvas.mousePressed(e);
break;
case MouseEvent.MOUSE_RELEASED:
cn1GrabbedDrag = false;
canvas.mouseReleased(e);
break;
case MouseEvent.MOUSE_WHEEL:
canvas.mouseWheelMoved((MouseWheelEvent)e);
break;
}
//return true;
if (cn1GrabbedDrag) {
return true;
}
if (cmp instanceof PeerComponent) {
return false;
}
return true;
//}
}
}
if (e.getID() == MouseEvent.MOUSE_RELEASED) {
cn1GrabbedDrag = false;
peerGrabbedDrag = false;
} else if (e.getID() == MouseEvent.MOUSE_PRESSED) {
peerGrabbedDrag = true;
}
return false;
}
private int getCN1X(MouseEvent e) {
if (canvas == null) {
int out = e.getXOnScreen();
if (out == 0) {
// For some reason the web browser would return 0 for screen coordinates
// but would still have correct values for getX() and getY() when
// dealing with mouse wheel events. In these cases we need to
// get the screen coordinate from the component
// and add it to the relative coordinate.
out = e.getX(); // In some cases absX is set to zero for mouse wheel events
Object source = e.getSource();
if (source instanceof java.awt.Component) {
Point pt = ((java.awt.Component)source).getLocationOnScreen();
out += pt.x;
}
}
return out;
}
java.awt.Rectangle screenCoords = getScreenCoordinates();
if (screenCoords == null) {
screenCoords = new java.awt.Rectangle(0, 0, 0, 0);
}
int x = e.getXOnScreen();
if (x == 0) {
// For some reason the web browser would return 0 for screen coordinates
// but would still have correct values for getX() and getY() when
// dealing with mouse wheel events. In these cases we need to
// get the screen coordinate from the component
// and add it to the relative coordinate.
x = e.getX();
Object source = e.getSource();
if (source instanceof java.awt.Component) {
Point pt = ((java.awt.Component)source).getLocationOnScreen();
x += pt.x;
}
}
return (int)((x - canvas.getLocationOnScreen().x - (canvas.x + screenCoords.x) * zoomLevel / retinaScale) / zoomLevel * retinaScale);
}
private int getCN1Y(MouseEvent e) {
if (canvas == null) {
int out = e.getYOnScreen();
if (out == 0) {
// For some reason the web browser would return 0 for screen coordinates
// but would still have correct values for getX() and getY() when
// dealing with mouse wheel events. In these cases we need to
// get the screen coordinate from the component
// and add it to the relative coordinate.
out = e.getY();
Object source = e.getSource();
if (source instanceof java.awt.Component) {
Point pt = ((java.awt.Component)source).getLocationOnScreen();
out += pt.y;
}
}
return out;
}
java.awt.Rectangle screenCoords = getScreenCoordinates();
if (screenCoords == null) {
screenCoords = new java.awt.Rectangle(0, 0, 0, 0);
}
int y = e.getYOnScreen();
if (y == 0) {
// For some reason the web browser would return 0 for screen coordinates
// but would still have correct values for getX() and getY() when
// dealing with mouse wheel events. In these cases we need to
// get the screen coordinate from the component
// and add it to the relative coordinate.
y = e.getY();
Object source = e.getSource();
if (source instanceof java.awt.Component) {
Point pt = ((java.awt.Component)source).getLocationOnScreen();
y += pt.y;
}
}
return (int)((y - canvas.getLocationOnScreen().y - (canvas.y + screenCoords.y) * zoomLevel / retinaScale) / zoomLevel * retinaScale);
}
public CN1JFXPanel() {
final CN1JFXPanel panel = this;
/*
panel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
sendToCn1(e);
}
@Override
public void mousePressed(MouseEvent e) {
sendToCn1(e);
}
@Override
public void mouseReleased(MouseEvent e) {
sendToCn1(e);
}
@Override
public void mouseEntered(MouseEvent e) {
//SEBrowserComponent.this.instance.canvas.mouseE
}
@Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
sendToCn1(e);
}
@Override
public void mouseMoved(MouseEvent e) {
sendToCn1(e);
}
});
panel.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
sendToCn1(e);
}
});
*/
}
}
protected BrowserWindowFactory createBrowserWindowFactory() {
return new BrowserWindowFactory() {
@Override
public AbstractBrowserWindowSE createBrowserWindow(String startURL) {
return new FXBrowserWindowSE(startURL);
}
};
}
}
| gpl-2.0 |
nextcloud/android | src/main/java/com/owncloud/android/utils/ScreenshotTest.java | 1228 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.utils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate any screenshot test with this so it is run only when updating/testing screenshots
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ScreenshotTest {
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/javax/swing/plaf/basic/BasicListUI.java | 108075 | /*
* Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.plaf.basic;
import sun.swing.DefaultLookup;
import sun.swing.UIAction;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.text.Position;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.Transferable;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import sun.swing.SwingUtilities2;
import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag;
/**
* An extensible implementation of {@code ListUI}.
* <p>
* {@code BasicListUI} instances cannot be shared between multiple
* lists.
*
* @author Hans Muller
* @author Philip Milne
* @author Shannon Hickey (drag and drop)
*/
public class BasicListUI extends ListUI
{
private static final StringBuilder BASELINE_COMPONENT_KEY =
new StringBuilder("List.baselineComponent");
protected JList list = null;
protected CellRendererPane rendererPane;
// Listeners that this UI attaches to the JList
protected FocusListener focusListener;
protected MouseInputListener mouseInputListener;
protected ListSelectionListener listSelectionListener;
protected ListDataListener listDataListener;
protected PropertyChangeListener propertyChangeListener;
private Handler handler;
protected int[] cellHeights = null;
protected int cellHeight = -1;
protected int cellWidth = -1;
protected int updateLayoutStateNeeded = modelChanged;
/**
* Height of the list. When asked to paint, if the current size of
* the list differs, this will update the layout state.
*/
private int listHeight;
/**
* Width of the list. When asked to paint, if the current size of
* the list differs, this will update the layout state.
*/
private int listWidth;
/**
* The layout orientation of the list.
*/
private int layoutOrientation;
// Following ivars are used if the list is laying out horizontally
/**
* Number of columns to create.
*/
private int columnCount;
/**
* Preferred height to make the list, this is only used if the
* the list is layed out horizontally.
*/
private int preferredHeight;
/**
* Number of rows per column. This is only used if the row height is
* fixed.
*/
private int rowsPerColumn;
/**
* The time factor to treate the series of typed alphanumeric key
* as prefix for first letter navigation.
*/
private long timeFactor = 1000L;
/**
* Local cache of JList's client property "List.isFileList"
*/
private boolean isFileList = false;
/**
* Local cache of JList's component orientation property
*/
private boolean isLeftToRight = true;
/* The bits below define JList property changes that affect layout.
* When one of these properties changes we set a bit in
* updateLayoutStateNeeded. The change is dealt with lazily, see
* maybeUpdateLayoutState. Changes to the JLists model, e.g. the
* models length changed, are handled similarly, see DataListener.
*/
protected final static int modelChanged = 1 << 0;
protected final static int selectionModelChanged = 1 << 1;
protected final static int fontChanged = 1 << 2;
protected final static int fixedCellWidthChanged = 1 << 3;
protected final static int fixedCellHeightChanged = 1 << 4;
protected final static int prototypeCellValueChanged = 1 << 5;
protected final static int cellRendererChanged = 1 << 6;
private final static int layoutOrientationChanged = 1 << 7;
private final static int heightChanged = 1 << 8;
private final static int widthChanged = 1 << 9;
private final static int componentOrientationChanged = 1 << 10;
private static final int DROP_LINE_THICKNESS = 2;
static void loadActionMap(LazyActionMap map) {
map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN));
map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN_EXTEND));
map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_NEXT_COLUMN));
map.put(new Actions(Actions.SELECT_NEXT_COLUMN_EXTEND));
map.put(new Actions(Actions.SELECT_NEXT_COLUMN_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_PREVIOUS_ROW));
map.put(new Actions(Actions.SELECT_PREVIOUS_ROW_EXTEND));
map.put(new Actions(Actions.SELECT_PREVIOUS_ROW_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_NEXT_ROW));
map.put(new Actions(Actions.SELECT_NEXT_ROW_EXTEND));
map.put(new Actions(Actions.SELECT_NEXT_ROW_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_FIRST_ROW));
map.put(new Actions(Actions.SELECT_FIRST_ROW_EXTEND));
map.put(new Actions(Actions.SELECT_FIRST_ROW_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_LAST_ROW));
map.put(new Actions(Actions.SELECT_LAST_ROW_EXTEND));
map.put(new Actions(Actions.SELECT_LAST_ROW_CHANGE_LEAD));
map.put(new Actions(Actions.SCROLL_UP));
map.put(new Actions(Actions.SCROLL_UP_EXTEND));
map.put(new Actions(Actions.SCROLL_UP_CHANGE_LEAD));
map.put(new Actions(Actions.SCROLL_DOWN));
map.put(new Actions(Actions.SCROLL_DOWN_EXTEND));
map.put(new Actions(Actions.SCROLL_DOWN_CHANGE_LEAD));
map.put(new Actions(Actions.SELECT_ALL));
map.put(new Actions(Actions.CLEAR_SELECTION));
map.put(new Actions(Actions.ADD_TO_SELECTION));
map.put(new Actions(Actions.TOGGLE_AND_ANCHOR));
map.put(new Actions(Actions.EXTEND_TO));
map.put(new Actions(Actions.MOVE_SELECTION_TO));
map.put(TransferHandler.getCutAction().getValue(Action.NAME),
TransferHandler.getCutAction());
map.put(TransferHandler.getCopyAction().getValue(Action.NAME),
TransferHandler.getCopyAction());
map.put(TransferHandler.getPasteAction().getValue(Action.NAME),
TransferHandler.getPasteAction());
}
/**
* Paint one List cell: compute the relevant state, get the "rubber stamp"
* cell renderer component, and then use the CellRendererPane to paint it.
* Subclasses may want to override this method rather than paint().
*
* @see #paint
*/
protected void paintCell(
Graphics g,
int row,
Rectangle rowBounds,
ListCellRenderer cellRenderer,
ListModel dataModel,
ListSelectionModel selModel,
int leadIndex)
{
Object value = dataModel.getElementAt(row);
boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
boolean isSelected = selModel.isSelectedIndex(row);
Component rendererComponent =
cellRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus);
int cx = rowBounds.x;
int cy = rowBounds.y;
int cw = rowBounds.width;
int ch = rowBounds.height;
if (isFileList) {
// Shrink renderer to preferred size. This is mostly used on Windows
// where selection is only shown around the file name, instead of
// across the whole list cell.
int w = Math.min(cw, rendererComponent.getPreferredSize().width + 4);
if (!isLeftToRight) {
cx += (cw - w);
}
cw = w;
}
rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch, true);
}
/**
* Paint the rows that intersect the Graphics objects clipRect. This
* method calls paintCell as necessary. Subclasses
* may want to override these methods.
*
* @see #paintCell
*/
public void paint(Graphics g, JComponent c) {
Shape clip = g.getClip();
paintImpl(g, c);
g.setClip(clip);
paintDropLine(g);
}
private void paintImpl(Graphics g, JComponent c)
{
switch (layoutOrientation) {
case JList.VERTICAL_WRAP:
if (list.getHeight() != listHeight) {
updateLayoutStateNeeded |= heightChanged;
redrawList();
}
break;
case JList.HORIZONTAL_WRAP:
if (list.getWidth() != listWidth) {
updateLayoutStateNeeded |= widthChanged;
redrawList();
}
break;
default:
break;
}
maybeUpdateLayoutState();
ListCellRenderer renderer = list.getCellRenderer();
ListModel dataModel = list.getModel();
ListSelectionModel selModel = list.getSelectionModel();
int size;
if ((renderer == null) || (size = dataModel.getSize()) == 0) {
return;
}
// Determine how many columns we need to paint
Rectangle paintBounds = g.getClipBounds();
int startColumn, endColumn;
if (c.getComponentOrientation().isLeftToRight()) {
startColumn = convertLocationToColumn(paintBounds.x,
paintBounds.y);
endColumn = convertLocationToColumn(paintBounds.x +
paintBounds.width,
paintBounds.y);
} else {
startColumn = convertLocationToColumn(paintBounds.x +
paintBounds.width,
paintBounds.y);
endColumn = convertLocationToColumn(paintBounds.x,
paintBounds.y);
}
int maxY = paintBounds.y + paintBounds.height;
int leadIndex = adjustIndex(list.getLeadSelectionIndex(), list);
int rowIncrement = (layoutOrientation == JList.HORIZONTAL_WRAP) ?
columnCount : 1;
for (int colCounter = startColumn; colCounter <= endColumn;
colCounter++) {
// And then how many rows in this columnn
int row = convertLocationToRowInColumn(paintBounds.y, colCounter);
int rowCount = getRowCount(colCounter);
int index = getModelIndex(colCounter, row);
Rectangle rowBounds = getCellBounds(list, index, index);
if (rowBounds == null) {
// Not valid, bail!
return;
}
while (row < rowCount && rowBounds.y < maxY &&
index < size) {
rowBounds.height = getHeight(colCounter, row);
g.setClip(rowBounds.x, rowBounds.y, rowBounds.width,
rowBounds.height);
g.clipRect(paintBounds.x, paintBounds.y, paintBounds.width,
paintBounds.height);
paintCell(g, index, rowBounds, renderer, dataModel, selModel,
leadIndex);
rowBounds.y += rowBounds.height;
index += rowIncrement;
row++;
}
}
// Empty out the renderer pane, allowing renderers to be gc'ed.
rendererPane.removeAll();
}
private void paintDropLine(Graphics g) {
JList.DropLocation loc = list.getDropLocation();
if (loc == null || !loc.isInsert()) {
return;
}
Color c = DefaultLookup.getColor(list, this, "List.dropLineColor", null);
if (c != null) {
g.setColor(c);
Rectangle rect = getDropLineRect(loc);
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
}
private Rectangle getDropLineRect(JList.DropLocation loc) {
int size = list.getModel().getSize();
if (size == 0) {
Insets insets = list.getInsets();
if (layoutOrientation == JList.HORIZONTAL_WRAP) {
if (isLeftToRight) {
return new Rectangle(insets.left, insets.top, DROP_LINE_THICKNESS, 20);
} else {
return new Rectangle(list.getWidth() - DROP_LINE_THICKNESS - insets.right,
insets.top, DROP_LINE_THICKNESS, 20);
}
} else {
return new Rectangle(insets.left, insets.top,
list.getWidth() - insets.left - insets.right,
DROP_LINE_THICKNESS);
}
}
Rectangle rect = null;
int index = loc.getIndex();
boolean decr = false;
if (layoutOrientation == JList.HORIZONTAL_WRAP) {
if (index == size) {
decr = true;
} else if (index != 0 && convertModelToRow(index)
!= convertModelToRow(index - 1)) {
Rectangle prev = getCellBounds(list, index - 1);
Rectangle me = getCellBounds(list, index);
Point p = loc.getDropPoint();
if (isLeftToRight) {
decr = Point2D.distance(prev.x + prev.width,
prev.y + (int)(prev.height / 2.0),
p.x, p.y)
< Point2D.distance(me.x,
me.y + (int)(me.height / 2.0),
p.x, p.y);
} else {
decr = Point2D.distance(prev.x,
prev.y + (int)(prev.height / 2.0),
p.x, p.y)
< Point2D.distance(me.x + me.width,
me.y + (int)(prev.height / 2.0),
p.x, p.y);
}
}
if (decr) {
index--;
rect = getCellBounds(list, index);
if (isLeftToRight) {
rect.x += rect.width;
} else {
rect.x -= DROP_LINE_THICKNESS;
}
} else {
rect = getCellBounds(list, index);
if (!isLeftToRight) {
rect.x += rect.width - DROP_LINE_THICKNESS;
}
}
if (rect.x >= list.getWidth()) {
rect.x = list.getWidth() - DROP_LINE_THICKNESS;
} else if (rect.x < 0) {
rect.x = 0;
}
rect.width = DROP_LINE_THICKNESS;
} else if (layoutOrientation == JList.VERTICAL_WRAP) {
if (index == size) {
index--;
rect = getCellBounds(list, index);
rect.y += rect.height;
} else if (index != 0 && convertModelToColumn(index)
!= convertModelToColumn(index - 1)) {
Rectangle prev = getCellBounds(list, index - 1);
Rectangle me = getCellBounds(list, index);
Point p = loc.getDropPoint();
if (Point2D.distance(prev.x + (int)(prev.width / 2.0),
prev.y + prev.height,
p.x, p.y)
< Point2D.distance(me.x + (int)(me.width / 2.0),
me.y,
p.x, p.y)) {
index--;
rect = getCellBounds(list, index);
rect.y += rect.height;
} else {
rect = getCellBounds(list, index);
}
} else {
rect = getCellBounds(list, index);
}
if (rect.y >= list.getHeight()) {
rect.y = list.getHeight() - DROP_LINE_THICKNESS;
}
rect.height = DROP_LINE_THICKNESS;
} else {
if (index == size) {
index--;
rect = getCellBounds(list, index);
rect.y += rect.height;
} else {
rect = getCellBounds(list, index);
}
if (rect.y >= list.getHeight()) {
rect.y = list.getHeight() - DROP_LINE_THICKNESS;
}
rect.height = DROP_LINE_THICKNESS;
}
return rect;
}
/**
* Returns the baseline.
*
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
public int getBaseline(JComponent c, int width, int height) {
super.getBaseline(c, width, height);
int rowHeight = list.getFixedCellHeight();
UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults();
Component renderer = (Component)lafDefaults.get(
BASELINE_COMPONENT_KEY);
if (renderer == null) {
ListCellRenderer lcr = (ListCellRenderer)UIManager.get(
"List.cellRenderer");
// fix for 6711072 some LAFs like Nimbus do not provide this
// UIManager key and we should not through a NPE here because of it
if (lcr == null) {
lcr = new DefaultListCellRenderer();
}
renderer = lcr.getListCellRendererComponent(
list, "a", -1, false, false);
lafDefaults.put(BASELINE_COMPONENT_KEY, renderer);
}
renderer.setFont(list.getFont());
// JList actually has much more complex behavior here.
// If rowHeight != -1 the rowHeight is either the max of all cell
// heights (layout orientation != VERTICAL), or is variable depending
// upon the cell. We assume a default size.
// We could theoretically query the real renderer, but that would
// not work for an empty model and the results may vary with
// the content.
if (rowHeight == -1) {
rowHeight = renderer.getPreferredSize().height;
}
return renderer.getBaseline(Integer.MAX_VALUE, rowHeight) +
list.getInsets().top;
}
/**
* Returns an enum indicating how the baseline of the component
* changes as the size changes.
*
* @throws NullPointerException {@inheritDoc}
* @see javax.swing.JComponent#getBaseline(int, int)
* @since 1.6
*/
public Component.BaselineResizeBehavior getBaselineResizeBehavior(
JComponent c) {
super.getBaselineResizeBehavior(c);
return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
}
/**
* The preferredSize of the list depends upon the layout orientation.
* <table summary="Describes the preferred size for each layout orientation">
* <tr><th>Layout Orientation</th><th>Preferred Size</th></tr>
* <tr>
* <td>JList.VERTICAL
* <td>The preferredSize of the list is total height of the rows
* and the maximum width of the cells. If JList.fixedCellHeight
* is specified then the total height of the rows is just
* (cellVerticalMargins + fixedCellHeight) * model.getSize() where
* rowVerticalMargins is the space we allocate for drawing
* the yellow focus outline. Similarly if fixedCellWidth is
* specified then we just use that.
* </td>
* <tr>
* <td>JList.VERTICAL_WRAP
* <td>If the visible row count is greater than zero, the preferredHeight
* is the maximum cell height * visibleRowCount. If the visible row
* count is <= 0, the preferred height is either the current height
* of the list, or the maximum cell height, whichever is
* bigger. The preferred width is than the maximum cell width *
* number of columns needed. Where the number of columns needs is
* list.height / max cell height. Max cell height is either the fixed
* cell height, or is determined by iterating through all the cells
* to find the maximum height from the ListCellRenderer.
* <tr>
* <td>JList.HORIZONTAL_WRAP
* <td>If the visible row count is greater than zero, the preferredHeight
* is the maximum cell height * adjustedRowCount. Where
* visibleRowCount is used to determine the number of columns.
* Because this lays out horizontally the number of rows is
* then determined from the column count. For example, lets say
* you have a model with 10 items and the visible row count is 8.
* The number of columns needed to display this is 2, but you no
* longer need 8 rows to display this, you only need 5, thus
* the adjustedRowCount is 5.
* <p>If the visible row
* count is <= 0, the preferred height is dictated by the
* number of columns, which will be as many as can fit in the width
* of the <code>JList</code> (width / max cell width), with at
* least one column. The preferred height then becomes the
* model size / number of columns * maximum cell height.
* Max cell height is either the fixed
* cell height, or is determined by iterating through all the cells
* to find the maximum height from the ListCellRenderer.
* </table>
* The above specifies the raw preferred width and height. The resulting
* preferred width is the above width + insets.left + insets.right and
* the resulting preferred height is the above height + insets.top +
* insets.bottom. Where the <code>Insets</code> are determined from
* <code>list.getInsets()</code>.
*
* @param c The JList component.
* @return The total size of the list.
*/
public Dimension getPreferredSize(JComponent c) {
maybeUpdateLayoutState();
int lastRow = list.getModel().getSize() - 1;
if (lastRow < 0) {
return new Dimension(0, 0);
}
Insets insets = list.getInsets();
int width = cellWidth * columnCount + insets.left + insets.right;
int height;
if (layoutOrientation != JList.VERTICAL) {
height = preferredHeight;
}
else {
Rectangle bounds = getCellBounds(list, lastRow);
if (bounds != null) {
height = bounds.y + bounds.height + insets.bottom;
}
else {
height = 0;
}
}
return new Dimension(width, height);
}
/**
* Selected the previous row and force it to be visible.
*
* @see JList#ensureIndexIsVisible
*/
protected void selectPreviousIndex() {
int s = list.getSelectedIndex();
if(s > 0) {
s -= 1;
list.setSelectedIndex(s);
list.ensureIndexIsVisible(s);
}
}
/**
* Selected the previous row and force it to be visible.
*
* @see JList#ensureIndexIsVisible
*/
protected void selectNextIndex()
{
int s = list.getSelectedIndex();
if((s + 1) < list.getModel().getSize()) {
s += 1;
list.setSelectedIndex(s);
list.ensureIndexIsVisible(s);
}
}
/**
* Registers the keyboard bindings on the <code>JList</code> that the
* <code>BasicListUI</code> is associated with. This method is called at
* installUI() time.
*
* @see #installUI
*/
protected void installKeyboardActions() {
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED);
SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED,
inputMap);
LazyActionMap.installLazyActionMap(list, BasicListUI.class,
"List.actionMap");
}
InputMap getInputMap(int condition) {
if (condition == JComponent.WHEN_FOCUSED) {
InputMap keyMap = (InputMap)DefaultLookup.get(
list, this, "List.focusInputMap");
InputMap rtlKeyMap;
if (isLeftToRight ||
((rtlKeyMap = (InputMap)DefaultLookup.get(list, this,
"List.focusInputMap.RightToLeft")) == null)) {
return keyMap;
} else {
rtlKeyMap.setParent(keyMap);
return rtlKeyMap;
}
}
return null;
}
/**
* Unregisters keyboard actions installed from
* <code>installKeyboardActions</code>.
* This method is called at uninstallUI() time - subclassess should
* ensure that all of the keyboard actions registered at installUI
* time are removed here.
*
* @see #installUI
*/
protected void uninstallKeyboardActions() {
SwingUtilities.replaceUIActionMap(list, null);
SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED, null);
}
/**
* Creates and installs the listeners for the JList, its model, and its
* selectionModel. This method is called at installUI() time.
*
* @see #installUI
* @see #uninstallListeners
*/
protected void installListeners()
{
TransferHandler th = list.getTransferHandler();
if (th == null || th instanceof UIResource) {
list.setTransferHandler(defaultTransferHandler);
// default TransferHandler doesn't support drop
// so we don't want drop handling
if (list.getDropTarget() instanceof UIResource) {
list.setDropTarget(null);
}
}
focusListener = createFocusListener();
mouseInputListener = createMouseInputListener();
propertyChangeListener = createPropertyChangeListener();
listSelectionListener = createListSelectionListener();
listDataListener = createListDataListener();
list.addFocusListener(focusListener);
list.addMouseListener(mouseInputListener);
list.addMouseMotionListener(mouseInputListener);
list.addPropertyChangeListener(propertyChangeListener);
list.addKeyListener(getHandler());
ListModel model = list.getModel();
if (model != null) {
model.addListDataListener(listDataListener);
}
ListSelectionModel selectionModel = list.getSelectionModel();
if (selectionModel != null) {
selectionModel.addListSelectionListener(listSelectionListener);
}
}
/**
* Removes the listeners from the JList, its model, and its
* selectionModel. All of the listener fields, are reset to
* null here. This method is called at uninstallUI() time,
* it should be kept in sync with installListeners.
*
* @see #uninstallUI
* @see #installListeners
*/
protected void uninstallListeners()
{
list.removeFocusListener(focusListener);
list.removeMouseListener(mouseInputListener);
list.removeMouseMotionListener(mouseInputListener);
list.removePropertyChangeListener(propertyChangeListener);
list.removeKeyListener(getHandler());
ListModel model = list.getModel();
if (model != null) {
model.removeListDataListener(listDataListener);
}
ListSelectionModel selectionModel = list.getSelectionModel();
if (selectionModel != null) {
selectionModel.removeListSelectionListener(listSelectionListener);
}
focusListener = null;
mouseInputListener = null;
listSelectionListener = null;
listDataListener = null;
propertyChangeListener = null;
handler = null;
}
/**
* Initializes list properties such as font, foreground, and background,
* and adds the CellRendererPane. The font, foreground, and background
* properties are only set if their current value is either null
* or a UIResource, other properties are set if the current
* value is null.
*
* @see #uninstallDefaults
* @see #installUI
* @see CellRendererPane
*/
protected void installDefaults()
{
list.setLayout(null);
LookAndFeel.installBorder(list, "List.border");
LookAndFeel.installColorsAndFont(list, "List.background", "List.foreground", "List.font");
LookAndFeel.installProperty(list, "opaque", Boolean.TRUE);
if (list.getCellRenderer() == null) {
list.setCellRenderer((ListCellRenderer)(UIManager.get("List.cellRenderer")));
}
Color sbg = list.getSelectionBackground();
if (sbg == null || sbg instanceof UIResource) {
list.setSelectionBackground(UIManager.getColor("List.selectionBackground"));
}
Color sfg = list.getSelectionForeground();
if (sfg == null || sfg instanceof UIResource) {
list.setSelectionForeground(UIManager.getColor("List.selectionForeground"));
}
Long l = (Long)UIManager.get("List.timeFactor");
timeFactor = (l!=null) ? l.longValue() : 1000L;
updateIsFileList();
}
private void updateIsFileList() {
boolean b = Boolean.TRUE.equals(list.getClientProperty("List.isFileList"));
if (b != isFileList) {
isFileList = b;
Font oldFont = list.getFont();
if (oldFont == null || oldFont instanceof UIResource) {
Font newFont = UIManager.getFont(b ? "FileChooser.listFont" : "List.font");
if (newFont != null && newFont != oldFont) {
list.setFont(newFont);
}
}
}
}
/**
* Sets the list properties that have not been explicitly overridden to
* {@code null}. A property is considered overridden if its current value
* is not a {@code UIResource}.
*
* @see #installDefaults
* @see #uninstallUI
* @see CellRendererPane
*/
protected void uninstallDefaults()
{
LookAndFeel.uninstallBorder(list);
if (list.getFont() instanceof UIResource) {
list.setFont(null);
}
if (list.getForeground() instanceof UIResource) {
list.setForeground(null);
}
if (list.getBackground() instanceof UIResource) {
list.setBackground(null);
}
if (list.getSelectionBackground() instanceof UIResource) {
list.setSelectionBackground(null);
}
if (list.getSelectionForeground() instanceof UIResource) {
list.setSelectionForeground(null);
}
if (list.getCellRenderer() instanceof UIResource) {
list.setCellRenderer(null);
}
if (list.getTransferHandler() instanceof UIResource) {
list.setTransferHandler(null);
}
}
/**
* Initializes <code>this.list</code> by calling <code>installDefaults()</code>,
* <code>installListeners()</code>, and <code>installKeyboardActions()</code>
* in order.
*
* @see #installDefaults
* @see #installListeners
* @see #installKeyboardActions
*/
public void installUI(JComponent c)
{
list = (JList)c;
layoutOrientation = list.getLayoutOrientation();
rendererPane = new CellRendererPane();
list.add(rendererPane);
columnCount = 1;
updateLayoutStateNeeded = modelChanged;
isLeftToRight = list.getComponentOrientation().isLeftToRight();
installDefaults();
installListeners();
installKeyboardActions();
}
/**
* Uninitializes <code>this.list</code> by calling <code>uninstallListeners()</code>,
* <code>uninstallKeyboardActions()</code>, and <code>uninstallDefaults()</code>
* in order. Sets this.list to null.
*
* @see #uninstallListeners
* @see #uninstallKeyboardActions
* @see #uninstallDefaults
*/
public void uninstallUI(JComponent c)
{
uninstallListeners();
uninstallDefaults();
uninstallKeyboardActions();
cellWidth = cellHeight = -1;
cellHeights = null;
listWidth = listHeight = -1;
list.remove(rendererPane);
rendererPane = null;
list = null;
}
/**
* Returns a new instance of BasicListUI. BasicListUI delegates are
* allocated one per JList.
*
* @return A new ListUI implementation for the Windows look and feel.
*/
public static ComponentUI createUI(JComponent list) {
return new BasicListUI();
}
/**
* {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public int locationToIndex(JList list, Point location) {
maybeUpdateLayoutState();
return convertLocationToModel(location.x, location.y);
}
/**
* {@inheritDoc}
*/
public Point indexToLocation(JList list, int index) {
maybeUpdateLayoutState();
Rectangle rect = getCellBounds(list, index, index);
if (rect != null) {
return new Point(rect.x, rect.y);
}
return null;
}
/**
* {@inheritDoc}
*/
public Rectangle getCellBounds(JList list, int index1, int index2) {
maybeUpdateLayoutState();
int minIndex = Math.min(index1, index2);
int maxIndex = Math.max(index1, index2);
if (minIndex >= list.getModel().getSize()) {
return null;
}
Rectangle minBounds = getCellBounds(list, minIndex);
if (minBounds == null) {
return null;
}
if (minIndex == maxIndex) {
return minBounds;
}
Rectangle maxBounds = getCellBounds(list, maxIndex);
if (maxBounds != null) {
if (layoutOrientation == JList.HORIZONTAL_WRAP) {
int minRow = convertModelToRow(minIndex);
int maxRow = convertModelToRow(maxIndex);
if (minRow != maxRow) {
minBounds.x = 0;
minBounds.width = list.getWidth();
}
}
else if (minBounds.x != maxBounds.x) {
// Different columns
minBounds.y = 0;
minBounds.height = list.getHeight();
}
minBounds.add(maxBounds);
}
return minBounds;
}
/**
* Gets the bounds of the specified model index, returning the resulting
* bounds, or null if <code>index</code> is not valid.
*/
private Rectangle getCellBounds(JList list, int index) {
maybeUpdateLayoutState();
int row = convertModelToRow(index);
int column = convertModelToColumn(index);
if (row == -1 || column == -1) {
return null;
}
Insets insets = list.getInsets();
int x;
int w = cellWidth;
int y = insets.top;
int h;
switch (layoutOrientation) {
case JList.VERTICAL_WRAP:
case JList.HORIZONTAL_WRAP:
if (isLeftToRight) {
x = insets.left + column * cellWidth;
} else {
x = list.getWidth() - insets.right - (column+1) * cellWidth;
}
y += cellHeight * row;
h = cellHeight;
break;
default:
x = insets.left;
if (cellHeights == null) {
y += (cellHeight * row);
}
else if (row >= cellHeights.length) {
y = 0;
}
else {
for(int i = 0; i < row; i++) {
y += cellHeights[i];
}
}
w = list.getWidth() - (insets.left + insets.right);
h = getRowHeight(index);
break;
}
return new Rectangle(x, y, w, h);
}
/**
* Returns the height of the specified row based on the current layout.
*
* @return The specified row height or -1 if row isn't valid.
* @see #convertYToRow
* @see #convertRowToY
* @see #updateLayoutState
*/
protected int getRowHeight(int row)
{
return getHeight(0, row);
}
/**
* Convert the JList relative coordinate to the row that contains it,
* based on the current layout. If y0 doesn't fall within any row,
* return -1.
*
* @return The row that contains y0, or -1.
* @see #getRowHeight
* @see #updateLayoutState
*/
protected int convertYToRow(int y0)
{
return convertLocationToRow(0, y0, false);
}
/**
* Return the JList relative Y coordinate of the origin of the specified
* row or -1 if row isn't valid.
*
* @return The Y coordinate of the origin of row, or -1.
* @see #getRowHeight
* @see #updateLayoutState
*/
protected int convertRowToY(int row)
{
if (row >= getRowCount(0) || row < 0) {
return -1;
}
Rectangle bounds = getCellBounds(list, row, row);
return bounds.y;
}
/**
* Returns the height of the cell at the passed in location.
*/
private int getHeight(int column, int row) {
if (column < 0 || column > columnCount || row < 0) {
return -1;
}
if (layoutOrientation != JList.VERTICAL) {
return cellHeight;
}
if (row >= list.getModel().getSize()) {
return -1;
}
return (cellHeights == null) ? cellHeight :
((row < cellHeights.length) ? cellHeights[row] : -1);
}
/**
* Returns the row at location x/y.
*
* @param closest If true and the location doesn't exactly match a
* particular location, this will return the closest row.
*/
private int convertLocationToRow(int x, int y0, boolean closest) {
int size = list.getModel().getSize();
if (size <= 0) {
return -1;
}
Insets insets = list.getInsets();
if (cellHeights == null) {
int row = (cellHeight == 0) ? 0 :
((y0 - insets.top) / cellHeight);
if (closest) {
if (row < 0) {
row = 0;
}
else if (row >= size) {
row = size - 1;
}
}
return row;
}
else if (size > cellHeights.length) {
return -1;
}
else {
int y = insets.top;
int row = 0;
if (closest && y0 < y) {
return 0;
}
int i;
for (i = 0; i < size; i++) {
if ((y0 >= y) && (y0 < y + cellHeights[i])) {
return row;
}
y += cellHeights[i];
row += 1;
}
return i - 1;
}
}
/**
* Returns the closest row that starts at the specified y-location
* in the passed in column.
*/
private int convertLocationToRowInColumn(int y, int column) {
int x = 0;
if (layoutOrientation != JList.VERTICAL) {
if (isLeftToRight) {
x = column * cellWidth;
} else {
x = list.getWidth() - (column+1)*cellWidth - list.getInsets().right;
}
}
return convertLocationToRow(x, y, true);
}
/**
* Returns the closest location to the model index of the passed in
* location.
*/
private int convertLocationToModel(int x, int y) {
int row = convertLocationToRow(x, y, true);
int column = convertLocationToColumn(x, y);
if (row >= 0 && column >= 0) {
return getModelIndex(column, row);
}
return -1;
}
/**
* Returns the number of rows in the given column.
*/
private int getRowCount(int column) {
if (column < 0 || column >= columnCount) {
return -1;
}
if (layoutOrientation == JList.VERTICAL ||
(column == 0 && columnCount == 1)) {
return list.getModel().getSize();
}
if (column >= columnCount) {
return -1;
}
if (layoutOrientation == JList.VERTICAL_WRAP) {
if (column < (columnCount - 1)) {
return rowsPerColumn;
}
return list.getModel().getSize() - (columnCount - 1) *
rowsPerColumn;
}
// JList.HORIZONTAL_WRAP
int diff = columnCount - (columnCount * rowsPerColumn -
list.getModel().getSize());
if (column >= diff) {
return Math.max(0, rowsPerColumn - 1);
}
return rowsPerColumn;
}
/**
* Returns the model index for the specified display location.
* If <code>column</code>x<code>row</code> is beyond the length of the
* model, this will return the model size - 1.
*/
private int getModelIndex(int column, int row) {
switch (layoutOrientation) {
case JList.VERTICAL_WRAP:
return Math.min(list.getModel().getSize() - 1, rowsPerColumn *
column + Math.min(row, rowsPerColumn-1));
case JList.HORIZONTAL_WRAP:
return Math.min(list.getModel().getSize() - 1, row * columnCount +
column);
default:
return row;
}
}
/**
* Returns the closest column to the passed in location.
*/
private int convertLocationToColumn(int x, int y) {
if (cellWidth > 0) {
if (layoutOrientation == JList.VERTICAL) {
return 0;
}
Insets insets = list.getInsets();
int col;
if (isLeftToRight) {
col = (x - insets.left) / cellWidth;
} else {
col = (list.getWidth() - x - insets.right - 1) / cellWidth;
}
if (col < 0) {
return 0;
}
else if (col >= columnCount) {
return columnCount - 1;
}
return col;
}
return 0;
}
/**
* Returns the row that the model index <code>index</code> will be
* displayed in..
*/
private int convertModelToRow(int index) {
int size = list.getModel().getSize();
if ((index < 0) || (index >= size)) {
return -1;
}
if (layoutOrientation != JList.VERTICAL && columnCount > 1 &&
rowsPerColumn > 0) {
if (layoutOrientation == JList.VERTICAL_WRAP) {
return index % rowsPerColumn;
}
return index / columnCount;
}
return index;
}
/**
* Returns the column that the model index <code>index</code> will be
* displayed in.
*/
private int convertModelToColumn(int index) {
int size = list.getModel().getSize();
if ((index < 0) || (index >= size)) {
return -1;
}
if (layoutOrientation != JList.VERTICAL && rowsPerColumn > 0 &&
columnCount > 1) {
if (layoutOrientation == JList.VERTICAL_WRAP) {
return index / rowsPerColumn;
}
return index % columnCount;
}
return 0;
}
/**
* If updateLayoutStateNeeded is non zero, call updateLayoutState() and reset
* updateLayoutStateNeeded. This method should be called by methods
* before doing any computation based on the geometry of the list.
* For example it's the first call in paint() and getPreferredSize().
*
* @see #updateLayoutState
*/
protected void maybeUpdateLayoutState()
{
if (updateLayoutStateNeeded != 0) {
updateLayoutState();
updateLayoutStateNeeded = 0;
}
}
/**
* Recompute the value of cellHeight or cellHeights based
* and cellWidth, based on the current font and the current
* values of fixedCellWidth, fixedCellHeight, and prototypeCellValue.
*
* @see #maybeUpdateLayoutState
*/
protected void updateLayoutState()
{
/* If both JList fixedCellWidth and fixedCellHeight have been
* set, then initialize cellWidth and cellHeight, and set
* cellHeights to null.
*/
int fixedCellHeight = list.getFixedCellHeight();
int fixedCellWidth = list.getFixedCellWidth();
cellWidth = (fixedCellWidth != -1) ? fixedCellWidth : -1;
if (fixedCellHeight != -1) {
cellHeight = fixedCellHeight;
cellHeights = null;
}
else {
cellHeight = -1;
cellHeights = new int[list.getModel().getSize()];
}
/* If either of JList fixedCellWidth and fixedCellHeight haven't
* been set, then initialize cellWidth and cellHeights by
* scanning through the entire model. Note: if the renderer is
* null, we just set cellWidth and cellHeights[*] to zero,
* if they're not set already.
*/
if ((fixedCellWidth == -1) || (fixedCellHeight == -1)) {
ListModel dataModel = list.getModel();
int dataModelSize = dataModel.getSize();
ListCellRenderer renderer = list.getCellRenderer();
if (renderer != null) {
for(int index = 0; index < dataModelSize; index++) {
Object value = dataModel.getElementAt(index);
Component c = renderer.getListCellRendererComponent(list, value, index, false, false);
rendererPane.add(c);
Dimension cellSize = c.getPreferredSize();
if (fixedCellWidth == -1) {
cellWidth = Math.max(cellSize.width, cellWidth);
}
if (fixedCellHeight == -1) {
cellHeights[index] = cellSize.height;
}
}
}
else {
if (cellWidth == -1) {
cellWidth = 0;
}
if (cellHeights == null) {
cellHeights = new int[dataModelSize];
}
for(int index = 0; index < dataModelSize; index++) {
cellHeights[index] = 0;
}
}
}
columnCount = 1;
if (layoutOrientation != JList.VERTICAL) {
updateHorizontalLayoutState(fixedCellWidth, fixedCellHeight);
}
}
/**
* Invoked when the list is layed out horizontally to determine how
* many columns to create.
* <p>
* This updates the <code>rowsPerColumn, </code><code>columnCount</code>,
* <code>preferredHeight</code> and potentially <code>cellHeight</code>
* instance variables.
*/
private void updateHorizontalLayoutState(int fixedCellWidth,
int fixedCellHeight) {
int visRows = list.getVisibleRowCount();
int dataModelSize = list.getModel().getSize();
Insets insets = list.getInsets();
listHeight = list.getHeight();
listWidth = list.getWidth();
if (dataModelSize == 0) {
rowsPerColumn = columnCount = 0;
preferredHeight = insets.top + insets.bottom;
return;
}
int height;
if (fixedCellHeight != -1) {
height = fixedCellHeight;
}
else {
// Determine the max of the renderer heights.
int maxHeight = 0;
if (cellHeights.length > 0) {
maxHeight = cellHeights[cellHeights.length - 1];
for (int counter = cellHeights.length - 2;
counter >= 0; counter--) {
maxHeight = Math.max(maxHeight, cellHeights[counter]);
}
}
height = cellHeight = maxHeight;
cellHeights = null;
}
// The number of rows is either determined by the visible row
// count, or by the height of the list.
rowsPerColumn = dataModelSize;
if (visRows > 0) {
rowsPerColumn = visRows;
columnCount = Math.max(1, dataModelSize / rowsPerColumn);
if (dataModelSize > 0 && dataModelSize > rowsPerColumn &&
dataModelSize % rowsPerColumn != 0) {
columnCount++;
}
if (layoutOrientation == JList.HORIZONTAL_WRAP) {
// Because HORIZONTAL_WRAP flows differently, the
// rowsPerColumn needs to be adjusted.
rowsPerColumn = (dataModelSize / columnCount);
if (dataModelSize % columnCount > 0) {
rowsPerColumn++;
}
}
}
else if (layoutOrientation == JList.VERTICAL_WRAP && height != 0) {
rowsPerColumn = Math.max(1, (listHeight - insets.top -
insets.bottom) / height);
columnCount = Math.max(1, dataModelSize / rowsPerColumn);
if (dataModelSize > 0 && dataModelSize > rowsPerColumn &&
dataModelSize % rowsPerColumn != 0) {
columnCount++;
}
}
else if (layoutOrientation == JList.HORIZONTAL_WRAP && cellWidth > 0 &&
listWidth > 0) {
columnCount = Math.max(1, (listWidth - insets.left -
insets.right) / cellWidth);
rowsPerColumn = dataModelSize / columnCount;
if (dataModelSize % columnCount > 0) {
rowsPerColumn++;
}
}
preferredHeight = rowsPerColumn * cellHeight + insets.top +
insets.bottom;
}
private Handler getHandler() {
if (handler == null) {
handler = new Handler();
}
return handler;
}
/**
* Mouse input, and focus handling for JList. An instance of this
* class is added to the appropriate java.awt.Component lists
* at installUI() time. Note keyboard input is handled with JComponent
* KeyboardActions, see installKeyboardActions().
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see #createMouseInputListener
* @see #installKeyboardActions
* @see #installUI
*/
public class MouseInputHandler implements MouseInputListener
{
public void mouseClicked(MouseEvent e) {
getHandler().mouseClicked(e);
}
public void mouseEntered(MouseEvent e) {
getHandler().mouseEntered(e);
}
public void mouseExited(MouseEvent e) {
getHandler().mouseExited(e);
}
public void mousePressed(MouseEvent e) {
getHandler().mousePressed(e);
}
public void mouseDragged(MouseEvent e) {
getHandler().mouseDragged(e);
}
public void mouseMoved(MouseEvent e) {
getHandler().mouseMoved(e);
}
public void mouseReleased(MouseEvent e) {
getHandler().mouseReleased(e);
}
}
/**
* Creates a delegate that implements MouseInputListener.
* The delegate is added to the corresponding java.awt.Component listener
* lists at installUI() time. Subclasses can override this method to return
* a custom MouseInputListener, e.g.
* <pre>
* class MyListUI extends BasicListUI {
* protected MouseInputListener <b>createMouseInputListener</b>() {
* return new MyMouseInputHandler();
* }
* public class MyMouseInputHandler extends MouseInputHandler {
* public void mouseMoved(MouseEvent e) {
* // do some extra work when the mouse moves
* super.mouseMoved(e);
* }
* }
* }
* </pre>
*
* @see MouseInputHandler
* @see #installUI
*/
protected MouseInputListener createMouseInputListener() {
return getHandler();
}
/**
* This inner class is marked "public" due to a compiler bug.
* This class should be treated as a "protected" inner class.
* Instantiate it only within subclasses of BasicTableUI.
*/
public class FocusHandler implements FocusListener
{
protected void repaintCellFocus()
{
getHandler().repaintCellFocus();
}
/* The focusGained() focusLost() methods run when the JList
* focus changes.
*/
public void focusGained(FocusEvent e) {
getHandler().focusGained(e);
}
public void focusLost(FocusEvent e) {
getHandler().focusLost(e);
}
}
protected FocusListener createFocusListener() {
return getHandler();
}
/**
* The ListSelectionListener that's added to the JLists selection
* model at installUI time, and whenever the JList.selectionModel property
* changes. When the selection changes we repaint the affected rows.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see #createListSelectionListener
* @see #getCellBounds
* @see #installUI
*/
public class ListSelectionHandler implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent e)
{
getHandler().valueChanged(e);
}
}
/**
* Creates an instance of ListSelectionHandler that's added to
* the JLists by selectionModel as needed. Subclasses can override
* this method to return a custom ListSelectionListener, e.g.
* <pre>
* class MyListUI extends BasicListUI {
* protected ListSelectionListener <b>createListSelectionListener</b>() {
* return new MySelectionListener();
* }
* public class MySelectionListener extends ListSelectionHandler {
* public void valueChanged(ListSelectionEvent e) {
* // do some extra work when the selection changes
* super.valueChange(e);
* }
* }
* }
* </pre>
*
* @see ListSelectionHandler
* @see #installUI
*/
protected ListSelectionListener createListSelectionListener() {
return getHandler();
}
private void redrawList() {
list.revalidate();
list.repaint();
}
/**
* The ListDataListener that's added to the JLists model at
* installUI time, and whenever the JList.model property changes.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see JList#getModel
* @see #maybeUpdateLayoutState
* @see #createListDataListener
* @see #installUI
*/
public class ListDataHandler implements ListDataListener
{
public void intervalAdded(ListDataEvent e) {
getHandler().intervalAdded(e);
}
public void intervalRemoved(ListDataEvent e)
{
getHandler().intervalRemoved(e);
}
public void contentsChanged(ListDataEvent e) {
getHandler().contentsChanged(e);
}
}
/**
* Creates an instance of ListDataListener that's added to
* the JLists by model as needed. Subclasses can override
* this method to return a custom ListDataListener, e.g.
* <pre>
* class MyListUI extends BasicListUI {
* protected ListDataListener <b>createListDataListener</b>() {
* return new MyListDataListener();
* }
* public class MyListDataListener extends ListDataHandler {
* public void contentsChanged(ListDataEvent e) {
* // do some extra work when the models contents change
* super.contentsChange(e);
* }
* }
* }
* </pre>
*
* @see ListDataListener
* @see JList#getModel
* @see #installUI
*/
protected ListDataListener createListDataListener() {
return getHandler();
}
/**
* The PropertyChangeListener that's added to the JList at
* installUI time. When the value of a JList property that
* affects layout changes, we set a bit in updateLayoutStateNeeded.
* If the JLists model changes we additionally remove our listeners
* from the old model. Likewise for the JList selectionModel.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans<sup><font size="-2">TM</font></sup>
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see #maybeUpdateLayoutState
* @see #createPropertyChangeListener
* @see #installUI
*/
public class PropertyChangeHandler implements PropertyChangeListener
{
public void propertyChange(PropertyChangeEvent e)
{
getHandler().propertyChange(e);
}
}
/**
* Creates an instance of PropertyChangeHandler that's added to
* the JList by installUI(). Subclasses can override this method
* to return a custom PropertyChangeListener, e.g.
* <pre>
* class MyListUI extends BasicListUI {
* protected PropertyChangeListener <b>createPropertyChangeListener</b>() {
* return new MyPropertyChangeListener();
* }
* public class MyPropertyChangeListener extends PropertyChangeHandler {
* public void propertyChange(PropertyChangeEvent e) {
* if (e.getPropertyName().equals("model")) {
* // do some extra work when the model changes
* }
* super.propertyChange(e);
* }
* }
* }
* </pre>
*
* @see PropertyChangeListener
* @see #installUI
*/
protected PropertyChangeListener createPropertyChangeListener() {
return getHandler();
}
/** Used by IncrementLeadSelectionAction. Indicates the action should
* change the lead, and not select it. */
private static final int CHANGE_LEAD = 0;
/** Used by IncrementLeadSelectionAction. Indicates the action should
* change the selection and lead. */
private static final int CHANGE_SELECTION = 1;
/** Used by IncrementLeadSelectionAction. Indicates the action should
* extend the selection from the anchor to the next index. */
private static final int EXTEND_SELECTION = 2;
private static class Actions extends UIAction {
private static final String SELECT_PREVIOUS_COLUMN =
"selectPreviousColumn";
private static final String SELECT_PREVIOUS_COLUMN_EXTEND =
"selectPreviousColumnExtendSelection";
private static final String SELECT_PREVIOUS_COLUMN_CHANGE_LEAD =
"selectPreviousColumnChangeLead";
private static final String SELECT_NEXT_COLUMN = "selectNextColumn";
private static final String SELECT_NEXT_COLUMN_EXTEND =
"selectNextColumnExtendSelection";
private static final String SELECT_NEXT_COLUMN_CHANGE_LEAD =
"selectNextColumnChangeLead";
private static final String SELECT_PREVIOUS_ROW = "selectPreviousRow";
private static final String SELECT_PREVIOUS_ROW_EXTEND =
"selectPreviousRowExtendSelection";
private static final String SELECT_PREVIOUS_ROW_CHANGE_LEAD =
"selectPreviousRowChangeLead";
private static final String SELECT_NEXT_ROW = "selectNextRow";
private static final String SELECT_NEXT_ROW_EXTEND =
"selectNextRowExtendSelection";
private static final String SELECT_NEXT_ROW_CHANGE_LEAD =
"selectNextRowChangeLead";
private static final String SELECT_FIRST_ROW = "selectFirstRow";
private static final String SELECT_FIRST_ROW_EXTEND =
"selectFirstRowExtendSelection";
private static final String SELECT_FIRST_ROW_CHANGE_LEAD =
"selectFirstRowChangeLead";
private static final String SELECT_LAST_ROW = "selectLastRow";
private static final String SELECT_LAST_ROW_EXTEND =
"selectLastRowExtendSelection";
private static final String SELECT_LAST_ROW_CHANGE_LEAD =
"selectLastRowChangeLead";
private static final String SCROLL_UP = "scrollUp";
private static final String SCROLL_UP_EXTEND =
"scrollUpExtendSelection";
private static final String SCROLL_UP_CHANGE_LEAD =
"scrollUpChangeLead";
private static final String SCROLL_DOWN = "scrollDown";
private static final String SCROLL_DOWN_EXTEND =
"scrollDownExtendSelection";
private static final String SCROLL_DOWN_CHANGE_LEAD =
"scrollDownChangeLead";
private static final String SELECT_ALL = "selectAll";
private static final String CLEAR_SELECTION = "clearSelection";
// add the lead item to the selection without changing lead or anchor
private static final String ADD_TO_SELECTION = "addToSelection";
// toggle the selected state of the lead item and move the anchor to it
private static final String TOGGLE_AND_ANCHOR = "toggleAndAnchor";
// extend the selection to the lead item
private static final String EXTEND_TO = "extendTo";
// move the anchor to the lead and ensure only that item is selected
private static final String MOVE_SELECTION_TO = "moveSelectionTo";
Actions(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
String name = getName();
JList list = (JList)e.getSource();
BasicListUI ui = (BasicListUI)BasicLookAndFeel.getUIOfType(
list.getUI(), BasicListUI.class);
if (name == SELECT_PREVIOUS_COLUMN) {
changeSelection(list, CHANGE_SELECTION,
getNextColumnIndex(list, ui, -1), -1);
}
else if (name == SELECT_PREVIOUS_COLUMN_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextColumnIndex(list, ui, -1), -1);
}
else if (name == SELECT_PREVIOUS_COLUMN_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextColumnIndex(list, ui, -1), -1);
}
else if (name == SELECT_NEXT_COLUMN) {
changeSelection(list, CHANGE_SELECTION,
getNextColumnIndex(list, ui, 1), 1);
}
else if (name == SELECT_NEXT_COLUMN_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextColumnIndex(list, ui, 1), 1);
}
else if (name == SELECT_NEXT_COLUMN_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextColumnIndex(list, ui, 1), 1);
}
else if (name == SELECT_PREVIOUS_ROW) {
changeSelection(list, CHANGE_SELECTION,
getNextIndex(list, ui, -1), -1);
}
else if (name == SELECT_PREVIOUS_ROW_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextIndex(list, ui, -1), -1);
}
else if (name == SELECT_PREVIOUS_ROW_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextIndex(list, ui, -1), -1);
}
else if (name == SELECT_NEXT_ROW) {
changeSelection(list, CHANGE_SELECTION,
getNextIndex(list, ui, 1), 1);
}
else if (name == SELECT_NEXT_ROW_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextIndex(list, ui, 1), 1);
}
else if (name == SELECT_NEXT_ROW_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextIndex(list, ui, 1), 1);
}
else if (name == SELECT_FIRST_ROW) {
changeSelection(list, CHANGE_SELECTION, 0, -1);
}
else if (name == SELECT_FIRST_ROW_EXTEND) {
changeSelection(list, EXTEND_SELECTION, 0, -1);
}
else if (name == SELECT_FIRST_ROW_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD, 0, -1);
}
else if (name == SELECT_LAST_ROW) {
changeSelection(list, CHANGE_SELECTION,
list.getModel().getSize() - 1, 1);
}
else if (name == SELECT_LAST_ROW_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
list.getModel().getSize() - 1, 1);
}
else if (name == SELECT_LAST_ROW_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
list.getModel().getSize() - 1, 1);
}
else if (name == SCROLL_UP) {
changeSelection(list, CHANGE_SELECTION,
getNextPageIndex(list, -1), -1);
}
else if (name == SCROLL_UP_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextPageIndex(list, -1), -1);
}
else if (name == SCROLL_UP_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextPageIndex(list, -1), -1);
}
else if (name == SCROLL_DOWN) {
changeSelection(list, CHANGE_SELECTION,
getNextPageIndex(list, 1), 1);
}
else if (name == SCROLL_DOWN_EXTEND) {
changeSelection(list, EXTEND_SELECTION,
getNextPageIndex(list, 1), 1);
}
else if (name == SCROLL_DOWN_CHANGE_LEAD) {
changeSelection(list, CHANGE_LEAD,
getNextPageIndex(list, 1), 1);
}
else if (name == SELECT_ALL) {
selectAll(list);
}
else if (name == CLEAR_SELECTION) {
clearSelection(list);
}
else if (name == ADD_TO_SELECTION) {
int index = adjustIndex(
list.getSelectionModel().getLeadSelectionIndex(), list);
if (!list.isSelectedIndex(index)) {
int oldAnchor = list.getSelectionModel().getAnchorSelectionIndex();
list.setValueIsAdjusting(true);
list.addSelectionInterval(index, index);
list.getSelectionModel().setAnchorSelectionIndex(oldAnchor);
list.setValueIsAdjusting(false);
}
}
else if (name == TOGGLE_AND_ANCHOR) {
int index = adjustIndex(
list.getSelectionModel().getLeadSelectionIndex(), list);
if (list.isSelectedIndex(index)) {
list.removeSelectionInterval(index, index);
} else {
list.addSelectionInterval(index, index);
}
}
else if (name == EXTEND_TO) {
changeSelection(
list, EXTEND_SELECTION,
adjustIndex(list.getSelectionModel().getLeadSelectionIndex(), list),
0);
}
else if (name == MOVE_SELECTION_TO) {
changeSelection(
list, CHANGE_SELECTION,
adjustIndex(list.getSelectionModel().getLeadSelectionIndex(), list),
0);
}
}
public boolean isEnabled(Object c) {
Object name = getName();
if (name == SELECT_PREVIOUS_COLUMN_CHANGE_LEAD ||
name == SELECT_NEXT_COLUMN_CHANGE_LEAD ||
name == SELECT_PREVIOUS_ROW_CHANGE_LEAD ||
name == SELECT_NEXT_ROW_CHANGE_LEAD ||
name == SELECT_FIRST_ROW_CHANGE_LEAD ||
name == SELECT_LAST_ROW_CHANGE_LEAD ||
name == SCROLL_UP_CHANGE_LEAD ||
name == SCROLL_DOWN_CHANGE_LEAD) {
// discontinuous selection actions are only enabled for
// DefaultListSelectionModel
return c != null && ((JList)c).getSelectionModel()
instanceof DefaultListSelectionModel;
}
return true;
}
private void clearSelection(JList list) {
list.clearSelection();
}
private void selectAll(JList list) {
int size = list.getModel().getSize();
if (size > 0) {
ListSelectionModel lsm = list.getSelectionModel();
int lead = adjustIndex(lsm.getLeadSelectionIndex(), list);
if (lsm.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
if (lead == -1) {
int min = adjustIndex(list.getMinSelectionIndex(), list);
lead = (min == -1 ? 0 : min);
}
list.setSelectionInterval(lead, lead);
list.ensureIndexIsVisible(lead);
} else {
list.setValueIsAdjusting(true);
int anchor = adjustIndex(lsm.getAnchorSelectionIndex(), list);
list.setSelectionInterval(0, size - 1);
// this is done to restore the anchor and lead
SwingUtilities2.setLeadAnchorWithoutSelection(lsm, anchor, lead);
list.setValueIsAdjusting(false);
}
}
}
private int getNextPageIndex(JList list, int direction) {
if (list.getModel().getSize() == 0) {
return -1;
}
int index = -1;
Rectangle visRect = list.getVisibleRect();
ListSelectionModel lsm = list.getSelectionModel();
int lead = adjustIndex(lsm.getLeadSelectionIndex(), list);
Rectangle leadRect =
(lead==-1) ? new Rectangle() : list.getCellBounds(lead, lead);
if (list.getLayoutOrientation() == JList.VERTICAL_WRAP &&
list.getVisibleRowCount() <= 0) {
if (!list.getComponentOrientation().isLeftToRight()) {
direction = -direction;
}
// apply for horizontal scrolling: the step for next
// page index is number of visible columns
if (direction < 0) {
// left
visRect.x = leadRect.x + leadRect.width - visRect.width;
Point p = new Point(visRect.x - 1, leadRect.y);
index = list.locationToIndex(p);
Rectangle cellBounds = list.getCellBounds(index, index);
if (visRect.intersects(cellBounds)) {
p.x = cellBounds.x - 1;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
}
// this is necessary for right-to-left orientation only
if (cellBounds.y != leadRect.y) {
p.x = cellBounds.x + cellBounds.width;
index = list.locationToIndex(p);
}
}
else {
// right
visRect.x = leadRect.x;
Point p = new Point(visRect.x + visRect.width, leadRect.y);
index = list.locationToIndex(p);
Rectangle cellBounds = list.getCellBounds(index, index);
if (visRect.intersects(cellBounds)) {
p.x = cellBounds.x + cellBounds.width;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
}
if (cellBounds.y != leadRect.y) {
p.x = cellBounds.x - 1;
index = list.locationToIndex(p);
}
}
}
else {
if (direction < 0) {
// up
// go to the first visible cell
Point p = new Point(leadRect.x, visRect.y);
index = list.locationToIndex(p);
if (lead <= index) {
// if lead is the first visible cell (or above it)
// adjust the visible rect up
visRect.y = leadRect.y + leadRect.height - visRect.height;
p.y = visRect.y;
index = list.locationToIndex(p);
Rectangle cellBounds = list.getCellBounds(index, index);
// go one cell down if first visible cell doesn't fit
// into adjasted visible rectangle
if (cellBounds.y < visRect.y) {
p.y = cellBounds.y + cellBounds.height;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
}
// if index isn't less then lead
// try to go to cell previous to lead
if (cellBounds.y >= leadRect.y) {
p.y = leadRect.y - 1;
index = list.locationToIndex(p);
}
}
}
else {
// down
// go to the last completely visible cell
Point p = new Point(leadRect.x,
visRect.y + visRect.height - 1);
index = list.locationToIndex(p);
Rectangle cellBounds = list.getCellBounds(index, index);
// go up one cell if last visible cell doesn't fit
// into visible rectangle
if (cellBounds.y + cellBounds.height >
visRect.y + visRect.height) {
p.y = cellBounds.y - 1;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
index = Math.max(index, lead);
}
if (lead >= index) {
// if lead is the last completely visible index
// (or below it) adjust the visible rect down
visRect.y = leadRect.y;
p.y = visRect.y + visRect.height - 1;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
// go one cell up if last visible cell doesn't fit
// into adjasted visible rectangle
if (cellBounds.y + cellBounds.height >
visRect.y + visRect.height) {
p.y = cellBounds.y - 1;
index = list.locationToIndex(p);
cellBounds = list.getCellBounds(index, index);
}
// if index isn't greater then lead
// try to go to cell next after lead
if (cellBounds.y <= leadRect.y) {
p.y = leadRect.y + leadRect.height;
index = list.locationToIndex(p);
}
}
}
}
return index;
}
private void changeSelection(JList list, int type,
int index, int direction) {
if (index >= 0 && index < list.getModel().getSize()) {
ListSelectionModel lsm = list.getSelectionModel();
// CHANGE_LEAD is only valid with multiple interval selection
if (type == CHANGE_LEAD &&
list.getSelectionMode()
!= ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) {
type = CHANGE_SELECTION;
}
// IMPORTANT - This needs to happen before the index is changed.
// This is because JFileChooser, which uses JList, also scrolls
// the selected item into view. If that happens first, then
// this method becomes a no-op.
adjustScrollPositionIfNecessary(list, index, direction);
if (type == EXTEND_SELECTION) {
int anchor = adjustIndex(lsm.getAnchorSelectionIndex(), list);
if (anchor == -1) {
anchor = 0;
}
list.setSelectionInterval(anchor, index);
}
else if (type == CHANGE_SELECTION) {
list.setSelectedIndex(index);
}
else {
// casting should be safe since the action is only enabled
// for DefaultListSelectionModel
((DefaultListSelectionModel)lsm).moveLeadSelectionIndex(index);
}
}
}
/**
* When scroll down makes selected index the last completely visible
* index. When scroll up makes selected index the first visible index.
* Adjust visible rectangle respect to list's component orientation.
*/
private void adjustScrollPositionIfNecessary(JList list, int index,
int direction) {
if (direction == 0) {
return;
}
Rectangle cellBounds = list.getCellBounds(index, index);
Rectangle visRect = list.getVisibleRect();
if (cellBounds != null && !visRect.contains(cellBounds)) {
if (list.getLayoutOrientation() == JList.VERTICAL_WRAP &&
list.getVisibleRowCount() <= 0) {
// horizontal
if (list.getComponentOrientation().isLeftToRight()) {
if (direction > 0) {
// right for left-to-right
int x =Math.max(0,
cellBounds.x + cellBounds.width - visRect.width);
int startIndex =
list.locationToIndex(new Point(x, cellBounds.y));
Rectangle startRect = list.getCellBounds(startIndex,
startIndex);
if (startRect.x < x && startRect.x < cellBounds.x) {
startRect.x += startRect.width;
startIndex =
list.locationToIndex(startRect.getLocation());
startRect = list.getCellBounds(startIndex,
startIndex);
}
cellBounds = startRect;
}
cellBounds.width = visRect.width;
}
else {
if (direction > 0) {
// left for right-to-left
int x = cellBounds.x + visRect.width;
int rightIndex =
list.locationToIndex(new Point(x, cellBounds.y));
Rectangle rightRect = list.getCellBounds(rightIndex,
rightIndex);
if (rightRect.x + rightRect.width > x &&
rightRect.x > cellBounds.x) {
rightRect.width = 0;
}
cellBounds.x = Math.max(0,
rightRect.x + rightRect.width - visRect.width);
cellBounds.width = visRect.width;
}
else {
cellBounds.x += Math.max(0,
cellBounds.width - visRect.width);
// adjust width to fit into visible rectangle
cellBounds.width = Math.min(cellBounds.width,
visRect.width);
}
}
}
else {
// vertical
if (direction > 0 &&
(cellBounds.y < visRect.y ||
cellBounds.y + cellBounds.height
> visRect.y + visRect.height)) {
//down
int y = Math.max(0,
cellBounds.y + cellBounds.height - visRect.height);
int startIndex =
list.locationToIndex(new Point(cellBounds.x, y));
Rectangle startRect = list.getCellBounds(startIndex,
startIndex);
if (startRect.y < y && startRect.y < cellBounds.y) {
startRect.y += startRect.height;
startIndex =
list.locationToIndex(startRect.getLocation());
startRect =
list.getCellBounds(startIndex, startIndex);
}
cellBounds = startRect;
cellBounds.height = visRect.height;
}
else {
// adjust height to fit into visible rectangle
cellBounds.height = Math.min(cellBounds.height, visRect.height);
}
}
list.scrollRectToVisible(cellBounds);
}
}
private int getNextColumnIndex(JList list, BasicListUI ui,
int amount) {
if (list.getLayoutOrientation() != JList.VERTICAL) {
int index = adjustIndex(list.getLeadSelectionIndex(), list);
int size = list.getModel().getSize();
if (index == -1) {
return 0;
} else if (size == 1) {
// there's only one item so we should select it
return 0;
} else if (ui == null || ui.columnCount <= 1) {
return -1;
}
int column = ui.convertModelToColumn(index);
int row = ui.convertModelToRow(index);
column += amount;
if (column >= ui.columnCount || column < 0) {
// No wrapping.
return -1;
}
int maxRowCount = ui.getRowCount(column);
if (row >= maxRowCount) {
return -1;
}
return ui.getModelIndex(column, row);
}
// Won't change the selection.
return -1;
}
private int getNextIndex(JList list, BasicListUI ui, int amount) {
int index = adjustIndex(list.getLeadSelectionIndex(), list);
int size = list.getModel().getSize();
if (index == -1) {
if (size > 0) {
if (amount > 0) {
index = 0;
}
else {
index = size - 1;
}
}
} else if (size == 1) {
// there's only one item so we should select it
index = 0;
} else if (list.getLayoutOrientation() == JList.HORIZONTAL_WRAP) {
if (ui != null) {
index += ui.columnCount * amount;
}
} else {
index += amount;
}
return index;
}
}
private class Handler implements FocusListener, KeyListener,
ListDataListener, ListSelectionListener,
MouseInputListener, PropertyChangeListener,
BeforeDrag {
//
// KeyListener
//
private String prefix = "";
private String typedString = "";
private long lastTime = 0L;
/**
* Invoked when a key has been typed.
*
* Moves the keyboard focus to the first element whose prefix matches the
* sequence of alphanumeric keys pressed by the user with delay less
* than value of <code>timeFactor</code> property (or 1000 milliseconds
* if it is not defined). Subsequent same key presses move the keyboard
* focus to the next object that starts with the same letter until another
* key is pressed, then it is treated as the prefix with appropriate number
* of the same letters followed by first typed another letter.
*/
public void keyTyped(KeyEvent e) {
JList src = (JList)e.getSource();
ListModel model = src.getModel();
if (model.getSize() == 0 || e.isAltDown() ||
BasicGraphicsUtils.isMenuShortcutKeyDown(e) ||
isNavigationKey(e)) {
// Nothing to select
return;
}
boolean startingFromSelection = true;
char c = e.getKeyChar();
long time = e.getWhen();
int startIndex = adjustIndex(src.getLeadSelectionIndex(), list);
if (time - lastTime < timeFactor) {
typedString += c;
if((prefix.length() == 1) && (c == prefix.charAt(0))) {
// Subsequent same key presses move the keyboard focus to the next
// object that starts with the same letter.
startIndex++;
} else {
prefix = typedString;
}
} else {
startIndex++;
typedString = "" + c;
prefix = typedString;
}
lastTime = time;
if (startIndex < 0 || startIndex >= model.getSize()) {
startingFromSelection = false;
startIndex = 0;
}
int index = src.getNextMatch(prefix, startIndex,
Position.Bias.Forward);
if (index >= 0) {
src.setSelectedIndex(index);
src.ensureIndexIsVisible(index);
} else if (startingFromSelection) { // wrap
index = src.getNextMatch(prefix, 0,
Position.Bias.Forward);
if (index >= 0) {
src.setSelectedIndex(index);
src.ensureIndexIsVisible(index);
}
}
}
/**
* Invoked when a key has been pressed.
*
* Checks to see if the key event is a navigation key to prevent
* dispatching these keys for the first letter navigation.
*/
public void keyPressed(KeyEvent e) {
if ( isNavigationKey(e) ) {
prefix = "";
typedString = "";
lastTime = 0L;
}
}
/**
* Invoked when a key has been released.
* See the class description for {@link KeyEvent} for a definition of
* a key released event.
*/
public void keyReleased(KeyEvent e) {
}
/**
* Returns whether or not the supplied key event maps to a key that is used for
* navigation. This is used for optimizing key input by only passing non-
* navigation keys to the first letter navigation mechanism.
*/
private boolean isNavigationKey(KeyEvent event) {
InputMap inputMap = list.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke key = KeyStroke.getKeyStrokeForEvent(event);
if (inputMap != null && inputMap.get(key) != null) {
return true;
}
return false;
}
//
// PropertyChangeListener
//
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
/* If the JList.model property changes, remove our listener,
* listDataListener from the old model and add it to the new one.
*/
if (propertyName == "model") {
ListModel oldModel = (ListModel)e.getOldValue();
ListModel newModel = (ListModel)e.getNewValue();
if (oldModel != null) {
oldModel.removeListDataListener(listDataListener);
}
if (newModel != null) {
newModel.addListDataListener(listDataListener);
}
updateLayoutStateNeeded |= modelChanged;
redrawList();
}
/* If the JList.selectionModel property changes, remove our listener,
* listSelectionListener from the old selectionModel and add it to the new one.
*/
else if (propertyName == "selectionModel") {
ListSelectionModel oldModel = (ListSelectionModel)e.getOldValue();
ListSelectionModel newModel = (ListSelectionModel)e.getNewValue();
if (oldModel != null) {
oldModel.removeListSelectionListener(listSelectionListener);
}
if (newModel != null) {
newModel.addListSelectionListener(listSelectionListener);
}
updateLayoutStateNeeded |= modelChanged;
redrawList();
}
else if (propertyName == "cellRenderer") {
updateLayoutStateNeeded |= cellRendererChanged;
redrawList();
}
else if (propertyName == "font") {
updateLayoutStateNeeded |= fontChanged;
redrawList();
}
else if (propertyName == "prototypeCellValue") {
updateLayoutStateNeeded |= prototypeCellValueChanged;
redrawList();
}
else if (propertyName == "fixedCellHeight") {
updateLayoutStateNeeded |= fixedCellHeightChanged;
redrawList();
}
else if (propertyName == "fixedCellWidth") {
updateLayoutStateNeeded |= fixedCellWidthChanged;
redrawList();
}
else if (propertyName == "selectionForeground") {
list.repaint();
}
else if (propertyName == "selectionBackground") {
list.repaint();
}
else if ("layoutOrientation" == propertyName) {
updateLayoutStateNeeded |= layoutOrientationChanged;
layoutOrientation = list.getLayoutOrientation();
redrawList();
}
else if ("visibleRowCount" == propertyName) {
if (layoutOrientation != JList.VERTICAL) {
updateLayoutStateNeeded |= layoutOrientationChanged;
redrawList();
}
}
else if ("componentOrientation" == propertyName) {
isLeftToRight = list.getComponentOrientation().isLeftToRight();
updateLayoutStateNeeded |= componentOrientationChanged;
redrawList();
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED);
SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED,
inputMap);
} else if ("List.isFileList" == propertyName) {
updateIsFileList();
redrawList();
} else if ("dropLocation" == propertyName) {
JList.DropLocation oldValue = (JList.DropLocation)e.getOldValue();
repaintDropLocation(oldValue);
repaintDropLocation(list.getDropLocation());
}
}
private void repaintDropLocation(JList.DropLocation loc) {
if (loc == null) {
return;
}
Rectangle r;
if (loc.isInsert()) {
r = getDropLineRect(loc);
} else {
r = getCellBounds(list, loc.getIndex());
}
if (r != null) {
list.repaint(r);
}
}
//
// ListDataListener
//
public void intervalAdded(ListDataEvent e) {
updateLayoutStateNeeded = modelChanged;
int minIndex = Math.min(e.getIndex0(), e.getIndex1());
int maxIndex = Math.max(e.getIndex0(), e.getIndex1());
/* Sync the SelectionModel with the DataModel.
*/
ListSelectionModel sm = list.getSelectionModel();
if (sm != null) {
sm.insertIndexInterval(minIndex, maxIndex - minIndex+1, true);
}
/* Repaint the entire list, from the origin of
* the first added cell, to the bottom of the
* component.
*/
redrawList();
}
public void intervalRemoved(ListDataEvent e)
{
updateLayoutStateNeeded = modelChanged;
/* Sync the SelectionModel with the DataModel.
*/
ListSelectionModel sm = list.getSelectionModel();
if (sm != null) {
sm.removeIndexInterval(e.getIndex0(), e.getIndex1());
}
/* Repaint the entire list, from the origin of
* the first removed cell, to the bottom of the
* component.
*/
redrawList();
}
public void contentsChanged(ListDataEvent e) {
updateLayoutStateNeeded = modelChanged;
redrawList();
}
//
// ListSelectionListener
//
public void valueChanged(ListSelectionEvent e) {
maybeUpdateLayoutState();
int size = list.getModel().getSize();
int firstIndex = Math.min(size - 1, Math.max(e.getFirstIndex(), 0));
int lastIndex = Math.min(size - 1, Math.max(e.getLastIndex(), 0));
Rectangle bounds = getCellBounds(list, firstIndex, lastIndex);
if (bounds != null) {
list.repaint(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
//
// MouseListener
//
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
// Whether or not the mouse press (which is being considered as part
// of a drag sequence) also caused the selection change to be fully
// processed.
private boolean dragPressDidSelection;
public void mousePressed(MouseEvent e) {
if (SwingUtilities2.shouldIgnore(e, list)) {
return;
}
boolean dragEnabled = list.getDragEnabled();
boolean grabFocus = true;
// different behavior if drag is enabled
if (dragEnabled) {
int row = SwingUtilities2.loc2IndexFileList(list, e.getPoint());
// if we have a valid row and this is a drag initiating event
if (row != -1 && DragRecognitionSupport.mousePressed(e)) {
dragPressDidSelection = false;
if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
// do nothing for control - will be handled on release
// or when drag starts
return;
} else if (!e.isShiftDown() && list.isSelectedIndex(row)) {
// clicking on something that's already selected
// and need to make it the lead now
list.addSelectionInterval(row, row);
return;
}
// could be a drag initiating event - don't grab focus
grabFocus = false;
dragPressDidSelection = true;
}
} else {
// When drag is enabled mouse drags won't change the selection
// in the list, so we only set the isAdjusting flag when it's
// not enabled
list.setValueIsAdjusting(true);
}
if (grabFocus) {
SwingUtilities2.adjustFocus(list);
}
adjustSelection(e);
}
private void adjustSelection(MouseEvent e) {
int row = SwingUtilities2.loc2IndexFileList(list, e.getPoint());
if (row < 0) {
// If shift is down in multi-select, we should do nothing.
// For single select or non-shift-click, clear the selection
if (isFileList &&
e.getID() == MouseEvent.MOUSE_PRESSED &&
(!e.isShiftDown() ||
list.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) {
list.clearSelection();
}
}
else {
int anchorIndex = adjustIndex(list.getAnchorSelectionIndex(), list);
boolean anchorSelected;
if (anchorIndex == -1) {
anchorIndex = 0;
anchorSelected = false;
} else {
anchorSelected = list.isSelectedIndex(anchorIndex);
}
if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
if (e.isShiftDown()) {
if (anchorSelected) {
list.addSelectionInterval(anchorIndex, row);
} else {
list.removeSelectionInterval(anchorIndex, row);
if (isFileList) {
list.addSelectionInterval(row, row);
list.getSelectionModel().setAnchorSelectionIndex(anchorIndex);
}
}
} else if (list.isSelectedIndex(row)) {
list.removeSelectionInterval(row, row);
} else {
list.addSelectionInterval(row, row);
}
} else if (e.isShiftDown()) {
list.setSelectionInterval(anchorIndex, row);
} else {
list.setSelectionInterval(row, row);
}
}
}
public void dragStarting(MouseEvent me) {
if (BasicGraphicsUtils.isMenuShortcutKeyDown(me)) {
int row = SwingUtilities2.loc2IndexFileList(list, me.getPoint());
list.addSelectionInterval(row, row);
}
}
public void mouseDragged(MouseEvent e) {
if (SwingUtilities2.shouldIgnore(e, list)) {
return;
}
if (list.getDragEnabled()) {
DragRecognitionSupport.mouseDragged(e, this);
return;
}
if (e.isShiftDown() || BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
return;
}
int row = locationToIndex(list, e.getPoint());
if (row != -1) {
// 4835633. Dragging onto a File should not select it.
if (isFileList) {
return;
}
Rectangle cellBounds = getCellBounds(list, row, row);
if (cellBounds != null) {
list.scrollRectToVisible(cellBounds);
list.setSelectionInterval(row, row);
}
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
if (SwingUtilities2.shouldIgnore(e, list)) {
return;
}
if (list.getDragEnabled()) {
MouseEvent me = DragRecognitionSupport.mouseReleased(e);
if (me != null) {
SwingUtilities2.adjustFocus(list);
if (!dragPressDidSelection) {
adjustSelection(me);
}
}
} else {
list.setValueIsAdjusting(false);
}
}
//
// FocusListener
//
protected void repaintCellFocus()
{
int leadIndex = adjustIndex(list.getLeadSelectionIndex(), list);
if (leadIndex != -1) {
Rectangle r = getCellBounds(list, leadIndex, leadIndex);
if (r != null) {
list.repaint(r.x, r.y, r.width, r.height);
}
}
}
/* The focusGained() focusLost() methods run when the JList
* focus changes.
*/
public void focusGained(FocusEvent e) {
repaintCellFocus();
}
public void focusLost(FocusEvent e) {
repaintCellFocus();
}
}
private static int adjustIndex(int index, JList list) {
return index < list.getModel().getSize() ? index : -1;
}
private static final TransferHandler defaultTransferHandler = new ListTransferHandler();
static class ListTransferHandler extends TransferHandler implements UIResource {
/**
* Create a Transferable to use as the source for a data transfer.
*
* @param c The component holding the data to be transfered. This
* argument is provided to enable sharing of TransferHandlers by
* multiple components.
* @return The representation of the data to be transfered.
*
*/
protected Transferable createTransferable(JComponent c) {
if (c instanceof JList) {
JList list = (JList) c;
Object[] values = list.getSelectedValues();
if (values == null || values.length == 0) {
return null;
}
StringBuffer plainBuf = new StringBuffer();
StringBuffer htmlBuf = new StringBuffer();
htmlBuf.append("<html>\n<body>\n<ul>\n");
for (int i = 0; i < values.length; i++) {
Object obj = values[i];
String val = ((obj == null) ? "" : obj.toString());
plainBuf.append(val + "\n");
htmlBuf.append(" <li>" + val + "\n");
}
// remove the last newline
plainBuf.deleteCharAt(plainBuf.length() - 1);
htmlBuf.append("</ul>\n</body>\n</html>");
return new BasicTransferable(plainBuf.toString(), htmlBuf.toString());
}
return null;
}
public int getSourceActions(JComponent c) {
return COPY;
}
}
}
| gpl-2.0 |
MatrixPeckham/Ray-Tracer-Ground-Up-Java | RayTracer-Core/src/com/matrixpeckham/raytracer/geometricobjects/partobjects/ConcavePartTorus.java | 3530 | /*
* Copyright (C) 2015 William Matrix Peckham
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.matrixpeckham.raytracer.geometricobjects.partobjects;
import com.matrixpeckham.raytracer.geometricobjects.parametric.Torus;
import com.matrixpeckham.raytracer.util.Utility;
/**
* Concave Part Torus class. same as ConvexPartTorus, but
* ConcavePartTorus.getNormalType() returns reverse
*
* @author William Matrix Peckham
*/
public class ConcavePartTorus extends Torus {
//for more comments see PartTorus
/**
* override parametric for min/max values
*/
protected static class PartTorusParam extends Torus.TorusParametric {
double phiMin, phiMax, thetaMin, thetaMax;
/**
*
* @param a
* @param b
*/
public PartTorusParam(double a, double b) {
this(a, b, 0, Utility.TWO_PI, 0, Utility.TWO_PI);
}
/**
*
* @param a
* @param b
* @param phiMin
* @param phiMax
* @param thetaMin
* @param thetaMax
*/
public PartTorusParam(double a, double b, double phiMin, double phiMax,
double thetaMin, double thetaMax) {
super(a, b);
this.phiMax = phiMax * Utility.PI_ON_180;
this.phiMin = phiMin * Utility.PI_ON_180;
this.thetaMax = thetaMax * Utility.PI_ON_180;
this.thetaMin = thetaMin * Utility.PI_ON_180;
}
@Override
public double getMaxU() {
return phiMax;
}
@Override
public double getMaxV() {
return thetaMax;
}
@Override
public double getMinU() {
return phiMin;
}
@Override
public double getMinV() {
return thetaMin;
}
@Override
public NormalType getNormalType() {
return NormalType.REVERSE;
}
@Override
public boolean isClosedU() {
return false;
}
@Override
public boolean isClosedV() {
return false;
}
}
/**
* default constructor
*/
public ConcavePartTorus() {
super(new PartTorusParam(1, 0.5));
}
/**
* initializing constructor
*
* @param a
* @param b
*/
public ConcavePartTorus(double a, double b) {
super(new PartTorusParam(a, b));
}
/**
* initializing constructor (degrees)
*
* @param a
* @param b
* @param phiMin
* @param phiMax
* @param thetaMin
* @param thetaMax
*/
public ConcavePartTorus(double a, double b, double phiMin, double phiMax,
double thetaMin, double thetaMax) {
super(new PartTorusParam(a, b, phiMin, phiMax, thetaMin, thetaMax));
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/sun/net/www/httptest/HttpTransaction.java | 11006 | /*
* Copyright 2002-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import sun.net.www.MessageHeader;
/**
* This class encapsulates a HTTP request received and a response to be
* generated in one transaction. It provides methods for examaining the
* request from the client, and for building and sending a reply.
*/
public class HttpTransaction {
String command;
URI requesturi;
HttpServer.Server server;
MessageHeader reqheaders, reqtrailers;
String reqbody;
byte[] rspbody;
MessageHeader rspheaders, rsptrailers;
SelectionKey key;
int rspbodylen;
boolean rspchunked;
HttpTransaction (HttpServer.Server server, String command,
URI requesturi, MessageHeader headers,
String body, MessageHeader trailers, SelectionKey key) {
this.command = command;
this.requesturi = requesturi;
this.reqheaders = headers;
this.reqbody = body;
this.reqtrailers = trailers;
this.key = key;
this.server = server;
}
/**
* Get the value of a request header whose name is specified by the
* String argument.
*
* @param key the name of the request header
* @return the value of the header or null if it does not exist
*/
public String getRequestHeader (String key) {
return reqheaders.findValue (key);
}
/**
* Get the value of a response header whose name is specified by the
* String argument.
*
* @param key the name of the response header
* @return the value of the header or null if it does not exist
*/
public String getResponseHeader (String key) {
return rspheaders.findValue (key);
}
/**
* Get the request URI
*
* @return the request URI
*/
public URI getRequestURI () {
return requesturi;
}
public String toString () {
StringBuffer buf = new StringBuffer();
buf.append ("Request from: ").append (key.channel().toString()).append("\r\n");
buf.append ("Command: ").append (command).append("\r\n");
buf.append ("Request URI: ").append (requesturi).append("\r\n");
buf.append ("Headers: ").append("\r\n");
buf.append (reqheaders.toString()).append("\r\n");
buf.append ("Body: ").append (reqbody).append("\r\n");
buf.append ("---------Response-------\r\n");
buf.append ("Headers: ").append("\r\n");
if (rspheaders != null) {
buf.append (rspheaders.toString()).append("\r\n");
}
String rbody = rspbody == null? "": new String (rspbody);
buf.append ("Body: ").append (rbody).append("\r\n");
return new String (buf);
}
/**
* Get the value of a request trailer whose name is specified by
* the String argument.
*
* @param key the name of the request trailer
* @return the value of the trailer or null if it does not exist
*/
public String getRequestTrailer (String key) {
return reqtrailers.findValue (key);
}
/**
* Add a response header to the response. Multiple calls with the same
* key value result in multiple header lines with the same key identifier
* @param key the name of the request header to add
* @param val the value of the header
*/
public void addResponseHeader (String key, String val) {
if (rspheaders == null)
rspheaders = new MessageHeader ();
rspheaders.add (key, val);
}
/**
* Set a response header. Searches for first header with named key
* and replaces its value with val
* @param key the name of the request header to add
* @param val the value of the header
*/
public void setResponseHeader (String key, String val) {
if (rspheaders == null)
rspheaders = new MessageHeader ();
rspheaders.set (key, val);
}
/**
* Add a response trailer to the response. Multiple calls with the same
* key value result in multiple trailer lines with the same key identifier
* @param key the name of the request trailer to add
* @param val the value of the trailer
*/
public void addResponseTrailer (String key, String val) {
if (rsptrailers == null)
rsptrailers = new MessageHeader ();
rsptrailers.add (key, val);
}
/**
* Get the request method
*
* @return the request method
*/
public String getRequestMethod (){
return command;
}
/**
* Perform an orderly close of the TCP connection associated with this
* request. This method guarantees that any response already sent will
* not be reset (by this end). The implementation does a shutdownOutput()
* of the TCP connection and for a period of time consumes and discards
* data received on the reading side of the connection. This happens
* in the background. After the period has expired the
* connection is completely closed.
*/
public void orderlyClose () {
try {
server.orderlyCloseChannel (key);
} catch (IOException e) {
System.out.println (e);
}
}
/**
* Do an immediate abortive close of the TCP connection associated
* with this request.
*/
public void abortiveClose () {
try {
server.abortiveCloseChannel(key);
} catch (IOException e) {
System.out.println (e);
}
}
/**
* Get the SocketChannel associated with this request
*
* @return the socket channel
*/
public SocketChannel channel() {
return (SocketChannel) key.channel();
}
/**
* Get the request entity body associated with this request
* as a single String.
*
* @return the entity body in one String
*/
public String getRequestEntityBody (){
return reqbody;
}
/**
* Set the entity response body with the given string
* The content length is set to the length of the string
* @param body the string to send in the response
*/
public void setResponseEntityBody (String body){
rspbody = body.getBytes();
rspbodylen = body.length();
rspchunked = false;
addResponseHeader ("Content-length", Integer.toString (rspbodylen));
}
/**
* Set the entity response body with the given byte[]
* The content length is set to the gven length
* @param body the string to send in the response
*/
public void setResponseEntityBody (byte[] body, int len){
rspbody = body;
rspbodylen = len;
rspchunked = false;
addResponseHeader ("Content-length", Integer.toString (rspbodylen));
}
/**
* Set the entity response body by reading the given inputstream
*
* @param is the inputstream from which to read the body
*/
public void setResponseEntityBody (InputStream is) throws IOException {
byte[] buf = new byte [2048];
byte[] total = new byte [2048];
int total_len = 2048;
int c, len=0;
while ((c=is.read (buf)) != -1) {
if (len+c > total_len) {
byte[] total1 = new byte [total_len * 2];
System.arraycopy (total, 0, total1, 0, len);
total = total1;
total_len = total_len * 2;
}
System.arraycopy (buf, 0, total, len, c);
len += c;
}
setResponseEntityBody (total, len);
}
/* chunked */
/**
* Set the entity response body with the given array of strings
* The content encoding is set to "chunked" and each array element
* is sent as one chunk.
* @param body the array of string chunks to send in the response
*/
public void setResponseEntityBody (String[] body) {
StringBuffer buf = new StringBuffer ();
int len = 0;
for (int i=0; i<body.length; i++) {
String chunklen = Integer.toHexString (body[i].length());
len += body[i].length();
buf.append (chunklen).append ("\r\n");
buf.append (body[i]).append ("\r\n");
}
buf.append ("0\r\n");
rspbody = new String (buf).getBytes();
rspbodylen = rspbody.length;
rspchunked = true;
addResponseHeader ("Transfer-encoding", "chunked");
}
/**
* Send the response with the current set of response parameters
* but using the response code and string tag line as specified
* @param rCode the response code to send
* @param rTag the response string to send with the response code
*/
public void sendResponse (int rCode, String rTag) throws IOException {
OutputStream os = new HttpServer.NioOutputStream(channel());
PrintStream ps = new PrintStream (os);
ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
if (rspheaders != null) {
rspheaders.print (ps);
} else {
ps.print ("\r\n");
}
ps.flush ();
if (rspbody != null) {
os.write (rspbody, 0, rspbodylen);
os.flush();
}
if (rsptrailers != null) {
rsptrailers.print (ps);
} else if (rspchunked) {
ps.print ("\r\n");
}
ps.flush();
}
/* sends one byte less than intended */
public void sendPartialResponse (int rCode, String rTag)throws IOException {
OutputStream os = new HttpServer.NioOutputStream(channel());
PrintStream ps = new PrintStream (os);
ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
ps.flush();
if (rspbody != null) {
os.write (rspbody, 0, rspbodylen-1);
os.flush();
}
if (rsptrailers != null) {
rsptrailers.print (ps);
}
ps.flush();
}
}
| gpl-2.0 |
632677663/repositoryJava | nagel/src/main/java/nagel/frame/category/controller/BaseController.java | 506 | package nagel.frame.category.controller;
import nagel.frame.category.util.Const;
public class BaseController {
protected int page = Const.PAGE;
protected int pageSize = Const.PAGE_SIZE;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
| gpl-2.0 |
exbluesbreaker/csu-code-analysis | java-xml/jcfgen/src/ru/csu/stan/java/cfg/jaxb/BaseCfgElement.java | 3165 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.02.27 at 10:05:31 PM YEKT
//
package ru.csu.stan.java.cfg.jaxb;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BaseCfgElement complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BaseCfgElement">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="fromlineno" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="col_offset" type="{http://www.w3.org/2001/XMLSchema}integer" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BaseCfgElement")
@XmlSeeAlso({
TryFinally.class,
TryExcept.class,
While.class,
For.class,
If.class,
With.class,
Block.class
})
public class BaseCfgElement {
@XmlAttribute
protected BigInteger id;
@XmlAttribute
protected BigInteger fromlineno;
@XmlAttribute(name = "col_offset")
protected BigInteger colOffset;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setId(BigInteger value) {
this.id = value;
}
/**
* Gets the value of the fromlineno property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getFromlineno() {
return fromlineno;
}
/**
* Sets the value of the fromlineno property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setFromlineno(BigInteger value) {
this.fromlineno = value;
}
/**
* Gets the value of the colOffset property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getColOffset() {
return colOffset;
}
/**
* Sets the value of the colOffset property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setColOffset(BigInteger value) {
this.colOffset = value;
}
}
| gpl-2.0 |
pspala/mpeg7 | MPEG7Annotation/src/org/exist/xquery/modules/mpeg7/net/semanticmetadata/lire/imageanalysis/fcth/FCTHQuant.java | 7700 | /*
* This file is part of the LIRE project: http://www.semanticmetadata.net/lire
* LIRE is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* LIRE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LIRE; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* We kindly ask you to refer the any or one of the following publications in
* any publication mentioning or employing Lire:
*
* Lux Mathias, Savvas A. Chatzichristofis. Lire: Lucene Image Retrieval –
* An Extensible Java CBIR Library. In proceedings of the 16th ACM International
* Conference on Multimedia, pp. 1085-1088, Vancouver, Canada, 2008
* URL: http://doi.acm.org/10.1145/1459359.1459577
*
* Lux Mathias. Content Based Image Retrieval with LIRE. In proceedings of the
* 19th ACM International Conference on Multimedia, pp. 735-738, Scottsdale,
* Arizona, USA, 2011
* URL: http://dl.acm.org/citation.cfm?id=2072432
*
* Mathias Lux, Oge Marques. Visual Information Retrieval using Java and LIRE
* Morgan & Claypool, 2013
* URL: http://www.morganclaypool.com/doi/abs/10.2200/S00468ED1V01Y201301ICR025
*
* Copyright statement:
* --------------------
* (c) 2002-2013 by Mathias Lux (mathias@juggle.at)
* http://www.semanticmetadata.net/lire, http://www.lire-project.net
*/
package org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.imageanalysis.fcth;
public class FCTHQuant {
private static double[] QuantTable =
{130.0887781556944, 9317.31301788632, 22434.355689233365, 43120.548602722061, 83168.640165905046, 101430.52589975641, 174840.65838706805, 224480.41479670047};
double[] QuantTable2 =
{130.0887781556944, 9317.31301788632, 22434.355689233365, 43120.548602722061, 83168.640165905046, 151430.52589975641, 174840.65838706805, 224480.41479670047};
double[] QuantTable3 =
{239.769468748322, 17321.704312335689, 39113.643180734696, 69333.512093874378, 79122.46400035513, 90980.3325940354, 161795.93301552488, 184729.98648386425};
double[] QuantTable4 =
{239.769468748322, 17321.704312335689, 39113.643180734696, 69333.512093874378, 79122.46400035513, 90980.3325940354, 161795.93301552488, 184729.98648386425};
double[] QuantTable5 =
{239.769468748322, 17321.704312335689, 39113.643180734696, 69333.512093874378, 79122.46400035513, 90980.3325940354, 161795.93301552488, 184729.98648386425};
double[] QuantTable6 =
{239.769468748322, 17321.704312335689, 39113.643180734696, 69333.512093874378, 79122.46400035513, 90980.3325940354, 161795.93301552488, 184729.98648386425};
double[] QuantTable7 =
{180.19686541079636, 23730.024499150866, 41457.152912541605, 53918.55437576842, 69122.46400035513, 81980.3325940354, 91795.93301552488, 124729.98648386425};
double[] QuantTable8 =
{180.19686541079636, 23730.024499150866, 41457.152912541605, 53918.55437576842, 69122.46400035513, 81980.3325940354, 91795.93301552488, 124729.98648386425};
public double[] Apply(double[] Local_Edge_Histogram) {
double[] Edge_HistogramElement = new double[Local_Edge_Histogram.length];
double[] ElementsDistance = new double[8];
double Max = 1;
for (int i = 0; i < 24; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 24; i < 48; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable2[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 48; i < 72; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable3[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 72; i < 96; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable4[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 96; i < 120; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable5[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 120; i < 144; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable6[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 144; i < 168; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable7[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
for (int i = 168; i < 192; i++) {
Edge_HistogramElement[i] = 0;
for (int j = 0; j < 8; j++) {
ElementsDistance[j] = Math.abs(Local_Edge_Histogram[i] - QuantTable8[j] / 1000000);
}
Max = 1;
for (int j = 0; j < 8; j++) {
if (ElementsDistance[j] < Max) {
Max = ElementsDistance[j];
Edge_HistogramElement[i] = j;
}
}
}
return Edge_HistogramElement;
}
}
| gpl-2.0 |
camposer/curso_in_spring | Ejercicio4/src/config/AppConfig.java | 1583 | package config;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import service.IPersonaService;
import service.PersonaService;
import dao.IPersonaDao;
import dao.PersonaDao;
@EnableTransactionManagement // Habilita el manejo de transacciones
@Configuration // Esta clase contiene configuraciones
public class AppConfig {
@Bean(name="entityManagerFactory") // Define un bean con id = entityManagerFactory
@Scope("singleton")
public EntityManagerFactory getEntityManagerFactory() { // El nombre del método es el id (si no tiene un Bean.name)
return Persistence.createEntityManagerFactory("PersonaJpa");
}
@Bean
public EntityManager entityManager() {
return getEntityManagerFactory().createEntityManager();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(getEntityManagerFactory());
return transactionManager;
}
@Bean
public IPersonaDao personaDao() {
return new PersonaDao();
}
@Bean
public IPersonaService personaService() {
return new PersonaService();
}
}
| gpl-2.0 |
flbaue/rnp-wise14 | Aufgabe2/src/main/java/flaue/pop3proxy/client/responses/ErrResponse.java | 334 | package flaue.pop3proxy.client.responses;
/**
* Created by flbaue on 08.11.14.
*/
public class ErrResponse extends AbstractResponse {
public static final String COMMAND = "-ERR";
public ErrResponse(final String payload) {
super(COMMAND, payload);
}
public ErrResponse() {
super(COMMAND);
}
}
| gpl-2.0 |
kartoFlane/OverdriveGDX | engine-core/src/main/java/com/ftloverdrive/util/MutableFloat.java | 269 | package com.ftloverdrive.util;
/**
* An object that wraps a float.
*/
public class MutableFloat {
protected float f = 0;
public void set( float f ) {
this.f = f;
}
public void increment( float f ) {
this.f += f;
}
public float get() {
return f;
}
}
| gpl-2.0 |
JuanLSanchez/Chefs | project/src/main/java/es/juanlsanchez/chefs/repository/PersistenceAuditEventRepository.java | 689 | package es.juanlsanchez.chefs.repository;
import es.juanlsanchez.chefs.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the PersistentAuditEvent entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfter(String principal, LocalDateTime after);
List<PersistentAuditEvent> findAllByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate);
}
| gpl-2.0 |
christianchristensen/resin | modules/resin/src/com/caucho/security/FormLogin.java | 11978 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.security;
import com.caucho.config.ConfigException;
import com.caucho.config.Service;
import com.caucho.server.http.CauchoRequest;
import com.caucho.server.http.CauchoResponse;
import com.caucho.server.session.SessionManager;
import com.caucho.server.webapp.WebApp;
import com.caucho.util.L10N;
import javax.annotation.PostConstruct;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;
import java.util.logging.Level;
/**
* Used to authenticate users in a servlet request. Applications will
* implement the Authenticator interface with a bean for authentication.
*
* @since Resin 2.0.2
*/
@Service
public class FormLogin extends AbstractLogin
{
private static final L10N L = new L10N(FormLogin.class);
public static final String LOGIN_CHECK
= "com.caucho.security.form.login";
public static final String LOGIN_SAVED_PATH
= "com.caucho.servlet.login.path";
public static final String LOGIN_SAVED_QUERY
= "com.caucho.servlet.login.query";
protected String _loginPage;
protected String _errorPage;
protected boolean _internalForward;
protected boolean _formURIPriority;
private WebApp _webApp = WebApp.getCurrent();
/**
* Sets the login page.
*/
public void setFormLoginPage(String formLoginPage)
throws ConfigException
{
int colon = formLoginPage.indexOf(':');
int slash = formLoginPage.indexOf('/');
if (colon > 0 && colon < slash) {
}
else if (slash != 0)
throw new ConfigException(L.l("form-login-page '{0}' must start with '/'. The form-login-page is relative to the web-app root.", formLoginPage));
_loginPage = formLoginPage;
}
public void setLoginPage(String loginPage)
{
setFormLoginPage(loginPage);
}
/**
* Gets the login page.
*/
public String getFormLoginPage()
{
return _loginPage;
}
/**
* Sets the error page.
*/
public void setFormErrorPage(String formErrorPage)
throws ConfigException
{
if (! formErrorPage.startsWith("/"))
throw new ConfigException(L.l("form-error-page '{0}' must start with '/'. The form-error-page is relative to the web-app root.", formErrorPage));
_errorPage = formErrorPage;
}
public void setErrorPage(String errorPage)
{
setFormErrorPage(errorPage);
}
/**
* Gets the error page.
*/
public String getFormErrorPage()
{
return _errorPage;
}
/**
* Returns true if a successful login allows an internal forward
* instead of a redirect.
*/
public boolean getInternalForward()
{
return _internalForward;
}
/**
* Set true if a successful login allows an internal forward
* instead of a redirect.
*/
public void setInternalForward(boolean internalForward)
{
_internalForward = internalForward;
}
/**
* Returns true if the form's j_uri has priority over the saved
* URL.
*/
public boolean getFormURIPriority()
{
return _formURIPriority;
}
/**
* True if the form's j_uri has priority over the saved URL.
*/
public void setFormURIPriority(boolean formPriority)
{
_formURIPriority = formPriority;
}
/**
* Initialize
*/
@PostConstruct
public void init()
throws ServletException
{
super.init();
if (_errorPage == null)
_errorPage = _loginPage;
if (_loginPage == null)
_loginPage = _errorPage;
if (_loginPage == null)
throw new ConfigException(L.l("FormLogin needs an form-login-page"));
}
/**
* Returns the authentication type.
*/
public String getAuthType()
{
return "Form";
}
/**
* Returns true if the request has a matching login.
*/
@Override
public boolean isLoginUsedForRequest(HttpServletRequest request)
{
return request.getServletPath().indexOf("j_security_check") >= 0;
}
/**
* Logs a user in with a user name and a password.
*
* @param request servlet request
*
* @return the logged in principal on success, null on failure.
*/
@Override
public Principal getUserPrincipalImpl(HttpServletRequest request)
{
Principal user;
Authenticator auth = getAuthenticator();
if (auth instanceof CookieAuthenticator) {
CookieAuthenticator cookieAuth = (CookieAuthenticator) auth;
Cookie resinAuth = ((CauchoRequest) request).getCookie("resinauthid");
if (resinAuth != null) {
user = cookieAuth.authenticateByCookie(resinAuth.getValue());
if (user != null)
return user;
}
}
String userName = request.getParameter("j_username");
String passwordString = request.getParameter("j_password");
if (userName == null || passwordString == null)
return null;
char []password = passwordString.toCharArray();
BasicPrincipal basicUser = new BasicPrincipal(userName);
Credentials credentials = new PasswordCredentials(password);
user = auth.authenticate(basicUser, credentials, request);
return user;
}
/**
* Returns true if a new login overrides the saved user
*/
@Override
protected boolean isSavedUserValid(HttpServletRequest request,
Principal savedUser)
{
String userName = request.getParameter("j_username");
// server/135j
return userName == null;// || userName.equals(savedUser.getName());
}
/**
* Updates after a successful login
*
* @param request servlet request
* @param response servlet response, in case any cookie need sending.
*
* @return the logged in principal on success, null on failure.
*/
@Override
public void loginSuccessResponse(Principal user,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
if (request.getAttribute(LOGIN_CHECK) != null)
return;
request.setAttribute(LOGIN_CHECK, "login");
WebApp app = _webApp;
String jUseCookieAuth = (String) request.getParameter("j_use_cookie_auth");
Authenticator auth = getAuthenticator();
if (auth instanceof CookieAuthenticator
&& ((CookieAuthenticator) auth).isCookieSupported(jUseCookieAuth)) {
CookieAuthenticator cookieAuth = (CookieAuthenticator) auth;
generateCookie(user, cookieAuth, app, request, response);
}
String path = request.getServletPath();
if (path == null)
path = request.getPathInfo();
else if (request.getPathInfo() != null)
path = path + request.getPathInfo();
if (path.equals("")) {
// Forward?
path = request.getContextPath() + "/";
response.sendRedirect(response.encodeRedirectURL(path));
return;
}
String uri = request.getRequestURI();
if (path.endsWith("/j_security_check")) {
RequestDispatcher disp;
disp = app.getNamedDispatcher("j_security_check");
if (disp == null)
throw new ServletException(L.l("j_security_check servlet must be defined to use form-based login."));
disp.forward(request, response);
return;
}
}
/**
* Logs a user in with a user name and a password.
*
* @param request servlet request
* @param response servlet response, in case any cookie need sending.
* @param application servlet application
*
* @return the logged in principal on success, null on failure.
*/
public void loginChallenge(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String path = request.getServletPath();
if (path == null)
path = request.getPathInfo();
else if (request.getPathInfo() != null)
path = path + request.getPathInfo();
if (path.equals("")) {
// Forward?
path = request.getContextPath() + "/";
response.sendRedirect(response.encodeRedirectURL(path));
return;
}
WebApp app = _webApp;
String uri = request.getRequestURI();
if (path.endsWith("/j_security_check")) {
// server/12d8, server/12bs
if (response instanceof CauchoResponse) {
((CauchoResponse) response).setNoCache(true);
}
else {
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
}
RequestDispatcher disp = app.getRequestDispatcher(_errorPage);
disp.forward(request, response);
/*
// && request.getAttribute(LOGIN_CHECK) == null) {
request.setAttribute(LOGIN_CHECK, "login");
RequestDispatcher disp;
disp = app.getNamedDispatcher("j_security_check");
if (disp == null)
throw new ServletException(L.l("j_security_check servlet must be defined to use form-based login."));
disp.forward(request, response);
*/
return;
}
else if (uri.equals(_loginPage) || uri.equals(_errorPage)) {
request.getRequestDispatcher(path).forward(request, response);
return;
}
HttpSession session = request.getSession();
session.putValue(LOGIN_SAVED_PATH, path);
session.putValue(LOGIN_SAVED_QUERY, request.getQueryString());
if (response instanceof CauchoResponse) {
((CauchoResponse) response).killCache();
((CauchoResponse) response).setNoCache(true);
}
else {
response.setHeader("Cache-Control", "no-cache");
}
// In case where the authenticator is something like https:/
if (! _loginPage.startsWith("/")) {
response.sendRedirect(response.encodeRedirectURL(_loginPage));
return;
}
// Forwards to the loginPage, never redirects according to the spec.
request.setAttribute(LOGIN_CHECK, "login");
//RequestDispatcher disp = app.getLoginDispatcher(loginPage);
RequestDispatcher disp = app.getRequestDispatcher(_loginPage);
disp.forward(request, response);
if (log.isLoggable(Level.FINE))
log.fine(this + " request '" + uri + "' has no authenticated user");
}
private void generateCookie(Principal user,
CookieAuthenticator auth,
WebApp webApp,
HttpServletRequest request,
HttpServletResponse response)
{
if (webApp == null)
return;
SessionManager manager = webApp.getSessionManager();
String value = manager.createCookieValue();
Cookie cookie = new Cookie("resinauthid", value);
cookie.setVersion(1);
long cookieMaxAge = 365L * 24L * 3600L * 1000L;
cookie.setMaxAge((int) (cookieMaxAge / 1000L));
cookie.setPath("/");
cookie.setDomain(webApp.generateCookieDomain(request));
auth.associateCookie(user, value);
response.addCookie(cookie);
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/util/Formatter/BasicLong.java | 21616 | /*
* Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* Type-specific source code for unit test
*
* Regenerate the BasicX classes via genBasic.sh whenever this file changes.
* We check in the generated source files so that the test tree can be used
* independently of the rest of the source tree.
*/
// -- This file was mechanically generated: Do not edit! -- //
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormatSymbols;
import java.util.*;
import static java.util.Calendar.*;
public class BasicLong extends Basic {
private static void test(String fs, String exp, Object ... args) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, args);
ck(fs, exp, f.toString());
}
private static void test(Locale l, String fs, String exp, Object ... args)
{
Formatter f = new Formatter(new StringBuilder(), l);
f.format(fs, args);
ck(fs, exp, f.toString());
}
private static void test(String fs, Object ... args) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, args);
ck(fs, "fail", f.toString());
}
private static void test(String fs) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, "fail");
ck(fs, "fail", f.toString());
}
private static void testSysOut(String fs, String exp, Object ... args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
PrintStream saveOut = System.out;
fos = new FileOutputStream("testSysOut");
System.setOut(new PrintStream(fos));
System.out.format(Locale.US, fs, args);
fos.close();
fis = new FileInputStream("testSysOut");
byte [] ba = new byte[exp.length()];
int len = fis.read(ba);
String got = new String(ba);
if (len != ba.length)
fail(fs, exp, got);
ck(fs, exp, got);
System.setOut(saveOut);
} catch (FileNotFoundException ex) {
fail(fs, ex.getClass());
} catch (IOException ex) {
fail(fs, ex.getClass());
} finally {
try {
if (fos != null)
fos.close();
if (fis != null)
fis.close();
} catch (IOException ex) {
fail(fs, ex.getClass());
}
}
}
private static void tryCatch(String fs, Class<?> ex) {
boolean caught = false;
try {
test(fs);
} catch (Throwable x) {
if (ex.isAssignableFrom(x.getClass()))
caught = true;
}
if (!caught)
fail(fs, ex);
else
pass();
}
private static void tryCatch(String fs, Class<?> ex, Object ... args) {
boolean caught = false;
try {
test(fs, args);
} catch (Throwable x) {
if (ex.isAssignableFrom(x.getClass()))
caught = true;
}
if (!caught)
fail(fs, ex);
else
pass();
}
private static long negate(long v) {
return (long) -v;
}
public static void test() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT-0800"));
// Any characters not explicitly defined as conversions, date/time
// conversion suffixes, or flags are illegal and are reserved for
// future extensions. Use of such a character in a format string will
// cause an UnknownFormatConversionException or
// UnknownFormatFlagsException to be thrown.
tryCatch("%q", UnknownFormatConversionException.class);
tryCatch("%t&", UnknownFormatConversionException.class);
tryCatch("%&d", UnknownFormatConversionException.class);
tryCatch("%^b", UnknownFormatConversionException.class);
//---------------------------------------------------------------------
// Formatter.java class javadoc examples
//---------------------------------------------------------------------
test(Locale.FRANCE, "e = %+10.4f", "e = +2,7183", Math.E);
test("%4$2s %3$2s %2$2s %1$2s", " d c b a", "a", "b", "c", "d");
test("Amount gained or lost since last statement: $ %,(.2f",
"Amount gained or lost since last statement: $ (6,217.58)",
(new BigDecimal("-6217.58")));
Calendar c = new GregorianCalendar(1969, JULY, 20, 16, 17, 0);
testSysOut("Local time: %tT", "Local time: 16:17:00", c);
test("Unable to open file '%1$s': %2$s",
"Unable to open file 'food': No such file or directory",
"food", "No such file or directory");
Calendar duke = new GregorianCalendar(1995, MAY, 23, 19, 48, 34);
duke.set(Calendar.MILLISECOND, 584);
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke);
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke.getTime());
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke.getTimeInMillis());
test("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",
"d c b a d c b a", "a", "b", "c", "d");
test("%s %s %<s %<s", "a b b b", "a", "b", "c", "d");
test("%s %s %s %s", "a b c d", "a", "b", "c", "d");
test("%2$s %s %<s %s", "b a a b", "a", "b", "c", "d");
//---------------------------------------------------------------------
// %b
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%b", "true", true);
test("%b", "false", false);
test("%B", "TRUE", true);
test("%B", "FALSE", false);
test("%b", "true", Boolean.TRUE);
test("%b", "false", Boolean.FALSE);
test("%B", "TRUE", Boolean.TRUE);
test("%B", "FALSE", Boolean.FALSE);
test("%14b", " true", true);
test("%-14b", "true ", true);
test("%5.1b", " f", false);
test("%-5.1b", "f ", false);
test("%b", "true", "foo");
test("%b", "false", (Object)null);
// Boolean.java hardcodes the Strings for "true" and "false", so no
// localization is possible.
test(Locale.FRANCE, "%b", "true", true);
test(Locale.FRANCE, "%b", "false", false);
// If you pass in a single array to a varargs method, the compiler
// uses it as the array of arguments rather than treating it as a
// single array-type argument.
test("%b", "false", (Object[])new String[2]);
test("%b", "true", new String[2], new String[2]);
int [] ia = { 1, 2, 3 };
test("%b", "true", ia);
//---------------------------------------------------------------------
// %b - errors
//---------------------------------------------------------------------
tryCatch("%#b", FormatFlagsConversionMismatchException.class);
tryCatch("%-b", MissingFormatWidthException.class);
// correct or side-effect of implementation?
tryCatch("%.b", UnknownFormatConversionException.class);
tryCatch("%,b", FormatFlagsConversionMismatchException.class);
//---------------------------------------------------------------------
// %c
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%c", "i", 'i');
test("%C", "I", 'i');
test("%4c", " i", 'i');
test("%-4c", "i ", 'i');
test("%4C", " I", 'i');
test("%-4C", "I ", 'i');
test("%c", "i", new Character('i'));
test("%c", "H", (byte) 72);
test("%c", "i", (short) 105);
test("%c", "!", (int) 33);
test("%c", "\u007F", Byte.MAX_VALUE);
test("%c", new String(Character.toChars(Short.MAX_VALUE)),
Short.MAX_VALUE);
test("%c", "null", (Object) null);
//---------------------------------------------------------------------
// %c - errors
//---------------------------------------------------------------------
tryCatch("%c", IllegalFormatConversionException.class,
Boolean.TRUE);
tryCatch("%c", IllegalFormatConversionException.class,
(float) 0.1);
tryCatch("%c", IllegalFormatConversionException.class,
new Object());
tryCatch("%c", IllegalFormatCodePointException.class,
Byte.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Short.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Integer.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Integer.MAX_VALUE);
tryCatch("%#c", FormatFlagsConversionMismatchException.class);
tryCatch("%,c", FormatFlagsConversionMismatchException.class);
tryCatch("%(c", FormatFlagsConversionMismatchException.class);
tryCatch("%$c", UnknownFormatConversionException.class);
tryCatch("%.2c", IllegalFormatPrecisionException.class);
//---------------------------------------------------------------------
// %s
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%s", "Hello, Duke", "Hello, Duke");
test("%S", "HELLO, DUKE", "Hello, Duke");
test("%20S", " HELLO, DUKE", "Hello, Duke");
test("%20s", " Hello, Duke", "Hello, Duke");
test("%-20s", "Hello, Duke ", "Hello, Duke");
test("%-20.5s", "Hello ", "Hello, Duke");
test("%s", "null", (Object)null);
StringBuffer sb = new StringBuffer("foo bar");
test("%s", sb.toString(), sb);
test("%S", sb.toString().toUpperCase(), sb);
//---------------------------------------------------------------------
// %s - errors
//---------------------------------------------------------------------
tryCatch("%-s", MissingFormatWidthException.class);
tryCatch("%--s", DuplicateFormatFlagsException.class);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, 0);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, 0.5f);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, "hello");
tryCatch("%#s", FormatFlagsConversionMismatchException.class, null);
//---------------------------------------------------------------------
// %h
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%h", Integer.toHexString("Hello, Duke".hashCode()),
"Hello, Duke");
test("%10h", " ddf63471", "Hello, Duke");
test("%-10h", "ddf63471 ", "Hello, Duke");
test("%-10H", "DDF63471 ", "Hello, Duke");
test("%10h", " 402e0000", 15.0);
test("%10H", " 402E0000", 15.0);
//---------------------------------------------------------------------
// %h - errors
//---------------------------------------------------------------------
tryCatch("%#h", FormatFlagsConversionMismatchException.class);
//---------------------------------------------------------------------
// flag/conversion errors
//---------------------------------------------------------------------
tryCatch("%F", UnknownFormatConversionException.class);
tryCatch("%#g", FormatFlagsConversionMismatchException.class);
long minByte = Byte.MIN_VALUE; // -128
//---------------------------------------------------------------------
// %d
//
// Numeric conversion applicable to byte, short, int, long, and
// BigInteger.
//---------------------------------------------------------------------
test("%d", "null", (Object)null);
//---------------------------------------------------------------------
// %d - int and long
//---------------------------------------------------------------------
long oneToSeven = (long) 1234567;
test("%d", "1234567", oneToSeven);
test("%,d", "1,234,567", oneToSeven);
test(Locale.FRANCE, "%,d", "1\u00a0234\u00a0567", oneToSeven);
test("%,d", "-1,234,567", negate(oneToSeven));
test("%(d", "1234567", oneToSeven);
test("%(d", "(1234567)", negate(oneToSeven));
test("% d", " 1234567", oneToSeven);
test("% d", "-1234567", negate(oneToSeven));
test("%+d", "+1234567", oneToSeven);
test("%+d", "-1234567", negate(oneToSeven));
test("%010d", "0001234567", oneToSeven);
test("%010d", "-001234567", negate(oneToSeven));
test("%(10d", " (1234567)", negate(oneToSeven));
test("%-10d", "1234567 ", oneToSeven);
test("%-10d", "-1234567 ", negate(oneToSeven));
//---------------------------------------------------------------------
// %d - errors
//---------------------------------------------------------------------
tryCatch("%#d", FormatFlagsConversionMismatchException.class);
tryCatch("%D", UnknownFormatConversionException.class);
tryCatch("%0d", MissingFormatWidthException.class);
tryCatch("%-d", MissingFormatWidthException.class);
tryCatch("%7.3d", IllegalFormatPrecisionException.class);
//---------------------------------------------------------------------
// %o
//
// Numeric conversion applicable to byte, short, int, long, and
// BigInteger.
//---------------------------------------------------------------------
test("%o", "null", (Object)null);
//---------------------------------------------------------------------
// %o - long
//---------------------------------------------------------------------
test("%024o", "001777777777777777777600", minByte);
test("%-24o", "1777777777777777777600 ", minByte);
test("%#24o", " 01777777777777777777600", minByte);
long oneToSevenOct = (long) 1234567;
test("%o", "4553207", oneToSevenOct);
test("%010o", "0004553207", oneToSevenOct);
test("%-10o", "4553207 ", oneToSevenOct);
test("%#10o", " 04553207", oneToSevenOct);
//---------------------------------------------------------------------
// %o - errors
//---------------------------------------------------------------------
tryCatch("%(o", FormatFlagsConversionMismatchException.class,
minByte);
tryCatch("%+o", FormatFlagsConversionMismatchException.class,
minByte);
tryCatch("% o", FormatFlagsConversionMismatchException.class,
minByte);
tryCatch("%0o", MissingFormatWidthException.class);
tryCatch("%-o", MissingFormatWidthException.class);
tryCatch("%,o", FormatFlagsConversionMismatchException.class);
tryCatch("%O", UnknownFormatConversionException.class);
//---------------------------------------------------------------------
// %x
//
// Numeric conversion applicable to byte, short, int, long, and
// BigInteger.
//---------------------------------------------------------------------
test("%x", "null", (Object)null);
//---------------------------------------------------------------------
// %x - long
//---------------------------------------------------------------------
long oneToSevenHex = (long)1234567;
test("%x", "null", (Object)null);
test("%x", "12d687", oneToSevenHex);
test("%010x", "000012d687", oneToSevenHex);
test("%-10x", "12d687 ", oneToSevenHex);
test("%#10x", " 0x12d687", oneToSevenHex);
test("%#10X", " 0X12D687",oneToSevenHex);
test("%X", "12D687", oneToSevenHex);
test("%018x", "00ffffffffffffff80", minByte);
test("%-18x", "ffffffffffffff80 ", minByte);
test("%#20x", " 0xffffffffffffff80", minByte);
test("%0#20x", "0x00ffffffffffffff80", minByte);
test("%#20X", " 0XFFFFFFFFFFFFFF80", minByte);
test("%X", "FFFFFFFFFFFFFF80", minByte);
//---------------------------------------------------------------------
// %x - errors
//---------------------------------------------------------------------
tryCatch("%,x", FormatFlagsConversionMismatchException.class);
tryCatch("%0x", MissingFormatWidthException.class);
tryCatch("%-x", MissingFormatWidthException.class);
//---------------------------------------------------------------------
// %t
//
// Date/Time conversions applicable to Calendar, Date, and long.
//---------------------------------------------------------------------
test("%tA", "null", (Object)null);
test("%TA", "NULL", (Object)null);
//---------------------------------------------------------------------
// %t - errors
//---------------------------------------------------------------------
tryCatch("%t", UnknownFormatConversionException.class);
tryCatch("%T", UnknownFormatConversionException.class);
tryCatch("%tP", UnknownFormatConversionException.class);
tryCatch("%TP", UnknownFormatConversionException.class);
tryCatch("%.5tB", IllegalFormatPrecisionException.class);
tryCatch("%#tB", FormatFlagsConversionMismatchException.class);
tryCatch("%-tB", MissingFormatWidthException.class);
//---------------------------------------------------------------------
// %n
//---------------------------------------------------------------------
test("%n", System.getProperty("line.separator"), (Object)null);
test("%n", System.getProperty("line.separator"), "");
tryCatch("%,n", IllegalFormatFlagsException.class);
tryCatch("%.n", UnknownFormatConversionException.class);
tryCatch("%5.n", UnknownFormatConversionException.class);
tryCatch("%5n", IllegalFormatWidthException.class);
tryCatch("%.7n", IllegalFormatPrecisionException.class);
tryCatch("%<n", IllegalFormatFlagsException.class);
//---------------------------------------------------------------------
// %%
//---------------------------------------------------------------------
test("%%", "%", (Object)null);
test("%%", "%", "");
tryCatch("%%%", UnknownFormatConversionException.class);
// perhaps an IllegalFormatArgumentIndexException should be defined?
tryCatch("%<%", IllegalFormatFlagsException.class);
}
}
| gpl-2.0 |
rodnaph/sockso | test/com/pugh/sockso/tests/TemplateTestCase.java | 485 |
package com.pugh.sockso.tests;
import org.jamon.Renderer;
public abstract class TemplateTestCase extends SocksoTestCase {
/**
* Render the template and return the result as a string
*
* @return
*
*/
public String render() {
return getTemplate().asString();
}
/**
* Returns the renderer for the template that will be under test
*
* @return
*
*/
public abstract Renderer getTemplate();
}
| gpl-2.0 |
flyroom/PeerfactSimKOM_Clone | src/org/peerfact/impl/analyzer/visualization2d/visualization2d/toolbar/ZoomButton.java | 2173 | /*
* Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org>
* Copyright (c) 2011-2012 University of Paderborn - UPB
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.peerfact.impl.analyzer.visualization2d.visualization2d.toolbar;
import javax.swing.ImageIcon;
import org.peerfact.Constants;
import org.peerfact.impl.analyzer.visualization2d.controller.commands.Zoom;
import org.peerfact.impl.analyzer.visualization2d.ui.common.toolbar.elements.SimpleToolbarButton;
import org.peerfact.impl.analyzer.visualization2d.visualization2d.Simple2DVisualization;
/**
* Button to zoom in
*
* @author Leo Nobach <peerfact@kom.tu-darmstadt.de>
* @author Kalman Graffi <info@peerfact.org>
*
* @version 08/18/2011
*
*/
public class ZoomButton extends SimpleToolbarButton {
/**
*
*/
private static final long serialVersionUID = -8883086992639815840L;
static final ImageIcon iconIn = new ImageIcon(Constants.ICONS_DIR
+ "/zoomIn.png");
static final ImageIcon iconOut = new ImageIcon(Constants.ICONS_DIR
+ "/zoomOut.png");
static final String tooltipIn = "Zoom in";
static final String tooltipOut = "Zoom out";
/**
* Default constructor
*
* @param zoomOut
* @param vis
*/
public ZoomButton(boolean zoomOut, Simple2DVisualization vis) {
super();
this.setIcon(zoomOut ? iconOut : iconIn);
this.setToolTipText(zoomOut ? tooltipOut : tooltipIn);
this.addCommand(new Zoom(zoomOut, vis));
}
}
| gpl-2.0 |
Blaez/ZiosGram | TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java | 6307 | /*
* This is the source code of ZiosGram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2017.
*/
package org.blaez.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.blaez.ziosgram.AndroidUtilities;
import org.blaez.ziosgram.ContactsController;
import org.blaez.ZiosGram.messagesController;
import org.blaez.tgnet.TLRPC;
import org.blaez.ui.ActionBar.Theme;
import org.blaez.ui.Components.AvatarDrawable;
import org.blaez.ui.Components.BackupImageView;
import org.blaez.ui.Components.LayoutHelper;
public class HintDialogCell extends FrameLayout {
private BackupImageView imageView;
private TextView nameTextView;
private AvatarDrawable avatarDrawable = new AvatarDrawable();
private RectF rect = new RectF();
private int lastUnreadCount;
private int countWidth;
private StaticLayout countLayout;
private long dialog_id;
public HintDialogCell(Context context) {
super(context);
imageView = new BackupImageView(context);
imageView.setRoundRadius(AndroidUtilities.dp(27));
addView(imageView, LayoutHelper.createFrame(54, 54, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 7, 0, 0));
nameTextView = new TextView(context);
nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setMaxLines(2);
nameTextView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
nameTextView.setLines(2);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 6, 64, 6, 0));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(100), MeasureSpec.EXACTLY));
}
public void checkUnreadCounter(int mask) {
if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
return;
}
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id);
if (dialog != null && dialog.unread_count != 0) {
if (lastUnreadCount != dialog.unread_count) {
lastUnreadCount = dialog.unread_count;
String countString = String.format("%d", dialog.unread_count);
countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(Theme.dialogs_countTextPaint.measureText(countString)));
countLayout = new StaticLayout(countString, Theme.dialogs_countTextPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
if (mask != 0) {
invalidate();
}
}
} else if (countLayout != null) {
if (mask != 0) {
invalidate();
}
lastUnreadCount = 0;
countLayout = null;
}
}
public void update() {
int uid = (int) dialog_id;
TLRPC.FileLocation photo = null;
if (uid > 0) {
TLRPC.User user = MessagesController.getInstance().getUser(uid);
avatarDrawable.setInfo(user);
} else {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-uid);
avatarDrawable.setInfo(chat);
}
}
public void setDialog(int uid, boolean counter, CharSequence name) {
dialog_id = uid;
TLRPC.FileLocation photo = null;
if (uid > 0) {
TLRPC.User user = MessagesController.getInstance().getUser(uid);
if (name != null) {
nameTextView.setText(name);
} else if (user != null) {
nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name));
} else {
nameTextView.setText("");
}
avatarDrawable.setInfo(user);
if (user != null && user.photo != null) {
photo = user.photo.photo_small;
}
} else {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-uid);
if (name != null) {
nameTextView.setText(name);
} else if (chat != null) {
nameTextView.setText(chat.title);
} else {
nameTextView.setText("");
}
avatarDrawable.setInfo(chat);
if (chat != null && chat.photo != null) {
photo = chat.photo.photo_small;
}
}
imageView.setImage(photo, "50_50", avatarDrawable);
if (counter) {
checkUnreadCounter(0);
} else {
countLayout = null;
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == imageView && countLayout != null) {
int top = AndroidUtilities.dp(6);
int left = AndroidUtilities.dp(54);
int x = left - AndroidUtilities.dp(5.5f);
rect.set(x, top, x + countWidth + AndroidUtilities.dp(11), top + AndroidUtilities.dp(23));
canvas.drawRoundRect(rect, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, MessagesController.getInstance().isDialogMuted(dialog_id) ? Theme.dialogs_countGrayPaint : Theme.dialogs_countPaint);
canvas.save();
canvas.translate(left, top + AndroidUtilities.dp(4));
countLayout.draw(canvas);
canvas.restore();
}
return result;
}
}
| gpl-2.0 |
Sami32/DigitalMediaServer | src/main/java/net/pms/remote/RemoteBrowseHandler.java | 9372 | package net.pms.remote;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.configuration.WebRender;
import net.pms.dlna.CodeEnter;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.Playlist;
import net.pms.dlna.RootFolder;
import net.pms.dlna.virtual.VirtualVideoAction;
import net.pms.formats.Format;
import net.pms.util.UMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("restriction")
public class RemoteBrowseHandler implements HttpHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteBrowseHandler.class);
private RemoteWeb parent;
private static PmsConfiguration configuration = PMS.getConfiguration();
public RemoteBrowseHandler(RemoteWeb parent) {
this.parent = parent;
}
private String mkBrowsePage(String id, HttpExchange t) throws IOException, InterruptedException {
LOGGER.debug("Make browse page " + id);
String user = RemoteUtil.userName(t);
RootFolder root = parent.getRoot(user, true, t);
String search = RemoteUtil.getQueryVars(t.getRequestURI().getQuery(), "str");
List<DLNAResource> resources = root.getDLNAResources(id, true, 0, 0, root.getDefaultRenderer(), search);
boolean upnpAllowed = RemoteUtil.bumpAllowed(t);
boolean upnpControl = RendererConfiguration.hasConnectedControlPlayers();
if (!resources.isEmpty() &&
resources.get(0).getParent() != null &&
(resources.get(0).getParent() instanceof CodeEnter)) {
// this is a code folder the search string is entered code
CodeEnter ce = (CodeEnter) resources.get(0).getParent();
ce.setEnteredCode(search);
if(!ce.validCode(ce)) {
// invalid code throw error
throw new IOException("Auth error");
}
DLNAResource real = ce.getResource();
if (!real.isFolder()) {
// no folder -> redirect
Headers hdr = t.getResponseHeaders();
hdr.add("Location", "/play/" + real.getId());
RemoteUtil.respond(t, "", 302, "text/html");
// return null here to avoid multiple responses
return null;
}
// redirect to ourself
Headers hdr = t.getResponseHeaders();
hdr.add("Location", "/browse/" + real.getResourceId());
RemoteUtil.respond(t, "", 302, "text/html");
return null;
}
if (StringUtils.isNotEmpty(search) && !(resources instanceof CodeEnter)) {
UMSUtils.postSearch(resources, search);
}
boolean hasFile = false;
ArrayList<String> folders = new ArrayList<>();
ArrayList<HashMap<String, String>> media = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.setLength(0);
sb.append("<a href=\"javascript:history.back()\" title=\"").append(RemoteUtil.getMsgString("Web.10", t)).append("\">");
sb.append("<span>").append(RemoteUtil.getMsgString("Web.10", t)).append("</span>");
sb.append("</a>");
folders.add(sb.toString());
// Generate innerHtml snippets for folders and media items
for (DLNAResource resource : resources) {
String newId = resource.getResourceId();
String idForWeb = URLEncoder.encode(newId, "UTF-8");
String thumb = "/thumb/" + idForWeb;
String name = StringEscapeUtils.escapeHtml3(resource.resumeName());
if (resource instanceof VirtualVideoAction) {
// Let's take the VVA real early
sb.setLength(0);
HashMap<String, String> item = new HashMap<>();
sb.append("<a href=\"#\" onclick=\"dmsAjax('/play/").append(idForWeb)
.append("', true);return false;\" title=\"").append(name).append("\">")
.append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">")
.append("</a>");
item.put("thumb", sb.toString());
sb.setLength(0);
sb.append("<a href=\"#\" onclick=\"dmsAjax('/play/").append(idForWeb)
.append("', true);return false;\" title=\"").append(name).append("\">")
.append("<span class=\"caption\">").append(name).append("</span>")
.append("</a>");
item.put("caption", sb.toString());
item.put("bump", "<span class=\"floatRight\"></span>");
media.add(item);
hasFile = true;
continue;
}
if (resource.isFolder()) {
sb.setLength(0);
// The resource is a folder
String p = "/browse/" + idForWeb;
boolean code = (resource instanceof CodeEnter);
String txt = RemoteUtil.getMsgString("Web.8", t);
if (code) {
txt = RemoteUtil.getMsgString("Web.9", t);
}
if (resource.getClass().getName().contains("SearchFolder") || code) {
// search folder add a prompt
// NOTE!!!
// Yes doing getClass.getname is REALLY BAD, but this
// is to make legacy plugins utilize this function as well
sb.append("<a href=\"javascript:void(0);\" onclick=\"searchFun('").append(p).append("','")
.append(txt).append("');\" title=\"").append(name).append("\">");
} else {
sb.append("<a href=\"").append(p).append("\" oncontextmenu=\"searchFun('").append(p)
.append("','").append(txt).append("');\" title=\"").append(name).append("\">");
}
sb.append("<span>").append(name).append("</span>");
sb.append("</a>");
folders.add(sb.toString());
} else {
// The resource is a media file
sb.setLength(0);
HashMap<String, String> item = new HashMap<>();
if (upnpAllowed) {
if (upnpControl) {
sb.append("<a class=\"bumpIcon\" href=\"javascript:bump.start('//")
.append(parent.getAddress()).append("','/play/").append(idForWeb).append("','")
.append(name.replace("'", "\\'")).append("')\" title=\"")
.append(RemoteUtil.getMsgString("Web.1", t)).append("\"></a>");
} else {
sb.append("<a class=\"bumpIcon icondisabled\" href=\"javascript:notify('warn','")
.append(RemoteUtil.getMsgString("Web.2", t))
.append("')\" title=\"").append(RemoteUtil.getMsgString("Web.3", t)).append("\"></a>");
}
if (resource.getParent() instanceof Playlist) {
sb.append("\n<a class=\"playlist_del\" href=\"#\" onclick=\"dmsAjax('/playlist/del/")
.append(idForWeb).append("', true);return false;\" title=\"")
.append(RemoteUtil.getMsgString("Web.4", t)).append("\"></a>");
} else {
sb.append("\n<a class=\"playlist_add\" href=\"#\" onclick=\"dmsAjax('/playlist/add/")
.append(idForWeb).append("', false);return false;\" title=\"")
.append(RemoteUtil.getMsgString("Web.5", t)).append("\"></a>");
}
} else {
// ensure that we got a string
sb.append("");
}
item.put("bump", sb.toString());
sb.setLength(0);
if (WebRender.supports(resource) || resource.isResume() || resource.getType() == Format.IMAGE) {
sb.append("<a href=\"/play/").append(idForWeb)
.append("\" title=\"").append(name).append("\">")
.append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">")
.append("</a>");
item.put("thumb", sb.toString());
sb.setLength(0);
sb.append("<a href=\"/play/").append(idForWeb)
.append("\" title=\"").append(name).append("\">")
.append("<span class=\"caption\">").append(name).append("</span>")
.append("</a>");
item.put("caption", sb.toString());
} else if (upnpControl && upnpAllowed) {
// Include it as a web-disabled item so it can be thrown via upnp
sb.append("<a class=\"webdisabled\" href=\"javascript:notify('warn','")
.append(RemoteUtil.getMsgString("Web.6", t)).append("')\"")
.append(" title=\"").append(name).append(' ').append(RemoteUtil.getMsgString("Web.7", t)).append("\">")
.append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">")
.append("</a>");
item.put("thumb", sb.toString());
sb.setLength(0);
sb.append("<span class=\"webdisabled caption\">").append(name).append("</span>");
item.put("caption", sb.toString());
}
media.add(item);
hasFile = true;
}
}
HashMap<String, Object> vars = new HashMap<>();
vars.put("name", id.equals("0") ? configuration.getServerDisplayName() :
StringEscapeUtils.escapeHtml3(root.getDLNAResource(id, null).getDisplayName()));
vars.put("hasFile", hasFile);
vars.put("folders", folders);
vars.put("media", media);
if (configuration.useWebControl()) {
vars.put("push", true);
}
return parent.getResources().getTemplate("browse.html").execute(vars);
}
@Override
public void handle(HttpExchange t) throws IOException {
try {
if (RemoteUtil.deny(t)) {
throw new IOException("Access denied");
}
String id = RemoteUtil.getId("browse/", t);
LOGGER.debug("Got a browse request found id " + id);
String response = mkBrowsePage(id, t);
LOGGER.trace("Browse page:\n{}", response);
RemoteUtil.respond(t, response, 200, "text/html");
} catch (IOException e) {
throw e;
} catch (Exception e) {
// Nothing should get here, this is just to avoid crashing the thread
LOGGER.error("Unexpected error in RemoteBrowseHandler.handle(): {}", e.getMessage());
LOGGER.trace("", e);
}
}
}
| gpl-2.0 |
kboom/setphrase | src/com/gdroid/setphrase/dictionary/extractor/base/TargetPhraseExtractor.java | 2544 | package com.gdroid.setphrase.dictionary.extractor.base;
import java.util.ArrayList;
import com.gdroid.setphrase.phrase.Phrase;
import com.gdroid.setphrase.phrase.SpeechPart;
import com.gdroid.setphrase.phrase.target.TargetPhrase;
import com.gdroid.utils.SLog;
/**
* Processes payload according to its type. Supported formats so far: PlainText,
* JSON, XML to be written SOAP *
*
* @author kboom
*/
public abstract class TargetPhraseExtractor {
static {
SLog.register(TargetPhraseExtractor.class);
SLog.setTag(TargetPhraseExtractor.class, "Target phrase extractor.");
SLog.setLevel(TargetPhraseExtractor.class, SLog.Level.INFO);
}
private TargetPhraseBuilder phraseBuilder;
public TargetPhraseExtractor() {
}
/**
* Set builder for building phrases. It will also filter them.
*
* @param builder
*/
public void setPhraseBuilder(TargetPhraseBuilder builder) {
phraseBuilder = builder;
}
/**
* Build a phrase with given parameters. Can contain null ones.
*
* @param phrase
* @param part
* @param synonyms
* @return
*/
public TargetPhrase buildPhrase(Phrase phrase, TargetPhraseParameters params) {
assert phrase != null;
assert params != null;
phraseBuilder.init();
phraseBuilder.setBasePhrase(phrase);
phraseBuilder.assignToSpeechPart(params.part);
if (params.synonyms != null)
phraseBuilder.addSynonym(params.synonyms);
if (params.definition != null)
phraseBuilder.setDefinition(params.definition);
return phraseBuilder.build();
}
public abstract TargetPhrase extract(Phrase phrase, SpeechPart part,
String response);
public abstract ArrayList<TargetPhrase> extractAll(Phrase phrase,
String response);
protected static class TargetPhraseParameters {
private SpeechPart part;
private String definition;
private ArrayList<String> synonyms;
}
public TargetPhraseParameters createPhraseParameters(SpeechPart part,
String def) {
TargetPhraseParameters tpp = new TargetPhraseParameters();
tpp.part = part;
tpp.definition = def;
return tpp;
}
public TargetPhraseParameters createPhraseParameters(SpeechPart part,
ArrayList<String> synonyms) {
TargetPhraseParameters tpp = new TargetPhraseParameters();
tpp.part = part;
tpp.synonyms = synonyms;
return tpp;
}
public TargetPhraseParameters createPhraseParameters(SpeechPart part,
String def, ArrayList<String> synonyms) {
TargetPhraseParameters tpp = new TargetPhraseParameters();
tpp.part = part;
tpp.definition = def;
tpp.synonyms = synonyms;
return tpp;
}
}
| gpl-2.0 |
susverwimp/lwjgl | lwjgl/src/skybox/SkyboxShader.java | 1743 | package skybox;
import math.Maths;
import math.Matrix4f;
import math.Vector3f;
import entities.Camera;
import shaders.ShaderProgram;
public class SkyboxShader extends ShaderProgram{
private static final String VERTEX_FILE = "shaders/skyboxVertexShader.txt";
private static final String FRAGMENT_FILE = "shaders/skyboxFragmentShader.txt";
private static final float ROTATE_SPEED = 0.01f;
private int location_projectionMatrix;
private int location_viewMatrix;
private int location_fogColor;
private float rotation = 0;
public SkyboxShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public void loadProjectionMatrix(Matrix4f matrix){
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(Camera camera){
Matrix4f matrix = Maths.createViewMatrix(camera);
matrix.m30 = 0;
matrix.m31 = 0;
matrix.m32 = 0;
rotation += ROTATE_SPEED;
Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0,1,0), matrix, matrix);
super.loadMatrix(location_viewMatrix, matrix);
}
@Override
protected void getAllUniformLocations() {
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
location_fogColor = super.getUniformLocation("fogColor");
}
public void loadFogColor(float r, float g, float b){
super.loadVector(location_fogColor, new Vector3f(r,g,b));
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
} | gpl-2.0 |
anudr01d/Varte | Android/app/src/main/java/app/anudroid/com/varte/RAL/RALModels/Feeds.java | 626 |
package app.anudroid.com.varte.RAL.RALModels;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Feeds {
@JsonInclude(JsonInclude.Include.NON_NULL)
private Query query;
/**
*
* @return
* The query
*/
public Query getQuery() {
return query;
}
/**
*
* @param query
* The query
*/
public void setQuery(Query query) {
this.query = query;
}
public Feeds reorderFeeds() {
return this;
}
}
| gpl-2.0 |
tauprojects/mpp | jmh/jmh-core/src/main/java/org/openjdk/jmh/results/format/XSVResultFormat.java | 4794 | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jmh.results.format;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.results.Result;
import org.openjdk.jmh.results.RunResult;
import java.io.PrintStream;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
/*
* CSV formatter follows the provisions of http://tools.ietf.org/html/rfc4180
*/
class XSVResultFormat implements ResultFormat {
private final PrintStream out;
private final String delimiter;
public XSVResultFormat(PrintStream out, String delimiter) {
this.out = out;
this.delimiter = delimiter;
}
@Override
public void writeOut(Collection<RunResult> results) {
SortedSet<String> params = new TreeSet<>();
for (RunResult res : results) {
params.addAll(res.getParams().getParamsKeys());
}
printHeader(params);
for (RunResult rr : results) {
BenchmarkParams benchParams = rr.getParams();
Result res = rr.getPrimaryResult();
printLine(benchParams.getBenchmark(), benchParams, params, res);
for (String label : rr.getSecondaryResults().keySet()) {
Result subRes = rr.getSecondaryResults().get(label);
printLine(benchParams.getBenchmark() + ":" + subRes.getLabel(), benchParams, params, subRes);
}
}
}
private void printHeader(SortedSet<String> params) {
out.print("\"Benchmark\"");
out.print(delimiter);
out.print("\"Mode\"");
out.print(delimiter);
out.print("\"Threads\"");
out.print(delimiter);
out.print("\"Samples\"");
out.print(delimiter);
out.print("\"Score\"");
out.print(delimiter);
out.printf("\"Score Error (%.1f%%)\"", 99.9);
out.print(delimiter);
out.print("\"Unit\"");
for (String k : params) {
out.print(delimiter);
out.print("\"Param: " + k + "\"");
}
out.print("\r\n");
}
private void printLine(String label, BenchmarkParams benchmarkParams, SortedSet<String> params, Result result) {
out.print("\"");
out.print(label);
out.print("\"");
out.print(delimiter);
out.print("\"");
out.print(benchmarkParams.getMode().shortLabel());
out.print("\"");
out.print(delimiter);
out.print(emit(benchmarkParams.getThreads()));
out.print(delimiter);
out.print(emit(result.getSampleCount()));
out.print(delimiter);
out.print(emit(result.getScore()));
out.print(delimiter);
out.print(emit(result.getScoreError()));
out.print(delimiter);
out.print("\"");
out.print(result.getScoreUnit());
out.print("\"");
for (String p : params) {
out.print(delimiter);
String v = benchmarkParams.getParam(p);
if (v != null) {
out.print(emit(v));
}
}
out.print("\r\n");
}
private String emit(String v) {
if (v.contains(delimiter) || v.contains(" ") || v.contains("\n") || v.contains("\r") || v.contains("\"")) {
return "\"" + v.replaceAll("\"", "\"\"") + "\"";
} else {
return v;
}
}
private String emit(int i) {
return emit(String.format("%d", i));
}
private String emit(long l) {
return emit(String.format("%d", l));
}
private String emit(double d) {
return emit(String.format("%f", d));
}
}
| gpl-2.0 |
sannysanoff/CodenameOne | CodenameOne/src/com/codename1/ui/Toolbar.java | 36962 | /*
* Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.ui;
import com.codename1.ui.animations.BubbleTransition;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.animations.Motion;
import com.codename1.ui.animations.Transition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.events.ScrollListener;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.layouts.LayeredLayout;
import com.codename1.ui.layouts.Layout;
import com.codename1.ui.list.DefaultListCellRenderer;
import com.codename1.ui.plaf.LookAndFeel;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
/**
* <p>Toolbar replaces the default title area with a powerful abstraction that allows functionality ranging
* from side menus (hamburger) to title animations and any arbitrary component type. Toolbar allows
* customizing the Form title with different commands on the title area, within the side menu or the overflow menu.</p>
*
* <p>
* The Toolbar allows placing components in one of 4 positions as illustrated by the sample below:
* </p>
* <script src="https://gist.github.com/codenameone/e72cfa6aedd7fcd1af72.js"></script>
* <img src="https://www.codenameone.com/img/developer-guide/components-toolbar.png" alt="Simple usage of Toolbar" />
*
* <p>
* The following code demonstrates a more advanced search widget where the data is narrowed as we type
* directly into the title area search. Notice that the {@code TextField} and its hint are styled to look like the title.
* </p>
* <script src="https://gist.github.com/codenameone/dce6598a226aaf9a3157.js"></script>
* <img src="https://www.codenameone.com/img/developer-guide/components-toolbar-search.png" alt="Dynamic TextField search using the Toolbar" />
*
* <p>
* This sample code show off title animations that allow a title to change (and potentially shrink) as the user scrolls
* down the UI. The 3 frames below show a step by step process in the change.
* </p>
* <script src="https://gist.github.com/codenameone/085e3a8fa1c36829d812.js"></script>
* <img src="https://www.codenameone.com/img/developer-guide/components-toolbar-animation-1.png" alt="Toolbar animation stages" />
* <img src="https://www.codenameone.com/img/developer-guide/components-toolbar-animation-2.png" alt="Toolbar animation stages" />
* <img src="https://www.codenameone.com/img/developer-guide/components-toolbar-animation-3.png" alt="Toolbar animation stages" />
*
* @author Chen
*/
public class Toolbar extends Container {
private Component titleComponent;
private ToolbarSideMenu sideMenu;
private Vector<Command> overflowCommands;
private Button menuButton;
private ScrollListener scrollListener;
private ActionListener releasedListener;
private boolean scrollOff = false;
private int initialY;
private int actualPaneInitialY;
private int actualPaneInitialH;
private Motion hideShowMotion;
private boolean showing;
private boolean layered = false;
private boolean initialized = false;
private static boolean permanentSideMenu;
private Container permanentSideMenuContainer;
private static boolean globalToolbar;
/**
* Empty Constructor
*/
public Toolbar() {
setLayout(new BorderLayout());
setUIID("Toolbar");
sideMenu = new ToolbarSideMenu();
}
/**
* Enables/disables the Toolbar for all the forms in the application. This flag can be flipped via the
* theme constant globalToobarBool.
* @param gt true to enable the toolbar globally
*/
public static void setGlobalToolbar(boolean gt) {
globalToolbar = gt;
}
/**
* Enables/disables the Toolbar for all the forms in the application. This flag can be flipped via the
* theme constant globalToobarBool.
*
* @return true if the toolbar API is turned on by default
*/
public static boolean isGlobalToolbar() {
return globalToolbar;
}
/**
* This constructor places the Toolbar on a different layer on top of the
* Content Pane.
*
* @param layered if true places the Toolbar on top of the Content Pane
*/
public Toolbar(boolean layered) {
this();
this.layered = layered;
}
/**
* Sets the title of the Toolbar.
*
* @param title the Toolbar title
*/
public void setTitle(String title) {
checkIfInitialized();
Component center = ((BorderLayout) getLayout()).getCenter();
if (center instanceof Label) {
((Label) center).setText(title);
} else {
titleComponent = new Label(title);
titleComponent.setUIID("Title");
if (center != null) {
replace(center, titleComponent, null);
} else {
addComponent(BorderLayout.CENTER, titleComponent);
}
}
}
/**
* Makes the title align to the center accurately by doing it at the layout level which also takes into
* account right/left commands
* @param cent whether the title should be centered
*/
public void setTitleCentered(boolean cent) {
((BorderLayout)getLayout()).setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE);
}
/**
* Returns true if the title is centered via the layout
* @return true if the title is centered
*/
public boolean isTitleCentered() {
return ((BorderLayout)getLayout()).getCenterBehavior() == BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE;
}
/**
* Creates a static side menu that doesn't fold instead of the standard sidemenu.
* This is common for tablet UI's where folding the side menu doesn't make as much sense.
*
* @param p true to have a permanent side menu
*/
public static void setPermanentSideMenu(boolean p) {
permanentSideMenu = p;
}
/**
* Creates a static side menu that doesn't fold instead of the standard sidemenu.
* This is common for tablet UI's where folding the side menu doesn't make as much sense.
*
* @return true if we will use a permanent sidemenu
*/
public static boolean isPermanentSideMenu() {
return permanentSideMenu;
}
/**
* Sets the Toolbar title component. This method allow placing any component
* in the Toolbar ceneter instead of the regular Label. Can be used to place
* a TextField to preform search operations
*
* @param titleCmp Comoponent to place in the Toolbar center.
*/
public void setTitleComponent(Component titleCmp) {
checkIfInitialized();
titleComponent = titleCmp;
addComponent(BorderLayout.CENTER, titleComponent);
}
/**
* Returns the Toolbar title Component.
*
* @return the Toolbar title component
*/
public Component getTitleComponent(){
return titleComponent;
}
/**
* Adds a Command to the overflow menu
*
* @param name the name/title of the command
* @param icon the icon for the command
* @param ev the even handler
* @return a newly created Command instance
*/
public Command addCommandToOverflowMenu(String name, Image icon, final ActionListener ev) {
Command cmd = Command.create(name, icon, ev);
addCommandToOverflowMenu(cmd);
return cmd;
}
/**
* Adds a Command to the overflow menu
*
* @param cmd a Command
*/
public void addCommandToOverflowMenu(Command cmd) {
checkIfInitialized();
if (overflowCommands == null) {
overflowCommands = new Vector<Command>();
}
overflowCommands.add(cmd);
sideMenu.installRightCommands();
}
/**
* Returns the commands within the overflow menu which can be useful for things like unit testing. Notice
* that you should not mutate the commands or the iteratable set in any way!
* @return the commands in the overflow menu
*/
public Iterable<Command> getOverflowCommands() {
return overflowCommands;
}
/**
* Adds a Command to the side navigation menu
*
* @param name the name/title of the command
* @param icon the icon for the command
* @param ev the even handler
* @return a newly created Command instance
*/
public Command addCommandToSideMenu(String name, Image icon, final ActionListener ev) {
Command cmd = Command.create(name, icon, ev);
addCommandToSideMenu(cmd);
return cmd;
}
/**
* Adds a Command to the side navigation menu
*
* @param cmd a Command
*/
public void addCommandToSideMenu(Command cmd) {
checkIfInitialized();
if(permanentSideMenu) {
constructPermanentSideMenu();
Button b = new Button(cmd);
b.setEndsWith3Points(false);
Integer gap = (Integer)cmd.getClientProperty("iconGap");
if(gap != null) {
b.setGap(gap.intValue());
}
b.setTextPosition(Label.RIGHT);
String uiid = (String)cmd.getClientProperty("uiid");
if(uiid != null) {
b.setUIID(uiid);
} else {
b.setUIID("SideCommand");
}
addComponentToSideMenu(permanentSideMenuContainer, b);
} else {
sideMenu.addCommand(cmd);
sideMenu.installMenuBar();
}
}
private void constructPermanentSideMenu() {
if(permanentSideMenuContainer == null) {
permanentSideMenuContainer = constructSideNavigationComponent();
Form parent = getComponentForm();
parent.addComponentToForm(BorderLayout.WEST, permanentSideMenuContainer);
}
}
/**
* Adds a Component to the side navigation menu. The Component is added to
* the navigation menu and the command gets the events once the Component is
* being pressed.
*
* @param cmp c Component to be added to the menu
* @param cmd a Command to handle the events
*/
public void addComponentToSideMenu(Component cmp, Command cmd) {
checkIfInitialized();
if(permanentSideMenu) {
constructPermanentSideMenu();
Container cnt = new Container(new BorderLayout());
cnt.addComponent(BorderLayout.CENTER, cmp);
Button btn = new Button(cmd);
btn.setParent(cnt);
cnt.setLeadComponent(btn);
addComponentToSideMenu(permanentSideMenuContainer, cnt);
} else {
cmd.putClientProperty(SideMenuBar.COMMAND_SIDE_COMPONENT, cmp);
cmd.putClientProperty(SideMenuBar.COMMAND_ACTIONABLE, Boolean.TRUE);
sideMenu.addCommand(cmd);
sideMenu.installMenuBar();
}
}
/**
* Adds a Component to the side navigation menu.
*
* @param cmp c Component to be added to the menu
*/
public void addComponentToSideMenu(Component cmp) {
checkIfInitialized();
if(permanentSideMenu) {
constructPermanentSideMenu();
addComponentToSideMenu(permanentSideMenuContainer, cmp);
} else {
Command cmd = new Command("");
cmd.putClientProperty(SideMenuBar.COMMAND_SIDE_COMPONENT, cmp);
cmd.putClientProperty(SideMenuBar.COMMAND_ACTIONABLE, Boolean.FALSE);
sideMenu.addCommand(cmd);
sideMenu.installMenuBar();
}
}
/**
* Find the command component instance if such an instance exists
* @param c the command instance
* @return the button instance
*/
public Button findCommandComponent(Command c) {
Button b = sideMenu.findCommandComponent(c);
if(b != null) {
return b;
}
return findCommandComponent(c, this);
}
private Button findCommandComponent(Command c, Container cnt) {
int count = cnt.getComponentCount();
for (int iter = 0; iter < count; iter++) {
Component current = cnt.getComponentAt(iter);
if (current instanceof Button) {
Button b = (Button) current;
if (b.getCommand() == c) {
return b;
}
} else {
if (current instanceof Container) {
Button b = findCommandComponent(c, (Container) current);
if(b != null) {
return b;
}
}
}
}
return null;
}
/**
* Adds a Command to the TitleArea on the right side.
*
* @param name the name/title of the command
* @param icon the icon for the command
* @param ev the even handler
* @return a newly created Command instance
*/
public Command addCommandToRightBar(String name, Image icon, final ActionListener ev) {
Command cmd = Command.create(name, icon, ev);
addCommandToRightBar(cmd);
return cmd;
}
/**
* Adds a Command to the TitleArea on the right side.
*
* @param cmd a Command
*/
public void addCommandToRightBar(Command cmd) {
checkIfInitialized();
cmd.putClientProperty("TitleCommand", Boolean.TRUE);
sideMenu.addCommand(cmd, 0);
}
/**
* Adds a Command to the TitleArea on the left side.
*
* @param name the name/title of the command
* @param icon the icon for the command
* @param ev the even handler
* @return a newly created Command instance
*/
public Command addCommandToLeftBar(String name, Image icon, final ActionListener ev) {
Command cmd = Command.create(name, icon, ev);
addCommandToLeftBar(cmd);
return cmd;
}
/**
* Adds a Command to the TitleArea on the left side.
*
* @param cmd a Command
*/
public void addCommandToLeftBar(Command cmd) {
checkIfInitialized();
cmd.putClientProperty("TitleCommand", Boolean.TRUE);
cmd.putClientProperty("Left", Boolean.TRUE);
sideMenu.addCommand(cmd, 0);
}
/**
* Returns the commands within the right bar section which can be useful for things like unit testing. Notice
* that you should not mutate the commands or the iteratable set in any way!
* @return the commands in the overflow menu
*/
public Iterable<Command> getRightBarCommands() {
return getBarCommands(null);
}
/**
* Returns the commands within the left bar section which can be useful for things like unit testing. Notice
* that you should not mutate the commands or the iteratable set in any way!
* @return the commands in the overflow menu
*/
public Iterable<Command> getLeftBarCommands() {
return getBarCommands(Boolean.TRUE);
}
private Iterable<Command> getBarCommands(Object leftValue) {
ArrayList<Command> cmds = new ArrayList<Command>();
findAllCommands(this, cmds);
int commandCount = cmds.size() - 1;
while(commandCount > 0) {
Command c = cmds.get(commandCount);
if(c.getClientProperty("Left") != leftValue) {
cmds.remove(commandCount);
}
commandCount--;
}
return cmds;
}
private void findAllCommands(Container cnt, ArrayList<Command> cmds) {
for(Component c : cnt) {
if(c instanceof Container) {
findAllCommands((Container)c, cmds);
continue;
}
if(c instanceof Button) {
cmds.add(((Button)c).getCommand());
}
}
}
/**
* Returns the associated SideMenuBar object of this Toolbar.
*
* @return the associated SideMenuBar object
*/
public MenuBar getMenuBar() {
return sideMenu;
}
/*
* A Overflow Menu is implemented as a dialog, this method allows you to
* override the dialog display in order to customize the dialog menu in
* various ways
*
* @param menu a dialog containing Overflow Menu options that can be
* customized
* @return the command selected by the user in the dialog
*/
protected Command showOverflowMenu(Dialog menu) {
Form parent = sideMenu.getParentForm();
int height;
int marginLeft;
int marginRight = 0;
Container dialogContentPane = menu.getDialogComponent();
marginLeft = parent.getWidth() - (dialogContentPane.getPreferredW()
+ menu.getStyle().getPadding(LEFT)
+ menu.getStyle().getPadding(RIGHT));
marginLeft = Math.max(0, marginLeft);
if (parent.getSoftButtonCount() > 1) {
height = parent.getHeight() - parent.getSoftButton(0).getParent().getPreferredH() - dialogContentPane.getPreferredH();
} else {
height = parent.getHeight() - dialogContentPane.getPreferredH();
}
height = Math.max(0, height);
int th = getHeight();
Transition transitionIn;
Transition transitionOut;
UIManager manager = parent.getUIManager();
LookAndFeel lf = manager.getLookAndFeel();
if (lf.getDefaultMenuTransitionIn() != null || lf.getDefaultMenuTransitionOut() != null) {
transitionIn = lf.getDefaultMenuTransitionIn();
if(transitionIn instanceof BubbleTransition){
((BubbleTransition)transitionIn).setComponentName("OverflowButton");
}
transitionOut = lf.getDefaultMenuTransitionOut();
} else {
transitionIn = CommonTransitions.createEmpty();
transitionOut = CommonTransitions.createEmpty();
}
menu.setTransitionInAnimator(transitionIn);
menu.setTransitionOutAnimator(transitionOut);
if(isRTL()){
marginRight = marginLeft;
marginLeft = 0;
}
int tint = parent.getTintColor();
parent.setTintColor(0x00FFFFFF);
parent.tint = false;
boolean showBelowTitle = manager.isThemeConstant("showMenuBelowTitleBool", true);
int topPadding = 0;
Component statusBar = ((BorderLayout) getLayout()).getNorth();
if (statusBar != null) {
topPadding = statusBar.getAbsoluteY() + statusBar.getHeight();
}
if(showBelowTitle){
topPadding = th;
}
Command r = menu.show(topPadding, Math.max(topPadding, height - topPadding), marginLeft, marginRight, true);
parent.setTintColor(tint);
return r;
}
/**
* Creates the list component containing the commands within the given
* vector used for showing the menu dialog
*
* @param commands list of command objects
* @return List object
*/
protected List createOverflowCommandList(Vector commands) {
List l = new List(commands);
l.setUIID("CommandList");
Component c = (Component) l.getRenderer();
c.setUIID("Command");
c = l.getRenderer().getListFocusComponent(l);
c.setUIID("CommandFocus");
l.setFixedSelection(List.FIXED_NONE_CYCLIC);
((DefaultListCellRenderer)l.getRenderer()).setShowNumbers(false);
return l;
}
/**
* Adds a status bar space to the north of the Component, subclasses can
* override this default behavior.
*/
protected void initTitleBarStatus() {
if (getUIManager().isThemeConstant("paintsTitleBarBool", false)) {
// check if its already added:
if (((BorderLayout) getLayout()).getNorth() == null) {
Container bar = new Container();
bar.setUIID("StatusBar");
addComponent(BorderLayout.NORTH, bar);
}
}
}
private void checkIfInitialized() {
if (!initialized) {
throw new IllegalStateException("Need to call "
+ "Form#setToolBar(Toolbar toolbar) before calling this method");
}
}
/**
* Sets the Toolbar to scroll off the screen upon content scroll. This
* feature can only work if the Form contentPane is scrollableY
*
* @param scrollOff if true the Toolbar needs to scroll off the screen when
* the Form ContentPane is scrolled
*/
public void setScrollOffUponContentPane(boolean scrollOff) {
if (initialized && !this.scrollOff && scrollOff) {
bindScrollListener(true);
}
this.scrollOff = scrollOff;
}
/**
* Hide the Toolbar if it is currently showing
*/
public void hideToolbar() {
showing = false;
if (actualPaneInitialH == 0) {
Form f = getComponentForm();
if(f != null){
initVars(f.getActualPane());
}
}
hideShowMotion = Motion.createSplineMotion(getY(), -getHeight(), 300);
getComponentForm().registerAnimated(this);
hideShowMotion.start();
}
/**
* Show the Toolbar if it is currently not showing
*/
public void showToolbar() {
showing = true;
hideShowMotion = Motion.createSplineMotion(getY(), initialY, 300);
getComponentForm().registerAnimated(this);
hideShowMotion.start();
}
public boolean animate() {
if (hideShowMotion != null) {
Form f = getComponentForm();
final Container actualPane = f.getActualPane();
int val = hideShowMotion.getValue();
setY(val);
if(!layered){
actualPane.setY(actualPaneInitialY + val);
if (showing) {
actualPane.setHeight(actualPaneInitialH + getHeight() - val);
} else {
actualPane.setHeight(actualPaneInitialH - val);
}
actualPane.doLayout();
}
f.repaint();
boolean finished = hideShowMotion.isFinished();
if (finished) {
f.deregisterAnimated(this);
hideShowMotion = null;
}
return !finished;
}
return false;
}
private void initVars(Container actualPane) {
initialY = getY();
actualPaneInitialY = actualPane.getY();
actualPaneInitialH = actualPane.getHeight();
}
private void bindScrollListener(boolean bind) {
final Form f = getComponentForm();
if (f != null) {
final Container actualPane = f.getActualPane();
final Container contentPane = f.getContentPane();
if (bind) {
initVars(actualPane);
scrollListener = new ScrollListener() {
public void scrollChanged(int scrollX, int scrollY, int oldscrollX, int oldscrollY) {
int diff = scrollY - oldscrollY;
int toolbarNewY = getY() - diff;
if (scrollY < 0 || Math.abs(toolbarNewY) < 2) {
return;
}
toolbarNewY = Math.max(toolbarNewY, -getHeight());
toolbarNewY = Math.min(toolbarNewY, initialY);
if (toolbarNewY != getY()) {
setY(toolbarNewY);
if(!layered){
actualPane.setY(actualPaneInitialY + toolbarNewY);
actualPane.setHeight(actualPaneInitialH + getHeight() - toolbarNewY);
actualPane.doLayout();
}
f.repaint();
}
}
};
contentPane.addScrollListener(scrollListener);
releasedListener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (getY() + getHeight() / 2 > 0) {
showToolbar();
} else {
hideToolbar();
}
f.repaint();
}
};
contentPane.addPointerReleasedListener(releasedListener);
} else {
if (scrollListener != null) {
contentPane.removeScrollListener(scrollListener);
contentPane.removePointerReleasedListener(releasedListener);
}
}
}
}
/**
* Creates the side navigation component with the Commands.
*
* @param commands the Command objects
* @return the Component to display on the side navigation
*/
protected Container createSideNavigationComponent(Vector commands, String placement) {
return sideMenu.createSideNavigationPanel(commands, placement);
}
/**
* Creates an empty side navigation panel.
*/
protected Container constructSideNavigationComponent() {
return sideMenu.constructSideNavigationPanel();
}
/**
* This method responsible to add a Component to the side navigation panel.
*
* @param menu the Menu Container that was created in the
* constructSideNavigationComponent() method
*
* @param cmp the Component to add to the side menu
*/
protected void addComponentToSideMenu(Container menu, Component cmp) {
sideMenu.addComponentToSideMenuImpl(menu, cmp);
}
/**
* Returns the commands within the side menu which can be useful for things like unit testing. Notice
* that you should not mutate the commands or the iteratable set in any way!
* @return the commands in the overflow menu
*/
public Iterable<Command> getSideMenuCommands() {
ArrayList<Command> cmds = new ArrayList<Command>();
if(permanentSideMenu) {
findAllCommands(permanentSideMenuContainer, cmds);
return cmds;
}
Form f = getComponentForm();
int commands = f.getCommandCount();
for(int iter = 0 ; iter < commands ; iter++) {
cmds.add(f.getCommand(iter));
}
return cmds;
}
class ToolbarSideMenu extends SideMenuBar {
@Override
protected Container createSideNavigationComponent(Vector commands, String placement) {
return Toolbar.this.createSideNavigationComponent(commands, placement);
}
@Override
protected Container constructSideNavigationComponent(){
return Toolbar.this.constructSideNavigationComponent();
}
@Override
protected void addComponentToSideMenu(Container menu, Component cmp) {
Toolbar.this.addComponentToSideMenu(menu, cmp);
}
@Override
protected Container getTitleAreaContainer() {
return Toolbar.this;
}
@Override
protected Component getTitleComponent() {
return Toolbar.this.getTitleComponent();
}
@Override
protected void initMenuBar(Form parent) {
Component ta = parent.getTitleArea();
parent.removeComponentFromForm(ta);
super.initMenuBar(parent);
if(layered){
Container layeredPane = parent.getLayeredPane();
Container p = layeredPane.getParent();
Container top = new Container(new BorderLayout());
top.addComponent(BorderLayout.NORTH, Toolbar.this);
p.addComponent(top);
}else{
parent.addComponentToForm(BorderLayout.NORTH, Toolbar.this);
}
initialized = true;
setTitle(parent.getTitle());
parent.revalidate();
initTitleBarStatus();
Display.getInstance().callSerially(new Runnable() {
public void run() {
if (scrollOff) {
bindScrollListener(true);
}
}
});
}
@Override
public boolean contains(int x, int y) {
return Toolbar.this.contains(x, y);
}
@Override
public Component getComponentAt(int x, int y) {
return Toolbar.this.getComponentAt(x, y);
}
@Override
void installRightCommands() {
super.installRightCommands();
if (overflowCommands != null && overflowCommands.size() > 0) {
Image i = (Image) UIManager.getInstance().getThemeImageConstant("menuImage");
if (i == null) {
i = FontImage.createMaterial(FontImage.MATERIAL_MORE_VERT, UIManager.getInstance().getComponentStyle("TitleCommand"), 4.5f);
}
menuButton = sideMenu.createTouchCommandButton(new Command("", i) {
public void actionPerformed(ActionEvent ev) {
sideMenu.showMenu();
}
});
menuButton.putClientProperty("overflow", Boolean.TRUE);
menuButton.setUIID("TitleCommand");
menuButton.setName("OverflowButton");
Layout l = getTitleAreaContainer().getLayout();
if (l instanceof BorderLayout) {
BorderLayout bl = (BorderLayout) l;
Component east = bl.getEast();
if (east == null) {
getTitleAreaContainer().addComponent(BorderLayout.EAST, menuButton);
} else {
if (east instanceof Container) {
Container cnt = (Container) east;
for (int j = 0; j < cnt.getComponentCount(); j++) {
Component c = cnt.getComponentAt(j);
if (c instanceof Button) {
//remove the menu button and add it last
if (c.getClientProperty("overflow") != null) {
cnt.removeComponent(c);
}
}
}
cnt.addComponent(cnt.getComponentCount(), menuButton);
} else {
if (east instanceof Button) {
if (east.getClientProperty("overflow") != null) {
return;
}
}
east.getParent().removeComponent(east);
Container buttons = new Container(new BoxLayout(BoxLayout.X_AXIS));
buttons.addComponent(east);
buttons.addComponent(menuButton);
getTitleAreaContainer().addComponent(BorderLayout.EAST, buttons);
}
}
}
}
}
@Override
protected Component createCommandComponent(Vector commands) {
return createOverflowCommandList(overflowCommands);
}
@Override
protected Button createBackCommandButton() {
Button back = new Button(getBackCommand());
return back;
}
@Override
protected Command showMenuDialog(Dialog menu) {
return showOverflowMenu(menu);
}
@Override
public int getCommandBehavior() {
return Display.COMMAND_BEHAVIOR_ICS;
}
@Override
void synchronizeCommandsWithButtonsInBackbutton() {
boolean hasSideCommands = false;
Vector commands = getCommands();
for (int iter = commands.size() - 1; iter > -1; iter--) {
Command c = (Command) commands.elementAt(iter);
if (c.getClientProperty("TitleCommand") == null) {
hasSideCommands = true;
break;
}
}
boolean hideBack = UIManager.getInstance().isThemeConstant("hideBackCommandBool", false);
boolean showBackOnTitle = UIManager.getInstance().isThemeConstant("showBackCommandOnTitleBool", false);
//need to put the back command
if (getBackCommand() != null) {
if (hasSideCommands && !hideBack) {
getCommands().remove(getBackCommand());
getCommands().add(getCommands().size(), getBackCommand());
} else {
if (!hideBack || showBackOnTitle) {
//put the back command on the title
Layout l = getTitleAreaContainer().getLayout();
if (l instanceof BorderLayout) {
BorderLayout bl = (BorderLayout) l;
Component west = bl.getWest();
Button back = createBackCommandButton();
if (!back.getUIID().equals("BackCommand")) {
back.setUIID("BackCommand");
}
hideEmptyCommand(back);
verifyBackCommandRTL(back);
if (west instanceof Container) {
((Container) west).addComponent(0, back);
} else {
Container left = new Container(new BoxLayout(BoxLayout.X_AXIS));
left.addComponent(back);
if (west != null) {
west.getParent().removeComponent(west);
left.addComponent(west);
}
getTitleAreaContainer().addComponent(BorderLayout.WEST, left);
}
}
}
}
}
}
@Override
void initTitleBarStatus() {
Toolbar.this.initTitleBarStatus();
}
}
}
| gpl-2.0 |
breandan/java-algebra-system | src/edu/jas/gbufd/GroebnerBaseQuotient.java | 6372 | /*
* $Id$
*/
package edu.jas.gbufd;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import edu.jas.gb.GroebnerBaseAbstract;
import edu.jas.gb.PairList;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.GenPolynomialRing;
import edu.jas.poly.PolyUtil;
import edu.jas.structure.GcdRingElem;
import edu.jas.ufd.PolyUfdUtil;
import edu.jas.ufd.Quotient;
import edu.jas.ufd.QuotientRing;
/**
* Groebner Base sequential algorithm for rational function coefficients,
* fraction free computation. Implements Groebner bases.
* @param <C> Quotient coefficient type
* @author Heinz Kredel
*/
public class GroebnerBaseQuotient<C extends GcdRingElem<C>> extends GroebnerBaseAbstract<Quotient<C>> {
private static final Logger logger = Logger.getLogger(GroebnerBaseQuotient.class);
private final boolean debug = logger.isDebugEnabled();
public final GroebnerBaseAbstract<GenPolynomial<C>> bba;
/**
* Constructor.
* @param rf quotient coefficient ring factory.
*/
public GroebnerBaseQuotient(QuotientRing<C> rf) {
this(new GroebnerBasePseudoRecSeq<C>(rf.ring));
}
/**
* Constructor.
* @param threads the number of parallel threads.
* @param rf quotient coefficient ring factory.
*/
public GroebnerBaseQuotient(int threads, QuotientRing<C> rf) {
this(new GroebnerBasePseudoRecParallel<C>(threads, rf.ring));
}
/**
* Constructor.
* @param rf quotient coefficient ring factory.
* @param pl pair selection strategy (for fraction parts).
*/
public GroebnerBaseQuotient(QuotientRing<C> rf, PairList<GenPolynomial<C>> pl) {
this(new GroebnerBasePseudoRecSeq<C>(rf.ring, pl));
}
/**
* Constructor.
* @param threads the number of parallel threads.
* @param rf quotient coefficient ring factory.
* @param pl pair selection strategy (for fraction parts).
*/
public GroebnerBaseQuotient(int threads, QuotientRing<C> rf, PairList<GenPolynomial<C>> pl) {
this(new GroebnerBasePseudoRecParallel<C>(threads, rf.ring, pl));
}
/**
* Constructor.
* @param bba Groebner base algorithm for GenPolynomial coefficients.
*/
public GroebnerBaseQuotient(GroebnerBaseAbstract<GenPolynomial<C>> bba) {
super();
this.bba = bba;
}
/**
* Get the String representation with GB engines.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.getClass().getSimpleName() + "(" + bba.toString() + ")";
}
/**
* Groebner base using fraction free computation.
* @param modv module variable number.
* @param F polynomial list.
* @return GB(F) a Groebner base of F.
*/
@Override
public List<GenPolynomial<Quotient<C>>> GB(int modv, List<GenPolynomial<Quotient<C>>> F) {
List<GenPolynomial<Quotient<C>>> G = F;
if (F == null || F.isEmpty()) {
return G;
}
GenPolynomialRing<Quotient<C>> rring = F.get(0).ring;
QuotientRing<C> cf = (QuotientRing<C>) rring.coFac;
GenPolynomialRing<GenPolynomial<C>> iring = new GenPolynomialRing<GenPolynomial<C>>(cf.ring, rring);
List<GenPolynomial<GenPolynomial<C>>> Fi = PolyUfdUtil.<C> integralFromQuotientCoefficients(iring, F);
//System.out.println("Fi = " + Fi);
logger.info("#Fi = " + Fi.size());
List<GenPolynomial<GenPolynomial<C>>> Gi = bba.GB(modv, Fi);
//System.out.println("Gi = " + Gi);
logger.info("#Gi = " + Gi.size());
G = PolyUfdUtil.<C> quotientFromIntegralCoefficients(rring, Gi);
G = PolyUtil.<Quotient<C>> monic(G);
return G;
}
/**
* Minimal ordered Groebner basis.
* @param Gp a Groebner base.
* @return a reduced Groebner base of Gp.
*/
@Override
public List<GenPolynomial<Quotient<C>>> minimalGB(List<GenPolynomial<Quotient<C>>> Gp) {
if (Gp == null || Gp.size() <= 1) {
return Gp;
}
// remove zero polynomials
List<GenPolynomial<Quotient<C>>> G = new ArrayList<GenPolynomial<Quotient<C>>>(Gp.size());
for (GenPolynomial<Quotient<C>> a : Gp) {
if (a != null && !a.isZERO()) { // always true in GB()
// already positive a = a.abs();
G.add(a);
}
}
if (G.size() <= 1) {
return G;
}
// remove top reducible polynomials
GenPolynomial<Quotient<C>> a;
List<GenPolynomial<Quotient<C>>> F;
F = new ArrayList<GenPolynomial<Quotient<C>>>(G.size());
while (G.size() > 0) {
a = G.remove(0);
if (red.isTopReducible(G, a) || red.isTopReducible(F, a)) {
// drop polynomial
if (debug) {
System.out.println("dropped " + a);
List<GenPolynomial<Quotient<C>>> ff;
ff = new ArrayList<GenPolynomial<Quotient<C>>>(G);
ff.addAll(F);
a = red.normalform(ff, a);
if (!a.isZERO()) {
System.out.println("error, nf(a) " + a);
}
}
} else {
F.add(a);
}
}
G = F;
if (G.size() <= 1) {
return G;
}
// reduce remaining polynomials
GenPolynomialRing<Quotient<C>> rring = G.get(0).ring;
QuotientRing<C> cf = (QuotientRing<C>) rring.coFac;
GenPolynomialRing<GenPolynomial<C>> iring = new GenPolynomialRing<GenPolynomial<C>>(cf.ring, rring);
List<GenPolynomial<GenPolynomial<C>>> Fi = PolyUfdUtil.integralFromQuotientCoefficients(iring, F);
logger.info("#Fi = " + Fi.size());
List<GenPolynomial<GenPolynomial<C>>> Gi = bba.minimalGB(Fi);
logger.info("#Gi = " + Gi.size());
G = PolyUfdUtil.<C> quotientFromIntegralCoefficients(rring, Gi);
G = PolyUtil.<Quotient<C>> monic(G);
return G;
}
/**
* Cleanup and terminate ThreadPool.
*/
@Override
public void terminate() {
bba.terminate();
}
/**
* Cancel ThreadPool.
*/
@Override
public int cancel() {
return bba.cancel();
}
}
| gpl-2.0 |
Johny-kann/Image_Wraping_and_Blending | src/main/java/com/computer_graphics/navigator/WrapperNavigator.java | 745 | package com.computer_graphics.navigator;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import com.computer_graphics.controller.gui.BlendController;
import com.computer_graphics.controller.gui.WrapController;
import com.computer_graphics.controller.gui.WrapperController;
public class WrapperNavigator {
public static WrapperController wrapper;
public static void setContentPane(String fxml)
{
try {
wrapper.setContentPane((Node)FXMLLoader.load(
WrapperNavigator.class.getResource(
fxml
)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
micwing/okcode | main-framework/src/main/java/okcode/framework/springmvc/annotation/RequestJsonParam.java | 1248 | /**
* @Project: main-framework
* @File: RequestJsonParam.java
* @package okcode.framework.springmvc.annotation
* @Description:
* @author micwing
* @date 2013-3-26 下午4:52:45
* @version V1.0
*
* Copyright (c) 2013 OneKr Soft Studio. All Rights Reserved.
*
* Copying of this document or code and giving it to others and the
* use or communication of the contents thereof, are forbidden without
* expressed authority. Offenders are liable to the payment of damages.
* All rights reserved in the event of the grant of a invention patent or the
* registration of a utility model, design or code.
*/
package okcode.framework.springmvc.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @ClassName: RequestJsonParam
* @Description:
* @author micwing
* @date 2013-3-26 下午5:31:15
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestJsonParam {
/**
* 用于绑定的请求参数名字
*/
String value() default "";
/**
* 是否必须,默认是
*/
boolean required() default true;
}
| gpl-2.0 |
jauler/VU_MIF_tasks | MagistroStudijos/ObjectOrientedTechnologies/OOT2/src/main/java/com/rytis/oot2/devices/Device5.java | 852 | package com.rytis.oot2.devices;
import com.rytis.oot2.memories.Memory;
import com.rytis.oot2.processors.CPU;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author rytis
*/
public class Device5 implements Device {
private CPU cpu;
private Memory memory;
private String program;
public void setCPU(CPU cpu) {
this.cpu = cpu;
}
public void setMemory(Memory memory) {
this.memory = memory;
}
public void setProgram(String program) {
this.program = program;
}
@Override
public void Boot() throws Throwable {
System.out.println("Booting Device5:");
cpu.Execute(program, memory);
System.out.println();
}
}
| gpl-2.0 |
mrstampy/gameboot | GameBoot/src/main/java/com/github/mrstampy/gameboot/processor/AbstractGameBootProcessor.java | 8330 | /*
* ______ ____ __
* / ____/___ _____ ___ ___ / __ )____ ____ / /_
* / / __/ __ `/ __ `__ \/ _ \ / __ / __ \/ __ \/ __/
* / /_/ / /_/ / / / / / / __/ / /_/ / /_/ / /_/ / /_
* \____/\__,_/_/ /_/ /_/\___/ /_____/\____/\____/\__/
*
* .-'\
* .-' `/\
* .-' `/\
* \ `/\
* \ `/\
* \ _- `/\ _.--.
* \ _- `/`-..--\ )
* \ _- `,',' / ,')
* `-_ - ` -- ~ ,','
* `- ,','
* \,--. ____==-~
* \ \_-~\
* `_-~_.-'
* \-~
*
* http://mrstampy.github.io/gameboot/
*
* Copyright (C) 2015, 2016 Burton Alexander
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package com.github.mrstampy.gameboot.processor;
import java.lang.invoke.MethodHandles;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.mrstampy.gameboot.exception.GameBootException;
import com.github.mrstampy.gameboot.exception.GameBootRuntimeException;
import com.github.mrstampy.gameboot.exception.GameBootThrowable;
import com.github.mrstampy.gameboot.locale.processor.LocaleRegistry;
import com.github.mrstampy.gameboot.messages.AbstractGameBootMessage;
import com.github.mrstampy.gameboot.messages.Response;
import com.github.mrstampy.gameboot.messages.Response.ResponseCode;
import com.github.mrstampy.gameboot.messages.context.ResponseContext;
import com.github.mrstampy.gameboot.messages.context.ResponseContextCodes;
import com.github.mrstampy.gameboot.messages.context.ResponseContextLookup;
import com.github.mrstampy.gameboot.systemid.SystemIdKey;
/**
* Abstract superclass for {@link GameBootProcessor}s.
*
* @param <M>
* the generic type
*/
public abstract class AbstractGameBootProcessor<M extends AbstractGameBootMessage>
implements GameBootProcessor<M>, ResponseContextCodes {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private ResponseContextLookup lookup;
@Autowired
private LocaleRegistry localeRegistry;
/**
* Sets the error lookup.
*
* @param lookup
* the new error lookup
*/
@Autowired
public void setErrorLookup(ResponseContextLookup lookup) {
this.lookup = lookup;
}
/*
* (non-Javadoc)
*
* @see
* com.github.mrstampy.gameboot.processor.GameBootProcessor#process(com.github
* .mrstampy.gameboot.messages.AbstractGameBootMessage)
*/
@Override
public Response process(M message) throws Exception {
if (message == null) fail(getResponseContext(NO_MESSAGE), "Null message");
String type = message.getType();
Integer id = message.getId();
log.debug("Processing message type {}, id {}", type, id);
try {
validate(message);
Response response = processImpl(message);
response.setId(id);
if (Response.TYPE.equals(response.getType())) response.setType(type);
log.debug("Created response, code {} for message type {}, id {}", response.getResponseCode(), type, id);
return response;
} catch (GameBootRuntimeException | GameBootException e) {
return gameBootErrorResponse(message, e);
} catch (Exception e) {
log.error("Error in processing {}, id {}", type, id, e);
Response r = failure(getResponseContext(UNEXPECTED_ERROR, message.getSystemId()),
message,
"An unexpected error has occurred");
r.setId(id);
return r;
}
}
/**
* Game boot error response.
*
* @param message
* the message
* @param e
* the e
* @return the response
*/
protected Response gameBootErrorResponse(M message, GameBootThrowable e) {
ResponseContext error = getError(message.getSystemId(), e);
log.error("Error in processing {} : {}, {}", message.getType(), error, e.getMessage());
Object[] payload = e.getError() == null ? null : e.getPayload();
Response r = new Response(message, ResponseCode.FAILURE, error, payload);
r.setId(message.getId());
r.setContext(error);
return r;
}
private ResponseContext getError(SystemIdKey systemId, GameBootThrowable e) {
if (e.getError() != null) return e.getError();
if (e.getErrorCode() == null) return null;
return lookup.lookup(e.getErrorCode(), localeRegistry.get(systemId), e.getPayload());
}
/**
* Gets the response context.
*
* @param code
* the code
* @param parameters
* the parameters
* @return the response context
*/
protected ResponseContext getResponseContext(Integer code, Object... parameters) {
return getResponseContext(code, null, parameters);
}
/**
* Gets the response context.
*
* @param code
* the code
* @param systemId
* the system id
* @param parameters
* the parameters
* @return the response context
*/
protected ResponseContext getResponseContext(Integer code, SystemIdKey systemId, Object... parameters) {
Locale locale = systemId == null ? Locale.getDefault() : localeRegistry.get(systemId);
return lookup.lookup(code, locale, parameters);
}
/**
* Fail, throwing a {@link GameBootRuntimeException} with the specified
* message. The exception is caught by the
* {@link #process(AbstractGameBootMessage)} implementation which after
* logging returns a failure response.
*
* @param rc
* the rc
* @param message
* the message
* @param payload
* the payload
* @throws GameBootRuntimeException
* the game boot runtime exception
*/
protected void fail(ResponseContext rc, String message, Object... payload) throws GameBootRuntimeException {
throw new GameBootRuntimeException(message, rc, payload);
}
/**
* Returns an initialized success {@link Response}.
*
* @param message
* the message
* @param response
* the response
* @return the response
*/
protected Response success(M message, Object... response) {
return new Response(message, ResponseCode.SUCCESS, response);
}
/**
* Returns an initialized failure {@link Response}.
*
* @param rc
* the rc
* @param message
* the message
* @param response
* the response
* @return the response
*/
protected Response failure(ResponseContext rc, M message, Object... response) {
return new Response(message, ResponseCode.FAILURE, rc, response);
}
/**
* Implement to perform any pre-processing validation.
*
* @param message
* the message
* @throws Exception
* the exception
*/
protected abstract void validate(M message) throws Exception;
/**
* Implement to process the {@link #validate(AbstractGameBootMessage)}'ed
* message.
*
* @param message
* the message
* @return the response
* @throws Exception
* the exception
*/
protected abstract Response processImpl(M message) throws Exception;
}
| gpl-2.0 |
digantDj/Gifff-Talk | TMessagesProj/src/main/java/org/giffftalk/messenger/query/SharedMediaQuery.java | 26007 | /*
* This is the source code of Telegram for Android v. 2.0.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.giffftalk.messenger.query;
import android.text.TextUtils;
import org.giffftalk.SQLite.SQLiteCursor;
import org.giffftalk.SQLite.SQLiteDatabase;
import org.giffftalk.SQLite.SQLitePreparedStatement;
import org.giffftalk.messenger.AndroidUtilities;
import org.giffftalk.messenger.ChatObject;
import org.giffftalk.messenger.ImageLoader;
import org.giffftalk.messenger.MessageObject;
import org.giffftalk.messenger.MessagesController;
import org.giffftalk.messenger.MessagesStorage;
import org.giffftalk.messenger.NotificationCenter;
import org.giffftalk.messenger.FileLog;
import org.giffftalk.tgnet.ConnectionsManager;
import org.giffftalk.tgnet.NativeByteBuffer;
import org.giffftalk.tgnet.RequestDelegate;
import org.giffftalk.tgnet.TLObject;
import org.giffftalk.tgnet.TLRPC;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public class SharedMediaQuery {
public final static int MEDIA_PHOTOVIDEO = 0;
public final static int MEDIA_FILE = 1;
public final static int MEDIA_AUDIO = 2;
public final static int MEDIA_URL = 3;
public final static int MEDIA_MUSIC = 4;
public final static int MEDIA_TYPES_COUNT = 5;
public static void loadMedia(final long uid, final int offset, final int count, final int max_id, final int type, final boolean fromCache, final int classGuid) {
final boolean isChannel = (int) uid < 0 && ChatObject.isChannel(-(int) uid);
int lower_part = (int)uid;
if (fromCache || lower_part == 0) {
loadMediaDatabase(uid, offset, count, max_id, type, classGuid, isChannel);
} else {
TLRPC.TL_messages_search req = new TLRPC.TL_messages_search();
req.offset = offset;
req.limit = count + 1;
req.max_id = max_id;
if (type == MEDIA_PHOTOVIDEO) {
req.filter = new TLRPC.TL_inputMessagesFilterPhotoVideo();
} else if (type == MEDIA_FILE) {
req.filter = new TLRPC.TL_inputMessagesFilterDocument();
} else if (type == MEDIA_AUDIO) {
req.filter = new TLRPC.TL_inputMessagesFilterVoice();
} else if (type == MEDIA_URL) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (type == MEDIA_MUSIC) {
req.filter = new TLRPC.TL_inputMessagesFilterMusic();
}
req.q = "";
req.peer = MessagesController.getInputPeer(lower_part);
if (req.peer == null) {
return;
}
int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
boolean topReached;
if (res.messages.size() > count) {
topReached = false;
res.messages.remove(res.messages.size() - 1);
} else {
topReached = true;
}
processLoadedMedia(res, uid, offset, count, max_id, type, false, classGuid, isChannel, topReached);
}
}
});
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
}
public static void getMediaCount(final long uid, final int type, final int classGuid, boolean fromCache) {
int lower_part = (int)uid;
if (fromCache || lower_part == 0) {
getMediaCountDatabase(uid, type, classGuid);
} else {
TLRPC.TL_messages_search req = new TLRPC.TL_messages_search();
req.offset = 0;
req.limit = 1;
req.max_id = 0;
if (type == MEDIA_PHOTOVIDEO) {
req.filter = new TLRPC.TL_inputMessagesFilterPhotoVideo();
} else if (type == MEDIA_FILE) {
req.filter = new TLRPC.TL_inputMessagesFilterDocument();
} else if (type == MEDIA_AUDIO) {
req.filter = new TLRPC.TL_inputMessagesFilterVoice();
} else if (type == MEDIA_URL) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (type == MEDIA_MUSIC) {
req.filter = new TLRPC.TL_inputMessagesFilterMusic();
}
req.q = "";
req.peer = MessagesController.getInputPeer(lower_part);
if (req.peer == null) {
return;
}
int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
int count;
if (res instanceof TLRPC.TL_messages_messages) {
count = res.messages.size();
} else {
count = res.count;
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().putUsers(res.users, false);
MessagesController.getInstance().putChats(res.chats, false);
}
});
processLoadedMediaCount(count, uid, type, classGuid, false);
}
}
});
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
}
public static int getMediaType(TLRPC.Message message) {
if (message == null) {
return -1;
}
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
return MEDIA_PHOTOVIDEO;
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (MessageObject.isVoiceMessage(message)) {
return MEDIA_AUDIO;
} else if (MessageObject.isVideoMessage(message)) {
return MEDIA_PHOTOVIDEO;
} else if (MessageObject.isStickerMessage(message)) {
return -1;
} else if (MessageObject.isMusicMessage(message)) {
return MEDIA_MUSIC;
} else {
return MEDIA_FILE;
}
} else if (!message.entities.isEmpty()) {
for (int a = 0; a < message.entities.size(); a++) {
TLRPC.MessageEntity entity = message.entities.get(a);
if (entity instanceof TLRPC.TL_messageEntityUrl || entity instanceof TLRPC.TL_messageEntityTextUrl || entity instanceof TLRPC.TL_messageEntityEmail) {
return MEDIA_URL;
}
}
}
return -1;
}
public static boolean canAddMessageToMedia(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret && message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl != 0 && message.ttl <= 60) {
return false;
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto ||
message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isGifDocument(message.media.document)) {
return true;
} else if (!message.entities.isEmpty()) {
for (int a = 0; a < message.entities.size(); a++) {
TLRPC.MessageEntity entity = message.entities.get(a);
if (entity instanceof TLRPC.TL_messageEntityUrl || entity instanceof TLRPC.TL_messageEntityTextUrl || entity instanceof TLRPC.TL_messageEntityEmail) {
return true;
}
}
}
return false;
}
private static void processLoadedMedia(final TLRPC.messages_Messages res, final long uid, int offset, int count, int max_id, final int type, final boolean fromCache, final int classGuid, final boolean isChannel, final boolean topReached) {
int lower_part = (int)uid;
if (fromCache && res.messages.isEmpty() && lower_part != 0) {
loadMedia(uid, offset, count, max_id, type, false, classGuid);
} else {
if (!fromCache) {
ImageLoader.saveMessagesThumbs(res.messages);
MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
putMediaDatabase(uid, type, res.messages, max_id, topReached);
}
final HashMap<Integer, TLRPC.User> usersDict = new HashMap<>();
for (int a = 0; a < res.users.size(); a++) {
TLRPC.User u = res.users.get(a);
usersDict.put(u.id, u);
}
final ArrayList<MessageObject> objects = new ArrayList<>();
for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a);
objects.add(new MessageObject(message, usersDict, true));
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
int totalCount = res.count;
MessagesController.getInstance().putUsers(res.users, fromCache);
MessagesController.getInstance().putChats(res.chats, fromCache);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mediaDidLoaded, uid, totalCount, objects, classGuid, type, topReached);
}
});
}
}
private static void processLoadedMediaCount(final int count, final long uid, final int type, final int classGuid, final boolean fromCache) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
int lower_part = (int) uid;
if (fromCache && count == -1 && lower_part != 0) {
getMediaCount(uid, type, classGuid, false);
} else {
if (!fromCache) {
putMediaCountDatabase(uid, type, count);
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mediaCountDidLoaded, uid, (fromCache && count == -1 ? 0 : count), fromCache, type);
}
}
});
}
private static void putMediaCountDatabase(final long uid, final int type, final int count) {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
SQLitePreparedStatement state2 = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?)");
state2.requery();
state2.bindLong(1, uid);
state2.bindInteger(2, type);
state2.bindInteger(3, count);
state2.step();
state2.dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
private static void getMediaCountDatabase(final long uid, final int type, final int classGuid) {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
int count = -1;
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT count FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type));
if (cursor.next()) {
count = cursor.intValue(0);
}
cursor.dispose();
int lower_part = (int)uid;
if (count == -1 && lower_part == 0) {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type));
if (cursor.next()) {
count = cursor.intValue(0);
}
cursor.dispose();
if (count != -1) {
putMediaCountDatabase(uid, type, count);
}
}
processLoadedMediaCount(count, uid, type, classGuid, true);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
private static void loadMediaDatabase(final long uid, final int offset, final int count, final int max_id, final int type, final int classGuid, final boolean isChannel) {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
boolean topReached = false;
TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages();
try {
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
int countToLoad = count + 1;
SQLiteCursor cursor;
SQLiteDatabase database = MessagesStorage.getInstance().getDatabase();
boolean isEnd = false;
if ((int) uid != 0) {
int channelId = 0;
long messageMaxId = max_id;
if (isChannel) {
channelId = -(int) uid;
}
if (messageMaxId != 0 && channelId != 0) {
messageMaxId |= ((long) channelId) << 32;
}
cursor = database.queryFinalized(String.format(Locale.US, "SELECT start FROM media_holes_v2 WHERE uid = %d AND type = %d AND start IN (0, 1)", uid, type));
if (cursor.next()) {
isEnd = cursor.intValue(0) == 1;
cursor.dispose();
} else {
cursor.dispose();
cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM media_v2 WHERE uid = %d AND type = %d AND mid > 0", uid, type));
if (cursor.next()) {
int mid = cursor.intValue(0);
if (mid != 0) {
SQLitePreparedStatement state = database.executeFast("REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");
state.requery();
state.bindLong(1, uid);
state.bindInteger(2, type);
state.bindInteger(3, 0);
state.bindInteger(4, mid);
state.step();
state.dispose();
}
}
cursor.dispose();
}
if (messageMaxId != 0) {
long holeMessageId = 0;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT end FROM media_holes_v2 WHERE uid = %d AND type = %d AND end <= %d ORDER BY end DESC LIMIT 1", uid, type, max_id));
if (cursor.next()) {
holeMessageId = cursor.intValue(0);
if (channelId != 0) {
holeMessageId |= ((long) channelId) << 32;
}
}
cursor.dispose();
if (holeMessageId > 1) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND mid < %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, messageMaxId, holeMessageId, type, countToLoad));
} else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, messageMaxId, type, countToLoad));
}
} else {
long holeMessageId = 0;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(end) FROM media_holes_v2 WHERE uid = %d AND type = %d", uid, type));
if (cursor.next()) {
holeMessageId = cursor.intValue(0);
if (channelId != 0) {
holeMessageId |= ((long) channelId) << 32;
}
}
cursor.dispose();
if (holeMessageId > 1) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d,%d", uid, holeMessageId, type, offset, countToLoad));
} else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC LIMIT %d,%d", uid, type, offset, countToLoad));
}
}
} else {
isEnd = true;
if (max_id != 0) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v2 as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, max_id, type, countToLoad));
} else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v2 as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND type = %d ORDER BY m.mid ASC LIMIT %d,%d", uid, type, offset, countToLoad));
}
}
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
message.id = cursor.intValue(1);
message.dialog_id = uid;
if ((int) uid == 0) {
message.random_id = cursor.longValue(2);
}
res.messages.add(message);
if (message.from_id > 0) {
if (!usersToLoad.contains(message.from_id)) {
usersToLoad.add(message.from_id);
}
} else {
if (!chatsToLoad.contains(-message.from_id)) {
chatsToLoad.add(-message.from_id);
}
}
}
}
cursor.dispose();
if (!usersToLoad.isEmpty()) {
MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), res.users);
}
if (!chatsToLoad.isEmpty()) {
MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), res.chats);
}
if (res.messages.size() > count) {
topReached = false;
res.messages.remove(res.messages.size() - 1);
} else {
topReached = isEnd;
}
} catch (Exception e) {
res.messages.clear();
res.chats.clear();
res.users.clear();
FileLog.e("tmessages", e);
} finally {
processLoadedMedia(res, uid, offset, count, max_id, type, true, classGuid, isChannel, topReached);
}
}
});
}
private static void putMediaDatabase(final long uid, final int type, final ArrayList<TLRPC.Message> messages, final int max_id, final boolean topReached) {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
if (messages.isEmpty() || topReached) {
MessagesStorage.getInstance().doneHolesInMedia(uid, max_id, type);
if (messages.isEmpty()) {
return;
}
}
MessagesStorage.getInstance().getDatabase().beginTransaction();
SQLitePreparedStatement state2 = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)");
for (TLRPC.Message message : messages) {
if (canAddMessageToMedia(message)) {
long messageId = message.id;
if (message.to_id.channel_id != 0) {
messageId |= ((long) message.to_id.channel_id) << 32;
}
state2.requery();
NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
message.serializeToStream(data);
state2.bindLong(1, messageId);
state2.bindLong(2, uid);
state2.bindInteger(3, message.date);
state2.bindInteger(4, type);
state2.bindByteBuffer(5, data);
state2.step();
data.reuse();
}
}
state2.dispose();
if (!topReached || max_id != 0) {
int minId = topReached ? 1 : messages.get(messages.size() - 1).id;
if (max_id != 0) {
MessagesStorage.getInstance().closeHolesInMedia(uid, minId, max_id, type);
} else {
MessagesStorage.getInstance().closeHolesInMedia(uid, minId, Integer.MAX_VALUE, type);
}
}
MessagesStorage.getInstance().getDatabase().commitTransaction();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public static void loadMusic(final long uid, final int max_id) {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
final ArrayList<MessageObject> arrayList = new ArrayList<>();
try {
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", uid, max_id, MEDIA_MUSIC));
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
if (MessageObject.isMusicMessage(message)) {
message.id = cursor.intValue(1);
message.dialog_id = uid;
arrayList.add(0, new MessageObject(message, null, false));
}
}
}
cursor.dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.musicDidLoaded, uid, arrayList);
}
});
}
});
}
}
| gpl-2.0 |
mviitanen/marsmod | mcp/src/minecraft_server/net/minecraft/world/gen/structure/MapGenStronghold.java | 6287 | package net.minecraft.world.gen.structure;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import net.minecraft.util.MathHelper;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
public class MapGenStronghold extends MapGenStructure
{
private List field_151546_e;
/**
* is spawned false and set true once the defined BiomeGenBases were compared with the present ones
*/
private boolean ranBiomeCheck;
private ChunkCoordIntPair[] structureCoords;
private double field_82671_h;
private int field_82672_i;
private static final String __OBFID = "CL_00000481";
public MapGenStronghold()
{
this.structureCoords = new ChunkCoordIntPair[3];
this.field_82671_h = 32.0D;
this.field_82672_i = 3;
this.field_151546_e = new ArrayList();
BiomeGenBase[] var1 = BiomeGenBase.registerStructurePiece();
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3)
{
BiomeGenBase var4 = var1[var3];
if (var4 != null && var4.minHeight > 0.0F)
{
this.field_151546_e.add(var4);
}
}
}
public MapGenStronghold(Map p_i2068_1_)
{
this();
Iterator var2 = p_i2068_1_.entrySet().iterator();
while (var2.hasNext())
{
Entry var3 = (Entry)var2.next();
if (((String)var3.getKey()).equals("distance"))
{
this.field_82671_h = MathHelper.func_82713_a((String)var3.getValue(), this.field_82671_h, 1.0D);
}
else if (((String)var3.getKey()).equals("count"))
{
this.structureCoords = new ChunkCoordIntPair[MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.structureCoords.length, 1)];
}
else if (((String)var3.getKey()).equals("spread"))
{
this.field_82672_i = MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.field_82672_i, 1);
}
}
}
public String func_143025_a()
{
return "Stronghold";
}
protected boolean canSpawnStructureAtCoords(int p_75047_1_, int p_75047_2_)
{
if (!this.ranBiomeCheck)
{
Random var3 = new Random();
var3.setSeed(this.worldObj.getSeed());
double var4 = var3.nextDouble() * Math.PI * 2.0D;
int var6 = 1;
for (int var7 = 0; var7 < this.structureCoords.length; ++var7)
{
double var8 = (1.25D * (double)var6 + var3.nextDouble()) * this.field_82671_h * (double)var6;
int var10 = (int)Math.round(Math.cos(var4) * var8);
int var11 = (int)Math.round(Math.sin(var4) * var8);
ChunkPosition var12 = this.worldObj.getWorldChunkManager().findBiomePosition((var10 << 4) + 8, (var11 << 4) + 8, 112, this.field_151546_e, var3);
if (var12 != null)
{
var10 = var12.chunkPosX >> 4;
var11 = var12.chunkPosZ >> 4;
}
this.structureCoords[var7] = new ChunkCoordIntPair(var10, var11);
var4 += (Math.PI * 2D) * (double)var6 / (double)this.field_82672_i;
if (var7 == this.field_82672_i)
{
var6 += 2 + var3.nextInt(5);
this.field_82672_i += 1 + var3.nextInt(2);
}
}
this.ranBiomeCheck = true;
}
ChunkCoordIntPair[] var13 = this.structureCoords;
int var14 = var13.length;
for (int var5 = 0; var5 < var14; ++var5)
{
ChunkCoordIntPair var15 = var13[var5];
if (p_75047_1_ == var15.chunkXPos && p_75047_2_ == var15.chunkZPos)
{
return true;
}
}
return false;
}
/**
* Returns a list of other locations at which the structure generation has been run, or null if not relevant to this
* structure generator.
*/
protected List getCoordList()
{
ArrayList var1 = new ArrayList();
ChunkCoordIntPair[] var2 = this.structureCoords;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
ChunkCoordIntPair var5 = var2[var4];
if (var5 != null)
{
var1.add(var5.func_151349_a(64));
}
}
return var1;
}
protected StructureStart getStructureStart(int p_75049_1_, int p_75049_2_)
{
MapGenStronghold.Start var3;
for (var3 = new MapGenStronghold.Start(this.worldObj, this.rand, p_75049_1_, p_75049_2_); var3.getComponents().isEmpty() || ((StructureStrongholdPieces.Stairs2)var3.getComponents().get(0)).strongholdPortalRoom == null; var3 = new MapGenStronghold.Start(this.worldObj, this.rand, p_75049_1_, p_75049_2_))
{
;
}
return var3;
}
public static class Start extends StructureStart
{
private static final String __OBFID = "CL_00000482";
public Start() {}
public Start(World p_i2067_1_, Random p_i2067_2_, int p_i2067_3_, int p_i2067_4_)
{
super(p_i2067_3_, p_i2067_4_);
StructureStrongholdPieces.prepareStructurePieces();
StructureStrongholdPieces.Stairs2 var5 = new StructureStrongholdPieces.Stairs2(0, p_i2067_2_, (p_i2067_3_ << 4) + 2, (p_i2067_4_ << 4) + 2);
this.components.add(var5);
var5.buildComponent(var5, this.components, p_i2067_2_);
List var6 = var5.field_75026_c;
while (!var6.isEmpty())
{
int var7 = p_i2067_2_.nextInt(var6.size());
StructureComponent var8 = (StructureComponent)var6.remove(var7);
var8.buildComponent(var5, this.components, p_i2067_2_);
}
this.updateBoundingBox();
this.markAvailableHeight(p_i2067_1_, p_i2067_2_, 10);
}
}
}
| gpl-2.0 |
NationalLibraryOfNorway/Bibliotekstatistikk | abmstatistikk-user-domain/src/main/java/no/abmu/user/domain/Principal.java | 7632 | /*$Id: Principal.java 13026 2009-02-14 01:28:46Z jens $*/
/*
****************************************************************************
* *
* (c) Copyright 2005 ABM-utvikling *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; either version 2 of the License, or (at your *
* option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
* Public License for more details. http://www.gnu.org/licenses/gpl.html *
* *
****************************************************************************
*/
package no.abmu.user.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import no.abmu.common.DomainObject;
import no.abmu.common.domain.Entity;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
/**
* Principal.
*
* @author Erik Romson, erik@zenior.no
* @author $Author: jens $
* @version $Rev: 13026 $
* @date $Date: 2009-02-14 02:28:46 +0100 (Sat, 14 Feb 2009) $
* @copyright ABM-Utvikling
*/
@SuppressWarnings("serial")
@javax.persistence.Entity
@Inheritance(strategy=InheritanceType.JOINED)
@GenericGenerator(name="increment", strategy = "increment")
public class Principal extends DomainObject implements Entity {
// private static final Log logger = (Log) LogFactory.getLog(Principal.class);
private String name;
private String description;
private List<RoleRelation> roles = new ArrayList<RoleRelation>();
private UserGroup parentGroup;
public Principal() {
}
public Principal(String name) {
this.name = name;
}
/**
* getId, primary key.
*
* @return
*/
@Id @GeneratedValue(generator="increment")
public Long getId() {
return super.getId();
}
/**
* getRoles.
*
* @return
* @hibernate.bag table="TBL_JOIN_USER_ROLE" cascade="all" inverse="false"
* @hibernate.key column="FK_USER_ID"
* @hibernate.key-column name="FK_USER_ID" index="roleRelation_FK_USER_ID_idx"
* @hibernate.many-to-many class="no.abmu.user.domain.RoleRelation" column="FK_ROLE_RELATION_ID"
* @hibernate.collection-key column="FK_USER_ID"
* @hibernate.collection-key-column name="FK_USER_ID" index="roleRelation_FK_USER_ID_idx"
* @hibernate.collection-many-to-many class="no.abmu.user.domain.RoleRelation" column="FK_ROLE_RELATION_ID"
*/
@ManyToMany(cascade={CascadeType.ALL}, targetEntity=RoleRelation.class, fetch=FetchType.EAGER)
@JoinTable(name="TBL_JOIN_USER_ROLE",
joinColumns=@JoinColumn(name="FK_USER_ID"),
inverseJoinColumns=@JoinColumn(name="FK_ROLE_RELATION_ID"))
public List<RoleRelation> getRoles() {
return roles;
}
public void addRole(RoleRelation roleRelation) {
roles.add(roleRelation);
}
/**
* Adds a collection of role relations to this user.
*
* @param rolesToAdd the collection of role relations
*/
public void addRoles(Set<RoleRelation> rolesToAdd) {
if (rolesToAdd != null) {
roles.addAll(rolesToAdd);
}
}
/**
* getName.
*
* @return
* @hibernate.property update="false"
* insert="true"
* unique="true"
* not-null="true"
* length="82"
* @hibernate.column name="name"
* index="principal_name_idx"
*/
//TODO: Should be unique=true, workaround to make bad tests run.
@Column(updatable=false, unique=false, nullable=false, length=82)
@Index(name="principal_name_idx") // Do we need an index when unique=true ?
public String getName() {
return name;
}
/**
* getDescription.
*
* @return
* @hibernate.property
*/
public String getDescription() {
return description;
}
/**
* getParentGroup.
*
* @hibernate.many-to-one column="FK_PARENT_GROUP_ID"
* class="no.abmu.user.domain.UserGroup"
* @hibernate.column name="FK_PARENT_GROUP_ID"
* index="principal_FK_PARENT_GROUP_ID_idx"
*/
@ManyToOne
@JoinColumn(name="FK_PARENT_GROUP_ID")
@Index(name="principal_FK_PARENT_GROUP_ID_idx")
public UserGroup getParentGroup() {
return parentGroup;
}
public void setParentGroup(UserGroup parentGroup) {
this.parentGroup = parentGroup;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setRoles(List<RoleRelation> roles) {
this.roles = roles;
}
public boolean equalsAttr(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Principal)) {
return false;
}
final Principal principal = (Principal) o;
if (getDescription() != null
? !getDescription().equals(principal.getDescription()) : principal.getDescription() != null) {
return false;
}
if (getName() != null ? !getName().equals(principal.getName()) : principal.getName() != null) {
return false;
}
if (getRoles() != null ? !getRoles().equals(principal.getRoles()) : principal.getRoles() != null) {
return false;
}
return true;
}
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final Principal principal = (Principal) obj;
if (getName() != null ? !getName().equals(principal.getName()) : principal.getName() != null) {
return false;
}
if (getDescription() != null
? !getDescription().equals(principal.getDescription()) : principal.getDescription() != null) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (getName() != null ? getName().hashCode() : 0);
result = 29 * result + (getDescription() != null ? getDescription().hashCode() : 0);
return result;
}
public String toString() {
return super.toString() + " ::: Principal{"
+ "name='" + name + "'"
+ ", description='" + description + "'"
+ ", roles=" + roles
+ "}";
}
}
| gpl-2.0 |
OpenYMSG/openymsg | src/main/java/org/openymsg/legacy/network/event/SessionListener.java | 1130 | /*
* OpenYMSG, an implementation of the Yahoo Instant Messaging and Chat protocol. Copyright (C) 2007 G. der Kinderen,
* Nimbuzz.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details. You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openymsg.legacy.network.event;
import org.openymsg.legacy.network.FireEvent;
/**
* Listener interface for Session events.
* @author G. der Kinderen, Nimbuzz B.V. guus@nimbuzz.com
* @author S.E. Morris
*/
public interface SessionListener {
public void dispatch(FireEvent event);
}
| gpl-2.0 |
yositune/mobile-mba-androidapp | AndroidAppLibrary/src/com/samknows/measurement/test/outparcer/ParcerDataType.java | 2500 | /*
2013 Measuring Broadband America Program
Mobile Measurement Android Application
Copyright (C) 2012 SamKnows Ltd.
The FCC Measuring Broadband America (MBA) Program's Mobile Measurement Effort developed in cooperation with SamKnows Ltd. and diverse stakeholders employs an client-server based anonymized data collection approach to gather broadband performance data in an open and transparent manner with the highest commitment to protecting participants privacy. All data collected is thoroughly analyzed and processed prior to public release to ensure that subscribers’ privacy interests are protected.
Data related to the radio characteristics of the handset, information about the handset type and operating system (OS) version, the GPS coordinates available from the handset at the time each test is run, the date and time of the observation, and the results of active test results are recorded on the handset in JSON(JavaScript Object Notation) nested data elements within flat files. These JSON files are then transmitted to storage servers at periodic intervals after the completion of active test measurements.
This Android application source code is made available under the GNU GPL2 for testing purposes only and intended for participants in the SamKnows/FCC Measuring Broadband American program. It is not intended for general release and this repository may be disabled at any time.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.samknows.measurement.test.outparcer;
import java.io.Serializable;
public class ParcerDataType implements Serializable{
private static final long serialVersionUID = 1L;
public int idx;
public ParcerFieldType type;
public String header;
public ParcerDataType(int idx, ParcerFieldType type, String header) {
super();
this.idx = idx;
this.type = type;
this.header = header;
}
}
| gpl-2.0 |
Yarichi/Proyecto-DASI | Malmo/Minecraft/build/sources/main/java/com/microsoft/Malmo/Schemas/RewardDensityForBuildAndBreak.java | 1207 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.05.22 at 05:10:17 PM CEST
//
package com.microsoft.Malmo.Schemas;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RewardDensityForBuildAndBreak.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="RewardDensityForBuildAndBreak">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="PER_BLOCK"/>
* <enumeration value="MISSION_END"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "RewardDensityForBuildAndBreak")
@XmlEnum
public enum RewardDensityForBuildAndBreak {
PER_BLOCK,
MISSION_END;
public String value() {
return name();
}
public static RewardDensityForBuildAndBreak fromValue(String v) {
return valueOf(v);
}
}
| gpl-2.0 |
pizaini/Kriptografi | src/kriptografi/SimpleDSA.java | 2902 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package kriptografi;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author Pizaini
*/
public class SimpleDSA {
public static void main(String [] a) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException{
String data = "Ini adalah dokumen dengan digital signature";
//key pairs gen
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(512, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
//System.out.println("Public Key: "+pub);
//sign the data - Proses penandaan
Signature dsa = Signature.getInstance("SHA1withDSA");
dsa.initSign(priv);
//verify algorithm Type from Public Key
PublicKey typePub = pair.getPublic();
System.out.println("Key type: "+typePub.getAlgorithm()+" - "+typePub.getEncoded().length);
dsa.update(data.getBytes());
byte[] realSign = dsa.sign();
System.out.println("Signed: "+realSign.length+" " +DatatypeConverter.printHexBinary(realSign));
//save to file
try{
FileOutputStream fos = new FileOutputStream("signatureDSA");
fos.write(realSign);
fos.close();
}catch(Exception exc){
}
//verify
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pub.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
try {
PublicKey pk2 = keyFactory.generatePublic(pubKeySpec);
System.out.println("Compare 2 public key "+Arrays.toString(pub.getEncoded()));
} catch (InvalidKeySpecException ex) {
Logger.getLogger(SimpleDSA.class.getName()).log(Level.SEVERE, null, ex);
}
dsa.initVerify(pub);
dsa.update(data.getBytes());
System.out.println("Is verivied? "+dsa.verify(realSign));
}
}
| gpl-2.0 |
CivilizationAlpha/CyberSym | Janosch/Repast/cybersym1/src/cybersym1/Request.java | 1546 | package cybersym1;
import java.util.List;
import repast.simphony.essentials.RepastEssentials;
public class Request {
private String ID;
private List<Character> request;
private Agent requester;
private int createdAt;
private boolean isResource;
private Agent lastLink;
private int nrLinks;
Request(List<Character> request, Agent requester) {
this.request = request;
this.requester = requester;
if (request.size() > 1) this.isResource = false;
else this.isResource = true;
this.lastLink = requester;
this.nrLinks = 0;
this.ID = requester.toString() + "R:" + request.toString();
this.createdAt = (int) RepastEssentials.GetTickCount();
}
Request(Request neighborRequest, Agent neighbor) {
this.request = neighborRequest.getRequest();
this.requester = neighborRequest.getRequester();
this.createdAt = neighborRequest.getCreatedAt();
if (neighborRequest.isResource) this.isResource = true;
else this.isResource = false;
this.nrLinks = neighborRequest.nrLinks+1;
this.lastLink = neighbor;
this.ID = neighborRequest.getID();
}
public Agent getLastLink() {
return lastLink;
}
public int getNrLinks() {
return nrLinks;
}
public boolean isResource() {
return isResource;
}
public List<Character> getRequest(){
return request;
}
public Agent getRequester() {
return requester;
}
public int getCreatedAt() {
return createdAt;
}
public String getID() {
return ID;
}
public int getWaitCounter() {
return (int) RepastEssentials.GetTickCount() - createdAt;
}
}
| gpl-2.0 |
campanhacompleta/zap | TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java | 7382 | /*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Components.LayoutHelper;
public class ChangePhoneHelpActivity extends BaseFragment {
@Override
public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.phone != null && user.phone.length() != 0) {
value = PhoneFormat.getInstance().format("+" + user.phone);
} else {
value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
actionBar.setTitle(value);
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
}
}
});
fragmentView = new RelativeLayout(context);
fragmentView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
RelativeLayout relativeLayout = (RelativeLayout) fragmentView;
ScrollView scrollView = new ScrollView(context);
relativeLayout.addView(scrollView);
RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) scrollView.getLayoutParams();
layoutParams3.width = LayoutHelper.MATCH_PARENT;
layoutParams3.height = LayoutHelper.WRAP_CONTENT;
layoutParams3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
scrollView.setLayoutParams(layoutParams3);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(0, AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20));
scrollView.addView(linearLayout);
ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) linearLayout.getLayoutParams();
layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT;
layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT;
linearLayout.setLayoutParams(layoutParams);
ImageView imageView = new ImageView(context);
imageView.setImageResource(R.drawable.phone_change);
linearLayout.addView(imageView);
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) imageView.getLayoutParams();
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.height = LayoutHelper.WRAP_CONTENT;
layoutParams2.gravity = Gravity.CENTER_HORIZONTAL;
imageView.setLayoutParams(layoutParams2);
TextView textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setTextColor(0xff212121);
try {
textView.setText(AndroidUtilities.replaceTags(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp)));
} catch (Exception e) {
FileLog.e("tmessages", e);
textView.setText(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp));
}
linearLayout.addView(textView);
layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams();
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.height = LayoutHelper.WRAP_CONTENT;
layoutParams2.gravity = Gravity.CENTER_HORIZONTAL;
layoutParams2.leftMargin = AndroidUtilities.dp(20);
layoutParams2.rightMargin = AndroidUtilities.dp(20);
layoutParams2.topMargin = AndroidUtilities.dp(56);
textView.setLayoutParams(layoutParams2);
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
//textView.setTextColor(0xff4d83b3);
textView.setTextColor(AndroidUtilities.getIntColor("themeColor"));
textView.setText(LocaleController.getString("PhoneNumberChange", R.string.PhoneNumberChange));
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10));
linearLayout.addView(textView);
layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams();
layoutParams2.width = LayoutHelper.WRAP_CONTENT;
layoutParams2.height = LayoutHelper.WRAP_CONTENT;
layoutParams2.gravity = Gravity.CENTER_HORIZONTAL;
layoutParams2.leftMargin = AndroidUtilities.dp(20);
layoutParams2.rightMargin = AndroidUtilities.dp(20);
layoutParams2.topMargin = AndroidUtilities.dp(46);
textView.setLayoutParams(layoutParams2);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("PhoneNumberAlert", R.string.PhoneNumberAlert));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
presentFragment(new ChangePhoneActivity(), true);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
});
return fragmentView;
}
}
| gpl-2.0 |
h3xstream/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01634.java | 7709 | /**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Dave Wichers
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/crypto-02/BenchmarkTest01634")
public class BenchmarkTest01634 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String queryString = request.getQueryString();
String paramval = "BenchmarkTest01634"+"=";
int paramLoc = -1;
if (queryString != null) paramLoc = queryString.indexOf(paramval);
if (paramLoc == -1) {
response.getWriter().println("getQueryString() couldn't find expected parameter '" + "BenchmarkTest01634" + "' in query string.");
return;
}
String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "BenchmarkTest01634" param is last parameter in query string.
// And then check to see if its in the middle of the query string and if so, trim off what comes after.
int ampersandLoc = queryString.indexOf("&", paramLoc);
if (ampersandLoc != -1) {
param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
}
param = java.net.URLDecoder.decode(param, "UTF-8");
String bar = new Test().doSomething(request, param);
// Code based on example from:
// http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/
// 8-byte initialization vector
// byte[] iv = {
// (byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2,
// (byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3033
// };
java.security.SecureRandom random = new java.security.SecureRandom();
byte[] iv = random.generateSeed(8); // DES requires 8 byte keys
try {
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
// Prepare the cipher to encrypt
javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey();
java.security.spec.AlgorithmParameterSpec paramSpec = new javax.crypto.spec.IvParameterSpec(iv);
c.init(javax.crypto.Cipher.ENCRYPT_MODE, key, paramSpec);
// encrypt and store the results
byte[] input = { (byte)'?' };
Object inputParam = bar;
if (inputParam instanceof String) input = ((String) inputParam).getBytes();
if (inputParam instanceof java.io.InputStream) {
byte[] strInput = new byte[1000];
int i = ((java.io.InputStream) inputParam).read(strInput);
if (i == -1) {
response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
return;
}
input = java.util.Arrays.copyOf(strInput, i);
}
byte[] result = c.doFinal( input );
java.io.File fileTarget = new java.io.File(
new java.io.File(org.owasp.benchmark.helpers.Utils.TESTFILES_DIR),"passwordFile.txt");
java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data
fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
fw.close();
response.getWriter().println(
"Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' encrypted and stored<br/>"
);
} catch (java.security.NoSuchAlgorithmException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
} catch (javax.crypto.IllegalBlockSizeException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
} catch (javax.crypto.BadPaddingException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
} catch (java.security.InvalidKeyException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
} catch (java.security.InvalidAlgorithmParameterException e) {
response.getWriter().println(
"Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"
);
e.printStackTrace(response.getWriter());
throw new ServletException(e);
}
response.getWriter().println(
"Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed"
);
} // end doPost
private class Test {
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a37769 = param; //assign
StringBuilder b37769 = new StringBuilder(a37769); // stick in stringbuilder
b37769.append(" SafeStuff"); // append some safe content
b37769.replace(b37769.length()-"Chars".length(),b37769.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map37769 = new java.util.HashMap<String,Object>();
map37769.put("key37769", b37769.toString()); // put in a collection
String c37769 = (String)map37769.get("key37769"); // get it back out
String d37769 = c37769.substring(0,c37769.length()-1); // extract most of it
String e37769 = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
org.apache.commons.codec.binary.Base64.encodeBase64( d37769.getBytes() ) )); // B64 encode and decode it
String f37769 = e37769.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g37769 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g37769); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
mdlavin/lendingclubtools | tests/org/github/lendingclubtools/tests/AvailabilityLookupTest.java | 3835 | package org.github.lendingclubtools.tests;
import java.util.Date;
import java.util.Set;
import junit.framework.Assert;
import org.github.lendingclubtools.AvailabilityLookup;
import org.github.lendingclubtools.CalendarHelper;
import org.github.lendingclubtools.HasAvailabilityDates;
import org.junit.Test;
public class AvailabilityLookupTest {
@Test
public void testGetLoans_empty() {
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(new TestObj[0]);
Assert.assertEquals("Avaiable loans", 0, avail.getLoans(new Date()).size());
}
@Test
public void testGetLoans_before_start_date() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 2));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2011, 1, 2));
Assert.assertEquals("Avaiable loans", 0, availLoan.size());
}
@Test
public void testGetLoans_on_start_date() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 2));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2012, 1, 1));
Assert.assertEquals("Avaiable loans", 1, availLoan.size());
Assert.assertTrue("Correct loan available", availLoan.contains(test));
}
@Test
public void testGetLoans_on_end_date() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 2));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2012, 1, 2));
Assert.assertEquals("Avaiable loans", 1, availLoan.size());
Assert.assertTrue("Correct loan available", availLoan.contains(test));
}
@Test
public void testGetLoans_after_end_date() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 2));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2011, 1, 3));
Assert.assertEquals("Avaiable loans", 0, availLoan.size());
}
@Test
public void testGetLoans_on_in_middle() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 3));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2012, 1, 2));
Assert.assertEquals("Avaiable loans", 1, availLoan.size());
Assert.assertTrue("Correct loan available", availLoan.contains(test));
}
@Test
public void testGetLoans_overlapping() {
TestObj test = new TestObj(CalendarHelper.newDateForDay(2012, 1, 1),
CalendarHelper.newDateForDay(2012, 1, 3));
TestObj test2 = new TestObj(CalendarHelper.newDateForDay(2012, 1, 2),
CalendarHelper.newDateForDay(2012, 1, 4));
AvailabilityLookup<TestObj> avail = new AvailabilityLookup<TestObj>(test, test2);
Set<TestObj> availLoan = avail.getLoans(CalendarHelper.newDateForDay(2012, 1, 2));
Assert.assertEquals("Avaiable loans", 2, availLoan.size());
Assert.assertTrue("loan 1 available", availLoan.contains(test));
Assert.assertTrue("loan 2 available", availLoan.contains(test2));
}
private class TestObj implements HasAvailabilityDates {
private final Date start;
private final Date end;
private TestObj(Date start, Date end) {
this.start = start;
this.end = end;
}
public Date getAvailabilityEndDate() {
return end;
}
public Date getAvailabilityStartDate() {
return start;
}
}
}
| gpl-2.0 |
icelemon1314/mapleLemon | src/server/quest/MapleQuest.java | 18359 | package server.quest;
import client.MapleCharacter;
import client.MapleQuestStatus;
import constants.GameConstants;
import database.DatabaseConnection;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import scripting.quest.QuestScriptManager;
import tools.FileoutputUtil;
import tools.MaplePacketCreator;
import tools.Pair;
public class MapleQuest implements Serializable {
private static final long serialVersionUID = 9179541993413738569L;
// 所有任务集合
private static final Map<Integer, MapleQuest> quests = new LinkedHashMap();
// 按照NPC来查任务
private static final Map<Integer,List<Integer>> npcQuest = new LinkedHashMap();
protected int id;
// 任务开始条件
protected List<MapleQuestRequirement> startReqs = new LinkedList();
// 任务完成条件
protected Map<String,List<MapleQuestComplete>> completeReqs = new LinkedHashMap();
// 任务状态流
protected Map<String,String> questStatusList = new LinkedHashMap();
// 任务奖励数据
protected Map<String,List<MapleQuestReward>> rewards = new LinkedHashMap();
// protected List<MapleQuestAction> startActs = new LinkedList();
// protected List<MapleQuestAction> completeActs = new LinkedList();
// protected Map<Integer, Integer> relevantMobs = new LinkedHashMap();
// protected Map<Integer, Integer> questItems = new LinkedHashMap();
// 脚本任务
private static final Map<Integer, MapleQuest> questScript = new LinkedHashMap();
protected Map<String, List<Pair<String, Pair<String, Integer>>>> partyQuestInfo = new LinkedHashMap();
private int npcId = 0;
private String startStatus = "";
private String endStatus = "";
private boolean autoStart = false;
private boolean autoPreComplete = false;
private boolean repeatable = false;
private boolean customend = false;
private boolean blocked = false;
private boolean autoAccept = false;
private boolean autoComplete = false;
private boolean scriptedStart = false;
private int viewMedalItem = 0;
private int selectedSkillID = 0;
protected String name = "";
public MapleQuest(int id) {
this.id = id;
}
protected MapleQuest() {}
/**
* 任务数据解析
* @param questData
* @return
* @throws SQLException
*/
private static MapleQuest loadQuest(ResultSet questData) throws SQLException {
MapleQuest ret = new MapleQuest(questData.getInt("questid"));
ret.name = questData.getString("name");
ret.npcId = questData.getInt("npcId");
ret.startStatus = questData.getString("start_status");
ret.endStatus = questData.getString("end_status");
Connection con = DatabaseConnection.getConnection();
// 开始这个任务需要的条件
PreparedStatement psr = con.prepareStatement("SELECT * FROM wz_questreqdata WHERE questid = ?");
psr.setInt(1, ret.id);
ResultSet rse = psr.executeQuery();
while (rse.next()) {
MapleQuestRequirementType type = MapleQuestRequirementType.getByWZName(rse.getString("name"));
MapleQuestRequirement req = new MapleQuestRequirement(ret, type, rse);
// if (type.equals(MapleQuestRequirementType.interval)) {
// ret.repeatable = true;
// } else if (type.equals(MapleQuestRequirementType.normalAutoStart)) {
// ret.repeatable = true;
// ret.autoStart = true;
// } else if (type.equals(MapleQuestRequirementType.startscript)) {
// ret.scriptedStart = true;
// } else if (type.equals(MapleQuestRequirementType.endscript)) {
// ret.customend = true;
// } else if (type.equals(MapleQuestRequirementType.mob)) {
// for (Pair<Integer, Integer> mob : req.getDataStore()) {
// ret.relevantMobs.put(mob.left, mob.right);
// }
// } else if (type.equals(MapleQuestRequirementType.item)) {
// for (Pair<Integer, Integer> it : req.getDataStore()) {
// ret.questItems.put(it.left, it.right);
// }
// }
ret.startReqs.add(req);
}
rse.close();
// 任务完成需要的数据
PreparedStatement psComplete = con.prepareStatement("SELECT * FROM wz_questcompletedata WHERE questid = ?");
psComplete.setInt(1,ret.id);
rse = psComplete.executeQuery();
while (rse.next()) {
MapleQuestCompleteType ty = MapleQuestCompleteType.getByWZName(rse.getString("name"));
MapleQuestComplete reward = new MapleQuestComplete(ty,rse.getInt("itemId"),rse.getInt("num"));
String questStatus = rse.getString("quest_status");
List<MapleQuestComplete> tmpReward = ret.completeReqs.get(questStatus);
if (tmpReward == null) {
tmpReward = new LinkedList();
}
tmpReward.add(reward);
ret.completeReqs.put(questStatus,tmpReward);
}
FileoutputUtil.log(ret.completeReqs.toString());
// 任务奖励数据
PreparedStatement psReward = con.prepareStatement("SELECT * FROM wz_questrewarddata WHERE questId = ?");
psReward.setInt(1,ret.id);
rse = psReward.executeQuery();
while (rse.next()) {
MapleQuestRewardType ty = MapleQuestRewardType.getByWZName(rse.getString("name"));
MapleQuestReward reward = new MapleQuestReward(ty,rse);
String questStatus = rse.getString("quest_status");
List<MapleQuestReward> tmpReward = ret.rewards.get(questStatus);
if (tmpReward == null) {
tmpReward = new LinkedList();
}
tmpReward.add(reward);
ret.rewards.put(questStatus,tmpReward);
}
// 任务流
PreparedStatement psStatus = con.prepareStatement("SELECT * FROM wz_queststatus WHERE questid = ?");
psStatus.setInt(1,ret.id);
rse = psStatus.executeQuery();
while (rse.next()) {
ret.questStatusList.put(rse.getString("cur_status"),rse.getString("next_status"));
}
// 组队任务
PreparedStatement psp = con.prepareStatement("SELECT * FROM wz_questpartydata WHERE questid = ?");
psp.setInt(1, ret.id);
rse = psp.executeQuery();
while (rse.next()) {
if (!ret.partyQuestInfo.containsKey(rse.getString("rank"))) {
ret.partyQuestInfo.put(rse.getString("rank"), new ArrayList());
}
((List) ret.partyQuestInfo.get(rse.getString("rank"))).add(new Pair(rse.getString("mode"), new Pair(rse.getString("property"), rse.getInt("value"))));
}
rse.close();
return ret;
}
public List<Pair<String, Pair<String, Integer>>> getInfoByRank(String rank) {
return (List) this.partyQuestInfo.get(rank);
}
public boolean isPartyQuest() {
return this.partyQuestInfo.size() > 0;
}
public int getSkillID() {
return this.selectedSkillID;
}
public String getName() {
return this.name;
}
public int getNpcId() {return this.npcId;}
public String getStartStatus() {return this.startStatus;}
/**
* 初始化任务数据
* @param reload
*/
public static void initQuests(boolean reload) {
if (reload) {
quests.clear();
}
if (!quests.isEmpty() ) {
return;
}
Connection con = DatabaseConnection.getConnection();
try (
PreparedStatement questData = con.prepareStatement("SELECT * FROM wz_questdata");
ResultSet rs = questData.executeQuery();
) {
while (rs.next()) {
List<Integer> tmp = npcQuest.get(rs.getInt("npcId"));
if (tmp == null) {
tmp = new LinkedList<>();
}
quests.put(rs.getInt("questid"), loadQuest(rs));
tmp.add(rs.getInt("questid"));
npcQuest.put(rs.getInt("npcId"), tmp);
}
questData.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static MapleQuest getInstance(int id) {
MapleQuest ret = quests.get(Integer.valueOf(id));
if (ret == null) {
// 这是一个脚本任务
FileoutputUtil.log("找不到任务:"+id+"有可能是脚本任务!");
MapleQuest vet = new MapleQuest(id);
quests.put(id,vet);
return vet;
}
return ret;
}
public static MapleQuest getInstatce(){
MapleQuest ret = new MapleQuest();
return ret;
}
public static Collection<MapleQuest> getAllInstances() {
Map<Integer, MapleQuest> mapVK = new LinkedHashMap();
Set col = quests.keySet();
Iterator iter = col.iterator();
while (iter.hasNext()) {
Integer key = (Integer) iter.next();
MapleQuest value = quests.get(key);
mapVK.put(key, value);
}
return mapVK.values();
}
public boolean canStartScriptQuest(String name){
Connection con = DatabaseConnection.getConnection();
try (
PreparedStatement questData = con.prepareStatement("SELECT * FROM wz_questdata");
ResultSet rs = questData.executeQuery();) {
// while (rs.next()) {
// quests.put(rs.getInt("questid"), loadQuest(rs, psr, psa, pss, psq, psi, psp));
// }
questData.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断这个NPC下是否有任务可以做
* @param chr
* @param npcid
* @return
*/
public boolean canStart(MapleCharacter chr, Integer npcid) {
// if ((chr.getQuest(this).getStatus() != MapleQuestStatus.QUEST_UNSTART)
// && ((chr.getQuest(this).getStatus() != MapleQuestStatus.QUEST_COMPLETED)
// )) {
// if (chr.isShowPacket()) {
// chr.dropMessage(6, new StringBuilder().append("开始任务 canStart: ").append(chr.getQuest(this).getStatus() != 0).append(" - ").append((chr.getQuest(this).getStatus() != 2) || (!this.repeatable)).append(" repeatable: ").append(this.repeatable).toString());
// }
// return false;
// }
if ((this.blocked) && (!chr.isGM())) {
if (chr.isShowPacket()) {
chr.dropMessage(6, new StringBuilder().append("开始任务 canStart - blocked ").append(this.blocked).toString());
}
return false;
}
Map<Integer,MapleQuestStatus> questComplete = chr.getCompletedQuests();
boolean isCanStart = false;
for (Integer r : getQuestIdByNpcId(npcid)) {
if (questComplete.containsKey(r)) {
break;
}
// 检查其它要求
if (this.startReqs.size() == 0) { // 没有条件要求
isCanStart = true;
break;
} else {
boolean isOk = true;
for(MapleQuestRequirement re : this.startReqs) {
if (re.check(chr,npcid) == false) {
isOk = false;
break;
}
}
isCanStart = isOk;
}
break;
}
// 检查已经开始的任务
MapleQuest tmp = chr.getQuestInfoById(getId());
if (tmp != null) {
return false;
}
return isCanStart;
}
/**
* 根据NPC来获取任务列表
* @param npcId
* @return
*/
public List <Integer> getQuestIdByNpcId(int npcId) {
List <Integer> questList = this.npcQuest.get(npcId);
if (questList == null) {
return new ArrayList<Integer>();
} else {
return questList;
}
}
/**
* 判断任务是否能够完成
* @param chr
* @return
*/
public boolean canComplete(MapleCharacter chr) {
if (chr.getQuest(this).getStatus() != 1) {
return false;
}
if ((this.blocked) && (!chr.isGM())) {
return false;
}
// if ((this.autoComplete) && (npcid != null) && (this.viewMedalItem <= 0)) {
// forceComplete(chr, npcid);
// return false;
// }
String queststatus = chr.getQuest(this).getCustomData();
List <MapleQuestComplete> com = this.completeReqs.get(queststatus);
if (com == null) {
return false;
}
for (MapleQuestComplete r : com) {
if (!r.check(chr)) {
return false;
}
}
return true;
}
public void RestoreLostItem(MapleCharacter chr, int itemid) {
if ((this.blocked) && (!chr.isGM())) {
return;
}
// for (MapleQuestAction a : this.startActs) {
// if (a.RestoreLostItem(chr, itemid)) {
// break;
// }
// }
}
/**
* 开始WZ中的任务
* @param chr
* @param npc
*/
public boolean start(MapleCharacter chr, int npc) {
boolean isComplete = false;
if ((checkNPCOnMap(chr, npc))) {
// 检查是否达到任务完成条件
for (Integer questId : getQuestIdByNpcId(npc)) {
MapleQuest chrQuest = chr.getQuestInfoById(questId);
if (chrQuest == null) {
isComplete = false;
break;
}
if (chrQuest.canComplete(chr)) {
chrQuest.complete(chr,npc);
isComplete = true;
}
}
return isComplete;
} else {
FileoutputUtil.log("NPC不在该地图上:"+npc);
return isComplete;
}
}
public void complete(MapleCharacter chr, int npc) {
complete(chr, npc, null);
}
/**
* 完成玩家的任务
* @param chr
* @param npc
* @param selection
*/
public void complete(MapleCharacter chr, int npc, Integer selection) {
if ((chr.getMap() != null) && ((this.autoPreComplete) || (checkNPCOnMap(chr, npc))) && (canComplete(chr))) {
// 扣除任务道具
List <MapleQuestComplete> com = this.completeReqs.get(chr.getQuest(this).getCustomData());
boolean removeItem = true;
for (MapleQuestComplete r : com) {
if (r.removeQuestItem(chr) == false) {
removeItem = false;
return ;
}
}
if (removeItem == true) {
// 更新玩家任务状态
forceComplete(chr, npc);
// 发送奖励
String curStatus = chr.getQuest(this).getCustomData();
List <MapleQuestReward> rewardData = this.rewards.get(curStatus);
// 通用奖励,金币和经验
if (rewardData == null) {
return ;
}
for (MapleQuestReward reward : rewardData) {
reward.getRewardToChr(chr);
}
}
}
}
public void forfeit(MapleCharacter chr) {
if (chr.getQuest(this).getStatus() != 1) {
return;
}
MapleQuestStatus oldStatus = chr.getQuest(this);
MapleQuestStatus newStatus = new MapleQuestStatus(this, 0);
newStatus.setForfeited(oldStatus.getForfeited() + 1);
newStatus.setCompletionTime(oldStatus.getCompletionTime());
chr.updateQuest(newStatus);
}
public void forceStart(MapleCharacter chr, int npc, String customData) {
MapleQuestStatus newStatus = new MapleQuestStatus(this, (byte) 1, npc);
newStatus.setForfeited(chr.getQuest(this).getForfeited());
newStatus.setCompletionTime(chr.getQuest(this).getCompletionTime());
newStatus.setCustomData(customData);
chr.updateQuest(newStatus);
}
/**
* 完成任务
* @param chr
* @param npc
*/
public void forceComplete(MapleCharacter chr, int npc) {
MapleQuestStatus newStatus = new MapleQuestStatus(this, (byte) MapleQuestStatus.QUEST_COMPLETED, npc);
newStatus.setForfeited(chr.getQuest(this).getForfeited());
String nextData = this.questStatusList.get(chr.getQuest(this).getCustomData());
if (nextData == null) {
nextData = this.endStatus;
}
newStatus.setCustomData(nextData);
chr.updateQuest(newStatus);
chr.dropMessage(0,"恭喜完成任务:"+this.getName());
}
public int getId() {
return this.id;
}
private boolean checkNPCOnMap(MapleCharacter player, int npcId) {
return ((npcId == 1013000)) || (npcId == 2151009) || (npcId == 3000018) || (npcId == 9010000) || ((npcId >= 2161000) && (npcId <= 2161011)) || (npcId == 9000040) || (npcId == 9000066) || (npcId == 2010010) || (npcId == 1032204) || (npcId == 0) || ((player.getMap() != null) && (player.getMap().containsNPC(npcId)));
}
public int getMedalItem() {
return this.viewMedalItem;
}
public boolean isBlocked() {
return this.blocked;
}
public boolean hasStartScript() {
return this.scriptedStart;
}
public boolean hasEndScript() {
return this.customend;
}
}
| gpl-2.0 |
bulhaa/translate-dhivehi | src/main/java/org/jboss/samples/webservices/HelloWorld.java | 359 | package org.jboss.samples.webservices;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.gmail.freestyle_reunion.Translator;
@WebService()
public class HelloWorld {
@WebMethod()
public String sayHello(String eText) {
String dText = Translator.translate(eText.split("\\s"), -1).getTranslatedText();
return "test"+ dText;
}
}
| gpl-2.0 |
Pyeroh/mobarenahelper | MobArena_Helper/src/model/GestYaml.java | 7825 | package model;
import java.io.*;
import java.util.*;
import model.exceptions.ArenaException;
import org.yaml.snakeyaml.*;
import org.yaml.snakeyaml.nodes.Tag;
/**
* Gestionnaire YAML. Gère en réalité l'instanciation du {@link Yaml} et la récupération des données dans une
* LinkedHashMap.
*
* @author Pyeroh
*/
public class GestYaml {
private LinkedHashMap<String, Object> data;
private Yaml yaml;
public static GestYaml S_gestionnaire;
private GestYaml() {
DumperOptions options = new DumperOptions();
options.setIndent(4);
yaml = new Yaml(options);
}
/**
* Instancie un gestionnaire Yaml avec un objet InputStream
*
* @param io
*/
@SuppressWarnings("unchecked")
public GestYaml(InputStream io) {
this();
data = (LinkedHashMap<String, Object>) yaml.load(io);
}
/**
* Instancie un gestionnaire Yaml à partir du fichier Yaml associé
*
* @param file
*/
@SuppressWarnings("unchecked")
public GestYaml(File file) {
this();
try {
data = (LinkedHashMap<String, Object>) yaml.load(new FileInputStream(file));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Instancie un gestionnaire Yaml à partir du chemin du fichier Yaml associé
*
* @param chemin
*/
@SuppressWarnings("unchecked")
public GestYaml(String chemin) {
this();
try {
File file = new File(chemin);
data = (LinkedHashMap<String, Object>) yaml.load(new FileInputStream(file));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Utilisé pour gérer les Map YAML issues d'un fichier
*
* @param map
*/
public GestYaml(Map<String, Object> map) {
this();
data = (LinkedHashMap<String, Object>) map;
}
/**
* Récupère une valeur pour une clé, en descendant dans l'arborescence avec des points (ex : node1.node2)
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
protected Object get(String key) {
String[] arbokey = key.split("[.]");
Map<String, Object> mapvalue = data;
for (int i = 0; i < arbokey.length - 1; i++) {
mapvalue = (Map<String, Object>) mapvalue.get(arbokey[i]);
}
Object value = mapvalue.get(arbokey[arbokey.length - 1]);
return value;
}
public LinkedHashMap<String, Object> getData() {
return data;
}
/**
* Renvoie une chaîne à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
public String getString(String key) {
return (String) get(key);
}
/**
* Renvoie un entier à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
public int getInt(String key) throws ArenaException {
int ret = 0;
Object got = get(key);
Tag tag = getTag(key);
if (tag == Tag.INT) {
ret = (int) got;
}
else if (tag == Tag.STR) {
try {
ret = Integer.parseInt((String) got);
}
catch (NumberFormatException e) {
throw new ArenaException("Not a valid number : " + got);
}
}
else if (tag == Tag.FLOAT) {
ret = Float.valueOf((float) got).intValue();
}
return ret;
}
/**
* Renvoie un décimal à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
public float getFloat(String key) throws ArenaException {
float ret = 0f;
Object got = get(key);
Tag tag = getTag(key);
if (tag == Tag.FLOAT || tag == Tag.INT) {
ret = Double.valueOf(got.toString()).floatValue();
}
else if (tag == Tag.STR) {
try {
ret = Integer.parseInt((String) got);
}
catch (NumberFormatException e) {
throw new ArenaException("Not a valid number : " + got);
}
}
return ret;
}
/**
* Renvoie un booléen à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
public boolean getBool(String key) {
return Boolean.parseBoolean(get(key).toString());
}
/**
* Renvoie un booléen à partir de la clé d'accès, ou la valeur par défaut si la clé n'existe pas
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @param defaultValue
* @return la valeur pour la clé passée en paramètre ou defaultValue
*/
public boolean getBool(String key, boolean defaultValue) {
boolean result = defaultValue;
if (get(key) != null) {
result = getBool(key);
}
return result;
}
/**
* Renvoie une Map à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
@SuppressWarnings("unchecked")
public LinkedHashMap<String, Object> getMap(String key) {
return (LinkedHashMap<String, Object>) get(key);
}
/**
* Renvoie une List à partir de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return la valeur pour la clé passée en paramètre
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getList(String key) {
return (ArrayList<String>) get(key);
}
/**
* Renvoie le tag du noeud correspondant au dernier noeud de la clé d'accès
*
* @param key
* peut être composée de '.', chacun indiquant un niveau dans l'arborescence YAML
* @return le tag du dernier noeud de la clé
*/
public Tag getTag(String key) {
return yaml.represent(get(key)).getTag();
}
/**
* Renvoie le tag de la Map du gestionnaire YAML en cours
*
* @return
*/
public Tag getTag() {
return yaml.represent(data).getTag();
}
/**
* Renvoie le gestionnaire associé à la clé passée en paramètre
*
* @param key
* @return
*/
public GestYaml getGest(String key) {
return new GestYaml(getMap(key));
}
/**
* Effectue un dump de la Map du gestionnaire en cours
*
* @return la chaîne de caractères complète représentant la Map du gestionnaire
*/
public String dump() {
return yaml.dumpAsMap(data);
}
/**
* Effectue un dump du noeud dont la clé est passée en paramètre
*
* @param key
* @return
*/
public String dump(String key) {
if (get(key) instanceof String)
return getString(key);
else
return yaml.dumpAsMap(getMap(key));
}
/**
* Réalise un dump de la Map chargée dans le fichier passé en paramètre
*
* @param file
* le fichier dans lequel on écrit
* @throws IOException
* exception à gérer pour l'écriture dans le fichier
*/
public void dumpAsFile(FileWriter file) throws IOException {
file.write("# MobArena v0.96.9 - Config-file" + "\n");
file.write("# Read the Wiki for details on how to set up this file: http://goo.gl/F5TTc" + "\n");
file.write("# Note: You -must- use spaces instead of tabs!" + "\n");
file.write("# Config file generated by Pyeroh's " + Messages.getString("MenuPrincipal.this.title") + "\n");
file.write(dump());
file.close();
}
/**
* Est-ce que la Map du gestionnaire contient la clé passée en paramètre ?
*
* @param key
* @return
*/
public boolean containsKey(String key) {
if (data != null)
return (data.containsKey(key) || get(key) != null);
else
return false;
}
}
| gpl-2.0 |
BiglySoftware/BiglyBT | uis/src/com/biglybt/ui/swt/views/tableitems/pieces/AvailabilityItem.java | 1928 | /*
* Copyright (C) Azureus Software, Inc, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.biglybt.ui.swt.views.tableitems.pieces;
import com.biglybt.core.peer.PEPiece;
import com.biglybt.pif.ui.tables.*;
import com.biglybt.ui.swt.views.PiecesView;
import com.biglybt.ui.swt.views.table.CoreTableColumnSWT;
/**
*
* @author TuxPaper
* @since 2.0.8.5
*/
public class AvailabilityItem
extends CoreTableColumnSWT
implements TableCellRefreshListener
{
/** Default Constructor */
public AvailabilityItem(String table_id) {
super("availability", ALIGN_TRAIL, POSITION_LAST, 80, table_id);
setRefreshInterval(INTERVAL_LIVE);
}
@Override
public void fillTableColumnInfo(TableColumnInfo info) {
info.addCategories(new String[] {
CAT_SWARM,
});
}
@Override
public void refresh(TableCell cell) {
PEPiece piece = (PEPiece)cell.getDataSource();
boolean is_uploading = piece instanceof PiecesView.PEPieceUploading;
if ( is_uploading ){
cell.setText("");
return;
}
long value = (piece == null) ? 0 : piece.getAvailability();
if( !cell.setSortValue( value ) && cell.isValid() ) {
return;
}
cell.setText(""+value);
}
}
| gpl-2.0 |
yongbam/Web | src/java/data/custom/Business_type.java | 321 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package data.custom;
/**
*
* @author yongbam
*/
public class Business_type {
public String Type;
public String Item;
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/core/env/PropertyResolver.java | 4886 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
/**
* Interface for resolving properties against any underlying source.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see Environment
* @see PropertySourcesPropertyResolver
*/
public interface PropertyResolver {
/**
* Return whether the given property key is available for resolution,
* i.e. if the value for the given key is not {@code null}.
*/
boolean containsProperty(String key);
/**
* Return the property value associated with the given key,
* or {@code null} if the key cannot be resolved.
* @param key the property name to resolve
* @see #getProperty(String, String)
* @see #getProperty(String, Class)
* @see #getRequiredProperty(String)
*/
String getProperty(String key);
/**
* Return the property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String)
* @see #getProperty(String, Class)
*/
String getProperty(String key, String defaultValue);
/**
* Return the property value associated with the given key,
* or {@code null} if the key cannot be resolved.
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @see #getRequiredProperty(String, Class)
*/
<T> T getProperty(String key, Class<T> targetType);
/**
* Return the property value associated with the given key,
* or {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String, Class)
*/
<T> T getProperty(String key, Class<T> targetType, T defaultValue);
/**
* Convert the property value associated with the given key to a {@code Class}
* of type {@code T} or {@code null} if the key cannot be resolved.
* @throws org.springframework.core.convert.ConversionException if class specified
* by property value cannot be found or loaded or if targetType is not assignable
* from class specified by property value
* @see #getProperty(String, Class)
* @deprecated as of 4.3, in favor of {@link #getProperty} with manual conversion
* to {@code Class} via the application's {@code ClassLoader}
*/
@Deprecated
<T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
/**
* Return the property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
* @see #getRequiredProperty(String, Class)
*/
String getRequiredProperty(String key) throws IllegalStateException;
/**
* Return the property value associated with the given key, converted to the given
* targetType (never {@code null}).
* @throws IllegalStateException if the given key cannot be resolved
*/
<T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException;
/**
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value are ignored and passed through unchanged.
* @param text the String to resolve
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* @see #resolveRequiredPlaceholders
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String)
*/
String resolvePlaceholders(String text);
/**
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value will cause an IllegalArgumentException to be thrown.
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* or if any placeholders are unresolvable
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String, boolean)
*/
String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
}
| gpl-2.0 |
axelcode/globalreports-editor | src/com/globalreports/editor/graphics/GRText.java | 21738 | /*
* ==========================================================================
* class name : com.globalreports.editor.graphics.GRText
* Begin :
* Last Update :
*
* Author : Alessandro Baldini - alex.baldini72@gmail.com
* License : GNU-GPL v2 (http://www.gnu.org/licenses/)
* ==========================================================================
*
* GlobalReports Editor
* Copyright (C) 2015 Alessandro Baldini
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Linking GlobalReports Editor(C) statically or dynamically with other
* modules is making a combined work based on GlobalReports Editor(C).
* Thus, the terms and conditions of the GNU General Public License cover
* the whole combination.
*
* In addition, as a special exception, the copyright holders
* of GlobalReports Editor(C) give you permission to combine
* GlobalReports Editor(C) program with free software programs or libraries
* that are released under the GNU LGPL and with code included
* in the standard release of GlobalReports Engine(C) under the CC license
* (or modified versions of such code, with unchanged license) and
* GlobalReports Compiler(C) under the CC license.
* You may copy and distribute such a system following the terms of the GNU GPL
* for GlobalReports Editor(C) and the licenses of the other code concerned,
* provided that you include the source code of that other code
* when and as the GNU GPL requires distribution of source code.
*
* Note that people who make modified versions of GlobalReports Editor(C)
* are not obligated to grant this special exception for their modified versions;
* it is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
*/
package com.globalreports.editor.graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Font;
import java.awt.Shape;
import java.awt.font.TextLayout;
import java.awt.font.FontRenderContext;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.swing.text.Document;
import javax.swing.text.Element;
import com.globalreports.compiler.gr.tools.GRDimension;
import com.globalreports.editor.GRSetting;
import com.globalreports.editor.configuration.font.GRFont;
import com.globalreports.editor.configuration.font.GRFontProperty;
import com.globalreports.editor.configuration.languages.GRLanguageMessage;
import com.globalreports.editor.designer.GRPage;
import com.globalreports.editor.designer.property.GRTableModel;
import com.globalreports.editor.designer.property.GRTableModelRectangle;
import com.globalreports.editor.designer.property.GRTableModelText;
import com.globalreports.editor.designer.property.GRTableProperty;
import com.globalreports.editor.designer.resources.GRResFonts;
import com.globalreports.editor.designer.resources.GRFontResource;
import com.globalreports.editor.designer.swing.table.GRTable;
import com.globalreports.editor.graphics.text.*;
import com.globalreports.editor.tools.GRCharCodeSet;
import com.globalreports.editor.tools.GRLibrary;
public class GRText extends GRObject {
private final String REG_TEXT = "\\[([a-zA-Z0-9\\-]+):([0-9]+)(:([0-9]+),([0-9]+),([0-9]+)){0,}\\]([a-zA-Z0-9 ,!£$%&;:\\\\\"\'\\?\\^\\.\\{\\}\\-\\/\\(\\)]+)";
private final String REG_VARIABLE = "[{]([a-zA-Z0-9_]+)(:{0,1})([a-zA-Z0-9, =!$%&;\\\\\"\'\\?\\^\\.\\-\\/\\(\\)]{0,})[}]";
public static final int ALIGNTEXT_LEFT = 0;
public static final int ALIGNTEXT_CENTER = 1;
public static final int ALIGNTEXT_RIGHT = 2;
public static final int ALIGNTEXT_JUSTIFY = 3;
public static final int ALIGNTEXT_SINGLELINE = 4;
public static final int STYLETEXT_NONE = -1;
public static final int STYLETEXT_NORMAL = 0;
public static final int STYLETEXT_BOLD = 1;
public static final int STYLETEXT_ITALIC = 2;
public static final int STYLETEXT_BOLDITALIC = 3;
private String value;
private String idFont;
private String fontName;
private int fontSize;
private int fontStyle;
private int alignment;
private float lineSpacing;
private float lineSpacingOriginal;
private Font font;
private FontMetrics metrics;
private Graphics gdc; // Graphics Device Context
private GRTextFormatted grtextFormatted;
private GRParagraph gpar;
private GRTableModelText modelTable;
public GRText(GRPage grpage, Graphics g, long id) {
super(GRObject.TYPEOBJ_TEXT,id,grpage);
this.gdc = g;
// Inizializza l'oggetto con valori predefiniti
value = "";
x1 = 0;
y1 = 0;
width = 0;
hPosition = false;
lineSpacing = GRSetting.LINESPACING;
lineSpacingOriginal = lineSpacing;
alignment = GRSetting.FONTALIGNMENT;
grtextFormatted = new GRTextFormatted();
x1Original = x1;
y1Original = y1;
widthOriginal = width;
tsx = new Rectangle(x1-6,y1-4,GRObject.DIM_ANCHOR,GRObject.DIM_ANCHOR);
tdx = new Rectangle(x1+width+2,y1-4,GRObject.DIM_ANCHOR,GRObject.DIM_ANCHOR);
bsx = new Rectangle(x1-6,y1+height,GRObject.DIM_ANCHOR,GRObject.DIM_ANCHOR);
bdx = new Rectangle(x1+width+2,y1+height,GRObject.DIM_ANCHOR,GRObject.DIM_ANCHOR);
typeModel = GRTableProperty.TYPEMODEL_TEXT;
this.refreshReferenceSection();
}
public GRText(GRPage grpage, Graphics g, long id, Document dc, int alignment, String value, Rectangle area) {
super(GRObject.TYPEOBJ_TEXT, id,grpage);
grtextFormatted = new GRTextFormatted(dc,alignment,value);
this.gdc = g;
this.value = value;
x1 = area.x;
y1 = area.y;
width = area.width;
hPosition = false;
lineSpacing = GRSetting.LINESPACING;
lineSpacingOriginal = lineSpacing;
this.alignment = alignment;
x1Original = x1;
y1Original = y1;
widthOriginal = width;
insertTextFormatted();
typeModel = GRTableProperty.TYPEMODEL_TEXT;
this.refreshReferenceSection();
}
public void setProperty(GRTable model) {
this.modelTable = (GRTableModelText)model;
modelTable.setGRObject(this);
this.refreshProperty();
}
public void refreshProperty() {
if(modelTable == null)
return ;
modelTable.setLeft(this.getOriginalX());
modelTable.setTop(this.getOriginalY());
modelTable.setWidth(this.getOriginalWidth());
modelTable.setFont(this.getFontFamily());
modelTable.setFontStyle(this.getFontStyleToString());
modelTable.setFontSize(this.getFontSize());
modelTable.setFontAlignment(this.getFontAlignmentToString());
modelTable.setLineSpacing(this.getLineSpacing());
modelTable.setHPosition(this.getHPosition());
if(this.hasListFather())
modelTable.setListFather(this.getListFather().getNameXml());
else
modelTable.setListFather(null);
/*
modelTable.setHPosition(this.getHPosition());
*
*/
}
public void setValueFromGRS(String value, GRResFonts resFont) {
Color fontColor = Color.black;
int cRED;
int cGREEN;
int cBLUE;
Pattern pattern = Pattern.compile(REG_TEXT);
Matcher matcher = pattern.matcher(value);
while(matcher.find()) {
idFont = matcher.group(1);
fontSize = Integer.parseInt(matcher.group(2));
if(matcher.group(3) != null) {
cRED = Integer.parseInt(matcher.group(4));
cGREEN = Integer.parseInt(matcher.group(5));
cBLUE = Integer.parseInt(matcher.group(6));
fontColor = new Color(cRED, cGREEN, cBLUE);
}
this.value = GRLibrary.lineOctToASCII(matcher.group(7));
if(resFont == null)
resFont = new GRResFonts();
resFont.addResource();
resFont.setFontBaseName(idFont);
fontName = resFont.getResource(idFont).getFontName();
fontStyle = GRLibrary.getFontStyleFromFontPDF(idFont);
grtextFormatted.addElement(fontName, fontSize, fontStyle, fontColor, this.value);
}
}
public void modifyText(Document dc, String value) {
grtextFormatted = new GRTextFormatted(dc,alignment,value);
for(int i = 0;i < grtextFormatted.getTotaleElement();i++) {
GRTextFormattedElement tfe = grtextFormatted.getElement(i);
tfe.setZoom(zoom);
}
insertTextFormatted();
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setFontId(String id) {
idFont = id;
}
public String getFontid() {
return idFont;
}
public void setLineSpacing(float value) {
lineSpacing = value * zoom;
this.setOriginalLineSpacing(lineSpacing);
}
public float getLineSpacing() {
return lineSpacing;
}
public void setOriginalLineSpacing(float value) {
lineSpacingOriginal = value / zoom;
}
public float getOriginalLineSpacing() {
return lineSpacingOriginal;
}
public void setFontFamily(String fName) {
this.fontName = fName;
grtextFormatted.setFontFamily(fName);
refresh();
}
public String getFontFamily() {
return grtextFormatted.getFontName();
}
public void setFontSize(int fSize) {
this.fontSize = fSize;
grtextFormatted.setFontSize(fSize);
refresh();
}
public int getFontSize() {
return grtextFormatted.getFontSize();
}
public void setFontAlignment(int align) {
this.alignment = align;
grtextFormatted.setAlignment(alignment);
}
public void setFontAlignment(String align) {
if(align.equals("Left") || align.equals("left"))
this.alignment = GRText.ALIGNTEXT_LEFT;
else if(align.equals("Center") || align.equals("center"))
this.alignment = GRText.ALIGNTEXT_CENTER;
else if(align.equals("Right") || align.equals("right"))
this.alignment = GRText.ALIGNTEXT_RIGHT;
else if(align.equals("Justify") || align.equals("justify"))
this.alignment = GRText.ALIGNTEXT_JUSTIFY;
grtextFormatted.setAlignment(alignment);
}
public int getFontAlignment() {
return alignment;
}
public String getFontAlignmentToString() {
switch(alignment) {
case GRText.ALIGNTEXT_LEFT:
return "Sinistra";
case GRText.ALIGNTEXT_CENTER:
return "Centrato";
case GRText.ALIGNTEXT_RIGHT:
return "Destra";
case GRText.ALIGNTEXT_JUSTIFY:
return "Giustificato";
}
return null;
}
public void setFontStyle(String style) {
if(style.equals("Normale"))
grtextFormatted.setFontStyle(GRText.STYLETEXT_NORMAL);
else if(style.equals("Corsivo"))
grtextFormatted.setFontStyle(GRText.STYLETEXT_ITALIC);
else if(style.equals("Grassetto"))
grtextFormatted.setFontStyle(GRText.STYLETEXT_BOLD);
else if(style.equals("Grassetto Corsivo"))
grtextFormatted.setFontStyle(GRText.STYLETEXT_BOLDITALIC);
//this.insertText();
}
public int getFontStyle() {
return grtextFormatted.getFontStyle();
}
public String getFontStyleToString() {
switch(grtextFormatted.getFontStyle()) {
case GRText.STYLETEXT_NONE:
return "";
case GRText.STYLETEXT_NORMAL:
return "Normale";
case GRText.STYLETEXT_ITALIC:
return "Corsivo";
case GRText.STYLETEXT_BOLD:
return "Grassetto";
case GRText.STYLETEXT_BOLDITALIC:
return "Grassetto Corsivo";
}
return null;
}
public void setFont(String fName, int fSize, int fStyle, int align) {
this.fontName = fName;
this.fontSize = fSize;
this.fontStyle = fStyle;
this.alignment = align;
font = new Font(fontName,fontStyle,fontSize);
}
public GRText clone(long id) {
int newX = x1Original;
int newY = y1Original+height;
Rectangle r = new Rectangle(newX,newY,widthOriginal,heightOriginal);
GRText grclone = new GRText(grpage,gdc,id,grtextFormatted.getDocument(),grtextFormatted.getAlignment(),grtextFormatted.getText(),r);
return grclone;
}
public void refresh() {
this.insertTextFormatted();
}
public void setZoom(float value) {
super.setZoom(value);
for(int i = 0;i < grtextFormatted.getTotaleElement();i++) {
GRTextFormattedElement tfe = grtextFormatted.getElement(i);
tfe.setZoom(value);
//grtextFormatted.getElement(i).setFontSize((int)(grtextFormatted.getElement(i).getFontSize() * zoom));
}
this.setLineSpacing(lineSpacingOriginal);
this.insertTextFormatted();
}
private void insertTextFormatted() {
int endStream = 0;
String tempStream = "";
int dim = 0;
gpar = new GRParagraph(x1, y1, grtextFormatted.getAlignment(), gdc);
gpar.newRow();
value = grtextFormatted.getText();
for(int i = 0;i < grtextFormatted.getTotaleElement();i++) {
GRTextFormattedElement grtextElement = grtextFormatted.getElement(i);
String fontName = grtextElement.getFontName();
int fontSize = grtextElement.getFontSize();
int fontStyle = grtextElement.getFontStyle();
Color fontColor = grtextElement.getFontColor();
GRFont f = GRFontProperty.getFont(GRLibrary.getFontPDF(fontName, fontStyle));
String value = grtextElement.getValue();
int lenStream = value.length();
int pointerStream = 0;
int startStream = 0;
while(pointerStream < lenStream) {
int c = value.codePointAt(pointerStream);
if(c > 255) {
c = GRCharCodeSet.CodeASCIILatinExtended(c);
}
dim = (int)(dim + Math.round((f.getWidth(c)*1.0588*fontSize)));
if(dim >= (width*1000)) {
if(tempStream.equals(""))
break;
gpar.addTextRow(fontName, fontSize, fontStyle, fontColor, tempStream);
gpar.newRow();
pointerStream = endStream;
startStream = endStream+1;
dim = 0;
tempStream = "";
} else {
if(c == 32) {
tempStream = value.substring(startStream,pointerStream);
endStream = pointerStream;
//tempBlank++;
} else if(c == 10) { // Carriage Return
if(startStream == lenStream)
tempStream = "";
else
tempStream = value.substring(startStream,pointerStream);
gpar.addTextRow(fontName, fontSize, fontStyle, fontColor, tempStream);
gpar.setLastRow();
gpar.newRow();
startStream = pointerStream+1;
dim = 0;
tempStream = "";
}
}
pointerStream++;
}
if(startStream < lenStream) {
tempStream = value.substring(startStream);
gpar.addTextRow(fontName, fontSize, fontStyle, fontColor, tempStream);
startStream = 0;
}
}
gpar.setLastRow();
/*
System.out.println("PARAGRAFO");
System.out.println("Totale row: "+gpar.getTotaleRow());
for(int i = 0;i < gpar.getTotaleRow();i++) {
System.out.println("ROW: "+i);
GRRowParagraph grrow = gpar.getLineParagraph(i);
for(int z = 0;z < grrow.getTotaleTextRow();z++) {
System.out.println("TEXT: "+grrow.getTokenTextRow(z).getValue());
}
System.out.println("\n");
}
*/
}
private void drawParagraph(GRRowParagraph grrow, FontRenderContext frc, Graphics2D g2, float y) {
Color oldColor = g2.getColor();
int widthToken = 0;
int widthRow = grrow.getWidthRow();
int widthParziale = 0;
int x = 0;
for(int i = 0;i < grrow.getTotaleTextRow();i++) {
GRTextRowParagraph grtext = grrow.getTokenTextRow(i);
String str = grtext.getValue();
Font f = grtext.getFont();
if(str.length() > 0) {
TextLayout tl = new TextLayout(str,f,frc);
switch(gpar.getAlignment()) {
case GRText.ALIGNTEXT_LEFT:
if(i == 0)
x = x1;
else
x = x + widthToken;
widthToken = grtext.getWidth();
break;
case GRText.ALIGNTEXT_CENTER:
if(i == 0)
x = x1 + ((width - grrow.getWidthRow()) / 2);
else
x = x + widthToken;
widthToken = grtext.getWidth();
break;
case GRText.ALIGNTEXT_RIGHT:
if(i == 0)
x = x1 + width - grrow.getWidthRow();
else
x = x + widthToken;
widthToken = grtext.getWidth();
break;
case GRText.ALIGNTEXT_JUSTIFY:
if(i == 0)
x = x1;
else {
x = x + widthToken;
}
if(!grrow.isLastRow()) {
if(grrow.getTotaleTextRow() == 1)
tl = tl.getJustifiedLayout(width);
else {
if((i+1) == grrow.getTotaleTextRow())
widthToken = width - widthParziale;
else
widthToken = (width * grtext.getWidth()) / widthRow;
tl = tl.getJustifiedLayout(widthToken);
}
} else {
widthToken = grtext.getWidth();
}
widthParziale = widthParziale + widthToken;
break;
}
g2.setColor(grtext.getFontColor());
tl.draw(g2,(float)x,y);
}
}
g2.setColor(oldColor);
}
public void draw(Graphics g) {
if(gpar == null) {
gdc = g;
this.insertTextFormatted();
}
Graphics2D g2 = (Graphics2D)g;
FontRenderContext frc = g2.getFontRenderContext();
Shape oldClip = g2.getClip();
int y1 = this.y1;
float y = 0;
gapH = -2;
if(hPosition) {
gapH = gapH + grpage.hPosition;
}
if(grgroup != null) {
y1 = y1 + grgroup.getY();
if(grgroup.getHPosition()) {
y1 = y1 + grgroup.gapH;
}
}
if(grlistFather != null) {
y1 = y1 + grlistFather.getTopPosition();
g2.setClip(0,grlistFather.getTopPosition(),grpage.getWidth(),grlistFather.getHeight()+1);
} else {
/*
Rectangle r = oldClip.getBounds();
if(width > r.getWidth() - x1)
g2.setClip(x1,y1,(int)(r.getWidth()-x1),height);
else
g2.setClip(x1,y1,width,height);
*/
}
for(int i = 0;i < gpar.getTotaleRow();i++) {
GRRowParagraph grrow = gpar.getLineParagraph(i);
float leading = ((float)grrow.getMaxHeight() + GRLibrary.getLeadingFromMillimeters(lineSpacing)) * 1.0588f;
if(i == 0) {
y = gapH + y1 + (float)grrow.getMaxHeight();
} else
y = y + leading;
this.drawParagraph(grrow,frc,g2,y);
}
height = (int)(y - (y1+gapH));
/* Allinea la dimensione verticale a quella del testo se questa eccede
if(grgroup != null)
if(grgroup.getHeight() < (this.getY() + this.getHeight()))
grgroup.setHeight(this.getY() + this.getHeight());
*/
grpage.hPosition = (int)y;
g2.setClip(oldClip);
if(selected) {
g.drawRect(x1-2,y1+gapH,width+4,height+4);
g.fillRect(x1-6,y1-4+gapH,4,4);
g.fillRect(x1-6,y1+height+gapH+4,4,4);
g.fillRect(x1+width+2,y1-4+gapH,4,4);
g.fillRect(x1+width+2,y1+height+gapH+4,4,4);
}
refreshReferenceSection();
}
public void setWidth(int width) {
super.setWidth(width);
//this.insertText();
}
public String toString() {
return value;
}
public GRTextFormatted getTextFormatted() {
return grtextFormatted;
}
public Vector<String> getVariables() {
Vector<String> listVariables = new Vector<String>();
Pattern pattern = Pattern.compile(REG_VARIABLE);
Matcher matcher = pattern.matcher(value);
while(matcher.find()) {
listVariables.add(matcher.group(1));
}
return listVariables;
}
public String createCodeGRS() {
StringBuffer buff = new StringBuffer();
String fontToken = "";
String fontTokenTemp = "";
String fontId = "";
int fontSize = 0;
Color fontColor = Color.black;
int y1 = this.y1Original;
if(section == GRObject.SECTION_BODY) {
y1 = y1 - grpage.getHeaderSize();
}
if(section == GRObject.SECTION_FOOTER) {
y1 = y1 - (grpage.getHeight() - grpage.getFooterSize());
}
buff.append("<text>\n");
buff.append("<alignment>");
switch(gpar.getAlignment()) {
case ALIGNTEXT_LEFT:
buff.append("left");
break;
case ALIGNTEXT_CENTER:
buff.append("center");
break;
case ALIGNTEXT_RIGHT:
buff.append("right");
break;
case ALIGNTEXT_JUSTIFY:
buff.append("justify");
break;
}
buff.append("</alignment>\n");
buff.append("<left>"+GRLibrary.fromPixelsToMillimeters(x1Original)+"</left>\n");
buff.append("<top>"+GRLibrary.fromPixelsToMillimeters(y1)+"</top>\n");
buff.append("<width>"+GRLibrary.fromPixelsToMillimeters(widthOriginal)+"</width>\n");
buff.append("<linespacing>"+lineSpacingOriginal+"</linespacing>\n");
buff.append("<hposition>");
if(hPosition)
buff.append("relative");
else
buff.append("absolute");
buff.append("</hposition>\n");
buff.append("<value>");
// Il testo completo è composto da tutti gli elementi di GRTextFormattedElement
for(int i = 0;i < grtextFormatted.getTotaleElement();i++) {
GRTextFormattedElement tfe = grtextFormatted.getElement(i);
fontId = tfe.getFontId();
fontSize = tfe.getOriginalFontSize();
fontColor = tfe.getFontColor();
fontTokenTemp = "["+fontId+":"+fontSize+":"+fontColor.getRed()+","+fontColor.getGreen()+","+fontColor.getBlue()+"]";
if(!fontTokenTemp.equals(fontToken)) {
fontToken = fontTokenTemp;
buff.append(fontToken);
}
buff.append(GRLibrary.lineASCIIToOct(tfe.getValue()));
}
buff.append("</value>\n");
buff.append("</text>");
return buff.toString();
}
@Override
public String getNameObject() {
return GRLanguageMessage.messages.getString("tlbgrtext");
}
@Override
public int getTypeModel() {
// TODO Auto-generated method stub
return typeModel;
}
} | gpl-2.0 |
UKPLab/wikulu | de.tudarmstadt.ukp.wikulu.wikiapi/src/main/java/de/tudarmstadt/ukp/dkpro/semantics/wiki/type/PageMetadata_Type.java | 5642 | /*******************************************************************************
* Copyright 2010-2016 Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*******************************************************************************/
/* First created by JCasGen Thu Jul 16 16:18:47 CEST 2009 */
package de.tudarmstadt.ukp.dkpro.semantics.wiki.type;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.Feature;
import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData_Type;
/**
* It represents a page metadata. Updated by JCasGen Wed Feb 17 14:48:09 CET
* 2010
*
* @generated
*/
public class PageMetadata_Type
extends DocumentMetaData_Type
{
/** @generated */
protected FSGenerator getFSGenerator()
{
return fsGenerator;
}
/** @generated */
private final FSGenerator fsGenerator = new FSGenerator()
{
public FeatureStructure createFS(int addr, CASImpl cas)
{
if (PageMetadata_Type.this.useExistingInstance) {
// Return eq fs instance if already created
FeatureStructure fs = PageMetadata_Type.this.jcas
.getJfsFromCaddr(addr);
if (null == fs) {
fs = new PageMetadata(addr, PageMetadata_Type.this);
PageMetadata_Type.this.jcas.putJfsFromCaddr(addr, fs);
return fs;
}
return fs;
}
else
return new PageMetadata(addr, PageMetadata_Type.this);
}
};
/** @generated */
public final static int typeIndexID = PageMetadata.typeIndexID;
/**
* @generated
* @modifiable
*/
public final static boolean featOkTst = JCasRegistry
.getFeatOkTst("de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
/** @generated */
final Feature casFeat_wikiSyntax;
/** @generated */
final int casFeatCode_wikiSyntax;
/** @generated */
public String getWikiSyntax(int addr)
{
if (featOkTst && casFeat_wikiSyntax == null)
jcas.throwFeatMissing("wikiSyntax",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
return ll_cas.ll_getStringValue(addr, casFeatCode_wikiSyntax);
}
/** @generated */
public void setWikiSyntax(int addr, String v)
{
if (featOkTst && casFeat_wikiSyntax == null)
jcas.throwFeatMissing("wikiSyntax",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
ll_cas.ll_setStringValue(addr, casFeatCode_wikiSyntax, v);
}
/** @generated */
final Feature casFeat_wikiApiUrl;
/** @generated */
final int casFeatCode_wikiApiUrl;
/** @generated */
public String getWikiApiUrl(int addr)
{
if (featOkTst && casFeat_wikiApiUrl == null)
jcas.throwFeatMissing("wikiApiUrl",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
return ll_cas.ll_getStringValue(addr, casFeatCode_wikiApiUrl);
}
/** @generated */
public void setWikiApiUrl(int addr, String v)
{
if (featOkTst && casFeat_wikiApiUrl == null)
jcas.throwFeatMissing("wikiApiUrl",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
ll_cas.ll_setStringValue(addr, casFeatCode_wikiApiUrl, v);
}
/** @generated */
final Feature casFeat_wikiViewUrl;
/** @generated */
final int casFeatCode_wikiViewUrl;
/** @generated */
public String getWikiViewUrl(int addr)
{
if (featOkTst && casFeat_wikiViewUrl == null)
jcas.throwFeatMissing("wikiViewUrl",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
return ll_cas.ll_getStringValue(addr, casFeatCode_wikiViewUrl);
}
/** @generated */
public void setWikiViewUrl(int addr, String v)
{
if (featOkTst && casFeat_wikiViewUrl == null)
jcas.throwFeatMissing("wikiViewUrl",
"de.tudarmstadt.ukp.dkpro.semantics.wiki.type.PageMetadata");
ll_cas.ll_setStringValue(addr, casFeatCode_wikiViewUrl, v);
}
/**
* initialize variables to correspond with Cas Type and Features
*
* @generated
*/
public PageMetadata_Type(JCas jcas, Type casType)
{
super(jcas, casType);
casImpl.getFSClassRegistry().addGeneratorForType(
(TypeImpl) this.casType, getFSGenerator());
casFeat_wikiSyntax = jcas.getRequiredFeatureDE(casType, "wikiSyntax",
"uima.cas.String", featOkTst);
casFeatCode_wikiSyntax = (null == casFeat_wikiSyntax) ? JCas.INVALID_FEATURE_CODE
: ((FeatureImpl) casFeat_wikiSyntax).getCode();
casFeat_wikiApiUrl = jcas.getRequiredFeatureDE(casType, "wikiApiUrl",
"uima.cas.String", featOkTst);
casFeatCode_wikiApiUrl = (null == casFeat_wikiApiUrl) ? JCas.INVALID_FEATURE_CODE
: ((FeatureImpl) casFeat_wikiApiUrl).getCode();
casFeat_wikiViewUrl = jcas.getRequiredFeatureDE(casType, "wikiViewUrl",
"uima.cas.String", featOkTst);
casFeatCode_wikiViewUrl = (null == casFeat_wikiViewUrl) ? JCas.INVALID_FEATURE_CODE
: ((FeatureImpl) casFeat_wikiViewUrl).getCode();
}
}
| gpl-3.0 |