answer
stringlengths
17
10.2M
package org.jcoderz.phoenix.report; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.JAXBException; import org.jcoderz.commons.util.Assert; import org.jcoderz.commons.util.Constants; import org.jcoderz.commons.util.IoUtil; import org.jcoderz.commons.util.JaxbUtil; import org.jcoderz.commons.util.ObjectUtil; import org.jcoderz.commons.util.StringUtil; import org.jcoderz.commons.util.JaxbUtil.UnmarshalResult; import org.jcoderz.phoenix.report.ftf.jaxb.FindingDescription; import org.jcoderz.phoenix.report.ftf.jaxb.FindingTypeFormat; import org.jcoderz.phoenix.report.jaxb.Item; import org.xml.sax.InputSource; /** * Reads reports with format definitions described in the * finding-type-format-definition.xds. * * To find the finding type format definition for requested format * the following locations are used: * * The name is converted to lower case. * * A file <i>name</i>.xml is searched in the * <code>org.jcoderz.phoenix.report.ftf</code> package. If * this is not found the file is searched in the <code>ftf</code> * directory. The directory must be available through the classpath. * * * @author Andreas Mandel * */ public final class GenericReportReader implements ReportReader { private static final int MAX_DEBUG_TEXT_CHARS = 100; private static final String CLASSNAME = GenericReportReader.class.getName(); private static final Logger logger = Logger.getLogger(CLASSNAME); private static final Pattern CODE_LINE_PATTERN = Pattern.compile("^.*$", Pattern.MULTILINE); private static final Pattern CARET_LINE_PATTERN = Pattern.compile("^\\s*\\^$", Pattern.MULTILINE); private static final Map<Origin, GenericReportReader> GENERIC_REPORT_TYPES = new HashMap<Origin, GenericReportReader>(); private final List<GenericFindingType> mFindingTypes = new ArrayList<GenericFindingType>(); private Map<ResourceInfo, List<Item>> mItems; private SourceFile mSourceFile; private final Pattern mMessagePattern; private final FindingTypeFormat mFindingTypeFormatDescription; private final int mTextPos; private final Origin mOrigin; private final int mFilePos; private final int mLineStart; private final Severity mDefaultSeverity; private Matcher mRootMatcher = null; private GenericReportReader (Origin type) throws JAXBException { mOrigin = type; mFindingTypeFormatDescription = loadFormatDescription(type); initializeFindingTypes(); final FindingDescription root = mFindingTypeFormatDescription.getRootType(); mMessagePattern = Pattern.compile(root.getPattern(), Pattern.MULTILINE); mTextPos = Integer.parseInt(root.getTextPos()); mFilePos = Integer.parseInt(root.getFilenamePos()); mLineStart = root.isSetLineStartPos() ? Integer.parseInt(root.getLineStartPos()) : -1; mDefaultSeverity = root.isSetSeverity() ? root.getSeverity() : Severity.CODE_STYLE; } /** * Initializes the selected finding type. * Might return <code>null</code> if the initialization fails. * CHECKME: Should return a null object? * @param findingType the type to load. * @return the loaded finding type. */ public static GenericReportReader initialize (Origin findingType) { GenericReportReader result = null; synchronized (GENERIC_REPORT_TYPES) { if (!GENERIC_REPORT_TYPES.containsKey(findingType)) { try { result = new GenericReportReader(findingType); } catch (Exception ex) { // TODO: collect this an add it to the findings map later! logger.log(Level.WARNING, "Could not load finding type for '" + findingType + "' failed with " + ex.getMessage() + ".", ex); } GENERIC_REPORT_TYPES.put(findingType, result); } result = GENERIC_REPORT_TYPES.get(findingType); } return result; } private static FindingTypeFormat loadFormatDescription (Origin type) throws JAXBException { FindingTypeFormat findingTypeFormatDescription = null; InputStream in = null; try { final String filename = type.toString().toLowerCase(Constants.SYSTEM_LOCALE) + ".xml"; in = GenericReportReader.class.getResourceAsStream( "ftf/" + filename); if (in == null) { in = GenericReportReader.class.getResourceAsStream( "/ftf/" + filename); } Assert.notNull(in, "report type description " + type); final UnmarshalResult unmarshal = JaxbUtil.unmarshal(new InputSource(in), "org.jcoderz.phoenix.report.ftf.jaxb"); findingTypeFormatDescription = (FindingTypeFormat) unmarshal.getParsedData(); } finally { IoUtil.close(in); } return findingTypeFormatDescription; } /** {@inheritDoc} */ public void parse (File f) throws JAXBException { try { mSourceFile = new SourceFile(f); mRootMatcher = mMessagePattern.matcher(mSourceFile.getContent()); } catch (IOException ex) { throw new JAXBException("Failed to read '" + f + "'.", ex); } } /** {@inheritDoc} */ public void merge (Map<ResourceInfo, List<Item>> items) throws JAXBException { mItems = items; while (!mSourceFile.readFully()) { parseNext(); } } /** * Reads the given message and tries to find a matching finding type. * @param message the message to read. * @return the finding type matching to the message, or null if no such * type was found. * @throws JAXBException if item creation fails. */ public Item detectFindingTypeForMessage (String message) throws JAXBException { Item result = null; for (final GenericFindingType type : mFindingTypes) { result = type.createItem(mSourceFile, message); if (result != null) { if (type.isSourceColumnByCaret()) { addPositionByCaret(result); } break; } } if (logger.isLoggable(Level.FINE)) { logger.fine("For text: '" + StringUtil.trimLength(message, MAX_DEBUG_TEXT_CHARS) + "' matched finding: " + (result == null ? "null" : result.getFindingType() + "'. End at " + mSourceFile.getPos())); } return result; } private void addPositionByCaret (final Item i) { final String text = mSourceFile.getContent().substring(mSourceFile.getPos()); final Matcher codeMat = CODE_LINE_PATTERN.matcher(text); if (codeMat.lookingAt()) { final String textAfterCode = mSourceFile.getContent().substring( mSourceFile.getPos() + codeMat.end() + 1); final Matcher caretMat = CARET_LINE_PATTERN.matcher(textAfterCode); if (caretMat.lookingAt()) { i.setColumn(caretMat.end()); mSourceFile.setPos( mSourceFile.getPos() + codeMat.end() + 1 + caretMat.end() + 1); } else { logger.fine("Caret defined but not found for '" + i.getFindingType() + "' Code Line: '" + codeMat + "' caretLine: '" + caretMat + "'. text: '" + StringUtil.trimLength( textAfterCode, MAX_DEBUG_TEXT_CHARS) + "'."); } } else { logger.fine("Caret defined but not found for '" + i.getFindingType() + "' Code Line: '" + codeMat + "'. text: '" + StringUtil.trimLength( text, MAX_DEBUG_TEXT_CHARS) + "'."); } } private void parseNext () throws JAXBException { if (mRootMatcher.find()) { final String text = mRootMatcher.group(mTextPos); mSourceFile.setPos(mRootMatcher.start(mTextPos)); final Item item = detectFindingTypeForMessage(text); if (item == null) { final int pos = mSourceFile.getContent().indexOf( '\n', mSourceFile.getPos()); if (pos != -1) { mSourceFile.setPos(pos + 1); } else { mSourceFile.setPos(mSourceFile.getContent().length()); } } else { item.setOrigin(mOrigin); if (!item.isSetSeverity()) { item.setSeverity(mDefaultSeverity); } if (!item.isSetLine() && mLineStart != -1 && mRootMatcher.group(mLineStart) != null) { item.setLine( Integer.parseInt(mRootMatcher.group(mLineStart))); } if (!item.isSetFindingType()) { item.setFindingType(mOrigin.toString()); } if (!item.isSetMessage()) { item.setMessage(mRootMatcher.group(mTextPos)); } if (mFindingTypeFormatDescription.getRootType().isGlobal()) { item.setGlobal(true); } addItemToResource(mRootMatcher.group(mFilePos), item); } } else { // set pos to end of file mSourceFile.setPos(mSourceFile.getContent().length()); } } private void addItemToResource (String resourceFilename, Item item) { final ResourceInfo info = ResourceInfo.lookup(resourceFilename); if (info != null || item.isGlobal()) { final List<Item> l; if (mItems.containsKey(info)) { l = mItems.get(info); } else { l = new ArrayList<Item>(); mItems.put(info, l); } // sometimes javadoc reports the same thing twice... final Iterator<Item> i = l.iterator(); while (i.hasNext()) { final Item it = i.next(); if (it.getLine() == item.getLine() && it.getColumn() == item.getColumn() && it.getOrigin() == item.getOrigin() && ObjectUtil.equals(it.getMessage(), item.getMessage())) { i.remove(); break; } } l.add(item); } else { logger.finer("Ignore findings for resource '" + resourceFilename + "' type was " + item.getFindingType() + "."); } } private void initializeFindingTypes () { final FindingDescription root = mFindingTypeFormatDescription.getRootType(); final List<FindingDescription> findingTypes = mFindingTypeFormatDescription.getFindingType(); for (FindingDescription findingDesc : findingTypes) { final GenericFindingType gft = new GenericFindingType(root, findingDesc); mFindingTypes.add(gft); } Collections.sort( mFindingTypes, new GenericFindingType.OrderByPriority()); } static final class SourceFile { private final File mFile; private final String mContent; private int mPos; public SourceFile (File file) throws IOException { mFile = file; Reader in = null; Reader buffered = null; try { in = new FileReader(file); buffered = new BufferedReader(in); mContent = IoUtil.readFullyNormalizeNewLine(buffered); } finally { IoUtil.close(buffered); IoUtil.close(in); } mPos = 0; } /** * @return the pos */ public int getPos () { logger.finest("getPos: " + mPos); return mPos; } /** * @param pos the pos to set */ public void setPos (int pos) { mPos = pos; } /** * @return the file */ public File getFile () { return mFile; } /** * @return the content */ public String getContent () { return mContent; } public boolean readFully () { return mPos >= mContent.length(); } } }
package org.xwiki.repository.internal.resources; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.apache.solr.common.SolrDocument; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.extension.Extension; import org.xwiki.extension.internal.maven.MavenUtils; import org.xwiki.extension.repository.xwiki.model.jaxb.AbstractExtension; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionAuthor; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionDependency; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionRating; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScm; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionScmConnection; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionSummary; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersion; import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionVersionSummary; import org.xwiki.extension.repository.xwiki.model.jaxb.License; import org.xwiki.extension.repository.xwiki.model.jaxb.ObjectFactory; import org.xwiki.extension.repository.xwiki.model.jaxb.Property; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.query.Query; import org.xwiki.query.QueryException; import org.xwiki.ratings.AverageRatingApi; import org.xwiki.ratings.RatingsManager; import org.xwiki.repository.internal.RepositoryManager; import org.xwiki.repository.internal.XWikiRepositoryModel; import org.xwiki.repository.internal.XWikiRepositoryModel.SolrField; import org.xwiki.rest.XWikiResource; import org.xwiki.security.authorization.ContextualAuthorizationManager; import org.xwiki.security.authorization.Right; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.classes.ListClass; /** * Base class for the annotation REST services, to implement common functionality to all annotation REST services. * * @version $Id$ * @since 3.2M3 */ public abstract class AbstractExtensionRESTResource extends XWikiResource implements Initializable { public static final String[] EPROPERTIES_SUMMARY = new String[] { XWikiRepositoryModel.PROP_EXTENSION_ID, XWikiRepositoryModel.PROP_EXTENSION_TYPE, XWikiRepositoryModel.PROP_EXTENSION_NAME }; public static final String[] EPROPERTIES_EXTRA = new String[] { XWikiRepositoryModel.PROP_EXTENSION_SUMMARY, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS, XWikiRepositoryModel.PROP_EXTENSION_FEATURES, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME, XWikiRepositoryModel.PROP_EXTENSION_SCMURL, XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION }; protected static final String DEFAULT_BOOST; protected static final String DEFAULT_FL; protected static Map<String, Integer> EPROPERTIES_INDEX = new HashMap<String, Integer>(); protected static String SELECT_EXTENSIONSUMMARY; protected static String SELECT_EXTENSION; static { StringBuilder pattern = new StringBuilder(); int j = 0; pattern.append("doc.name"); EPROPERTIES_INDEX.put("doc.name", j++); pattern.append(", "); pattern.append("doc.space"); EPROPERTIES_INDEX.put("doc.space", j++); // Extension summary for (int i = 0; i < EPROPERTIES_SUMMARY.length; ++i, ++j) { String value = EPROPERTIES_SUMMARY[i]; pattern.append(", extension."); pattern.append(value); EPROPERTIES_INDEX.put(value, j); } SELECT_EXTENSIONSUMMARY = pattern.toString(); // Extension extra for (int i = 0; i < EPROPERTIES_EXTRA.length; ++i, ++j) { pattern.append(", extension."); pattern.append(EPROPERTIES_EXTRA[i]); EPROPERTIES_INDEX.put(EPROPERTIES_EXTRA[i], j); } SELECT_EXTENSION = pattern.toString(); // Solr StringBuilder boostBuilder = new StringBuilder(); StringBuilder flBuilder = new StringBuilder("wiki,spaces,name"); for (SolrField field : XWikiRepositoryModel.SOLR_FIELDS.values()) { // Boost if (field.boostValue != null) { if (boostBuilder.length() > 0) { boostBuilder.append(' '); } boostBuilder.append(field.boostName); boostBuilder.append('^'); boostBuilder.append(field.boostValue); } // Fields list if (field.name != null) { if (flBuilder.length() > 0) { flBuilder.append(','); } flBuilder.append(field.name); } } DEFAULT_BOOST = boostBuilder.toString(); DEFAULT_FL = flBuilder.toString(); } @Inject protected RepositoryManager repositoryManager; @Inject protected ContextualAuthorizationManager authorization; @Inject @Named("separate") protected RatingsManager ratingsManager; /** * Used to extract a document reference from a {@link SolrDocument}. */ @Inject private DocumentReferenceResolver<SolrDocument> solrDocumentReferenceResolver; /** * The object factory for model objects to be used when creating representations. */ protected ObjectFactory extensionObjectFactory; @Override public void initialize() throws InitializationException { super.initialize(); this.extensionObjectFactory = new ObjectFactory(); } public XWikiDocument getExistingExtensionDocumentById(String extensionId) throws QueryException, XWikiException { XWikiDocument document = this.repositoryManager.getExistingExtensionDocumentById(extensionId); if (document == null) { throw new WebApplicationException(Status.NOT_FOUND); } return document; } protected Query createExtensionsCountQuery(String from, String where) throws QueryException { // select String select = "count(extension." + XWikiRepositoryModel.PROP_EXTENSION_ID + ")"; return createExtensionsQuery(select, from, where, 0, -1, false); } protected long getExtensionsCountResult(Query query) throws QueryException { return ((Number) query.execute().get(0)).intValue(); } protected Query createExtensionsQuery(String from, String where, int offset, int number) throws QueryException { // select String select = SELECT_EXTENSION; // TODO: add support for real lists: need a HQL or JPQL equivalent to MySQL GROUP_CONCAT // * dependencies // Link to last version object if (where != null) { where = "(" + where + ") and "; } else { where = ""; } where += "extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + " = extension." + XWikiRepositoryModel.PROP_EXTENSION_LASTVERSION; return createExtensionsQuery(select, from, where, offset, number, true); } protected Query createExtensionsSummariesQuery(String from, String where, int offset, int number, boolean versions) throws QueryException { String select = SELECT_EXTENSIONSUMMARY; return createExtensionsQuery(select, from, where, offset, number, versions); } private Query createExtensionsQuery(String select, String from, String where, int offset, int number, boolean versions) throws QueryException { // select StringBuilder queryStr = new StringBuilder("select "); queryStr.append(select); if (versions) { queryStr.append(", extensionVersion." + XWikiRepositoryModel.PROP_VERSION_VERSION + ""); } // from queryStr .append(" from Document doc, doc.object(" + XWikiRepositoryModel.EXTENSION_CLASSNAME + ") as extension"); if (versions) { queryStr .append(", doc.object(" + XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME + ") as extensionVersion"); } if (from != null) { queryStr.append(','); queryStr.append(from); } // where queryStr.append(" where "); if (where != null) { queryStr.append('('); queryStr.append(where); queryStr.append(')'); queryStr.append(" and "); } queryStr.append("extension." + XWikiRepositoryModel.PROP_EXTENSION_VALIDEXTENSION + " = 1"); Query query = this.queryManager.createQuery(queryStr.toString(), Query.XWQL); if (offset > 0) { query.setOffset(offset); } if (number > 0) { query.setLimit(number); } return query; } protected BaseObject getExtensionObject(XWikiDocument extensionDocument) { return extensionDocument.getXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE); } protected BaseObject getExtensionObject(String extensionId) throws XWikiException, QueryException { return getExtensionObject(getExistingExtensionDocumentById(extensionId)); } protected BaseObject getExtensionVersionObject(XWikiDocument extensionDocument, String version) { if (version == null) { List<BaseObject> objects = extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONVERSION_CLASSREFERENCE); if (objects == null || objects.isEmpty()) { return null; } else { return objects.get(objects.size() - 1); } } return extensionDocument.getObject(XWikiRepositoryModel.EXTENSIONVERSION_CLASSNAME, "version", version, false); } protected BaseObject getExtensionVersionObject(String extensionId, String version) throws XWikiException, QueryException { return getExtensionVersionObject(getExistingExtensionDocumentById(extensionId), version); } protected <E extends AbstractExtension> E createExtension(XWikiDocument extensionDocument, String version) { BaseObject extensionObject = getExtensionObject(extensionDocument); DocumentReference extensionDocumentReference = extensionDocument.getDocumentReference(); if (extensionObject == null) { throw new WebApplicationException(Status.NOT_FOUND); } AbstractExtension extension; ExtensionVersion extensionVersion; if (version == null) { extension = this.extensionObjectFactory.createExtension(); extensionVersion = null; } else { BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, version); if (extensionVersionObject == null) { throw new WebApplicationException(Status.NOT_FOUND); } extensionVersion = this.extensionObjectFactory.createExtensionVersion(); extension = extensionVersion; extensionVersion.setVersion((String) getValue(extensionVersionObject, XWikiRepositoryModel.PROP_VERSION_VERSION)); } extension.setId((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_ID)); extension.setType((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE)); License license = this.extensionObjectFactory.createLicense(); license.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME)); extension.getLicenses().add(license); extension.setRating(getExtensionRating(extensionDocumentReference)); extension.setSummary((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY)); extension.setDescription((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_DESCRIPTION)); extension.setName((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_NAME)); extension.setCategory((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_CATEGORY)); extension.setWebsite(StringUtils.defaultIfEmpty( (String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE), extensionDocument.getExternalURL("view", getXWikiContext()))); // SCM ExtensionScm scm = new ExtensionScm(); scm.setUrl((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SCMURL)); scm.setConnection(toScmConnection((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION))); scm.setDeveloperConnection(toScmConnection((String) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION))); extension.setScm(scm); // Authors List<String> authors = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS); if (authors != null) { for (String authorId : authors) { extension.getAuthors().add(resolveExtensionAuthor(authorId)); } } // Features List<String> features = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_FEATURES); if (features != null) { extension.getFeatures().addAll(features); } // Properties List<String> properties = (List<String>) getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_PROPERTIES); if (properties != null) { for (String stringProperty : properties) { int index = stringProperty.indexOf('='); if (index > 0) { Property property = new Property(); property.setKey(stringProperty.substring(0, index)); property.setStringValue((index + 1) < stringProperty.length() ? stringProperty.substring(index + 1) : ""); extension.getProperties().add(property); } } } // Dependencies if (extensionVersion != null) { List<BaseObject> dependencies = extensionDocument.getXObjects(XWikiRepositoryModel.EXTENSIONDEPENDENCY_CLASSREFERENCE); if (dependencies != null) { for (BaseObject dependencyObject : dependencies) { if (dependencyObject != null) { if (StringUtils.equals( getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_EXTENSIONVERSION, (String) null), version)) { ExtensionDependency dependency = extensionObjectFactory.createExtensionDependency(); dependency.setId((String) getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_ID)); dependency.setConstraint((String) getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_CONSTRAINT)); extensionVersion.getDependencies().add(dependency); } } } } } return (E) extension; } protected ExtensionScmConnection toScmConnection(String connectionString) { if (connectionString != null) { org.xwiki.extension.ExtensionScmConnection connection = MavenUtils.toExtensionScmConnection(connectionString); ExtensionScmConnection restConnection = new ExtensionScmConnection(); restConnection.setPath(connection.getPath()); restConnection.setSystem(connection.getSystem()); return restConnection; } return null; } protected ExtensionAuthor resolveExtensionAuthor(String authorId) { ExtensionAuthor author = new ExtensionAuthor(); XWikiContext xcontext = getXWikiContext(); XWikiDocument document; try { document = xcontext.getWiki().getDocument(authorId, xcontext); } catch (XWikiException e) { document = null; } if (document != null && !document.isNew()) { author.setName(xcontext.getWiki().getPlainUserName(document.getDocumentReference(), xcontext)); author.setUrl(document.getExternalURL("view", xcontext)); } else { author.setName(authorId); } return author; } protected void getExtensions(List<ExtensionVersion> extensions, Query query) throws QueryException { List<Object[]> entries = query.execute(); for (Object[] entry : entries) { extensions.add(createExtensionVersionFromQueryResult(entry)); } } protected <T> T getSolrValue(SolrDocument document, String property, boolean emptyIsNull) { return getSolrValue(document, property, emptyIsNull, null); } protected <T> T getSolrValue(SolrDocument document, String property, boolean emptyIsNull, T def) { Object value = document.getFieldValue(XWikiRepositoryModel.toSolrField(property)); if (value instanceof Collection) { Collection collectionValue = (Collection) value; value = collectionValue.size() > 0 ? collectionValue.iterator().next() : null; } if (value == null || (emptyIsNull && value instanceof String && ((String) value).isEmpty())) { value = def; } return (T) value; } protected <T> Collection<T> getSolrValues(SolrDocument document, String property) { return (Collection) document.getFieldValues(XWikiRepositoryModel.toSolrField(property)); } protected <T> T getQueryValue(Object[] entry, String property) { return (T) entry[EPROPERTIES_INDEX.get(property)]; } protected ExtensionVersion createExtensionVersionFromQueryResult(Object[] entry) { XWikiContext xcontext = getXWikiContext(); String documentName = (String) entry[0]; String documentSpace = (String) entry[1]; ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion(); extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID)); extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE)); extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME)); extension.setSummary(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SUMMARY)); // SCM ExtensionScm scm = new ExtensionScm(); scm.setUrl(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SCMURL)); scm.setConnection(toScmConnection(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION))); scm.setDeveloperConnection(toScmConnection(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION))); extension.setScm(scm); // Rating DocumentReference extensionDocumentReference = new DocumentReference(xcontext.getWikiId(), documentSpace, documentName); // FIXME: this adds potentially tons of new request to what used to be carefully crafted to produce a single // request for the whole search... Should be cached in a filed of the document (like the last version is for // example). extension.setRating(getExtensionRating(extensionDocumentReference)); // Website extension.setWebsite(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_WEBSITE)); if (StringUtils.isBlank(extension.getWebsite())) { extension.setWebsite(xcontext.getWiki().getURL( new DocumentReference(xcontext.getWikiId(), documentSpace, documentName), "view", xcontext)); } // Authors for (String authorId : ListClass.getListFromString( this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_AUTHORS), "|", false)) { extension.getAuthors().add(resolveExtensionAuthor(authorId)); } // Features extension.getFeatures().addAll( ListClass.getListFromString( this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_FEATURES), "|", false)); License license = this.extensionObjectFactory.createLicense(); license.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_LICENSENAME)); extension.getLicenses().add(license); // Version extension.setVersion((String) entry[EPROPERTIES_INDEX.size()]); // TODO: add support for // * description // * dependencies return extension; } protected ExtensionVersion createExtensionVersionFromSolrDocument(SolrDocument document) { XWikiContext xcontext = getXWikiContext(); ExtensionVersion extension = this.extensionObjectFactory.createExtensionVersion(); extension.setId(this.<String>getSolrValue(document, Extension.FIELD_ID, true)); extension.setType(this.<String>getSolrValue(document, Extension.FIELD_TYPE, true)); extension.setName(this.<String>getSolrValue(document, Extension.FIELD_NAME, false)); extension.setSummary(this.<String>getSolrValue(document, Extension.FIELD_SUMMARY, false)); // SCM ExtensionScm scm = new ExtensionScm(); scm.setUrl(this.<String>getSolrValue(document, Extension.FIELD_SCM, true)); scm.setConnection(toScmConnection(this.<String>getSolrValue(document, XWikiRepositoryModel.PROP_EXTENSION_SCMCONNECTION, true))); scm.setDeveloperConnection(toScmConnection(this.<String>getSolrValue(document, XWikiRepositoryModel.PROP_EXTENSION_SCMDEVCONNECTION, true))); if (scm.getUrl() != null || scm.getConnection() != null || scm.getDeveloperConnection() != null) { extension.setScm(scm); } // Rating ExtensionRating extensionRating = this.extensionObjectFactory.createExtensionRating(); extensionRating.setTotalVotes(getSolrValue(document, XWikiRepositoryModel.PROP_RATING_TOTALVOTES, false, 0)); extensionRating .setAverageVote(getSolrValue(document, XWikiRepositoryModel.PROP_RATING_AVERAGEVOTE, false, 0.0f)); extension.setRating(extensionRating); // Website extension.setWebsite(this.<String>getSolrValue(document, Extension.FIELD_WEBSITE, true)); if (extension.getWebsite() == null) { DocumentReference extensionDocumentReference = this.solrDocumentReferenceResolver.resolve(document); extension.setWebsite(xcontext.getWiki().getURL(extensionDocumentReference, xcontext)); } // Authors Collection<String> authors = this.<String>getSolrValues(document, Extension.FIELD_AUTHORS); if (authors != null) { for (String authorId : authors) { extension.getAuthors().add(resolveExtensionAuthor(authorId)); } } // Features Collection<String> features = this.<String>getSolrValues(document, Extension.FIELD_FEATURES); if (features != null) { extension.getFeatures().addAll(features); } String licenseName = this.<String>getSolrValue(document, Extension.FIELD_LICENSE, true); if (licenseName != null) { License license = this.extensionObjectFactory.createLicense(); license.setName(licenseName); extension.getLicenses().add(license); } // Version extension.setVersion(this.<String>getSolrValue(document, Extension.FIELD_VERSION, true)); // TODO: add support for // * dependencies return extension; } protected ExtensionRating getExtensionRating(DocumentReference extensionDocumentReference) { ExtensionRating extensionRating = this.extensionObjectFactory.createExtensionRating(); try { AverageRatingApi averageRating = new AverageRatingApi(ratingsManager.getAverageRating(extensionDocumentReference)); extensionRating.setTotalVotes(averageRating.getNbVotes()); extensionRating.setAverageVote(averageRating.getAverageVote()); } catch (XWikiException e) { extensionRating.setTotalVotes(0); extensionRating.setAverageVote(0); } return extensionRating; } protected <E extends ExtensionSummary> void getExtensionSummaries(List<E> extensions, Query query) throws QueryException { List<Object[]> entries = query.execute(); for (Object[] entry : entries) { extensions.add((E) createExtensionSummaryFromQueryResult(entry)); } } protected ExtensionSummary createExtensionSummaryFromQueryResult(Object[] entry) { ExtensionSummary extension; ExtensionVersionSummary extensionVersion; int versionIndex = EPROPERTIES_INDEX.get(EPROPERTIES_SUMMARY[EPROPERTIES_SUMMARY.length - 1]) + 1; if (entry.length == versionIndex) { // It's a extension summary without version extension = this.extensionObjectFactory.createExtensionSummary(); extensionVersion = null; } else { extension = extensionVersion = this.extensionObjectFactory.createExtensionVersionSummary(); extensionVersion.setVersion((String) entry[versionIndex]); } extension.setId(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_ID)); extension.setType(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_TYPE)); extension.setName(this.<String>getQueryValue(entry, XWikiRepositoryModel.PROP_EXTENSION_NAME)); return extension; } protected <T> T getValue(BaseObject object, String field) { return getValue(object, field, (T) null); } protected <T> T getValue(BaseObject object, String field, T def) { BaseProperty<?> property = (BaseProperty<?>) object.safeget(field); return property != null ? (T) property.getValue() : def; } protected ResponseBuilder getAttachmentResponse(XWikiAttachment xwikiAttachment) throws XWikiException { if (xwikiAttachment == null) { throw new WebApplicationException(Status.NOT_FOUND); } ResponseBuilder response = Response.ok(); XWikiContext xcontext = getXWikiContext(); response = response.type(xwikiAttachment.getMimeType(xcontext)); response = response.entity(xwikiAttachment.getContent(xcontext)); response = response.header("content-disposition", "attachment; filename=\"" + xwikiAttachment.getFilename() + "\""); return response; } protected void checkRights(XWikiDocument document) throws XWikiException { if (!this.authorization.hasAccess(Right.VIEW, document.getDocumentReference())) { throw new WebApplicationException(Status.FORBIDDEN); } } }
package org.jdesktop.swingx.combobox; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; /** * <p>A ComboBoxModel implementation that safely wraps an Enum. It allows the * developer to directly use an enum as their model for a combobox without any * extra work, though the display can can be further customized. </p> * * <h4>Simple Usage</h4> * * <p>The simplest usage is to wrap an <code>enum</code> inside the * <code>EnumComboBoxModel</code> and then set it as the model on the * combo box. The combo box will then appear on screen with each value * in the <code>enum</code> as a value in the combobox. * </p> * <p>ex:</p> * <pre><code> * enum MyEnum { GoodStuff, BadStuff }; * ... * JComboBox combo = new JComboBox(); * combo.setModel(new EnumComboBoxModel(MyEnum.class)); * </code></pre> * * <h4>Type safe access</h4> * <p>By using generics and co-variant types you can make accessing elements from the model * be completely typesafe. ex: *</p> * *<pre><code> * EnumComboBoxModel<MyEnum> enumModel = new EnumComboBoxModel<MyEnum1>(MyEnum1.class); * MyEnum first = enumModel.getElement(0); * MyEnum selected = enumModel.getSelectedItem(); *</code></pre> * * <h4>Advanced Usage</h4> * <p>Since the exact <code>toString()</code> value of each enum constant * may not be exactly what you want on screen (the values * won't have spaces, for example) you can override to * toString() method on the values when you declare your * enum. Thus the display value is localized to the enum * and not in your GUI code. ex: * <pre><code> * private enum MyEnum {GoodStuff, BadStuff; * public String toString() { * switch(this) { * case GoodStuff: return "Some Good Stuff"; * case BadStuff: return "Some Bad Stuff"; * } * return "ERROR"; * } * }; * </code></pre> * * * @author joshy */ public class EnumComboBoxModel<E extends Enum<E>> extends AbstractListModel implements ComboBoxModel { private E selected = null; private List<E> list; public EnumComboBoxModel(Class<E> en) { EnumSet<E> ens = EnumSet.allOf(en); list = new ArrayList<E>(ens); selected = list.get(0); } public int getSize() { return list.size(); } public E getElementAt(int index) { return list.get(index); } public void setSelectedItem(Object anItem) { selected = (E)anItem; this.fireContentsChanged(this,0,getSize()); } public E getSelectedItem() { return selected; } /* public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS)); JComboBox combo1 = new JComboBox(); combo1.setModel(new EnumComboBoxModel(MyEnum1.class)); frame.add(combo1); JComboBox combo2 = new JComboBox(); combo2.setModel(new EnumComboBoxModel(MyEnum2.class)); frame.add(combo2); EnumComboBoxModel<MyEnum1> enumModel = new EnumComboBoxModel<MyEnum1>(MyEnum1.class); JComboBox combo3 = new JComboBox(); combo3.setModel(enumModel); frame.add(combo3); MyEnum1 selected = enumModel.getSelectedItem(); frame.pack(); frame.setVisible(true); } private enum MyEnum1 {GoodStuff, BadStuff}; private enum MyEnum2 {GoodStuff, BadStuff; public String toString() { switch(this) { case GoodStuff: return "Some Good Stuff"; case BadStuff: return "Some Bad Stuff"; } return "ERROR"; } }; */ }
package org.gemoc.gemoc_language_workbench.conf.presentation; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; import org.eclipse.emf.transaction.RecordingCommand; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.ColumnLayout; import org.eclipse.ui.forms.widgets.FormToolkit; import org.gemoc.commons.eclipse.ui.OpenEditor; import org.gemoc.gemoc_language_workbench.conf.EditorProject; import org.gemoc.gemoc_language_workbench.conf.LanguageDefinition; import org.gemoc.gemoc_language_workbench.conf.XTextEditorProject; import org.gemoc.gemoc_language_workbench.ui.activeFile.ActiveFile; import org.gemoc.gemoc_language_workbench.ui.activeFile.ActiveFileEcore; import org.gemoc.gemoc_language_workbench.ui.commands.ENamedElementQualifiedNameLabelProvider; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectAnyConcreteEClassDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectAnyEObjectDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectAnyIFileDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectDSAIProjectDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectEMFIProjectDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectODesignIProjectDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectPluginIProjectDialog; import org.gemoc.gemoc_language_workbench.ui.dialogs.SelectXtextIProjectDialog; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateDSEWizardContextAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateDSEWizardContextAction.CreateDSEAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateDomainModelWizardContextAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateDomainModelWizardContextAction.CreateDomainModelAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateEditorProjectWizardContextAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateEditorProjectWizardContextAction.CreateEditorProjectAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateMOCCWizardContextAction; import org.gemoc.gemoc_language_workbench.ui.wizards.CreateMOCCWizardContextAction.CreateMOCCAction; import org.gemoc.gemoc_language_workbench.ui.wizards.contextDSA.CreateDSAWizardContextActionDSAK3; /* * IMPORTANT : this file has been edited using Windows builder. * This is why the structure is quite "unstructured" and use long methods. * The data binding is also managed via Windows Builder. */ public class GemocXDSMLFormComposite extends Composite { private DataBindingContext m_bindingContext; private final FormToolkit toolkit = new FormToolkit(Display.getCurrent()); private Text txtLanguageName; private Text txtEMFProject; private Text txtRootContainerModelElement; private Text txtXTextEditorProject; private Text txtSiriusEditorProject; private Text txtDSAProject; private Text txtCodeExecutorClass; private Text txtDSEProject; private Text txtQvtoURI; private Text txtMoCCProject; private Text txtSiriusAnimationProject; private Text txtGenmodel; LanguageDefinition rootModelElement; AdapterFactoryEditingDomain editingDomain; protected XDSMLModelWrapper xdsmlWrappedObject = new XDSMLModelWrapper(); /** * Create the composite. * * @param parent * @param style */ public GemocXDSMLFormComposite(Composite parent, int style) { super(parent, SWT.NONE); addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); } }); toolkit.adapt(this); toolkit.paintBordersFor(this); setLayout(new ColumnLayout()); Group grpLanguageDefinition = new Group(this, SWT.NONE); grpLanguageDefinition.setText("Language definition"); toolkit.adapt(grpLanguageDefinition); toolkit.paintBordersFor(grpLanguageDefinition); grpLanguageDefinition.setLayout(new GridLayout(2, false)); Label lblThisSectionDescribes = new Label(grpLanguageDefinition, SWT.WRAP); lblThisSectionDescribes.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); toolkit.adapt(lblThisSectionDescribes, true, true); lblThisSectionDescribes .setText("This section describes general information about this language."); Label lblNewLabel = new Label(grpLanguageDefinition, SWT.NONE); toolkit.adapt(lblNewLabel, true, true); lblNewLabel.setText("Language name"); txtLanguageName = new Text(grpLanguageDefinition, SWT.BORDER); txtLanguageName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); toolkit.adapt(txtLanguageName, true, true); new Label(grpLanguageDefinition, SWT.NONE); new Label(grpLanguageDefinition, SWT.NONE); Group grpDomainModelDefinition = new Group(this, SWT.NONE); grpDomainModelDefinition.setText("Domain Model"); toolkit.adapt(grpDomainModelDefinition); toolkit.paintBordersFor(grpDomainModelDefinition); grpDomainModelDefinition.setLayout(new GridLayout(3, false)); Link linkEMFProject = new Link(grpDomainModelDefinition, SWT.NONE); linkEMFProject.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); linkEMFProject.setBounds(0, 0, 49, 15); toolkit.adapt(linkEMFProject, true, true); linkEMFProject.setText("<a>EMF project</a>"); txtEMFProject = new Text(grpDomainModelDefinition, SWT.BORDER); GridData gd_txtEMFProject = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_txtEMFProject.widthHint = 226; txtEMFProject.setLayoutData(gd_txtEMFProject); txtEMFProject.setBounds(0, 0, 244, 21); toolkit.adapt(txtEMFProject, true, true); Button btnBrowseEMFProject = new Button(grpDomainModelDefinition, SWT.NONE); btnBrowseEMFProject.setBounds(0, 0, 50, 25); toolkit.adapt(btnBrowseEMFProject, true, true); btnBrowseEMFProject.setText("Browse"); Link linkGenmodel = new Link(grpDomainModelDefinition, 0); linkGenmodel.setToolTipText("URI of the main genmodel for the Domain project."); linkGenmodel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); linkGenmodel.setText("<a>Genmodel URI</a>"); toolkit.adapt(linkGenmodel, true, true); txtGenmodel = new Text(grpDomainModelDefinition, SWT.BORDER); txtGenmodel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); toolkit.adapt(txtGenmodel, true, true); Button btnBrowseGenmodel = new Button(grpDomainModelDefinition, SWT.NONE); btnBrowseGenmodel.setText("Browse"); toolkit.adapt(btnBrowseGenmodel, true, true); Label lblRootContainerModel = new Label(grpDomainModelDefinition, SWT.NONE); lblRootContainerModel.setBounds(0, 0, 55, 15); toolkit.adapt(lblRootContainerModel, true, true); lblRootContainerModel.setText("Root container model element"); txtRootContainerModelElement = new Text(grpDomainModelDefinition, SWT.BORDER); txtRootContainerModelElement.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); txtRootContainerModelElement.setBounds(0, 0, 76, 21); toolkit.adapt(txtRootContainerModelElement, true, true); Button btSelectRootModelElement = new Button(grpDomainModelDefinition, SWT.NONE); btSelectRootModelElement.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btSelectRootModelElement.setBounds(0, 0, 75, 25); toolkit.adapt(btSelectRootModelElement, true, true); btSelectRootModelElement.setText("Select"); Group grpConcreteSyntaxDefinition = new Group(this, SWT.NONE); grpConcreteSyntaxDefinition.setText("Concrete syntax definition"); toolkit.adapt(grpConcreteSyntaxDefinition); toolkit.paintBordersFor(grpConcreteSyntaxDefinition); grpConcreteSyntaxDefinition.setLayout(new GridLayout(1, false)); Group grpTextualEditor = new Group(grpConcreteSyntaxDefinition, SWT.NONE); grpTextualEditor.setLayout(new GridLayout(3, false)); GridData gd_grpTextualEditor = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_grpTextualEditor.heightHint = 49; grpTextualEditor.setLayoutData(gd_grpTextualEditor); grpTextualEditor.setText("Textual editor"); grpTextualEditor.setBounds(0, 0, 70, 82); toolkit.adapt(grpTextualEditor); toolkit.paintBordersFor(grpTextualEditor); Link linkXTextEditorProject = new Link(grpTextualEditor, SWT.NONE); linkXTextEditorProject.setBounds(0, 0, 49, 15); toolkit.adapt(linkXTextEditorProject, true, true); linkXTextEditorProject.setText("<a>xText project</a>"); txtXTextEditorProject = new Text(grpTextualEditor, SWT.BORDER); GridData gd_txtXTextEditorProject = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_txtXTextEditorProject.widthHint = 279; txtXTextEditorProject.setLayoutData(gd_txtXTextEditorProject); txtXTextEditorProject.setBounds(0, 0, 76, 21); toolkit.adapt(txtXTextEditorProject, true, true); Button btnBrowseXtextEditor = new Button(grpTextualEditor, SWT.NONE); btnBrowseXtextEditor.setBounds(0, 0, 75, 25); toolkit.adapt(btnBrowseXtextEditor, true, true); btnBrowseXtextEditor.setText("Browse"); Group grpGraphicalEditor = new Group(grpConcreteSyntaxDefinition, SWT.NONE); grpGraphicalEditor.setLayout(new GridLayout(3, false)); grpGraphicalEditor.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); grpGraphicalEditor.setText("Graphical editor"); grpGraphicalEditor.setBounds(0, 0, 70, 82); toolkit.adapt(grpGraphicalEditor); toolkit.paintBordersFor(grpGraphicalEditor); Link linkSiriusEditorProject = new Link(grpGraphicalEditor, 0); linkSiriusEditorProject .setText("<a>Sirius viewpoint design project</a>"); linkSiriusEditorProject.setBounds(0, 0, 49, 15); toolkit.adapt(linkSiriusEditorProject, true, true); txtSiriusEditorProject = new Text(grpGraphicalEditor, SWT.BORDER); GridData gd_txtSiriusEditorProject = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_txtSiriusEditorProject.widthHint = 181; txtSiriusEditorProject.setLayoutData(gd_txtSiriusEditorProject); txtSiriusEditorProject.setBounds(0, 0, 76, 21); toolkit.adapt(txtSiriusEditorProject, true, true); Button btnBrowseSiriusEditor = new Button(grpGraphicalEditor, SWT.NONE); btnBrowseSiriusEditor.setText("Browse"); btnBrowseSiriusEditor.setBounds(0, 0, 75, 25); toolkit.adapt(btnBrowseSiriusEditor, true, true); Group grpAnimationDefinition = new Group(grpConcreteSyntaxDefinition, SWT.NONE); grpAnimationDefinition.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); grpAnimationDefinition.setText("Animation definition"); toolkit.adapt(grpAnimationDefinition); toolkit.paintBordersFor(grpAnimationDefinition); grpAnimationDefinition.setLayout(new GridLayout(3, false)); Label lblThisSectionDescribes_3 = new Label(grpAnimationDefinition, SWT.NONE); lblThisSectionDescribes_3.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); lblThisSectionDescribes_3 .setText("This section describes the animation views for this language."); toolkit.adapt(lblThisSectionDescribes_3, true, true); Link linkSiriusAnimatorProject = new Link(grpAnimationDefinition, 0); linkSiriusAnimatorProject .setText("<a>Sirius viewpoint design project</a>"); toolkit.adapt(linkSiriusAnimatorProject, true, true); txtSiriusAnimationProject = new Text(grpAnimationDefinition, SWT.BORDER); GridData gd_txtSiriusAnimationProject = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_txtSiriusAnimationProject.widthHint = 182; txtSiriusAnimationProject.setLayoutData(gd_txtSiriusAnimationProject); toolkit.adapt(txtSiriusAnimationProject, true, true); Button btnBrowseSiriusAnimator = new Button(grpAnimationDefinition, SWT.NONE); btnBrowseSiriusAnimator.setText("Browse"); toolkit.adapt(btnBrowseSiriusAnimator, true, true); new Label(grpAnimationDefinition, SWT.NONE); new Label(grpAnimationDefinition, SWT.NONE); new Label(grpAnimationDefinition, SWT.NONE); Group grpBehaviorDefinition = new Group(this, SWT.NONE); grpBehaviorDefinition.setText("Behavior definition"); toolkit.adapt(grpBehaviorDefinition); toolkit.paintBordersFor(grpBehaviorDefinition); grpBehaviorDefinition.setLayout(new GridLayout(1, false)); Group grpDsaDefinition = new Group(grpBehaviorDefinition, SWT.NONE); grpDsaDefinition.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); grpDsaDefinition.setText("DSA definition"); toolkit.adapt(grpDsaDefinition); toolkit.paintBordersFor(grpDsaDefinition); grpDsaDefinition.setLayout(new GridLayout(3, false)); Label lblNewLabel_1 = new Label(grpDsaDefinition, SWT.NONE); lblNewLabel_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); lblNewLabel_1.setBounds(0, 0, 55, 15); toolkit.adapt(lblNewLabel_1, true, true); lblNewLabel_1 .setText("This section describes the execution function and data about this language."); Link linkDSAProject = new Link(grpDsaDefinition, SWT.NONE); linkDSAProject.setBounds(0, 0, 49, 15); toolkit.adapt(linkDSAProject, true, true); linkDSAProject.setText("<a>K3 project</a>"); txtDSAProject = new Text(grpDsaDefinition, SWT.BORDER); GridData gd_txtDSAProject = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtDSAProject.widthHint = 215; txtDSAProject.setLayoutData(gd_txtDSAProject); txtDSAProject.setBounds(0, 0, 76, 21); toolkit.adapt(txtDSAProject, true, true); Button btnBrowseDSAProject = new Button(grpDsaDefinition, SWT.NONE); btnBrowseDSAProject.setBounds(0, 0, 75, 25); toolkit.adapt(btnBrowseDSAProject, true, true); btnBrowseDSAProject.setText("Browse"); Link linkCodeExecutorClass = new Link(grpDsaDefinition, SWT.NONE); linkCodeExecutorClass.setToolTipText("Optional, if not set, a default K3 code executor will be generated for the DSA.\r\nIf set, this is the name of a class in the xdsml project classpath."); toolkit.adapt(linkCodeExecutorClass, true, true); linkCodeExecutorClass.setText("<a>Code executor class name</a>"); txtCodeExecutorClass = new Text(grpDsaDefinition, SWT.BORDER); txtCodeExecutorClass.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); toolkit.adapt(txtCodeExecutorClass, true, true); Button btnBrowseCodeExecutorClass = new Button(grpDsaDefinition, SWT.NONE); toolkit.adapt(btnBrowseCodeExecutorClass, true, true); btnBrowseCodeExecutorClass.setText("Browse"); Group grpMocDefinitionLibrary = new Group(grpBehaviorDefinition, SWT.NONE); grpMocDefinitionLibrary.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); grpMocDefinitionLibrary.setText("MoC definition library"); toolkit.adapt(grpMocDefinitionLibrary); toolkit.paintBordersFor(grpMocDefinitionLibrary); grpMocDefinitionLibrary.setLayout(new GridLayout(3, false)); Label lblThisSectionDescribes_2 = new Label(grpMocDefinitionLibrary, SWT.NONE); lblThisSectionDescribes_2.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); lblThisSectionDescribes_2 .setText("This section describes the reusable MoC definitions used by this language."); lblThisSectionDescribes_2.setBounds(0, 0, 397, 15); toolkit.adapt(lblThisSectionDescribes_2, true, true); Link linkMoCCMLProject = new Link(grpMocDefinitionLibrary, 0); linkMoCCMLProject.setText("<a>MoCCML project</a>"); linkMoCCMLProject.setBounds(0, 0, 60, 15); toolkit.adapt(linkMoCCMLProject, true, true); txtMoCCProject = new Text(grpMocDefinitionLibrary, SWT.BORDER); GridData gd_txtMoCCProject = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtMoCCProject.widthHint = 178; txtMoCCProject.setLayoutData(gd_txtMoCCProject); txtMoCCProject.setBounds(0, 0, 76, 21); toolkit.adapt(txtMoCCProject, true, true); Button btnBrowseMoCCProject = new Button(grpMocDefinitionLibrary, SWT.NONE); btnBrowseMoCCProject.setText("Browse"); btnBrowseMoCCProject.setBounds(0, 0, 50, 25); toolkit.adapt(btnBrowseMoCCProject, true, true); Group grpDSEDefinition = new Group(grpBehaviorDefinition, SWT.NONE); grpDSEDefinition.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); grpDSEDefinition.setText("DSE definition"); toolkit.adapt(grpDSEDefinition); toolkit.paintBordersFor(grpDSEDefinition); grpDSEDefinition.setLayout(new GridLayout(3, false)); Label lblThisSectionDescribes_1 = new Label(grpDSEDefinition, SWT.NONE); lblThisSectionDescribes_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); lblThisSectionDescribes_1 .setText("This section describes the Domain Specific Event of this language."); lblThisSectionDescribes_1.setBounds(0, 0, 397, 15); toolkit.adapt(lblThisSectionDescribes_1, true, true); Link linkDSEProject = new Link(grpDSEDefinition, 0); linkDSEProject.setText("<a>ECL project</a>"); linkDSEProject.setBounds(0, 0, 53, 15); toolkit.adapt(linkDSEProject, true, true); txtDSEProject = new Text(grpDSEDefinition, SWT.BORDER); GridData gd_txtDSEProject = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtDSEProject.widthHint = 212; txtDSEProject.setLayoutData(gd_txtDSEProject); txtDSEProject.setBounds(0, 0, 76, 21); toolkit.adapt(txtDSEProject, true, true); Button btnBrowseDSEProject = new Button(grpDSEDefinition, SWT.NONE); btnBrowseDSEProject.setText("Browse"); btnBrowseDSEProject.setBounds(0, 0, 50, 25); toolkit.adapt(btnBrowseDSEProject, true, true); Link linkQvtoURI = new Link(grpDSEDefinition, SWT.NONE); linkQvtoURI.setToolTipText("Path to the qvto file that is produced by the DSE project."); toolkit.adapt(linkQvtoURI, true, true); linkQvtoURI.setText("<a>Qvto File path</a>"); txtQvtoURI = new Text(grpDSEDefinition, SWT.BORDER); txtQvtoURI.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); toolkit.adapt(txtQvtoURI, true, true); Button btnBrowseQvtoURI = new Button(grpDSEDefinition, SWT.NONE); toolkit.adapt(btnBrowseQvtoURI, true, true); btnBrowseQvtoURI.setText("Browse"); m_bindingContext = initDataBindings(); initLinkListeners(linkEMFProject, linkGenmodel, linkXTextEditorProject, linkSiriusEditorProject, linkSiriusAnimatorProject, linkDSAProject, linkCodeExecutorClass, linkDSEProject, linkQvtoURI, linkMoCCMLProject); initButtonListeners(btnBrowseEMFProject, btnBrowseGenmodel, btSelectRootModelElement, btnBrowseXtextEditor, btnBrowseSiriusEditor, btnBrowseSiriusAnimator, btnBrowseDSAProject, btnBrowseMoCCProject, btnBrowseDSEProject); } public void initControl(AdapterFactoryEditingDomain editingDomain) { if (editingDomain != null) { this.editingDomain = editingDomain; editingDomain.toString(); if (editingDomain.getResourceSet().getResources().size() > 0) { if (editingDomain.getResourceSet().getResources().get(0) .getContents().size() > 0) { EObject eObject = editingDomain.getResourceSet() .getResources().get(0).getContents().get(0); if (eObject instanceof LanguageDefinition) { rootModelElement = (LanguageDefinition) eObject; // txtLanguageName.setText(confModelElement.getLanguageDefinition().getName()); XDSMLModelWrapperHelper.init(xdsmlWrappedObject, rootModelElement); } } } } initControlFromWrappedObject(); initTxtListeners(); } /** * Sets the initial values of the fields when opening the view */ protected void initControlFromWrappedObject() { txtLanguageName.setText(xdsmlWrappedObject.getLanguageName()); txtEMFProject.setText(xdsmlWrappedObject.getDomainModelProjectName()); txtGenmodel.setText(xdsmlWrappedObject.getGenmodelLocationURI()); txtRootContainerModelElement.setText(xdsmlWrappedObject .getRootContainerModelElement()); txtXTextEditorProject.setText(xdsmlWrappedObject .getXTextEditorProjectName()); txtSiriusEditorProject.setText(xdsmlWrappedObject .getSiriusEditorProjectName()); txtSiriusAnimationProject.setText(xdsmlWrappedObject .getSiriusAnimatorProjectName()); txtDSAProject.setText(xdsmlWrappedObject.getDSAProjectName()); txtCodeExecutorClass.setText(xdsmlWrappedObject.getCodeExecutorClass()); txtDSEProject.setText(xdsmlWrappedObject.getDSEProjectName()); txtQvtoURI.setText(xdsmlWrappedObject.getQvtoURI()); txtMoCCProject.setText(xdsmlWrappedObject.getMoCCProjectName()); } /** * Initialize the modifyListener for the txt field They are in charge of * reflecting the change to the underlying model via the bean Note that they * must act in a TransactionalEditingDomain in order to be correctly handled */ protected void initTxtListeners() { // all the listeners that will really edit the model txtLanguageName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { rootModelElement.setName(text.getText()); } }); } }); txtEMFProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject .setDomainModelProjectName(text .getText()); /* * rootModelElement.getLanguageDefinition() * .getDomainModelProject() * .setProjectName(text.getText()); */ } }); } }); txtXTextEditorProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { for (EditorProject editor : rootModelElement .getEditorProjects()) { if (editor instanceof XTextEditorProject) { editor.setProjectName(text.getText()); } } } }); } }); txtSiriusEditorProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject .setSiriusEditorProjectName(text .getText()); } }); } }); txtGenmodel.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setGenmodelLocationURI(text .getText()); } }); } }); txtRootContainerModelElement.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject .setRootContainerModelElement(text .getText()); } }); } }); txtSiriusAnimationProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject .setSiriusAnimatorProjectName(text .getText()); } }); } }); txtDSAProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setDSAProjectName(text .getText()); } }); } }); txtCodeExecutorClass.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setCodeExecutorClass(text .getText()); } }); } }); txtDSEProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setDSEProjectName(text .getText()); } }); } }); txtQvtoURI.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setQvtoURI(text .getText()); } }); } }); txtMoCCProject.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // Get the widget whose text was modified final Text text = (Text) e.widget; TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { xdsmlWrappedObject.setMoCCProjectName(text .getText()); } }); } }); } /** * Creates the listeners in charge of the behavior for the links */ protected void initLinkListeners(Link linkEMFProject, Link linkGenmodel, Link linkXTextEditorProject, Link linkSiriusEditorProject, Link linkSiriusAnimatorProject, Link linkDSAProject, Link linkCodeExecutor, Link linkDSEProject, Link linkQvtoFile, Link linkMoCCMLProject) { linkEMFProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtEMFProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtEMFProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateDomainModelWizardContextAction action = new CreateDomainModelWizardContextAction( rootModelElement); action.actionToExecute = CreateDomainModelAction.CREATE_NEW_EMF_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); linkGenmodel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtGenmodel.getText().isEmpty()) { // open the MANIFEST.MF of the project IFile file = ResourcesPlugin .getWorkspace() .getRoot() .getFile( new Path(txtGenmodel.getText() .replaceFirst("platform:/resource", ""))); if (file.exists()) { // open the editor on the manifest file OpenEditor.openIFile(file); return; } } } }); linkXTextEditorProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtXTextEditorProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtXTextEditorProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateEditorProjectWizardContextAction action = new CreateEditorProjectWizardContextAction( rootModelElement); action.actionToExecute = CreateEditorProjectAction.CREATE_NEW_XTEXT_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); linkSiriusEditorProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtSiriusEditorProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtSiriusEditorProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateEditorProjectWizardContextAction action = new CreateEditorProjectWizardContextAction( rootModelElement); action.actionToExecute = CreateEditorProjectAction.CREATE_NEW_SIRIUS_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); linkSiriusAnimatorProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtSiriusAnimationProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtSiriusAnimationProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateEditorProjectWizardContextAction action = new CreateEditorProjectWizardContextAction( rootModelElement); action.actionToExecute = CreateEditorProjectAction.CREATE_NEW_SIRIUS_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); linkDSAProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtDSAProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtDSAProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateDSAWizardContextActionDSAK3 action = new CreateDSAWizardContextActionDSAK3( getCurrentIFile().getProject(), rootModelElement); action.createNewDSAProject(); initControlFromWrappedObject(); } }); } }); linkCodeExecutor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtCodeExecutorClass.getText().isEmpty()) { // open the MANIFEST.MF of the project IFile file = ResourcesPlugin .getWorkspace() .getRoot() .getFile( new Path(txtCodeExecutorClass.getText())); if (file.exists()) { // open the editor on the manifest file OpenEditor.openIFile(file); return; } } } }); linkDSEProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtDSEProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtDSEProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateDSEWizardContextAction action = new CreateDSEWizardContextAction( getCurrentIFile().getProject(), rootModelElement); action.actionToExecute = CreateDSEAction.CREATE_NEW_DSE_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); linkQvtoFile.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtQvtoURI.getText().isEmpty()) { // find the file IFile file = ResourcesPlugin .getWorkspace() .getRoot() .getFile( new Path(txtQvtoURI.getText())); if (file.exists()) { // open the editor on the file OpenEditor.openIFile(file); return; } } } }); linkMoCCMLProject.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!txtMoCCProject.getText().isEmpty()) { // open the MANIFEST.MF of the project IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(txtMoCCProject.getText()); if (project.exists()) { // open the editor on the manifest file OpenEditor.openManifestForProject(project); return; } } // open the wizard to propose to create the project TransactionalEditingDomain teditingDomain = TransactionalEditingDomain.Factory.INSTANCE .createEditingDomain(); editingDomain.getCommandStack().execute( new RecordingCommand(teditingDomain) { public void doExecute() { CreateMOCCWizardContextAction action = new CreateMOCCWizardContextAction( rootModelElement); action.actionToExecute = CreateMOCCAction.CREATE_NEW_MOCC_PROJECT; action.execute(); initControlFromWrappedObject(); } }); } }); } /** * Creates the listeners in charge of the behavior for the buttons */ protected void initButtonListeners(Button btnBrowseEMFProject, Button btnBrowseGenmodel, Button btSelectRootModelElement, Button btnBrowseXtextEditor, Button btnBrowseSiriusEditor, Button btnBrowseSiriusAnimator, Button btnBrowseDSAProject, Button btnBrowseMoCCProject, Button btnBrowseDSEProject) { btnBrowseEMFProject.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectEMFIProjectDialog dialog = new SelectEMFIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtEMFProject.setText(((IProject) dialog.getResult()[0]) .getName()); } break; } } }); btnBrowseGenmodel.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectAnyIFileDialog dialog = new SelectAnyIFileDialog(); dialog.setPattern("*.genmodel"); if (dialog.open() == Dialog.OK) { txtGenmodel.setText("platform:/resource" + ((IResource) dialog.getResult()[0]) .getFullPath().toString()); } break; } } }); btSelectRootModelElement.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: ActiveFile activeFileEcore = new ActiveFileEcore( getCurrentIFile().getProject()); IFile ecoreFile = activeFileEcore.getActiveFile(); if (ecoreFile != null) { LabelProvider labelProvider = new ENamedElementQualifiedNameLabelProvider(); ResourceSet resSet = new ResourceSetImpl(); // get the resource Resource resource = resSet.getResource(URI .createURI(ecoreFile.getLocationURI() .toString()), true); SelectAnyEObjectDialog dialog = new SelectAnyConcreteEClassDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), resource, labelProvider); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model // xdsmlWrappedObject.setRootContainerModelElement(labelProvider.getText(dialog.getFirstResult())); txtRootContainerModelElement.setText(labelProvider .getText(dialog.getFirstResult())); } } break; } } }); btnBrowseXtextEditor.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectXtextIProjectDialog dialog = new SelectXtextIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtXTextEditorProject.setText(((IProject) dialog .getResult()[0]).getName()); } break; } } }); btnBrowseSiriusEditor.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectODesignIProjectDialog dialog = new SelectODesignIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtSiriusEditorProject.setText(((IProject) dialog .getResult()[0]).getName()); } break; } } }); btnBrowseSiriusAnimator.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectODesignIProjectDialog dialog = new SelectODesignIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtSiriusAnimationProject.setText(((IProject) dialog .getResult()[0]).getName()); } break; } } }); btnBrowseDSAProject.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectDSAIProjectDialog dialog = new SelectDSAIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtDSAProject.setText(((IProject) dialog.getResult()[0]) .getName()); } break; } } }); btnBrowseMoCCProject.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectPluginIProjectDialog dialog = new SelectPluginIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtMoCCProject.setText(((IProject) dialog.getResult()[0]) .getName()); } break; } } }); btnBrowseDSEProject.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { switch (e.type) { case SWT.Selection: SelectPluginIProjectDialog dialog = new SelectPluginIProjectDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); int res = dialog.open(); if (res == WizardDialog.OK) { // update the project model txtDSEProject.setText(((IProject) dialog.getResult()[0]) .getName()); } break; } } }); } protected IFile getCurrentIFile() { String platformString = rootModelElement.eResource().getURI() .toPlatformString(true); return ResourcesPlugin.getWorkspace().getRoot() .getFile(new Path(platformString)); } protected DataBindingContext initDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); IObservableValue observeTextTxtLanguageNameObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtLanguageName); IObservableValue languageNameXdsmlWrappedObjectObserveValue = BeanProperties.value("languageName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtLanguageNameObserveWidget, languageNameXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtEMFProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtEMFProject); IObservableValue eMFProjectXdsmlWrappedObjectObserveValue = BeanProperties.value("domainModelProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtEMFProjectObserveWidget, eMFProjectXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtXTextEditorProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtXTextEditorProject); IObservableValue xTextEditorProjectXdsmlWrappedObjectObserveValue = BeanProperties.value("XTextEditorProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtXTextEditorProjectObserveWidget, xTextEditorProjectXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtSiriusEditorProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtSiriusEditorProject); IObservableValue siriusEditorProjectXdsmlWrappedObjectObserveValue = BeanProperties.value("siriusEditorProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtSiriusEditorProjectObserveWidget, siriusEditorProjectXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtSiriusAnimationProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtSiriusAnimationProject); IObservableValue siriusAnimatorProjectNameXdsmlWrappedObjectObserveValue = BeanProperties.value("siriusAnimatorProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtSiriusAnimationProjectObserveWidget, siriusAnimatorProjectNameXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtGenmodelObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtGenmodel); IObservableValue genmodelLocationURIXdsmlWrappedObjectObserveValue = BeanProperties.value("genmodelLocationURI").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtGenmodelObserveWidget, genmodelLocationURIXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtDSAProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtDSAProject); IObservableValue dSAProjectNameXdsmlWrappedObjectObserveValue = BeanProperties.value("DSAProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtDSAProjectObserveWidget, dSAProjectNameXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtMoCCProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtMoCCProject); IObservableValue moCCProjectNameXdsmlWrappedObjectObserveValue = BeanProperties.value("moCCProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtMoCCProjectObserveWidget, moCCProjectNameXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtDSEProjectObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtDSEProject); IObservableValue dSEProjectNameXdsmlWrappedObjectObserveValue = BeanProperties.value("DSEProjectName").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtDSEProjectObserveWidget, dSEProjectNameXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtRootContainerModelElementObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtRootContainerModelElement); IObservableValue rootContainerModelElementXdsmlWrappedObjectObserveValue = BeanProperties.value("rootContainerModelElement").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtRootContainerModelElementObserveWidget, rootContainerModelElementXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtCodeExecutorClassObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtCodeExecutorClass); IObservableValue codeExecutorClassXdsmlWrappedObjectObserveValue = BeanProperties.value("codeExecutorClass").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtCodeExecutorClassObserveWidget, codeExecutorClassXdsmlWrappedObjectObserveValue, null, null); IObservableValue observeTextTxtQvtoURIObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtQvtoURI); IObservableValue qvtoURIXdsmlWrappedObjectObserveValue = BeanProperties.value("qvtoURI").observe(xdsmlWrappedObject); bindingContext.bindValue(observeTextTxtQvtoURIObserveWidget, qvtoURIXdsmlWrappedObjectObserveValue, null, null); return bindingContext; } }
package org.jdesktop.swingx.plaf.basic; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.event.MouseInputAdapter; import javax.swing.event.MouseInputListener; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicGraphicsUtils; import org.jdesktop.swingx.JXCollapsiblePane; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXTaskPane; import org.jdesktop.swingx.icon.EmptyIcon; import org.jdesktop.swingx.plaf.TaskPaneUI; /** * Base implementation of the <code>JXTaskPane</code> UI. * * @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a> */ public class BasicTaskPaneUI extends TaskPaneUI { private static FocusListener focusListener = new RepaintOnFocus(); public static ComponentUI createUI(JComponent c) { return new BasicTaskPaneUI(); } protected int titleHeight = 25; protected int roundHeight = 5; protected JXTaskPane group; protected boolean mouseOver; protected MouseInputListener mouseListener; protected PropertyChangeListener propertyListener; /** * {@inheritDoc} */ @Override public void installUI(JComponent c) { super.installUI(c); group = (JXTaskPane) c; installDefaults(); installListeners(); installKeyboardActions(); } /** * Installs default properties. Following properties are installed: * <ul> * <li>TaskPane.background</li> * <li>TaskPane.foreground</li> * <li>TaskPane.font</li> * <li>TaskPane.borderColor</li> * <li>TaskPane.titleForeground</li> * <li>TaskPane.titleBackgroundGradientStart</li> * <li>TaskPane.titleBackgroundGradientEnd</li> * <li>TaskPane.titleOver</li> * <li>TaskPane.specialTitleOver</li> * <li>TaskPane.specialTitleForeground</li> * <li>TaskPane.specialTitleBackground</li> * </ul> */ protected void installDefaults() { group.setOpaque(true); group.setBorder(createPaneBorder()); ((JComponent) group.getContentPane()) .setBorder(createContentPaneBorder()); LookAndFeel.installColorsAndFont(group, "TaskPane.background", "TaskPane.foreground", "TaskPane.font"); LookAndFeel.installColorsAndFont((JComponent) group.getContentPane(), "TaskPane.background", "TaskPane.foreground", "TaskPane.font"); } /** * Installs listeners for UI delegate. */ protected void installListeners() { mouseListener = createMouseInputListener(); group.addMouseMotionListener(mouseListener); group.addMouseListener(mouseListener); group.addFocusListener(focusListener); propertyListener = createPropertyListener(); group.addPropertyChangeListener(propertyListener); } /** * Installs keyboard actions to allow task pane to react on hot keys. */ protected void installKeyboardActions() { InputMap inputMap = (InputMap) UIManager.get("TaskPane.focusInputMap"); if (inputMap != null) { SwingUtilities.replaceUIInputMap(group, JComponent.WHEN_FOCUSED, inputMap); } ActionMap map = getActionMap(); if (map != null) { SwingUtilities.replaceUIActionMap(group, map); } } ActionMap getActionMap() { ActionMap map = new ActionMapUIResource(); map.put("toggleCollapsed", new ToggleCollapsedAction()); return map; } @Override public void uninstallUI(JComponent c) { uninstallListeners(); super.uninstallUI(c); } /** * Uninstalls previously installed listeners to free component for garbage collection. */ protected void uninstallListeners() { group.removeMouseListener(mouseListener); group.removeMouseMotionListener(mouseListener); group.removeFocusListener(focusListener); group.removePropertyChangeListener(propertyListener); } /** * Creates new toggle listener. * @return MouseInputListener reacting on toggle events of task pane. */ protected MouseInputListener createMouseInputListener() { return new ToggleListener(); } /** * Creates property change listener for task pane. * @return Property change listener reacting on changes to the task pane. */ protected PropertyChangeListener createPropertyListener() { return new ChangeListener(); } /** * Evaluates whenever given mouse even have occurred within borders of task pane. * @param event Evaluated event. * @return True if event occurred within task pane area, false otherwise. */ protected boolean isInBorder(MouseEvent event) { return event.getY() < getTitleHeight(event.getComponent()); } /** * Gets current title height. Default value is 25 if not specified otherwise. Method checks * provided component for user set font (!instanceof FontUIResource), if font is set, height * will be calculated from font metrics instead of using internal preset height. * @return Current title height. */ protected int getTitleHeight(Component c) { if (c instanceof JXTaskPane) { JXTaskPane taskPane = (JXTaskPane) c; Font font = taskPane.getFont(); int height = titleHeight; if (font != null && !(font instanceof FontUIResource)) { height = Math.max(height, taskPane.getFontMetrics(font).getHeight()); } Icon icon = taskPane.getIcon(); if (icon != null) { height = Math.max(height, icon.getIconHeight() + 4); } return height; } return titleHeight; } /** * Creates new border for task pane. * @return Fresh border on every call. */ protected Border createPaneBorder() { return new PaneBorder(); } @Override public Dimension getPreferredSize(JComponent c) { Component component = group.getComponent(0); if (!(component instanceof JXCollapsiblePane)) { // something wrong in this JXTaskPane return super.getPreferredSize(c); } JXCollapsiblePane collapsible = (JXCollapsiblePane) component; Dimension dim = collapsible.getPreferredSize(); Border groupBorder = group.getBorder(); if (groupBorder instanceof PaneBorder) { Dimension border = ((PaneBorder) groupBorder) .getPreferredSize(group); dim.width = Math.max(dim.width, border.width); dim.height += border.height; } else { dim.height += getTitleHeight(c); } return dim; } /** * Creates content pane border. * @return Fresh content pane border initialized with current value of TaskPane.borderColor * on every call. */ protected Border createContentPaneBorder() { Color borderColor = UIManager.getColor("TaskPane.borderColor"); return new CompoundBorder(new ContentPaneBorder(borderColor), BorderFactory.createEmptyBorder(10, 10, 10, 10)); } @Override public Component createAction(Action action) { JXHyperlink link = new JXHyperlink(action) { @Override public void updateUI() { super.updateUI(); // ensure the ui of this link is correctly update on l&f changes configure(this); } }; configure(link); return link; } /** * Configures internally used hyperlink on new action creation and on every call to * <code>updateUI()</code>. * @param link Configured hyperlink. */ protected void configure(JXHyperlink link) { link.setOpaque(false); link.setBorder(null); link.setBorderPainted(false); link.setFocusPainted(true); link.setForeground(UIManager.getColor("TaskPane.titleForeground")); } /** * Ensures expanded group is visible. Issues delayed request for scrolling to visible. */ protected void ensureVisible() { SwingUtilities.invokeLater(new Runnable() { public void run() { group.scrollRectToVisible(new Rectangle(group.getWidth(), group .getHeight())); } }); } /** * Focus listener responsible for repainting of the taskpane on focus change. */ static class RepaintOnFocus implements FocusListener { public void focusGained(FocusEvent e) { e.getComponent().repaint(); } public void focusLost(FocusEvent e) { e.getComponent().repaint(); } } /** * Change listener responsible for change handling. */ class ChangeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { // if group is expanded but not animated // or if animated has reached expanded state // scroll to visible if scrollOnExpand is enabled if (("collapsed".equals(evt.getPropertyName()) && Boolean.TRUE.equals(evt.getNewValue()) && !group .isAnimated()) || (JXCollapsiblePane.ANIMATION_STATE_KEY.equals(evt .getPropertyName()) && "expanded".equals(evt .getNewValue()))) { if (group.isScrollOnExpand()) { ensureVisible(); } } else if (JXTaskPane.ICON_CHANGED_KEY .equals(evt.getPropertyName()) || JXTaskPane.TITLE_CHANGED_KEY.equals(evt .getPropertyName()) || JXTaskPane.SPECIAL_CHANGED_KEY.equals(evt .getPropertyName())) { // icon, title, special must lead to a repaint() group.repaint(); } } } /** * Mouse listener responsible for handling of toggle events. */ class ToggleListener extends MouseInputAdapter { public void mouseEntered(MouseEvent e) { if (isInBorder(e)) { e.getComponent().setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else { mouseOver = false; group.repaint(0, 0, group.getWidth(), getTitleHeight(group)); } } public void mouseExited(MouseEvent e) { e.getComponent().setCursor(null); mouseOver = false; group.repaint(0, 0, group.getWidth(), getTitleHeight(group)); } public void mouseMoved(MouseEvent e) { if (isInBorder(e)) { e.getComponent().setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); mouseOver = true; } else { e.getComponent().setCursor(null); mouseOver = false; } group.repaint(0, 0, group.getWidth(), getTitleHeight(group)); } public void mouseReleased(MouseEvent e) { if (isInBorder(e)) { group.setCollapsed(!group.isCollapsed()); } } } /** * Toggle expanded action. */ class ToggleCollapsedAction extends AbstractAction { /** * Serial version UID. */ private static final long serialVersionUID = 5676859881615358815L; public ToggleCollapsedAction() { super("toggleCollapsed"); } public void actionPerformed(ActionEvent e) { group.setCollapsed(!group.isCollapsed()); } public boolean isEnabled() { return group.isVisible(); } } /** * Toggle icon. */ protected static class ChevronIcon implements Icon { boolean up = true; public ChevronIcon(boolean up) { this.up = up; } public int getIconHeight() { return 3; } public int getIconWidth() { return 6; } public void paintIcon(Component c, Graphics g, int x, int y) { if (up) { g.drawLine(x + 3, y, x, y + 3); g.drawLine(x + 3, y, x + 6, y + 3); } else { g.drawLine(x, y, x + 3, y + 3); g.drawLine(x + 3, y + 3, x + 6, y); } } } /** * The border around the content pane */ protected static class ContentPaneBorder implements Border, UIResource { Color color; public ContentPaneBorder(Color color) { this.color = color; } public Insets getBorderInsets(Component c) { return new Insets(0, 1, 1, 1); } public boolean isBorderOpaque() { return true; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { g.setColor(color); g.drawLine(x, y, x, y + height - 1); g.drawLine(x, y + height - 1, x + width - 1, y + height - 1); g.drawLine(x + width - 1, y, x + width - 1, y + height - 1); } } /** * The border of the taskpane group paints the "text", the "icon", the * "expanded" status and the "special" type. * */ protected class PaneBorder implements Border, UIResource { protected Color borderColor; protected Color titleForeground; protected Color specialTitleBackground; protected Color specialTitleForeground; protected Color titleBackgroundGradientStart; protected Color titleBackgroundGradientEnd; protected Color titleOver; protected Color specialTitleOver; protected JLabel label; /** * Creates new instance of individual pane border. */ public PaneBorder() { borderColor = UIManager.getColor("TaskPane.borderColor"); titleForeground = UIManager.getColor("TaskPane.titleForeground"); specialTitleBackground = UIManager .getColor("TaskPane.specialTitleBackground"); specialTitleForeground = UIManager .getColor("TaskPane.specialTitleForeground"); titleBackgroundGradientStart = UIManager .getColor("TaskPane.titleBackgroundGradientStart"); titleBackgroundGradientEnd = UIManager .getColor("TaskPane.titleBackgroundGradientEnd"); titleOver = UIManager.getColor("TaskPane.titleOver"); if (titleOver == null) { titleOver = specialTitleBackground.brighter(); } specialTitleOver = UIManager.getColor("TaskPane.specialTitleOver"); if (specialTitleOver == null) { specialTitleOver = specialTitleBackground.brighter(); } label = new JLabel(); label.setOpaque(false); label.setIconTextGap(8); } public Insets getBorderInsets(Component c) { return new Insets(getTitleHeight(c), 0, 0, 0); } /** * Overwritten to always return <code>true</code> to speed up * painting. Don't use transparent borders unless providing UI delegate * that provides proper return value when calling this method. * * @see javax.swing.border.Border#isBorderOpaque() */ public boolean isBorderOpaque() { return true; } /** * Calculates the preferred border size, its size so all its content * fits. * * @param group * Selected group. */ public Dimension getPreferredSize(JXTaskPane group) { // calculate the title width so it is fully visible // it starts with the title width configureLabel(group); Dimension dim = label.getPreferredSize(); // add the title left offset dim.width += 3; // add the controls width dim.width += getTitleHeight(group); // and some space between label and controls dim.width += 3; dim.height = getTitleHeight(group); return dim; } /** * Paints background of the title. This may differ based on properties * of the group. * * @param group * Selected group. * @param g * Target graphics. */ protected void paintTitleBackground(JXTaskPane group, Graphics g) { if (group.isSpecial()) { g.setColor(specialTitleBackground); } else { g.setColor(titleBackgroundGradientStart); } g.fillRect(0, 0, group.getWidth(), getTitleHeight(group) - 1); } /** * Paints current group title. * * @param group * Selected group. * @param g * Target graphics. * @param textColor * Title color. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintTitle(JXTaskPane group, Graphics g, Color textColor, int x, int y, int width, int height) { configureLabel(group); label.setForeground(textColor); if (group.getFont() != null && ! (group.getFont() instanceof FontUIResource)) { label.setFont(group.getFont()); } g.translate(x, y); label.setBounds(0, 0, width, height); label.paint(g); g.translate(-x, -y); } /** * Configures label for the group using its title, font, icon and * orientation. * * @param group * Selected group. */ protected void configureLabel(JXTaskPane group) { label.applyComponentOrientation(group.getComponentOrientation()); label.setFont(group.getFont()); label.setText(group.getTitle()); label.setIcon(group.getIcon() == null ? new EmptyIcon() : group .getIcon()); } /** * Paints expanded controls. Default implementation does nothing. * * @param group * Expanded group. * @param g * Target graphics. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintExpandedControls(JXTaskPane group, Graphics g, int x, int y, int width, int height) { } /** * Gets current paint color. * * @param group * Selected group. * @return Color to be used for painting provided group. */ protected Color getPaintColor(JXTaskPane group) { Color paintColor; if (isMouseOverBorder()) { if (mouseOver) { if (group.isSpecial()) { paintColor = specialTitleOver; } else { paintColor = titleOver; } } else { if (group.isSpecial()) { paintColor = specialTitleForeground; } else { paintColor = group.getForeground() == null || group.getForeground() instanceof ColorUIResource ? titleForeground : group.getForeground(); } } } else { if (group.isSpecial()) { paintColor = specialTitleForeground; } else { paintColor = group.getForeground() == null || group.getForeground() instanceof ColorUIResource ? titleForeground : group.getForeground(); } } return paintColor; } /* * @see javax.swing.border.Border#paintBorder(java.awt.Component, * java.awt.Graphics, int, int, int, int) */ public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { JXTaskPane group = (JXTaskPane) c; // calculate position of title and toggle controls int controlWidth = getTitleHeight(group) - 2 * getRoundHeight(); int controlX = group.getWidth() - getTitleHeight(group); int controlY = getRoundHeight() - 1; int titleX = 3; int titleY = 0; int titleWidth = group.getWidth() - getTitleHeight(group) - 3; int titleHeight = getTitleHeight(group); if (!group.getComponentOrientation().isLeftToRight()) { controlX = group.getWidth() - controlX - controlWidth; titleX = group.getWidth() - titleX - titleWidth; } // paint the title background paintTitleBackground(group, g); // paint the the toggles paintExpandedControls(group, g, controlX, controlY, controlWidth, controlWidth); // paint the title text and icon Color paintColor = getPaintColor(group); // focus painted same color as text if (group.hasFocus()) { paintFocus(g, paintColor, 3, 3, width - 6, getTitleHeight(group) - 6); } paintTitle(group, g, paintColor, titleX, titleY, titleWidth, titleHeight); } /** * Paints oval 'border' area around the control itself. * * @param group * Expanded group. * @param g * Target graphics. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintRectAroundControls(JXTaskPane group, Graphics g, int x, int y, int width, int height, Color highColor, Color lowColor) { if (mouseOver) { int x2 = x + width; int y2 = y + height; g.setColor(highColor); g.drawLine(x, y, x2, y); g.drawLine(x, y, x, y2); g.setColor(lowColor); g.drawLine(x2, y, x2, y2); g.drawLine(x, y2, x2, y2); } } /** * Paints oval 'border' area around the control itself. * * @param group * Expanded group. * @param g * Target graphics. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintOvalAroundControls(JXTaskPane group, Graphics g, int x, int y, int width, int height) { if (group.isSpecial()) { g.setColor(specialTitleBackground.brighter()); g.drawOval(x, y, width, height); } else { g.setColor(titleBackgroundGradientStart); g.fillOval(x, y, width, height); g.setColor(titleBackgroundGradientEnd.darker()); g.drawOval(x, y, width, width); } } /** * Paints controls for the group. * * @param group * Expanded group. * @param g * Target graphics. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintChevronControls(JXTaskPane group, Graphics g, int x, int y, int width, int height) { ChevronIcon chevron; if (group.isCollapsed()) { chevron = new ChevronIcon(false); } else { chevron = new ChevronIcon(true); } int chevronX = x + width / 2 - chevron.getIconWidth() / 2; int chevronY = y + (height / 2 - chevron.getIconHeight()); chevron.paintIcon(group, g, chevronX, chevronY); chevron.paintIcon(group, g, chevronX, chevronY + chevron.getIconHeight() + 1); } /** * Paints focused group. * * @param g * Target graphics. * @param paintColor * Focused group color. * @param x * X coordinate of the top left corner. * @param y * Y coordinate of the top left corner. * @param width * Width of the box. * @param height * Height of the box. */ protected void paintFocus(Graphics g, Color paintColor, int x, int y, int width, int height) { g.setColor(paintColor); BasicGraphicsUtils.drawDashedRect(g, x, y, width, height); } /** * Default implementation returns false. * * @return true if this border wants to display things differently when * the mouse is over it */ protected boolean isMouseOverBorder() { return false; } } /** * Gets size of arc used to round corners. * * @return size of arc used to round corners of the panel. */ protected int getRoundHeight() { return roundHeight; } }
package org.opentdc.resources.file; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.opentdc.addressbooks.ContactModel; import org.opentdc.file.AbstractFileServiceProvider; import org.opentdc.rates.RateModel; import org.opentdc.resources.RateRefModel; import org.opentdc.resources.RatedResource; import org.opentdc.resources.ResourceModel; import org.opentdc.resources.ServiceProvider; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; import org.opentdc.util.PrettyPrinter; /** * File-based (and transient) implementation of ResourcesService. * @author Bruno Kaiser * */ public class FileServiceProvider extends AbstractFileServiceProvider<RatedResource> implements ServiceProvider { protected static Map<String, RatedResource> index = new HashMap<String, RatedResource>(); protected static Map<String, RateRefModel> rateRefIndex = new HashMap<String, RateRefModel>(); protected static final Logger logger = Logger.getLogger(FileServiceProvider.class.getName()); /** * Constructor. * @param context the servlet context (for config) * @param prefix the directory name where the seed and data.json reside (typically the classname of the service) * @throws IOException */ public FileServiceProvider( ServletContext context, String prefix ) throws IOException { super(context, prefix); if (index == null) { index = new HashMap<String, RatedResource>(); List<RatedResource> _resources = importJson(); for (RatedResource _resource : _resources) { index.put(_resource.getModel().getId(), _resource); } } } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#listResources(java.lang.String, java.lang.String, int, int) */ @Override public List<ResourceModel> listResources( String query, String queryType, int position, int size) { ArrayList<ResourceModel> _resources = new ArrayList<ResourceModel>(); for (RatedResource _ratedRes : index.values()) { _resources.add(_ratedRes.getModel()); } Collections.sort(_resources, ResourceModel.ResourceComparator); ArrayList<ResourceModel> _selection = new ArrayList<ResourceModel>(); for (int i = 0; i < _resources.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_resources.get(i)); } } logger.info("listResources(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " resources."); return _selection; } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#createResource(org.opentdc.resources.ResourceModel) */ @Override public ResourceModel createResource( ResourceModel resource ) throws DuplicateException, ValidationException { logger.info("createResource(" + PrettyPrinter.prettyPrintAsJSON(resource) + ")"); String _id = resource.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (index.get(_id) != null) { // object with same ID exists already throw new DuplicateException("resource <" + resource.getId() + "> exists already."); } else { throw new ValidationException("resource <" + resource.getId() + "> contains an ID generated on the client. This is not allowed."); } } if (resource.getName() == null || resource.getName().length() == 0) { throw new ValidationException("resource <" + _id + "> must have a valid name."); } if (resource.getContactId() == null || resource.getContactId().length() == 0) { throw new ValidationException("resource <" + _id + "> must have a valid contactId."); } ContactModel _contactModel = getContactModel(resource.getContactId()); if (resource.getFirstName() != null && !resource.getFirstName().isEmpty()) { logger.warning("resource <" + _id + ">: firstName is a derived field and will be overwritten."); } resource.setFirstName(_contactModel.getFirstName()); if (resource.getLastName() != null && !resource.getLastName().isEmpty()) { logger.warning("resource <" + _id + ">: lastName is a derived field and will be overwritten."); } resource.setLastName(_contactModel.getLastName()); resource.setId(_id); Date _date = new Date(); resource.setCreatedAt(_date); resource.setCreatedBy(getPrincipal()); resource.setModifiedAt(_date); resource.setModifiedBy(getPrincipal()); RatedResource _ratedRes = new RatedResource(); _ratedRes.setModel(resource); index.put(_id, _ratedRes); logger.info("createResource() -> " + PrettyPrinter.prettyPrintAsJSON(resource)); if (isPersistent) { exportJson(index.values()); } return resource; } private ContactModel getContactModel( String contactId) { return org.opentdc.addressbooks.file.FileServiceProvider.getContactModel(contactId); } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#readResource(java.lang.String) */ @Override public ResourceModel readResource( String resourceId) throws NotFoundException { ResourceModel _resource = readRatedResource(resourceId).getModel(); logger.info("readResource(" + resourceId + ") -> " + _resource); return _resource; } /** * Retrieve the RatedResource based on the resourceId. * @param resourceId the unique id of the resource * @return the RatedResource that contains the resource as its model * @throws NotFoundException if no resource with this id was found */ private static RatedResource readRatedResource( String resourceId) throws NotFoundException { RatedResource _ratedRes = index.get(resourceId); if (_ratedRes == null) { throw new NotFoundException("no resource with id <" + resourceId + "> was found."); } logger.info("readRatedResource(" + resourceId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_ratedRes)); return _ratedRes; } /** * Retrieve a ResourceModel by its ID. * @param id the ID of the resource * @return the resource found * @throws NotFoundException if not resource with such an ID was found */ public static ResourceModel getResourceModel( String id) throws NotFoundException { return readRatedResource(id).getModel(); } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#updateResource(java.lang.String, org.opentdc.resources.ResourceModel) */ @Override public ResourceModel updateResource( String id, ResourceModel resource ) throws NotFoundException, ValidationException { RatedResource _ratedRes = readRatedResource(id); ResourceModel _resModel = _ratedRes.getModel(); if (! _resModel.getCreatedAt().equals(resource.getCreatedAt())) { logger.warning("resource<" + id + ">: ignoring createdAt value <" + resource.getCreatedAt().toString() + "> because it was set on the client."); } if (!_resModel.getCreatedBy().equalsIgnoreCase(resource.getCreatedBy())) { logger.warning("resource<" + id + ">: ignoring createdBy value <" + resource.getCreatedBy() + "> because it was set on the client."); } _resModel.setName(resource.getName()); _resModel.setFirstName(resource.getFirstName()); _resModel.setLastName(resource.getLastName()); _resModel.setContactId(resource.getContactId()); _resModel.setModifiedAt(new Date()); _resModel.setModifiedBy(getPrincipal()); _ratedRes.setModel(_resModel); index.put(id, _ratedRes); logger.info("updateResource(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_resModel)); if (isPersistent) { exportJson(index.values()); } return _resModel; } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#deleteResource(java.lang.String) */ @Override public void deleteResource( String id) throws NotFoundException, InternalServerErrorException { RatedResource _ratedRes = readRatedResource(id); // remove all rateRefs of this ratedRes from rateRefIndex for (RateRefModel _rateRef : _ratedRes.getRateRefs()) { if (rateRefIndex.remove(_rateRef.getId()) == null) { throw new InternalServerErrorException("rateRef <" + _rateRef.getId() + "> can not be removed, because it does not exist in the rateRefIndex"); } } if (index.remove(id) == null) { throw new InternalServerErrorException("resource <" + id + "> can not be removed, because it does not exist in the index"); } logger.info("deleteResource(" + id + ") -> OK"); if (isPersistent) { exportJson(index.values()); } } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#listRateRefs(java.lang.String, java.lang.String, java.lang.String, int, int) */ @Override public List<RateRefModel> listRateRefs( String resourceId, String queryType, String query, int position, int size) { List<RateRefModel> _rates = readRatedResource(resourceId).getRateRefs(); Collections.sort(_rates, RateRefModel.RatesRefComparator); ArrayList<RateRefModel> _selection = new ArrayList<RateRefModel>(); for (int i = 0; i < _rates.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_rates.get(i)); } } logger.info("listRateRefs(<" + resourceId + ">, <" + queryType + ">, <" + query + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " values"); return _selection; } /** * Retrieve a rate by ID * @param rateId the id of the rate to look for * @return the rate found */ private RateModel getRateModel( String rateId) { return org.opentdc.rates.file.FileServiceProvider.getRatesModel(rateId); } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#createRateRef(java.lang.String, org.opentdc.resources.RateRefModel) */ @Override public RateRefModel createRateRef( String resourceId, RateRefModel model) throws DuplicateException, ValidationException { RatedResource _ratedRes = readRatedResource(resourceId); if (model.getRateId() == null || model.getRateId().isEmpty()) { throw new ValidationException("RateRef in Resource <" + resourceId + "> must contain a valid rateId."); } if (model.getRateTitle() != null && !model.getRateTitle().isEmpty()) { logger.warning("RateRef in Resource <" + resourceId + ">: title is a derived field and will be overwritten."); } // a rate can be contained as a RateRef within Resource 0 or 1 times if (_ratedRes.containsRate(model.getRateId())) { throw new DuplicateException("RateRef with Rate <" + model.getRateId() + "> exists already in Resource <" + resourceId + ">."); } model.setRateTitle(getRateModel(model.getRateId()).getTitle()); String _id = model.getId(); if (_id == null || _id.isEmpty()) { _id = UUID.randomUUID().toString(); } else { if (rateRefIndex.get(_id) != null) { throw new DuplicateException("RateRef with id <" + _id + "> exists already in rateRefIndex."); } else { throw new ValidationException("RateRef with id <" + _id + "> contains an ID generated on the client. This is not allowed."); } } model.setId(_id); model.setCreatedAt(new Date()); model.setCreatedBy(getPrincipal()); rateRefIndex.put(_id, model); _ratedRes.addRateRef(model); logger.info("createRateRef(" + resourceId + ") -> " + PrettyPrinter.prettyPrintAsJSON(model)); if (isPersistent) { exportJson(index.values()); } return model; } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#readRateRef(java.lang.String, java.lang.String) */ @Override public RateRefModel readRateRef( String resourceId, String rateRefId) throws NotFoundException { readRatedResource(resourceId); // verify that the resource exists RateRefModel _rateRef = rateRefIndex.get(rateRefId); if (_rateRef == null) { throw new NotFoundException("RateRef <" + resourceId + "/rateref/" + rateRefId + "> was not found."); } logger.info("readRateRef(" + resourceId + ", " + rateRefId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_rateRef)); return _rateRef; } /* (non-Javadoc) * @see org.opentdc.resources.ServiceProvider#deleteRateRef(java.lang.String, java.lang.String) */ @Override public void deleteRateRef( String resourceId, String rateRefId) throws NotFoundException, InternalServerErrorException { RatedResource _ratedRes = readRatedResource(resourceId); RateRefModel _rateRef = rateRefIndex.get(rateRefId); if (_rateRef == null) { throw new NotFoundException("RateRef <" + resourceId + "/rateref/" + rateRefId + "> was not found."); } // 1) remove the RateRef from its Resource if (_ratedRes.removeRateRef(_rateRef) == false) { throw new InternalServerErrorException("RateRef <" + resourceId + "/rateref/" + rateRefId + "> can not be removed, because it is an orphan."); } // 2) remove the RateRef from the rateRefIndex if (rateRefIndex.remove(_rateRef.getId()) == null) { throw new InternalServerErrorException("RateRef <" + resourceId + "/rateref/" + rateRefId + "> can not be removed, because it does not exist in the index."); } logger.info("deleteRateRef(" + resourceId + ", " + rateRefId + ") -> OK"); if (isPersistent) { exportJson(index.values()); } } }
package org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.VelocityContext; import org.json.simple.JSONObject; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.ResourceEndpoint; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.template.APITemplateException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Set Resource-Endpoint in context */ public class ResourceEndpointConfigContext extends ConfigContextDecorator { private List<ResourceEndpoint> resourceEndpoints; private API api; private APIProduct apiProduct; private JSONObject resourceEndpointConfig; private Map<String, Map<String, EndpointSecurityModel>> resourceEndpointSecurityConfig; public ResourceEndpointConfigContext(ConfigContext context, List<ResourceEndpoint> resourceEndpoints, API api) { super(context); this.resourceEndpoints = resourceEndpoints; this.api = api; } public ResourceEndpointConfigContext(ConfigContext context, List<ResourceEndpoint> resourceEndpoints, APIProduct apiProduct) { super(context); this.resourceEndpoints = resourceEndpoints; this.apiProduct = apiProduct; } public void validate() throws APITemplateException, APIManagementException { super.validate(); JSONObject resourceEndpointMap = new JSONObject(); Map<String, Map<String, EndpointSecurityModel>> securityConfig = new HashMap<>(); if (resourceEndpoints != null) { for (ResourceEndpoint resourceEndpoint : resourceEndpoints) { JSONObject resourceEndpointConfig = constructEndpointConfig(resourceEndpoint); resourceEndpointMap.put(resourceEndpoint.getId(), resourceEndpointConfig); if (resourceEndpoint.getSecurityConfig() != null) { Map<String, EndpointSecurityModel> endpointSecurityConfig = new HashMap<>(); endpointSecurityConfig.put("resource", constructSecurityConfig(resourceEndpoint)); securityConfig.put(resourceEndpoint.getId(), endpointSecurityConfig); } } } this.resourceEndpointConfig = resourceEndpointMap; this.resourceEndpointSecurityConfig = securityConfig; } private JSONObject constructEndpointConfig(ResourceEndpoint resourceEndpoint) { JSONObject endpointConfig = new JSONObject(); JSONObject resourceEndpointConfig = new JSONObject(); endpointConfig.put("endpoint_type", resourceEndpoint.getEndpointType().toString().toLowerCase()); if (this.api != null) { endpointConfig.put("endpointKey", this.api.getUuid() + "--" + resourceEndpoint.getId()); } else { endpointConfig.put("endpointKey", this.apiProduct.getUuid() + "--" + resourceEndpoint.getId()); } resourceEndpointConfig.put("url", resourceEndpoint.getUrl()); Gson gson = new Gson(); if (resourceEndpoint.getGeneralConfig() != null && !resourceEndpoint.getGeneralConfig().isEmpty()) { resourceEndpointConfig.put("config", gson.toJson(resourceEndpoint.getGeneralConfig())); } endpointConfig.put("resource_endpoints", resourceEndpointConfig); return endpointConfig; } private EndpointSecurityModel constructSecurityConfig(ResourceEndpoint resourceEndpoint) throws APITemplateException { Gson gson = new Gson(); ObjectMapper mapper = new ObjectMapper(); Map<String, String> securityConfig = resourceEndpoint.getSecurityConfig(); EndpointSecurityModel endpointSecurityModel = null; try { String jsonString = mapper.writeValueAsString(securityConfig); endpointSecurityModel = gson.fromJson(jsonString, EndpointSecurityModel.class); //Add support for BASIC if (endpointSecurityModel != null && endpointSecurityModel.isEnabled()) { if (StringUtils.isNotBlank(endpointSecurityModel.getUsername()) && StringUtils .isNotBlank(endpointSecurityModel.getPassword())) { endpointSecurityModel.setBase64EncodedPassword(new String(Base64.encodeBase64( endpointSecurityModel.getUsername().concat(":").concat(endpointSecurityModel.getPassword()) .getBytes()))); } } if (APIConstants.ENDPOINT_SECURITY_TYPE_OAUTH.equalsIgnoreCase(endpointSecurityModel.getType())) { String uniqueIdentifier; if (api != null) { uniqueIdentifier = api.getUuid() + "--" + resourceEndpoint.getId(); } else { uniqueIdentifier = apiProduct.getUuid() + "--" + resourceEndpoint.getId(); } endpointSecurityModel.setUniqueIdentifier(uniqueIdentifier); } } catch (JsonProcessingException e) { this.handleException("Unable to process the endpoint security JSON config"); } return endpointSecurityModel; } public VelocityContext getContext() { VelocityContext context = super.getContext(); context.put("resource_endpoint_config", this.resourceEndpointConfig); context.put("resource_endpoint_security_config", this.resourceEndpointSecurityConfig); return context; } }
package org.helioviewer.gl3d.camera; public class GL3DSpaceObject { private final String urlName; private final String labelName; private static GL3DSpaceObject objectList[]; public static GL3DSpaceObject[] getObjectList() { if (objectList == null) { createObjectList(); } return objectList; } private static void createObjectList() { objectList = new GL3DSpaceObject[14]; objectList[0] = new GL3DSpaceObject("Mercury", "Mercury"); objectList[1] = new GL3DSpaceObject("Venus", "Venus"); objectList[2] = new GL3DSpaceObject("Earth", "Earth"); objectList[3] = new GL3DSpaceObject("Moon", "Moon"); objectList[4] = new GL3DSpaceObject("Mars%20Barycenter", "Mars"); objectList[5] = new GL3DSpaceObject("Jupiter%20Barycenter", "Jupiter"); objectList[6] = new GL3DSpaceObject("Saturn%20Barycenter", "Saturn"); objectList[7] = new GL3DSpaceObject("Uranus%20Barycenter", "Uranus"); objectList[8] = new GL3DSpaceObject("Neptune%20Barycenter", "Neptune"); objectList[9] = new GL3DSpaceObject("Pluto%20Barycenter", "Pluto"); objectList[10] = new GL3DSpaceObject("STEREO%20Ahead", "STEREO Ahead"); objectList[11] = new GL3DSpaceObject("STEREO%20Behind", "STEREO Behind"); objectList[12] = new GL3DSpaceObject("Solar%20Orbiter", "Solar Orbiter"); objectList[13] = new GL3DSpaceObject("CHURYUMOV-GERASIMENKO", "67P/Churyumov-Gerasimenko"); } private GL3DSpaceObject(String urlName, String labelName) { this.urlName = urlName; this.labelName = labelName; } public String getUrlName() { return this.urlName; } @Override public String toString() { return this.labelName; } }
package org.helioviewer.jhv.camera; import java.util.Date; import org.helioviewer.base.math.GL3DQuatd; import org.helioviewer.base.math.GL3DVec3d; import org.helioviewer.base.physics.Astronomy; import org.helioviewer.base.physics.Constants; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.display.TimeListener; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.LayersModel; import org.helioviewer.jhv.renderable.components.RenderableCamera; import org.helioviewer.viewmodel.view.AbstractView; import org.helioviewer.viewmodel.view.jp2view.JHVJPXView; public class GL3DExpertCamera extends GL3DCamera implements LayersListener, TimeListener { private final GL3DExpertCameraOptionPanel followObjectCameraOptionPanel; private final GL3DPositionLoading positionLoading; private double currentL = 0.; private double currentB = 0.; private double currentDistance = Constants.SunMeanDistanceToEarth / Constants.SunRadius; private Date cameraDate; private boolean interpolation; public GL3DExpertCamera() { super(); followObjectCameraOptionPanel = new GL3DExpertCameraOptionPanel(this); positionLoading = new GL3DPositionLoading(this); LayersModel.addLayersListener(this); this.timeChanged(Displayer.getLastUpdatedTimestamp()); followObjectCameraOptionPanel.syncWithLayerBeginTime(false); followObjectCameraOptionPanel.syncWithLayerEndTime(true); } @Override public void reset() { forceTimeChanged(cameraDate); super.reset(); } @Override public void activate(GL3DCamera precedingCamera) { super.activate(precedingCamera); this.activeLayerChanged(LayersModel.getActiveView()); this.timeChanged(Displayer.getLastUpdatedTimestamp()); Displayer.addFirstTimeListener(this); } @Override public void deactivate() { super.deactivate(); Displayer.removeTimeListener(this); } @Override public String getName() { return "Follow object camera"; } @Override public void timeChanged(Date date) { if (!this.getTrackingMode()) { forceTimeChanged(date); } } public void forceTimeChanged(Date date) { if (date != null && this.positionLoading.isLoaded()) { long currentCameraTime, dateTime = date.getTime(); if (interpolation) { long t1 = 0, t2 = 0; // Active layer times AbstractView view = LayersModel.getActiveView(); if (view instanceof JHVJPXView) { t1 = LayersModel.getStartDate(view).getTime(); t2 = LayersModel.getEndDate(view).getTime(); } //Camera times long t3 = this.positionLoading.getBeginDate().getTime(); long t4 = this.positionLoading.getEndDate().getTime(); if (t2 != t1) { currentCameraTime = (long) (t3 + (t4 - t3) * (dateTime - t1) / (double) (t2 - t1)); } else { currentCameraTime = t4; } } else { currentCameraTime = dateTime; } cameraDate = new Date(currentCameraTime); RenderableCamera renderableCamera = ImageViewerGui.getRenderableCamera(); if (renderableCamera != null) { renderableCamera.setTimeString(cameraDate); ImageViewerGui.getRenderableContainer().fireTimeUpdated(renderableCamera); } GL3DVec3d position = this.positionLoading.getInterpolatedPosition(currentCameraTime); if (position != null) { currentL = position.y; currentB = -position.z; currentDistance = position.x; updateRotation(date); } } else if (date != null) { currentL = 0; currentB = Astronomy.getB0Radians(date); currentDistance = Astronomy.getDistanceSolarRadii(date); updateRotation(date); } } private void updateRotation(Date date) { double currentRotation = (-currentL + Astronomy.getL0Radians(date)) % (Math.PI * 2.0); GL3DQuatd newRotation = GL3DQuatd.createRotation(-currentB, GL3DVec3d.XAxis); newRotation.rotate(GL3DQuatd.createRotation(currentRotation, GL3DVec3d.YAxis)); this.setLocalRotation(newRotation); this.setZTranslation(-currentDistance); this.updateCameraTransformation(); } public void fireNewLoaded(String state) { followObjectCameraOptionPanel.fireLoaded(state); Displayer.render(); } public void setBeginDate(Date date, boolean applyChanges) { this.positionLoading.setBeginDate(date, applyChanges); } public void setEndDate(Date date, boolean applyChanges) { this.positionLoading.setEndDate(date, applyChanges); } public void setObservingObject(String object, boolean applyChanges) { this.positionLoading.setObserver(object, applyChanges); } public void setInterpolation(boolean interpolation) { this.interpolation = interpolation; } @Override public void layerAdded(int idx) { } @Override public void layerRemoved(int oldIdx) { } @Override public void activeLayerChanged(AbstractView view) { if (!interpolation && view instanceof JHVJPXView) { positionLoading.setBeginDate(LayersModel.getStartDate(view), false); positionLoading.setEndDate(LayersModel.getEndDate(view), true); } } public Date getBeginTime() { return this.positionLoading.getBeginDate(); } public Date getEndTime() { return this.positionLoading.getEndDate(); } @Override public GL3DCameraOptionPanel getOptionPanel() { return followObjectCameraOptionPanel; } }
package org.opennms.features.topology.plugins.topo.vmware.internal; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.opennms.features.topology.api.GraphContainer; import org.opennms.features.topology.api.OperationContext; import org.opennms.features.topology.api.support.VertexHopGraphProvider; import org.opennms.features.topology.api.topo.AbstractVertex; import org.opennms.features.topology.api.topo.Edge; import org.opennms.features.topology.api.topo.EdgeRef; import org.opennms.features.topology.api.topo.GraphProvider; import org.opennms.features.topology.api.topo.SearchProvider; import org.opennms.features.topology.api.topo.SearchQuery; import org.opennms.features.topology.api.topo.SearchResult; import org.opennms.features.topology.api.topo.Vertex; import org.opennms.features.topology.api.topo.VertexRef; import org.opennms.features.topology.plugins.topo.simple.SimpleGraphProvider; import org.opennms.netmgt.dao.api.IpInterfaceDao; import org.opennms.netmgt.dao.api.NodeDao; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; public class VmwareTopologyProvider extends SimpleGraphProvider implements GraphProvider, SearchProvider { public static final String TOPOLOGY_NAMESPACE_VMWARE = "vmware"; private static final Logger LOG = LoggerFactory.getLogger(VmwareTopologyProvider.class); private static final String SPLIT_REGEXP = " *, *"; private NodeDao m_nodeDao; private IpInterfaceDao m_ipInterfaceDao; private boolean m_generated = false; public VmwareTopologyProvider() { super(TOPOLOGY_NAMESPACE_VMWARE); } public NodeDao getNodeDao() { return m_nodeDao; } public void setNodeDao(NodeDao nodeDao) { m_nodeDao = nodeDao; } public IpInterfaceDao getIpInterfaceDao() { return m_ipInterfaceDao; } public void setIpInterfaceDao(IpInterfaceDao ipInterfaceDao) { m_ipInterfaceDao = ipInterfaceDao; } public boolean isGenerated() { return m_generated; } public void debug(Vertex vmwareVertex) { LOG.debug("-+- id: {}", vmwareVertex.getId()); LOG.debug(" |- hashCode: {}", vmwareVertex.hashCode()); LOG.debug(" |- label: {}", vmwareVertex.getLabel()); LOG.debug(" |- ip: {}", vmwareVertex.getIpAddress()); LOG.debug(" |- iconKey: {}", vmwareVertex.getIconKey()); LOG.debug(" |- nodeId: {}", vmwareVertex.getNodeID()); for (EdgeRef edge : getEdgeIdsForVertex(vmwareVertex)) { Edge vmwareEdge = getEdge(edge); VertexRef edgeTo = vmwareEdge.getTarget().getVertex(); if (vmwareVertex.equals(edgeTo)) { edgeTo = vmwareEdge.getSource().getVertex(); } LOG.debug(" |- edgeTo: {}", edgeTo); } LOG.debug(" '- parent: {}", (vmwareVertex.getParent() == null ? null : vmwareVertex.getParent().getId())); } public void debugAll() { for (Vertex id : getVertices()) { debug(id); } } private AbstractVertex addDatacenterGroup(String vertexId, String groupName) { if (containsVertexId(vertexId)) { return (AbstractVertex) getVertex(TOPOLOGY_NAMESPACE_VMWARE, vertexId); } return addGroup(vertexId, "DATACENTER_ICON", groupName); } private AbstractVertex addNetworkVertex(String vertexId, String vertexName) { if (containsVertexId(vertexId)) { return (AbstractVertex) getVertex(TOPOLOGY_NAMESPACE_VMWARE, vertexId); } AbstractVertex vertex = addVertex(vertexId, 50, 50); vertex.setIconKey("NETWORK_ICON"); vertex.setLabel(vertexName); return vertex; } private AbstractVertex addDatastoreVertex(String vertexId, String vertexName) { if (containsVertexId(vertexId)) { return (AbstractVertex) getVertex(TOPOLOGY_NAMESPACE_VMWARE, vertexId); } AbstractVertex vertex = addVertex(vertexId, 50, 50); vertex.setIconKey("DATASTORE_ICON"); vertex.setLabel(vertexName); return vertex; } private AbstractVertex addVirtualMachineVertex(String vertexId, String vertexName, String primaryInterface, int id, String powerState) { if (containsVertexId(vertexId)) { return (AbstractVertex) getVertex(TOPOLOGY_NAMESPACE_VMWARE, vertexId); } String icon = "VIRTUALMACHINE_ICON_UNKNOWN"; if ("poweredOn".equals(powerState)) { icon = "VIRTUALMACHINE_ICON_ON"; } else if ("poweredOff".equals(powerState)) { icon = "VIRTUALMACHINE_ICON_OFF"; } else if ("suspended".equals(powerState)) { icon = "VIRTUALMACHINE_ICON_SUSPENDED"; } AbstractVertex vertex = addVertex(vertexId, 50, 50); vertex.setIconKey(icon); vertex.setLabel(vertexName); vertex.setIpAddress(primaryInterface); vertex.setNodeID(id); return vertex; } private AbstractVertex addHostSystemVertex(String vertexId, String vertexName, String primaryInterface, int id, String powerState) { if (containsVertexId(vertexId)) { return (AbstractVertex) getVertex(TOPOLOGY_NAMESPACE_VMWARE, vertexId); } String icon = "HOSTSYSTEM_ICON_UNKNOWN"; if ("poweredOn".equals(powerState)) { icon = "HOSTSYSTEM_ICON_ON"; } else if ("poweredOff".equals(powerState)) { icon = "HOSTSYSTEM_ICON_OFF"; } else if ("standBy".equals(powerState)) { icon = "HOSTSYSTEM_ICON_STANDBY"; } AbstractVertex vertex = addVertex(vertexId, 50, 50); vertex.setIconKey(icon); vertex.setLabel(vertexName); vertex.setIpAddress(primaryInterface); vertex.setNodeID(id); return vertex; } private void addHostSystem(OnmsNode hostSystem) { // getting data for nodes String vmwareManagementServer = hostSystem.getAssetRecord().getVmwareManagementServer().trim(); String vmwareManagedObjectId = hostSystem.getAssetRecord().getVmwareManagedObjectId().trim(); String vmwareTopologyInfo = hostSystem.getAssetRecord().getVmwareTopologyInfo().trim(); String vmwareState = hostSystem.getAssetRecord().getVmwareState().trim(); String datacenterMoId = null; String datacenterName = "Datacenter (" + vmwareManagementServer + ")"; ArrayList<String> networks = new ArrayList<String>(); ArrayList<String> datastores = new ArrayList<String>(); HashMap<String, String> moIdToName = new HashMap<String, String>(); String[] entities = vmwareTopologyInfo.split(SPLIT_REGEXP); for (String entityAndName : entities) { String[] splitBySlash = entityAndName.split("/"); String entityId = splitBySlash[0]; String entityName = "unknown"; if (splitBySlash.length > 1) { try { entityName = new String(URLDecoder.decode(splitBySlash[1], "UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } } String entityType = entityId.split("-")[0]; if ("network".equals(entityType)) { networks.add(entityId); } if ("datastore".equals(entityType)) { datastores.add(entityId); } if ("datacenter".equals(entityType)) { datacenterMoId = entityId; } moIdToName.put(entityId, entityName); } if (datacenterMoId != null) { datacenterName = moIdToName.get(datacenterMoId) + " (" + vmwareManagementServer + ")"; } AbstractVertex datacenterVertex = addDatacenterGroup(vmwareManagementServer, datacenterName); String primaryInterface = "unknown"; // get the primary interface ip address OnmsIpInterface ipInterface = m_ipInterfaceDao.findPrimaryInterfaceByNodeId(hostSystem.getId()); if (ipInterface != null) { primaryInterface = ipInterface.getIpHostName(); } AbstractVertex hostSystemVertex = addHostSystemVertex(vmwareManagementServer + "/" + vmwareManagedObjectId, hostSystem.getLabel(), primaryInterface, hostSystem.getId(), vmwareState); // set the parent vertex // hostSystemVertex.setParent(datacenterVertex); if (!hostSystemVertex.equals(datacenterVertex)) setParent(hostSystemVertex, datacenterVertex); for (String network : networks) { AbstractVertex networkVertex = addNetworkVertex(vmwareManagementServer + "/" + network, moIdToName.get(network)); // networkVertex.setParent(datacenterVertex); if (!networkVertex.equals(datacenterVertex)) setParent(networkVertex, datacenterVertex); connectVertices(vmwareManagementServer + "/" + vmwareManagedObjectId + "->" + network, hostSystemVertex, networkVertex); } for (String datastore : datastores) { AbstractVertex datastoreVertex = addDatastoreVertex(vmwareManagementServer + "/" + datastore, moIdToName.get(datastore)); // datastoreVertex.setParent(datacenterVertex); if (!datastoreVertex.equals(datacenterVertex)) setParent(datastoreVertex, datacenterVertex); connectVertices(vmwareManagementServer + "/" + vmwareManagedObjectId + "->" + datastore, hostSystemVertex, datastoreVertex); } } private void addVirtualMachine(OnmsNode virtualMachine) { // getting data for nodes String vmwareManagementServer = virtualMachine.getAssetRecord().getVmwareManagementServer().trim(); String vmwareManagedObjectId = virtualMachine.getAssetRecord().getVmwareManagedObjectId().trim(); String vmwareTopologyInfo = virtualMachine.getAssetRecord().getVmwareTopologyInfo().trim(); String vmwareState = virtualMachine.getAssetRecord().getVmwareState().trim(); String datacenterMoId = null; String datacenterName = "Datacenter (" + vmwareManagementServer + ")"; String vmwareHostSystemId = null; ArrayList<String> networks = new ArrayList<String>(); ArrayList<String> datastores = new ArrayList<String>(); HashMap<String, String> moIdToName = new HashMap<String, String>(); String[] entities = vmwareTopologyInfo.split(SPLIT_REGEXP); for (String entityAndName : entities) { String[] splitBySlash = entityAndName.split("/"); String entityId = splitBySlash[0]; String entityName = "unknown"; if (splitBySlash.length > 1) { try { entityName = new String(URLDecoder.decode(splitBySlash[1], "UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } } String entityType = entityId.split("-")[0]; if ("network".equals(entityType)) { networks.add(entityId); } if ("datastore".equals(entityType)) { datastores.add(entityId); } if ("datacenter".equals(entityType)) { datacenterMoId = entityId; } if ("host".equals(entityType)) { vmwareHostSystemId = entityId; } moIdToName.put(entityId, entityName); } if (datacenterMoId != null) { datacenterName = moIdToName.get(datacenterMoId) + " (" + vmwareManagementServer + ")"; } if (vmwareHostSystemId == null) { LOG.warn("Cannot find host system id for virtual machine {}/{}", vmwareManagementServer, vmwareManagedObjectId); } AbstractVertex datacenterVertex = addDatacenterGroup(vmwareManagementServer, datacenterName); String primaryInterface = "unknown"; // get the primary interface ip address OnmsIpInterface ipInterface = m_ipInterfaceDao.findPrimaryInterfaceByNodeId(virtualMachine.getId()); if (ipInterface != null) { primaryInterface = ipInterface.getIpHostName(); } // add a vertex for the virtual machine AbstractVertex virtualMachineVertex = addVirtualMachineVertex(vmwareManagementServer + "/" + vmwareManagedObjectId, virtualMachine.getLabel(), primaryInterface, virtualMachine.getId(), vmwareState); if (containsVertexId(vmwareManagementServer + "/" + vmwareHostSystemId)) { // and set the parent vertex // virtualMachineVertex.setParent(datacenterVertex); if (!virtualMachineVertex.equals(datacenterVertex)) setParent(virtualMachineVertex, datacenterVertex); } else { addHostSystemVertex(vmwareManagementServer + "/" + vmwareHostSystemId, moIdToName.get(vmwareHostSystemId) + " (not in database)", "", -1, "unknown"); } // connect the virtual machine to the host system connectVertices(vmwareManagementServer + "/" + vmwareManagedObjectId + "->" + vmwareManagementServer + "/" + vmwareHostSystemId, virtualMachineVertex, getVertex(getVertexNamespace(), vmwareManagementServer + "/" + vmwareHostSystemId)); } @Override public void refresh() { m_generated = true; resetContainer(); // get all host systems List<OnmsNode> hostSystems = m_nodeDao.findAllByVarCharAssetColumn("vmwareManagedEntityType", "HostSystem"); if (hostSystems.isEmpty()) { LOG.info("refresh: No host systems with defined VMware assets fields found!"); } else { for (OnmsNode hostSystem : hostSystems) { addHostSystem(hostSystem); } } // get all virtual machines List<OnmsNode> virtualMachines = m_nodeDao.findAllByVarCharAssetColumn("vmwareManagedEntityType", "VirtualMachine"); if (virtualMachines.isEmpty()) { LOG.info("refresh: No virtual machines with defined VMware assets fields found!"); } else { for (OnmsNode virtualMachine : virtualMachines) { addVirtualMachine(virtualMachine); } } debugAll(); } @Override public void onFocusSearchResult(SearchResult searchResult, OperationContext operationContext) { GraphContainer m_graphContainer = operationContext.getGraphContainer(); VertexRef vertexRef = getVertex(searchResult.getNamespace(), searchResult.getId()); m_graphContainer.getSelectionManager().setSelectedVertexRefs(Lists.newArrayList(vertexRef)); } @Override public void onDefocusSearchResult(SearchResult searchResult, OperationContext operationContext) { GraphContainer graphContainer = operationContext.getGraphContainer(); VertexRef vertexRef = getVertex(searchResult.getNamespace(), searchResult.getId()); graphContainer.getSelectionManager().deselectVertexRefs(Lists.newArrayList(vertexRef)); } @Override public void onCenterSearchResult(final SearchResult searchResult, final GraphContainer graphContainer) { // TODO: implement? } @Override public void onToggleCollapse(final SearchResult searchResult, final GraphContainer graphContainer) { // TODO: implement? } @Override public String getSearchProviderNamespace() { return "vmware"; } @Override public boolean supportsPrefix(String searchPrefix) { return searchPrefix.contains("nodes="); } @Override public List<VertexRef> getVertexRefsBy(SearchResult searchResult) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void addVertexHopCriteria(SearchResult searchResult, GraphContainer container) { VertexHopGraphProvider.FocusNodeHopCriteria criteria = VertexHopGraphProvider.getFocusNodeHopCriteriaForContainer(container); criteria.add(getVertex(searchResult.getNamespace(), searchResult.getId())); } @Override public void removeVertexHopCriteria(SearchResult searchResult, GraphContainer container) { VertexHopGraphProvider.FocusNodeHopCriteria criteria = VertexHopGraphProvider.getFocusNodeHopCriteriaForContainer(container); criteria.remove(getVertex(searchResult.getNamespace(), searchResult.getLabel())); } @Override public List<SearchResult> query(SearchQuery searchQuery) { List<Vertex> vertices = m_vertexProvider.getVertices(); List<SearchResult> searchResults = Lists.newArrayList(); for(Vertex vertex : vertices){ if(searchQuery.matches(vertex.getLabel())) { searchResults.add(new SearchResult(vertex)); } } return searchResults; } }
package org.xwiki.rendering.internal.macro.rss; import java.io.File; import java.io.FileInputStream; import java.util.Collections; import java.util.List; import javax.inject.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.properties.internal.DefaultBeanManager; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.GroupBlock; import org.xwiki.rendering.block.ImageBlock; import org.xwiki.rendering.block.LinkBlock; import org.xwiki.rendering.block.NewLineBlock; import org.xwiki.rendering.block.ParagraphBlock; import org.xwiki.rendering.block.RawBlock; import org.xwiki.rendering.block.WordBlock; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.listener.reference.ResourceType; import org.xwiki.rendering.macro.MacroContentParser; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.macro.rss.RssMacroParameters; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.transformation.MacroTransformationContext; import org.xwiki.test.annotation.ComponentList; import org.xwiki.test.junit5.mockito.ComponentTest; import org.xwiki.test.junit5.mockito.InjectMockComponents; import org.xwiki.test.junit5.mockito.MockComponent; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit tests for {@link RssMacro}. * * @version $Id$ * @since 1.9 */ @ComponentTest @ComponentList({ DefaultBeanManager.class }) public class RssMacroTest { @InjectMockComponents private RssMacro macro; @MockComponent private Execution execution; @MockComponent private ExecutionContext context; @MockComponent @Named("plain/1.0") private Parser plainTextParser; @MockComponent private MacroContentParser contentParser; @Mock private RomeFeedFactory romeFeedFactory; @BeforeEach public void setup() { when(execution.getContext()).thenReturn(context); } /** * Tests whether the macro throws the appropriate exception * in cases where the required 'feed' parameter is missing. */ @Test public void testRequiredParameterMissing() throws Exception { Throwable exception = assertThrows(MacroExecutionException.class, () -> { this.macro.execute(new RssMacroParameters(), null, null); }); assertEquals("The required 'feed' parameter is missing", exception.getMessage()); } /** * Tests the macro's behavior when the server hosting the feeds doesn't respond. */ @Test public void testInvalidDocument() throws Exception { final RssMacroParameters parameters = new RssMacroParameters(); MacroExecutionException expectedException = new MacroExecutionException("Error"); when(romeFeedFactory.createFeed(parameters)).thenThrow(expectedException); this.macro.setFeedFactory(romeFeedFactory); // Dummy URL since a feed URL is mandatory parameters.setFeed("http: Throwable exception = assertThrows(MacroExecutionException.class, () -> { this.macro.execute(parameters, null, null); }); assertSame(expectedException, exception); } @Test public void execute() throws Exception { RssMacroParameters rssMacroParameters = new RssMacroParameters(); rssMacroParameters.setContent(true); rssMacroParameters.setCount(4); rssMacroParameters.setImage(true); rssMacroParameters.setWidth("100"); rssMacroParameters.setEncoding("UTF-8"); rssMacroParameters.setDecoration(true); rssMacroParameters.setFeed("http: MacroTransformationContext macroTransformationContext = mock(MacroTransformationContext.class); File feedFile = new File("src/test/resources/feed1.xml"); SyndFeed syndFeed = new SyndFeedInput().build(new XmlReader(new FileInputStream(feedFile), true, rssMacroParameters.getEncoding())); when(romeFeedFactory.createFeed(rssMacroParameters)).thenReturn(syndFeed); when(context.getProperty("RssMacro.feed")).thenReturn(syndFeed); this.macro.setFeedFactory(romeFeedFactory); List<Block> expectedBlockList = Collections.singletonList( new GroupBlock(Collections.singletonList(new WordBlock("foo"))) ); when(plainTextParser.parse(any())).thenReturn(new XDOM(expectedBlockList)); when(contentParser.parse("Some content", macroTransformationContext, false, false)) .thenReturn(new XDOM(expectedBlockList)); List<Block> obtainedContent = this.macro.execute(rssMacroParameters, "Some content", macroTransformationContext); assertEquals(1, obtainedContent.size()); GroupBlock groupBlock = (GroupBlock) obtainedContent.get(0); // checking main parameters assertEquals("box rssfeed", groupBlock.getParameter("class")); assertEquals("width:100", groupBlock.getParameter("style")); // start checking children List<Block> children = groupBlock.getChildren(); assertEquals(12, children.size()); // checking created image assertTrue(children.get(0) instanceof ImageBlock); ImageBlock imageBlock = (ImageBlock) children.get(0); assertEquals("http: assertTrue(children.get(1) instanceof NewLineBlock); // checking first paragraph and first group presenting channel description assertTrue(children.get(2) instanceof ParagraphBlock); ParagraphBlock paragraphBlock = (ParagraphBlock) children.get(2); assertEquals("rsschanneltitle", paragraphBlock.getParameter("class")); assertEquals(2, paragraphBlock.getChildren().size()); assertTrue(paragraphBlock.getChildren().get(0) instanceof LinkBlock); LinkBlock firstLink = (LinkBlock) paragraphBlock.getChildren().get(0); assertEquals("http://liftoff.msfc.nasa.gov/", firstLink.getReference().getReference()); assertEquals(ResourceType.URL, firstLink.getReference().getType()); assertEquals(1, firstLink.getChildren().size()); assertEquals(new WordBlock("foo"), firstLink.getChildren().get(0)); assertTrue(paragraphBlock.getChildren().get(1) instanceof LinkBlock); LinkBlock secondLink = (LinkBlock) paragraphBlock.getChildren().get(1); assertEquals("http://liftoff.msfc.nasa.gov/", secondLink.getReference().getReference()); assertEquals(ResourceType.URL, secondLink.getReference().getType()); assertEquals(1, secondLink.getChildren().size()); assertTrue(secondLink.getChildren().get(0) instanceof ImageBlock); assertEquals(expectedBlockList.get(0), children.get(3)); // checking second paragraph presenting first item link assertTrue(children.get(4) instanceof ParagraphBlock); paragraphBlock = (ParagraphBlock) children.get(4); assertEquals("rssitemtitle", paragraphBlock.getParameter("class")); assertEquals(1, paragraphBlock.getChildren().size()); assertTrue(paragraphBlock.getChildren().get(0) instanceof LinkBlock); firstLink = (LinkBlock) paragraphBlock.getChildren().get(0); assertEquals("http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp", firstLink.getReference().getReference()); assertEquals(ResourceType.URL, firstLink.getReference().getType()); assertEquals(1, firstLink.getChildren().size()); assertEquals(new WordBlock("foo"), firstLink.getChildren().get(0)); // checking second group block presenting first item description assertTrue(children.get(5) instanceof GroupBlock); groupBlock = (GroupBlock) children.get(5); assertEquals("rssitemdescription", groupBlock.getParameter("class")); assertEquals(1, groupBlock.getChildren().size()); assertEquals( new RawBlock("How do Americans get ready to work with Russians aboard the International Space Station?", Syntax.XHTML_1_0), groupBlock.getChildren().get(0)); } }
package br.com.fourdev.orderfood.model; public enum StatusMesa { DISPONIVEL("Disponivel"), OCUPADA("Ocupada"); private String descricao; private StatusMesa(String descricao) { this.descricao = descricao; } }
package codemining.java.codeutils; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map.Entry; import java.util.SortedMap; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringEscapeUtils; import codemining.java.tokenizers.JavaTokenizer; import codemining.languagetools.ColoredToken; import codemining.languagetools.ITokenizer; import codemining.languagetools.ITokenizer.FullToken; import codemining.util.SettingsLoader; /** * Output java code to HTML with optional coloring. Not thread-safe. * * @author Miltos Allamanis <m.allamanis@ed.ac.uk> * */ public class JavaCodePrinter { /** * The tokenizer used to tokenize code. */ final ITokenizer jTokenizer; /** * The background Color of the output HTML document. */ final Color documentBackgroundColor; int lineNumber = 1; private final boolean ignoreTokBG = SettingsLoader.getBooleanSetting( "ignoreTokenBackground", true); public static final String CSS_STYLE = "<style>\n.line {font-family:monospace; " + "font: 14px/1.3 \"Source Code Pro\", \"Fira Mono OT\", monospace;white-space:pre;}\n" + ".line:hover {font-family:monospace; " + "font: 14px/1.3 \"Source Code Pro\", \"Fira Mono OT\", monospace;white-space:pre; background-color:rgb(240,240,240);}\n" + "</style>"; public JavaCodePrinter() { jTokenizer = new JavaTokenizer(); documentBackgroundColor = Color.WHITE; } public JavaCodePrinter(final Color documentBackgroundColor) { jTokenizer = new JavaTokenizer(); this.documentBackgroundColor = documentBackgroundColor; } public JavaCodePrinter(final ITokenizer tokenizer, final Color documentBackgroundColor) { this.jTokenizer = tokenizer; this.documentBackgroundColor = documentBackgroundColor; } private void addSlack(final String substring, final StringBuffer buf) { for (final char c : StringEscapeUtils.escapeHtml(substring) .toCharArray()) { if (c == '\n') { appendLineDiv(buf, true); } else { buf.append(c); } } } private void appendLineDiv(final StringBuffer buf, final boolean closePrevious) { if (closePrevious) { buf.append("<br/></div>\n"); } buf.append("<div class='line' id='C" + lineNumber + "'>"); lineNumber++; } /** * Return a StringBuffer with colored tokens as specified from the * coloredTokens. There should be one-to-one correspondence with the actual * tokens. */ public StringBuffer writeHTMLwithColors( final List<ColoredToken> coloredTokens, final File codeFile) throws IOException, InstantiationException, IllegalAccessException { final String code = FileUtils.readFileToString(codeFile); lineNumber = 1; final StringBuffer buf = new StringBuffer(); final SortedMap<Integer, FullToken> toks = jTokenizer .fullTokenListWithPos(code.toCharArray()); int i = 0; int prevPos = 0; buf.append("<html>\n<head>\n<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400,500,600,700,800,900' rel='stylesheet' type='text/css'>\n"); buf.append(CSS_STYLE); buf.append("</head>\n<body style='background-color:rgb(" + documentBackgroundColor.getRed() + "," + documentBackgroundColor.getGreen() + "," + documentBackgroundColor.getBlue() + ")'>"); appendLineDiv(buf, false); for (final Entry<Integer, FullToken> entry : toks.entrySet()) { if (i == 0 || entry.getKey() == Integer.MAX_VALUE) { i++; continue; } addSlack(code.substring(prevPos, entry.getKey()), buf); final ColoredToken tok = coloredTokens.get(i); buf.append("<span style='background-color:rgba(" + tok.bgColor.getRed() + "," + tok.bgColor.getGreen() + "," + tok.bgColor.getBlue() + "," + (ignoreTokBG ? "0" : "1") + "); color:rgb(" + tok.fontColor.getRed() + "," + tok.fontColor.getGreen() + "," + tok.fontColor.getBlue() + "); " + tok.extraStyle + "'>" + StringEscapeUtils.escapeHtml(entry.getValue().token) + "</span>"); i++; prevPos = entry.getKey() + entry.getValue().token.length(); } buf.append("</div></body></html>"); return buf; } }
package com.amee.service.item; import com.amee.base.domain.ResultsWrapper; import com.amee.base.transaction.TransactionController; import com.amee.base.utils.UidGen; import com.amee.domain.*; import com.amee.domain.data.*; import com.amee.domain.item.BaseItem; import com.amee.domain.item.BaseItemValue; import com.amee.domain.item.HistoryValue; import com.amee.domain.item.data.BaseDataItemValue; import com.amee.domain.item.data.DataItem; import com.amee.domain.item.data.DataItemNumberValue; import com.amee.domain.item.data.DataItemTextValue; import com.amee.domain.sheet.Choice; import com.amee.domain.sheet.Choices; import com.amee.platform.science.ExternalHistoryValue; import com.amee.platform.science.StartEndDate; import com.amee.service.invalidation.InvalidationService; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; @Service public class DataItemServiceImpl extends AbstractItemService implements DataItemService { private final Log log = LogFactory.getLog(getClass()); @Autowired private TransactionController transactionController; @Autowired private InvalidationService invalidationService; @Autowired private DataItemServiceDAO dao; @Override public long getDataItemCount(IDataCategoryReference dataCategory) { return dao.getDataItemCount(dataCategory); } @Override public List<DataItem> getDataItems(IDataCategoryReference dataCategory) { return getDataItems(dataCategory, true); } @Override public List<DataItem> getDataItems(IDataCategoryReference dataCategory, boolean checkDataItems) { return activeDataItems(dao.getDataItems(dataCategory), checkDataItems, true); } @Override @SuppressWarnings(value = "unchecked") public List<DataItem> getDataItems(Set<Long> dataItemIds) { return activeDataItems(dao.getDataItems(dataItemIds), false, true); } @Override @SuppressWarnings(value = "unchecked") public Map<String, DataItem> getDataItemMap(Set<Long> dataItemIds, boolean loadValues) { Map<String, DataItem> dataItemMap = new HashMap<String, DataItem>(); Set<BaseItemValue> dataItemValues = new HashSet<BaseItemValue>(); // Load all DataItems and BaseItemValues, if required. List<DataItem> dataItems = activeDataItems(dao.getDataItems(dataItemIds), false, loadValues); // Add DataItems to map. Add BaseItemValue, if required. for (DataItem dataItem : dataItems) { dataItemMap.put(dataItem.getUid(), dataItem); if (loadValues) { dataItemValues.addAll(getItemValues(dataItem)); } } localeService.loadLocaleNamesForDataItems(dataItemMap.values(), dataItemValues); return dataItemMap; } private List<DataItem> activeDataItems(List<DataItem> dataItems, boolean checkDataItems, boolean loadValues) { List<DataItem> activeDataItems = new ArrayList<DataItem>(); for (DataItem dataItem : dataItems) { if (!dataItem.isTrash()) { if (checkDataItems) { checkDataItem(dataItem); } activeDataItems.add(dataItem); } } if (loadValues) { loadItemValuesForItems((List) activeDataItems); } localeService.loadLocaleNamesForDataItems(activeDataItems); return activeDataItems; } @Override public DataItem getDataItemByIdentifier(DataCategory parent, String path) { DataItem dataItem = null; if (!StringUtils.isBlank(path)) { if (UidGen.INSTANCE_12.isValid(path)) { dataItem = getDataItemByUid(parent, path); } if (dataItem == null) { dataItem = getDataItemByPath(parent, path); } } return dataItem; } @Override public DataItem getDataItemByUid(DataCategory parent, String uid) { DataItem dataItem = getItemByUid(uid); if ((dataItem != null) && dataItem.getDataCategory().equals(parent)) { return dataItem; } else { return null; } } @Override public DataItem getItemByUid(String uid) { DataItem dataItem = dao.getItemByUid(uid); if ((dataItem != null) && (!dataItem.isTrash())) { checkDataItem(dataItem); return dataItem; } else { return null; } } @Override public DataItem getDataItemByPath(DataCategory parent, String path) { DataItem dataItem = dao.getDataItemByPath(parent, path); if ((dataItem != null) && !dataItem.isTrash()) { checkDataItem(dataItem); return dataItem; } else { return null; } } @Override public String getLabel(DataItem dataItem) { String label = ""; BaseItemValue itemValue; ItemDefinition itemDefinition = dataItem.getItemDefinition(); for (Choice choice : itemDefinition.getDrillDownChoices()) { itemValue = getItemValue(dataItem, choice.getName()); if ((itemValue != null) && (itemValue.getValueAsString().length() > 0) && !itemValue.getValueAsString().equals("-")) { if (label.length() > 0) { label = label.concat(", "); } label = label.concat(itemValue.getValueAsString()); } } if (label.length() == 0) { label = dataItem.getDisplayPath(); } return label; } @Override public Choices getUserValueChoices(DataItem dataItem, APIVersion apiVersion) { List<Choice> userValueChoices = new ArrayList<Choice>(); for (ItemValueDefinition ivd : dataItem.getItemDefinition().getItemValueDefinitions()) { if (ivd.isFromProfile() && ivd.isValidInAPIVersion(apiVersion)) { // start default value with value from ItemValueDefinition String defaultValue = ivd.getValue(); // next give DataItem a chance to set the default value, if appropriate if (ivd.isFromData()) { BaseItemValue dataItemValue = getItemValue(dataItem, ivd.getPath()); if ((dataItemValue != null) && (dataItemValue.getValueAsString().length() > 0)) { defaultValue = dataItemValue.getValueAsString(); } } // create Choice userValueChoices.add(new Choice(ivd.getPath(), defaultValue)); } } return new Choices("userValueChoices", userValueChoices); } /** * Add to the {@link com.amee.domain.item.data.DataItem} any {@link com.amee.domain.item.data.BaseDataItemValue}s it is missing. * This will be the case on first persist (this method acting as a reification function), and between GETs if any * new {@link com.amee.domain.data.ItemValueDefinition}s have been added to the underlying * {@link com.amee.domain.data.ItemDefinition}. * <p/> * Any updates to the {@link com.amee.domain.item.data.DataItem} will be persisted to the database. * * @param dataItem - the DataItem to check */ @SuppressWarnings(value = "unchecked") public void checkDataItem(DataItem dataItem) { if (dataItem == null) { return; } Set<ItemValueDefinition> existingItemValueDefinitions = getItemValueDefinitionsInUse(dataItem); Set<ItemValueDefinition> missingItemValueDefinitions = new HashSet<ItemValueDefinition>(); // find ItemValueDefinitions not currently implemented in this Item for (ItemValueDefinition ivd : dataItem.getItemDefinition().getItemValueDefinitions()) { if (ivd.isFromData()) { if (!existingItemValueDefinitions.contains(ivd)) { missingItemValueDefinitions.add(ivd); } } } // Do we need to add any ItemValueDefinitions? if (missingItemValueDefinitions.size() > 0) { // Ensure a transaction has been opened. The implementation of open-session-in-view we are using // does not open transactions for GETs. This method is called for certain GETs. transactionController.begin(true); // create missing ItemValues for (ItemValueDefinition ivd : missingItemValueDefinitions) { BaseDataItemValue itemValue; // Create a value. if (ivd.getValueDefinition().getValueType().equals(ValueType.INTEGER) || ivd.getValueDefinition().getValueType().equals(ValueType.DOUBLE)) { // Item is a number. itemValue = new DataItemNumberValue(ivd, dataItem); } else { // Item is text. itemValue = new DataItemTextValue(ivd, dataItem, ""); } persist(itemValue); } // clear caches clearItemValues(); invalidationService.add(dataItem.getDataCategory()); } } /** * Returns the most recent modified timestamp of DataItems for the supplied DataCategory. Will return the * date of the epoch if there are no matching DataItems. * * @param dataCategory to get modified timestamp for * @return most recent modified timestamp or the epoch value if not available. */ @Override public Date getDataItemsModified(DataCategory dataCategory) { Date modified = dao.getDataItemsModified(dataCategory); if (modified == null) { modified = DataItemService.EPOCH; } return modified; } /** * Returns true if the path of the supplied DataItem is unique amongst peers with the same * DataCategory. Empty paths are always treated as 'unique'. * * @param dataItem to check for uniqueness * @return true if the DataItem has a unique path amongst peers or the path is simply empty */ @Override public boolean isDataItemUniqueByPath(DataItem dataItem) { return dataItem.getPath().isEmpty() || dao.isDataItemUniqueByPath(dataItem); } @Override public void remove(DataItem dataItem) { dataItem.setStatus(AMEEStatus.TRASH); } @Override public void persist(DataItem dataItem) { persist(dataItem, true); } @Override public void persist(DataItem dataItem, boolean checkDataItem) { dao.persist(dataItem); if (checkDataItem) { checkDataItem(dataItem); } } // ItemValues. @Override public ResultsWrapper<BaseDataItemValue> getAllItemValues(DataItemValuesFilter filter) { boolean handledFirst = false; boolean truncated = false; int count = 0; // Get *all* item value for the current DataItem and ItemValueDefinition. List<BaseItemValue> itemValues = new ArrayList<BaseItemValue>( getAllItemValues(filter.getDataItem(), filter.getItemValueDefinition().getPath())); // Sort so earliest item value comes first, based on the startDate. Collections.sort(itemValues, new BaseItemValueStartDateComparator()); // Create and populate a ResultsWrapper. List<BaseDataItemValue> results = new ArrayList<BaseDataItemValue>(); for (BaseItemValue biv : itemValues) { BaseDataItemValue bdiv = (BaseDataItemValue) biv; if (BaseItemValueStartDateComparator.isHistoricValue(bdiv)) { ExternalHistoryValue ehv = (ExternalHistoryValue) bdiv; // At or beyond the start date? if (ehv.getStartDate().compareTo(filter.getStartDate()) >= 0) { // Before the end date? if (ehv.getStartDate().before(filter.getEndDate())) { // On or after the resultStart? if (count >= filter.getResultStart()) { // Before the resultLimit? if (results.size() < filter.getResultLimit()) { // Safe to add this item value. results.add(bdiv); } else { // Gone beyond the resultLimit. // The results are truncated and we can ignore the other item values. truncated = true; break; } } // Increment count of eligible item values. count++; } else { // Gone beyond the end date and we can ignore the other item values. break; } } else { // Before the start date. } } else { // We should only execute this section once. if (handledFirst) { // Should never get here. Implies that the list contains a non-historical item value // is in the wrong place in the list. throw new IllegalStateException("Unexpected non-historical item value: " + biv); } // On or after the resultStart? Filter at the epoch? if ((count >= filter.getResultStart()) && filter.getStartDate().equals(DataItemService.EPOCH)) { // This *must* be the first item value. results.add(bdiv); } // Increment count of eligible item values. count++; // We only work in this section once. handledFirst = true; } } // Create the ResultsWrapper and return. return new ResultsWrapper<BaseDataItemValue>(results, truncated); } @Override public boolean isDataItemValueUniqueByStartDate(BaseDataItemValue itemValue) { if (HistoryValue.class.isAssignableFrom(itemValue.getClass())) { HistoryValue historyValue = (HistoryValue) itemValue; for (BaseItemValue existingItemValue : getActiveItemValues(itemValue.getDataItem())) { if (existingItemValue.getItemValueDefinition().equals(itemValue.getItemValueDefinition()) && HistoryValue.class.isAssignableFrom(existingItemValue.getClass())) { HistoryValue existingHistoryValue = (HistoryValue) existingItemValue; if (!historyValue.equals(existingHistoryValue) && historyValue.getStartDate().equals(existingHistoryValue.getStartDate())) { return false; } } } return true; } else { throw new IllegalStateException("Should not be checking a non-historical DataItemValue."); } } /** * Get an {@link BaseItemValue} belonging to this Item using some identifier and prevailing datetime context. * * @param identifier - a value to be compared to the path and then the uid of the Item Values belonging * to this Item. * @return the matched {@link BaseItemValue} or NULL if no match is found. */ @Override public BaseItemValue getItemValue(BaseItem item, String identifier) { if (!DataItem.class.isAssignableFrom(item.getClass())) throw new IllegalStateException("A DataItem instance was expected."); return getItemValue(item, identifier, item.getEffectiveStartDate()); } /** * Updates the Data Item Values for the supplied DataItem based on the properties of the values * bean within the DataItem. Internally uses the Spring and Java beans API to access values in the * CGLIB created DataItem.values JavaBean. * <p/> * If a Data Item Value is modified then the Data Item is also marked as modified. * * @param dataItem to update */ @Override public void updateDataItemValues(DataItem dataItem) { boolean modified = false; Object values = dataItem.getValues(); ItemValueMap itemValues = getItemValuesMap(dataItem); for (String key : itemValues.keySet()) { BaseItemValue value = itemValues.get(key); PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(values.getClass(), key); if (pd != null) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { try { Object v = readMethod.invoke(values); if (v != null) { value.setValue(v.toString()); modified = true; } } catch (IllegalAccessException e) { throw new RuntimeException("Caught IllegalAccessException: " + e.getMessage()); } catch (InvocationTargetException e) { throw new RuntimeException("Caught InvocationTargetException: " + e.getMessage()); } } else { log.warn("updateDataItemValues() Write Method was null: " + key); } } else { log.warn("updateDataItemValues() PropertyDescriptor was null: " + key); } } // Mark the DataItem as modified. if (modified) { dataItem.onModify(); } } @Override public void persist(BaseItemValue itemValue) { dao.persist(itemValue); } @Override public void remove(BaseItemValue itemValue) { itemValue.setStatus(AMEEStatus.TRASH); } @Override public StartEndDate getStartDate(DataItem dataItem) { return null; } @Override public StartEndDate getEndDate(DataItem dataItem) { return null; } @Override protected DataItemServiceDAO getDao() { return dao; } /** * Checks if a DataItem already exists with the same drill down values. * NB: This method uses the transient values returned from com.amee.domain.item.data.DataItem#getValues() * * @param dataItem the DataItem to check for equivalents. * @return true if a DataItem already exists with the same category and drill down values. Otherwise, false. */ @Override public boolean equivalentDataItemExists(DataItem dataItem) { // Get a list of this data item's values for the drill downs. // The values for these values are null :-( List<String> drillDownPaths = getDrillDownPaths(dataItem); boolean isEqual = false; // Check the drilldown values for all existing data items for the same category. for (DataItem existingDataItem : getDataItems(dataItem.getDataCategory())) { // Ignore the one we just added. This is the one we are checking! if (existingDataItem.getUid().equals(dataItem.getUid())) { continue; } // Must have the same item definition to be considered a dupe. if (existingDataItem.getItemDefinition().equals(dataItem.getItemDefinition())) { // check if it has the same values for the drillDowns we have // Check the values for each choice. Map<String, String> newValues = new HashMap<String, String>(); Map<String, String> existingValues = new HashMap<String, String>(); // Create maps of new and existing values for (String path : drillDownPaths) { String newValue = null; // Use reflection to get the values. See: com.amee.domain.item.data.DataItem#getValues(). try { String pathMethod = "get" + StringUtils.capitalize(path); Method getter = dataItem.getValues().getClass().getMethod(pathMethod); newValue = String.valueOf(getter.invoke(dataItem.getValues())); } catch (Exception e) { throw new RuntimeException("equivalentDataItemExists() caught Exception: " + e.getMessage(), e); } newValues.put(path, newValue); String existingValue = getItemValue(existingDataItem, path).getValueAsString(); existingValues.put(path, existingValue); } isEqual = newValues.equals(existingValues); } } return isEqual; } /** * Get an {@code ItemValueMap} containing the given DataItem's DrillDown values. * * @param dataItem the DataItem to get the drilldown values for. * @return an ItemValueMap with the drilldown values. */ @Override public ItemValueMap getDrillDownValuesMap(DataItem dataItem) { // First get all the item values ItemValueMap allValuesMap = getItemValuesMap(dataItem); // Then make a new map with just the drillDowns values. ItemValueMap drillDownValuesMap = new ItemValueMap(); List<Choice> drillDownChoices = dataItem.getItemDefinition().getDrillDownChoices(); for (Choice choice : drillDownChoices) { drillDownValuesMap.put(allValuesMap.get(choice.getValue()).getDisplayPath(), allValuesMap.get(choice.getValue())); } return drillDownValuesMap; } private List<String> getDrillDownPaths(DataItem dataItem) { // First get all the item values ItemValueMap allValuesMap = getItemValuesMap(dataItem); // Then make a list of the drill down paths List<String> drillDownPaths = new ArrayList<String>(); List<Choice> drillDownChoices = dataItem.getItemDefinition().getDrillDownChoices(); for (Choice choice : drillDownChoices) { drillDownPaths.add(allValuesMap.get(choice.getValue()).getDisplayPath()); } return drillDownPaths; } }
package com.devotedmc.ExilePearl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.devotedmc.ExilePearl.command.PearlCommand; import com.devotedmc.ExilePearl.core.CorePearlFactory; import com.devotedmc.ExilePearl.command.BaseCommand; import com.devotedmc.ExilePearl.command.CmdAutoHelp; import com.devotedmc.ExilePearl.command.CmdExilePearl; import com.devotedmc.ExilePearl.listener.ExileListener; import com.devotedmc.ExilePearl.listener.PlayerListener; import com.devotedmc.ExilePearl.storage.MySqlStorage; import com.devotedmc.ExilePearl.storage.AsyncStorageWriter; import com.devotedmc.ExilePearl.storage.PluginStorage; import com.devotedmc.ExilePearl.util.TextUtil; import vg.civcraft.mc.civmodcore.ACivMod; import vg.civcraft.mc.namelayer.NameAPI; /** * An offshoot of Civcraft's PrisonPearl plugin * @author GordonFreemanQ * */ public class ExilePearlPlugin extends ACivMod implements ExilePearlApi, PlayerNameProvider { private final ExilePearlConfig pearlConfig = new ExilePearlConfig(this); private final PearlFactory pearlFactory = new CorePearlFactory(this); private final PluginStorage storage = new AsyncStorageWriter(new MySqlStorage(pearlFactory), this); private final PearlManager pearlManager = pearlFactory.createPearlManager(); private final PearlWorker pearlWorker = pearlFactory.createPearlWorker(); private final PlayerListener playerListener = new PlayerListener(this); private final ExileListener exileListener = new ExileListener(this, pearlConfig); private final HashSet<PearlCommand> commands = new HashSet<PearlCommand>(); private final CmdAutoHelp autoHelp = new CmdAutoHelp(this); /** * * ProgrammerDan - Today at 2:00 PM * my "wish list" would be * (1) supports reload * (2) exposes command to self-reload * (3) individual configuration options can be changed at runtime and saved to config * (4) admins can exile players or de-exile them either in game or on console; * if on console exiling a player requires giving coordinates to a chest / InventoryHolder tile entity or player name * (5)easy admin command to see which players are exiled * (6) Throw bukkit events for when players are exiled or freed from exile, and when they attempt to breach their exile, * and when an ExilePearl is placed in an InventoryHolder tile entity or picked up / in a player inventory (for tracking). * */ /** * Spigot enable method */ @Override public void onEnable() { log("=== ENABLE START ==="); long timeEnableStart = System.currentTimeMillis(); super.onEnable(); // Storage connect and load if (!storage.connect()) { log(Level.SEVERE, "Failed to connect to database."); return; } pearlManager.loadPearls(); // Add commands commands.add(new CmdExilePearl(this)); // Register events this.getServer().getPluginManager().registerEvents(playerListener, this); this.getServer().getPluginManager().registerEvents(exileListener, this); // Start tasks pearlWorker.start(); log("=== ENABLE DONE (Took "+(System.currentTimeMillis() - timeEnableStart)+"ms) ==="); } /** * Spigot disable method */ @Override public void onDisable() { super.onDisable(); pearlWorker.stop(); storage.disconnect(); } /** * Gets the pearl configuration * @return The pearl configuration */ public ExilePearlConfig getPearlConfig() { return pearlConfig; } /** * Gets the plugin storage * @return The storage instance */ public PluginStorage getStorage() { return storage; } /** * Gets the pearl manager * @return The pearl manager instance */ public PearlManager getPearlManager() { return pearlManager; } /** * Gets the auto-help command * @return The auto-help command */ public PearlCommand getAutoHelp() { return autoHelp; } /** * Handles a bukkit command event */ @Override public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) { for (BaseCommand<? extends ExilePearlPlugin> c : commands) { List<String> aliases = c.getAliases(); if (aliases.contains(cmd.getLabel())) { // Set the label to the default alias cmd.setLabel(aliases.get(0)); c.execute(sender, new ArrayList<String>(Arrays.asList(args))); return true; } } return false; } /** * Handles a tab complete event */ @Override public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) { for (BaseCommand<? extends ExilePearlPlugin> c : commands) { List<String> aliases = c.getAliases(); if (aliases.contains(cmd.getLabel())) { // Set the label to the default alias cmd.setLabel(aliases.get(0)); return c.getTabList(sender, new ArrayList<String>(Arrays.asList(args))); } } return null; } /** * Gets the plugin name */ @Override protected final String getPluginName() { return "ExilePearl"; } public void log(Level level, String msg, Object... args) { getLogger().log(level, String.format(msg, args)); } public void log(String msg, Object... args) { log(Level.INFO, msg, args); } public String formatText(String text, Object... args) { return TextUtil.instance().parse(text, args); } @Override public ExilePearl exilePlayer(Player exiled, Player killedBy) { return pearlManager.exilePlayer(exiled, killedBy); } @Override public ExilePearl getPearl(String name) { return pearlManager.getPearl(name); } @Override public ExilePearl getPearl(UUID uid) { return pearlManager.getPearl(uid); } @Override public Collection<ExilePearl> getPearls() { return pearlManager.getPearls(); } @Override public boolean isPlayerExiled(Player player) { return pearlManager.isPlayerExiled(player); } @Override public boolean isPlayerExiled(UUID uid) { return pearlManager.isPlayerExiled(uid); } @Override public ExilePearl getPearlFromItemStack(ItemStack is) { return pearlManager.getPearlFromItemStack(is); } @Override public boolean freePearl(ExilePearl pearl) { return pearlManager.freePearl(pearl); } @Override public PearlPlayer getPearlPlayer(final UUID uid) { Player player = Bukkit.getPlayer(uid); if (player == null) { return null; } return pearlFactory.createPearlPlayer(player); } @Override public PearlPlayer getPearlPlayer(final String name) { return getPearlPlayer(getUniqueId(name)); } @Override public String getName(UUID uid) { if (isNameLayerEnabled()) { return NameAPI.getCurrentName(uid); } return Bukkit.getOfflinePlayer(uid).getName(); } @SuppressWarnings("deprecation") @Override public UUID getUniqueId(String name) { if (isNameLayerEnabled()) { return NameAPI.getUUID(name); } return Bukkit.getOfflinePlayer(name).getUniqueId(); } private boolean isNameLayerEnabled() { return Bukkit.getPluginManager().isPluginEnabled("NameLayer"); } }
package com.elmakers.mine.bukkit.utility; import org.bukkit.Bukkit; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Contains some raw methods for doing some simple NMS utilities. * * This is not meant to be a replacement for full-on NMS or Protocol libs, * but it is enough for Magic to use internally without requiring any * external dependencies. * * Use any of this at your own risk! */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class NMSUtils { protected static boolean failed = false; protected static String versionPrefix = ""; protected final static int NBT_TYPE_COMPOUND = 10; protected final static int NBT_TYPE_INT_ARRAY= 11; protected final static int NBT_TYPE_DOUBLE = 6; protected final static int NBT_TYPE_FLOAT = 5; protected final static int NBT_TYPE_STRING = 8; protected static int WITHER_SKULL_TYPE = 66; protected static int FIREWORK_TYPE = 76; protected static Class<?> class_ItemStack; protected static Class<?> class_NBTBase; protected static Class<?> class_NBTTagCompound; protected static Class<?> class_NBTTagList; protected static Class<?> class_NBTTagByte; protected static Class<?> class_NBTTagString; protected static Class<?> class_CraftTask; protected static Class<?> class_CraftInventoryCustom; protected static Class<?> class_CraftItemStack; protected static Class<?> class_CraftBlockState; protected static Class<?> class_CraftLivingEntity; protected static Class<?> class_CraftWorld; protected static Class<?> class_Entity; protected static Class<?> class_EntityCreature; protected static Class<?> class_EntityLiving; protected static Class<?> class_DataWatcher; protected static Class<?> class_DamageSource; protected static Class<?> class_EntityDamageSource; protected static Class<?> class_World; protected static Class<?> class_WorldServer; protected static Class<?> class_Packet; protected static Class<Enum> class_EnumSkyBlock; protected static Class<?> class_EntityPainting; protected static Class<?> class_EntityItemFrame; protected static Class<?> class_EntityMinecartRideable; protected static Class<?> class_EntityTNTPrimed; protected static Class<?> class_AxisAlignedBB; protected static Class<?> class_PathPoint; protected static Class<?> class_PathEntity; protected static Class<?> class_EntityFirework; protected static Class<?> class_CraftSkull; protected static Class<?> class_CraftBanner; protected static Class<?> class_CraftMetaSkull; protected static Class<?> class_CraftMetaBanner; protected static Class<?> class_GameProfile; protected static Class<?> class_GameProfileProperty; protected static Class<?> class_BlockPosition; protected static Class<?> class_NBTCompressedStreamTools; protected static Class<?> class_TileEntity; protected static Class<?> class_TileEntitySign; protected static Class<?> class_TileEntityContainer; protected static Class<?> class_ChestLock; protected static Class<Enum> class_EnumDirection; protected static Class<?> class_EntityHorse; protected static Class<?> class_EntityWitherSkull; protected static Class<?> class_PacketPlayOutAttachEntity; protected static Class<?> class_PacketPlayOutEntityDestroy; protected static Class<?> class_PacketPlayOutSpawnEntity; protected static Class<?> class_PacketPlayOutSpawnEntityLiving; protected static Class<?> class_PacketPlayOutEntityMetadata; protected static Class<?> class_PacketPlayOutEntityStatus; protected static Class<?> class_PacketPlayOutCustomSoundEffect; protected static Class<?> class_PacketPlayOutExperience; protected static Enum<?> enum_SoundCategory_PLAYERS; protected static Class<Enum> class_EnumSoundCategory; protected static Class<?> class_EntityFallingBlock; protected static Class<?> class_EntityArmorStand; protected static Class<?> class_EntityPlayer; protected static Class<?> class_PlayerConnection; protected static Class<?> class_Chunk; protected static Class<?> class_CraftPlayer; protected static Class<?> class_CraftChunk; protected static Class<?> class_CraftEntity; protected static Class<?> class_EntityProjectile; protected static Class<?> class_EntityFireball; protected static Class<?> class_EntityArrow; protected static Class<?> class_CraftArrow; protected static Class<?> class_MinecraftServer; protected static Class<?> class_CraftServer; protected static Class<?> class_DataWatcherObject; protected static Method class_NBTTagList_addMethod; protected static Method class_NBTTagList_getMethod; protected static Method class_NBTTagList_getDoubleMethod; protected static Method class_NBTTagList_sizeMethod; protected static Method class_NBTTagList_removeMethod; protected static Method class_NBTTagCompound_getKeysMethod; protected static Method class_NBTTagCompound_setMethod; protected static Method class_DataWatcher_setMethod; protected static Method class_World_getEntitiesMethod; protected static Method class_Entity_setSilentMethod; protected static Method class_Entity_setYawPitchMethod; protected static Method class_Entity_getBukkitEntityMethod; protected static Method class_EntityLiving_damageEntityMethod; protected static Method class_DamageSource_getMagicSourceMethod; protected static Method class_EntityDamageSource_setThornsMethod; protected static Method class_World_explodeMethod; protected static Method class_NBTTagCompound_setBooleanMethod; protected static Method class_NBTTagCompound_setStringMethod; protected static Method class_NBTTagCompound_setDoubleMethod; protected static Method class_NBTTagCompound_setLongMethod; protected static Method class_NBTTagCompound_setIntMethod; protected static Method class_NBTTagCompound_removeMethod; protected static Method class_NBTTagCompound_getStringMethod; protected static Method class_NBTTagCompound_getBooleanMethod; protected static Method class_NBTTagCompound_getIntMethod; protected static Method class_NBTTagCompound_getByteMethod; protected static Method class_NBTTagCompound_getMethod; protected static Method class_NBTTagCompound_getCompoundMethod; protected static Method class_NBTTagCompound_getShortMethod; protected static Method class_NBTTagCompound_getByteArrayMethod; protected static Method class_NBTTagCompound_getListMethod; protected static Method class_Entity_saveMethod; protected static Method class_Entity_getTypeMethod; protected static Method class_TileEntity_loadMethod; protected static Method class_TileEntity_saveMethod; protected static Method class_TileEntity_updateMethod; protected static Method class_World_addEntityMethod; protected static Method class_CraftMetaBanner_getPatternsMethod; protected static Method class_CraftMetaBanner_setPatternsMethod; protected static Method class_CraftMetaBanner_getBaseColorMethod; protected static Method class_CraftMetaBanner_setBaseColorMethod; protected static Method class_CraftBanner_getPatternsMethod; protected static Method class_CraftBanner_setPatternsMethod; protected static Method class_CraftBanner_getBaseColorMethod; protected static Method class_CraftBanner_setBaseColorMethod; protected static Method class_NBTCompressedStreamTools_loadFileMethod; protected static Method class_ItemStack_createStackMethod; protected static Method class_CraftItemStack_asBukkitCopyMethod; protected static Method class_CraftItemStack_copyMethod; protected static Method class_CraftItemStack_mirrorMethod; protected static Method class_NBTTagCompound_hasKeyMethod; protected static Method class_CraftWorld_getTileEntityAtMethod; protected static Method class_CraftWorld_spawnMethod; protected static Method class_Entity_setLocationMethod; protected static Method class_Entity_getIdMethod; protected static Method class_Entity_getDataWatcherMethod; protected static Method class_Entity_getBoundingBox; protected static Method class_TileEntityContainer_setLock; protected static Method class_TileEntityContainer_getLock; protected static Method class_ChestLock_isEmpty; protected static Method class_ChestLock_getString; protected static Method class_ArmorStand_setInvisible; protected static Method class_ArmorStand_setGravity; protected static Method class_CraftPlayer_getHandleMethod; protected static Method class_CraftChunk_getHandleMethod; protected static Method class_CraftEntity_getHandleMethod; protected static Method class_CraftLivingEntity_getHandleMethod; protected static Method class_CraftWorld_getHandleMethod; protected static Method class_EntityPlayer_openSignMethod; protected static Method class_CraftServer_getServerMethod; protected static Method class_MinecraftServer_getResourcePackMethod; protected static Method class_MinecraftServer_getResourcePackHashMethod; protected static Method class_MinecraftServer_setResourcePackMethod; protected static Constructor class_NBTTagString_consructor; protected static Constructor class_CraftInventoryCustom_constructor; protected static Constructor class_NBTTagByte_constructor; protected static Constructor class_NBTTagByte_legacy_constructor; protected static Constructor class_EntityFireworkConstructor; protected static Constructor class_EntityPaintingConstructor; protected static Constructor class_EntityItemFrameConstructor; protected static Constructor class_BlockPositionConstructor; protected static Constructor class_PacketSpawnEntityConstructor; protected static Constructor class_PacketSpawnLivingEntityConstructor; protected static Constructor class_PacketPlayOutEntityMetadata_Constructor; protected static Constructor class_PacketPlayOutEntityStatus_Constructor; protected static Constructor class_PacketPlayOutEntityDestroy_Constructor; protected static Constructor class_PacketPlayOutCustomSoundEffect_Constructor; protected static Constructor class_PacketPlayOutExperience_Constructor; protected static Constructor class_ChestLock_Constructor; protected static Constructor class_ArmorStand_Constructor; protected static Constructor class_AxisAlignedBB_Constructor; protected static Field class_Entity_invulnerableField; protected static Field class_Entity_motXField; protected static Field class_Entity_motYField; protected static Field class_Entity_motZField; protected static Field class_WorldServer_entitiesByUUIDField; protected static Field class_ItemStack_tagField; protected static Field class_DamageSource_MagicField; protected static Field class_Firework_ticksFlownField; protected static Field class_Firework_expectedLifespanField; protected static Field class_CraftSkull_profile; protected static Field class_CraftMetaSkull_profile; protected static Field class_GameProfile_properties; protected static Field class_GameProfileProperty_value; protected static Field class_ItemStack_count; protected static Field class_EntityTNTPrimed_source; protected static Field class_NBTTagList_list; protected static Field class_AxisAlignedBB_minXField; protected static Field class_AxisAlignedBB_minYField; protected static Field class_AxisAlignedBB_minZField; protected static Field class_AxisAlignedBB_maxXField; protected static Field class_AxisAlignedBB_maxYField; protected static Field class_AxisAlignedBB_maxZField; protected static Field class_EntityFallingBlock_hurtEntitiesField; protected static Field class_EntityFallingBlock_fallHurtMaxField; protected static Field class_EntityFallingBlock_fallHurtAmountField; protected static Field class_EntityArmorStand_disabledSlotsField; protected static Field class_EntityPlayer_playerConnectionField; protected static Field class_PlayerConnection_floatCountField; protected static Field class_Chunk_doneField; protected static Field class_CraftItemStack_getHandleField; protected static Field class_EntityArrow_lifeField = null; protected static Field class_EntityArrow_damageField; protected static Field class_CraftWorld_environmentField; protected static Field class_EntityLiving_potionBubblesField; protected static Field class_MemorySection_mapField; static { // Find classes Bukkit hides from us. :-D // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. String className = Bukkit.getServer().getClass().getName(); String[] packages = className.split("\\."); if (packages.length == 5) { versionPrefix = packages[3] + "."; } try { class_Entity = fixBukkitClass("net.minecraft.server.Entity"); class_EntityLiving = fixBukkitClass("net.minecraft.server.EntityLiving"); class_ItemStack = fixBukkitClass("net.minecraft.server.ItemStack"); class_DataWatcher = fixBukkitClass("net.minecraft.server.DataWatcher"); class_DataWatcherObject = fixBukkitClass("net.minecraft.server.DataWatcherObject"); class_NBTBase = fixBukkitClass("net.minecraft.server.NBTBase"); class_NBTTagCompound = fixBukkitClass("net.minecraft.server.NBTTagCompound"); class_NBTTagList = fixBukkitClass("net.minecraft.server.NBTTagList"); class_NBTTagString = fixBukkitClass("net.minecraft.server.NBTTagString"); class_NBTTagByte = fixBukkitClass("net.minecraft.server.NBTTagByte"); class_CraftWorld = fixBukkitClass("org.bukkit.craftbukkit.CraftWorld"); class_CraftInventoryCustom = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftInventoryCustom"); class_CraftItemStack = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftItemStack"); class_CraftBlockState = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBlockState"); class_CraftTask = fixBukkitClass("org.bukkit.craftbukkit.scheduler.CraftTask"); class_CraftLivingEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftLivingEntity"); class_Packet = fixBukkitClass("net.minecraft.server.Packet"); class_World = fixBukkitClass("net.minecraft.server.World"); class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); class_EnumSkyBlock = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumSkyBlock"); class_EnumSoundCategory = (Class<Enum>)fixBukkitClass("net.minecraft.server.SoundCategory"); enum_SoundCategory_PLAYERS = Enum.valueOf(class_EnumSoundCategory, "PLAYERS"); class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame"); class_EntityMinecartRideable = fixBukkitClass("net.minecraft.server.EntityMinecartRideable"); class_EntityTNTPrimed = fixBukkitClass("net.minecraft.server.EntityTNTPrimed"); class_AxisAlignedBB = fixBukkitClass("net.minecraft.server.AxisAlignedBB"); class_DamageSource = fixBukkitClass("net.minecraft.server.DamageSource"); class_EntityDamageSource = fixBukkitClass("net.minecraft.server.EntityDamageSource"); class_PathEntity = fixBukkitClass("net.minecraft.server.PathEntity"); class_PathPoint = fixBukkitClass("net.minecraft.server.PathPoint"); class_EntityFirework = fixBukkitClass("net.minecraft.server.EntityFireworks"); class_CraftSkull = fixBukkitClass("org.bukkit.craftbukkit.block.CraftSkull"); class_CraftMetaSkull = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaSkull"); class_NBTCompressedStreamTools = fixBukkitClass("net.minecraft.server.NBTCompressedStreamTools"); class_TileEntity = fixBukkitClass("net.minecraft.server.TileEntity"); class_EntityHorse = fixBukkitClass("net.minecraft.server.EntityHorse"); class_EntityWitherSkull = fixBukkitClass("net.minecraft.server.EntityWitherSkull"); class_PacketPlayOutAttachEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutAttachEntity"); class_PacketPlayOutEntityDestroy = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityDestroy"); class_PacketPlayOutSpawnEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntity"); class_PacketPlayOutSpawnEntityLiving = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntityLiving"); class_PacketPlayOutEntityMetadata = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityMetadata"); class_PacketPlayOutEntityStatus = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityStatus"); class_PacketPlayOutCustomSoundEffect = fixBukkitClass("net.minecraft.server.PacketPlayOutCustomSoundEffect"); class_PacketPlayOutExperience = fixBukkitClass("net.minecraft.server.PacketPlayOutExperience"); class_EntityFallingBlock = fixBukkitClass("net.minecraft.server.EntityFallingBlock"); class_EntityArmorStand = fixBukkitClass("net.minecraft.server.EntityArmorStand"); class_EntityPlayer = fixBukkitClass("net.minecraft.server.EntityPlayer"); class_PlayerConnection = fixBukkitClass("net.minecraft.server.PlayerConnection"); class_Chunk = fixBukkitClass("net.minecraft.server.Chunk"); class_CraftPlayer = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftPlayer"); class_CraftChunk = fixBukkitClass("org.bukkit.craftbukkit.CraftChunk"); class_CraftEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftEntity"); class_TileEntitySign = fixBukkitClass("net.minecraft.server.TileEntitySign"); class_CraftServer = fixBukkitClass("org.bukkit.craftbukkit.CraftServer"); class_MinecraftServer = fixBukkitClass("net.minecraft.server.MinecraftServer"); class_EntityProjectile = NMSUtils.getBukkitClass("net.minecraft.server.EntityProjectile"); class_EntityFireball = NMSUtils.getBukkitClass("net.minecraft.server.EntityFireball"); class_EntityArrow = NMSUtils.getBukkitClass("net.minecraft.server.EntityArrow"); class_CraftArrow = NMSUtils.getBukkitClass("org.bukkit.craftbukkit.entity.CraftArrow"); class_NBTTagList_addMethod = class_NBTTagList.getMethod("add", class_NBTBase); class_NBTTagList_getMethod = class_NBTTagList.getMethod("get", Integer.TYPE); class_NBTTagList_getDoubleMethod = class_NBTTagList.getMethod("e", Integer.TYPE); class_NBTTagList_sizeMethod = class_NBTTagList.getMethod("size"); class_NBTTagList_removeMethod = class_NBTTagList.getMethod("remove", Integer.TYPE); class_NBTTagCompound_setMethod = class_NBTTagCompound.getMethod("set", String.class, class_NBTBase); class_World_getEntitiesMethod = class_World.getMethod("getEntities", class_Entity, class_AxisAlignedBB); class_CraftWorld_getTileEntityAtMethod = class_CraftWorld.getMethod("getTileEntityAt", Integer.TYPE, Integer.TYPE, Integer.TYPE); class_CraftWorld_spawnMethod = class_CraftWorld.getMethod("spawn", Location.class, Class.class, CreatureSpawnEvent.SpawnReason.class); class_Entity_getBukkitEntityMethod = class_Entity.getMethod("getBukkitEntity"); class_Entity_setYawPitchMethod = class_Entity.getDeclaredMethod("setYawPitch", Float.TYPE, Float.TYPE); class_Entity_setYawPitchMethod.setAccessible(true); class_Entity_setSilentMethod = class_Entity.getDeclaredMethod("c", Boolean.TYPE); class_AxisAlignedBB_Constructor = class_AxisAlignedBB.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE); class_World_explodeMethod = class_World.getMethod("createExplosion", class_Entity, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE, Boolean.TYPE); class_NBTTagCompound_setBooleanMethod = class_NBTTagCompound.getMethod("setBoolean", String.class, Boolean.TYPE); class_NBTTagCompound_setStringMethod = class_NBTTagCompound.getMethod("setString", String.class, String.class); class_NBTTagCompound_setDoubleMethod = class_NBTTagCompound.getMethod("setDouble", String.class, Double.TYPE); class_NBTTagCompound_setLongMethod = class_NBTTagCompound.getMethod("setLong", String.class, Long.TYPE); class_NBTTagCompound_setIntMethod = class_NBTTagCompound.getMethod("setInt", String.class, Integer.TYPE); class_NBTTagCompound_removeMethod = class_NBTTagCompound.getMethod("remove", String.class); class_NBTTagCompound_getStringMethod = class_NBTTagCompound.getMethod("getString", String.class); class_NBTTagCompound_getShortMethod = class_NBTTagCompound.getMethod("getShort", String.class); class_NBTTagCompound_getIntMethod = class_NBTTagCompound.getMethod("getInt", String.class); class_NBTTagCompound_getBooleanMethod = class_NBTTagCompound.getMethod("getBoolean", String.class); class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class); class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound); class_NBTTagCompound_hasKeyMethod = class_NBTTagCompound.getMethod("hasKey", String.class); class_NBTTagCompound_getMethod = class_NBTTagCompound.getMethod("get", String.class); class_NBTTagCompound_getCompoundMethod = class_NBTTagCompound.getMethod("getCompound", String.class); class_EntityLiving_damageEntityMethod = class_EntityLiving.getMethod("damageEntity", class_DamageSource, Float.TYPE); class_DamageSource_getMagicSourceMethod = class_DamageSource.getMethod("b", class_Entity, class_Entity); class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class); class_NBTCompressedStreamTools_loadFileMethod = class_NBTCompressedStreamTools.getMethod("a", InputStream.class); class_TileEntity_loadMethod = class_TileEntity.getMethod("a", class_NBTTagCompound); class_TileEntity_updateMethod = class_TileEntity.getMethod("update"); class_Entity_setLocationMethod = class_Entity.getMethod("setLocation", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE); class_Entity_getIdMethod = class_Entity.getMethod("getId"); class_Entity_getDataWatcherMethod = class_Entity.getMethod("getDataWatcher"); class_ArmorStand_setInvisible = class_EntityArmorStand.getDeclaredMethod("setInvisible", Boolean.TYPE); class_ArmorStand_setGravity = class_EntityArmorStand.getDeclaredMethod("setGravity", Boolean.TYPE); class_CraftPlayer_getHandleMethod = class_CraftPlayer.getMethod("getHandle"); class_CraftChunk_getHandleMethod = class_CraftChunk.getMethod("getHandle"); class_CraftEntity_getHandleMethod = class_CraftEntity.getMethod("getHandle"); class_CraftLivingEntity_getHandleMethod = class_CraftLivingEntity.getMethod("getHandle"); class_CraftWorld_getHandleMethod = class_CraftWorld.getMethod("getHandle"); class_EntityPlayer_openSignMethod = class_EntityPlayer.getMethod("openSign", class_TileEntitySign); class_CraftServer_getServerMethod = class_CraftServer.getMethod("getServer"); class_MinecraftServer_getResourcePackMethod = class_MinecraftServer.getMethod("getResourcePack"); class_MinecraftServer_getResourcePackHashMethod = class_MinecraftServer.getMethod("getResourcePackHash"); class_MinecraftServer_setResourcePackMethod = class_MinecraftServer.getMethod("setResourcePack", String.class, String.class); class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack); class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE); class_PacketSpawnLivingEntityConstructor = class_PacketPlayOutSpawnEntityLiving.getConstructor(class_EntityLiving); class_PacketPlayOutEntityMetadata_Constructor = class_PacketPlayOutEntityMetadata.getConstructor(Integer.TYPE, class_DataWatcher, Boolean.TYPE); class_PacketPlayOutEntityStatus_Constructor = class_PacketPlayOutEntityStatus.getConstructor(class_Entity, Byte.TYPE); class_PacketPlayOutEntityDestroy_Constructor = class_PacketPlayOutEntityDestroy.getConstructor(int[].class); class_PacketPlayOutCustomSoundEffect_Constructor = class_PacketPlayOutCustomSoundEffect.getConstructor(String.class, class_EnumSoundCategory, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE); class_PacketPlayOutExperience_Constructor = class_PacketPlayOutExperience.getConstructor(Float.TYPE, Integer.TYPE, Integer.TYPE); class_CraftWorld_environmentField = class_CraftWorld.getDeclaredField("environment"); class_CraftWorld_environmentField.setAccessible(true); class_Entity_invulnerableField = class_Entity.getDeclaredField("invulnerable"); class_Entity_invulnerableField.setAccessible(true); class_Entity_motXField = class_Entity.getDeclaredField("motX"); class_Entity_motXField.setAccessible(true); class_Entity_motYField = class_Entity.getDeclaredField("motY"); class_Entity_motYField.setAccessible(true); class_Entity_motZField = class_Entity.getDeclaredField("motZ"); class_Entity_motZField.setAccessible(true); class_WorldServer_entitiesByUUIDField = class_WorldServer.getDeclaredField("entitiesByUUID"); class_WorldServer_entitiesByUUIDField.setAccessible(true); class_ItemStack_tagField = class_ItemStack.getDeclaredField("tag"); class_ItemStack_tagField.setAccessible(true); class_DamageSource_MagicField = class_DamageSource.getField("MAGIC"); class_EntityTNTPrimed_source = class_EntityTNTPrimed.getDeclaredField("source"); class_EntityTNTPrimed_source.setAccessible(true); class_AxisAlignedBB_minXField = class_AxisAlignedBB.getField("a"); class_AxisAlignedBB_minYField = class_AxisAlignedBB.getField("b"); class_AxisAlignedBB_minZField = class_AxisAlignedBB.getField("c"); class_AxisAlignedBB_maxXField = class_AxisAlignedBB.getField("d"); class_AxisAlignedBB_maxYField = class_AxisAlignedBB.getField("e"); class_AxisAlignedBB_maxZField = class_AxisAlignedBB.getField("f"); class_EntityPlayer_playerConnectionField = class_EntityPlayer.getDeclaredField("playerConnection"); class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("g"); class_PlayerConnection_floatCountField.setAccessible(true); class_Firework_ticksFlownField = class_EntityFirework.getDeclaredField("ticksFlown"); class_Firework_ticksFlownField.setAccessible(true); class_Firework_expectedLifespanField = class_EntityFirework.getDeclaredField("expectedLifespan"); class_Firework_expectedLifespanField.setAccessible(true); class_NBTTagString_consructor = class_NBTTagString.getConstructor(String.class); class_NBTTagByte_constructor = class_NBTTagByte.getConstructor(Byte.TYPE); class_ItemStack_count = class_ItemStack.getDeclaredField("count"); class_ItemStack_count.setAccessible(true); class_NBTTagList_list = class_NBTTagList.getDeclaredField("list"); class_NBTTagList_list.setAccessible(true); class_EntityFallingBlock_hurtEntitiesField = class_EntityFallingBlock.getDeclaredField("hurtEntities"); class_EntityFallingBlock_hurtEntitiesField.setAccessible(true); class_EntityFallingBlock_fallHurtAmountField = class_EntityFallingBlock.getDeclaredField("fallHurtAmount"); class_EntityFallingBlock_fallHurtAmountField.setAccessible(true); class_EntityFallingBlock_fallHurtMaxField = class_EntityFallingBlock.getDeclaredField("fallHurtMax"); class_EntityFallingBlock_fallHurtMaxField.setAccessible(true); class_Chunk_doneField = class_Chunk.getDeclaredField("done"); class_Chunk_doneField.setAccessible(true); class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle"); class_CraftItemStack_getHandleField.setAccessible(true); class_EntityLiving_potionBubblesField = class_EntityLiving.getDeclaredField("f"); class_EntityLiving_potionBubblesField.setAccessible(true); class_MemorySection_mapField = MemorySection.class.getDeclaredField("map"); class_MemorySection_mapField.setAccessible(true); class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer"); class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock"); class_ChestLock_isEmpty = class_ChestLock.getMethod("a"); class_ChestLock_getString = class_ChestLock.getMethod("b"); class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox"); class_GameProfile = getClass("com.mojang.authlib.GameProfile"); class_GameProfileProperty = getClass("com.mojang.authlib.properties.Property"); class_CraftSkull_profile = class_CraftSkull.getDeclaredField("profile"); class_CraftSkull_profile.setAccessible(true); class_CraftMetaSkull_profile = class_CraftMetaSkull.getDeclaredField("profile"); class_CraftMetaSkull_profile.setAccessible(true); class_GameProfile_properties = class_GameProfile.getDeclaredField("properties"); class_GameProfile_properties.setAccessible(true); class_GameProfileProperty_value = class_GameProfileProperty.getDeclaredField("value"); class_GameProfileProperty_value.setAccessible(true); class_CraftMetaBanner = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaBanner"); class_CraftMetaBanner_getBaseColorMethod = class_CraftMetaBanner.getMethod("getBaseColor"); class_CraftMetaBanner_getPatternsMethod = class_CraftMetaBanner.getMethod("getPatterns"); class_CraftMetaBanner_setPatternsMethod = class_CraftMetaBanner.getMethod("setPatterns", List.class); class_CraftMetaBanner_setBaseColorMethod = class_CraftMetaBanner.getMethod("setBaseColor", DyeColor.class); class_CraftBanner = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBanner"); class_CraftBanner_getBaseColorMethod = class_CraftBanner.getMethod("getBaseColor"); class_CraftBanner_getPatternsMethod = class_CraftBanner.getMethod("getPatterns"); class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class); class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class); class_BlockPosition = fixBukkitClass("net.minecraft.server.BlockPosition"); class_EnumDirection = (Class<Enum>)fixBukkitClass("net.minecraft.server.EnumDirection"); class_BlockPositionConstructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); class_ChestLock_Constructor = class_ChestLock.getConstructor(String.class); class_ArmorStand_Constructor = class_EntityArmorStand.getConstructor(class_World); try { try { class_DataWatcher_setMethod = class_DataWatcher.getMethod("set", class_DataWatcherObject, Object.class); class_TileEntity_saveMethod = class_TileEntity.getMethod("save", class_NBTTagCompound); class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bz"); class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock); class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("y_"); class_Entity_saveMethod = class_Entity.getMethod("e", class_NBTTagCompound); class_Entity_getTypeMethod = class_Entity.getDeclaredMethod("as"); class_Entity_getTypeMethod.setAccessible(true); class_NBTTagCompound_getKeysMethod = class_NBTTagCompound.getMethod("c"); class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("w"); } catch (Throwable ignore) { // 1.8 and lower class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("v"); class_TileEntity_saveMethod = class_TileEntity.getMethod("b", class_NBTTagCompound); class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bi"); class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock); class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("i"); } class_EntityArmorStand_disabledSlotsField.setAccessible(true); class_EntityArrow_damageField = class_EntityArrow.getDeclaredField("damage"); class_EntityArrow_damageField.setAccessible(true); // This is kinda hacky, like fer reals :\ try { // 1.8.3 class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ar"); } catch (Throwable ignore3) { try { class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ap"); } catch (Throwable ignore2) { try { class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("at"); } catch (Throwable ignore) { // Prior class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("j"); } } } } catch (Throwable ex) { class_EntityArrow_lifeField = null; } if (class_EntityArrow_lifeField != null) { class_EntityArrow_lifeField.setAccessible(true); } } catch (Throwable ex) { failed = true; ex.printStackTrace(); } } public static boolean getFailed() { return failed; } public static Class<?> getVersionedBukkitClass(String newVersion, String oldVersion) { Class<?> c = getBukkitClass(newVersion); if (c == null) { c = getBukkitClass(oldVersion); if (c == null) { Bukkit.getLogger().warning("Could not bind to " + newVersion + " or " + oldVersion); } } return c; } public static Class<?> getClass(String className) { Class<?> result = null; try { result = NMSUtils.class.getClassLoader().loadClass(className); } catch (Exception ex) { result = null; } return result; } public static Class<?> getBukkitClass(String className) { Class<?> result = null; try { result = fixBukkitClass(className); } catch (Exception ex) { result = null; } return result; } public static Class<?> fixBukkitClass(String className) throws ClassNotFoundException { if (!versionPrefix.isEmpty()) { className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); } return NMSUtils.class.getClassLoader().loadClass(className); } public static Object getHandle(org.bukkit.Server server) { Object handle = null; try { handle = class_CraftServer_getServerMethod.invoke(server); } catch (Throwable ex) { handle = null; } return handle; } public static Object getHandle(org.bukkit.inventory.ItemStack stack) { Object handle = null; try { handle = class_CraftItemStack_getHandleField.get(stack); } catch (Throwable ex) { handle = null; } return handle; } public static Object getHandle(org.bukkit.World world) { if (world == null) return null; Object handle = null; try { handle = class_CraftWorld_getHandleMethod.invoke(world); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.Entity entity) { if (entity == null) return null; Object handle = null; try { handle = class_CraftEntity_getHandleMethod.invoke(entity); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.LivingEntity entity) { if (entity == null) return null; Object handle = null; try { handle = class_CraftLivingEntity_getHandleMethod.invoke(entity); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static boolean isDone(org.bukkit.Chunk chunk) { Object chunkHandle = getHandle(chunk); boolean done = false; try { done = (Boolean)class_Chunk_doneField.get(chunkHandle); } catch (Throwable ex) { ex.printStackTrace(); } return done; } public static Object getHandle(org.bukkit.Chunk chunk) { Object handle = null; try { handle = class_CraftChunk_getHandleMethod.invoke(chunk); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } public static Object getHandle(org.bukkit.entity.Player player) { Object handle = null; try { handle = class_CraftPlayer_getHandleMethod.invoke(player); } catch (Throwable ex) { ex.printStackTrace(); } return handle; } protected static void sendPacket(Server server, Location source, Collection<? extends Player> players, Object packet) throws Exception { players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); int viewDistance = Bukkit.getServer().getViewDistance() * 16; int viewDistanceSquared = viewDistance * viewDistance; World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); if (!location.getWorld().equals(sourceWorld)) continue; if (location.distanceSquared(source) <= viewDistanceSquared) { sendPacket(player, packet); } } } protected static void sendPacket(Player player, Object packet) throws Exception { Object playerHandle = getHandle(player); Field connectionField = playerHandle.getClass().getField("playerConnection"); Object connection = connectionField.get(playerHandle); Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); sendPacketMethod.invoke(connection, packet); } public static int getFacing(BlockFace direction) { int dir; switch (direction) { case SOUTH: default: dir = 0; break; case WEST: dir = 1; break; case NORTH: dir = 2; break; case EAST: dir = 3; break; } return dir; } public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { if (entity == null) return null; try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null; return (org.bukkit.entity.Entity)bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } return null; } public static Object getTag(Object mcItemStack) { Object tag = null; try { tag = class_ItemStack_tagField.get(mcItemStack); } catch (Throwable ex) { ex.printStackTrace(); } return tag; } protected static Object getNMSCopy(ItemStack stack) { Object nms = null; try { nms = class_CraftItemStack_copyMethod.invoke(null, stack); } catch (Throwable ex) { ex.printStackTrace(); } return nms; } public static ItemStack getCopy(ItemStack stack) { if (stack == null) return null; try { Object craft = getNMSCopy(stack); stack = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, craft); } catch (Throwable ex) { stack = null; } return stack; } public static ItemStack makeReal(ItemStack stack) { if (stack == null) return null; Object nmsStack = getHandle(stack); if (nmsStack == null) { stack = getCopy(stack); nmsStack = getHandle(stack); } if (nmsStack == null) { return null; } try { Object tag = class_ItemStack_tagField.get(nmsStack); if (tag == null) { class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance()); } } catch (Throwable ex) { ex.printStackTrace(); return null; } return stack; } public static String getMeta(ItemStack stack, String tag, String defaultValue) { String result = getMeta(stack, tag); return result == null ? defaultValue : result; } public static boolean hasMeta(ItemStack stack, String tag) { return getNode(stack, tag) != null; } public static Object getNode(ItemStack stack, String tag) { if (stack == null) return null; Object meta = null; try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static boolean containsNode(Object nbtBase, String tag) { if (nbtBase == null) return false; Boolean result = false; try { result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } return result; } public static Object getNode(Object nbtBase, String tag) { if (nbtBase == null) return null; Object meta = null; try { meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Object createNode(Object nbtBase, String tag) { if (nbtBase == null) return null; Object meta = null; try { meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); class_NBTTagCompound_setMethod.invoke(nbtBase, tag, meta); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Object createNode(ItemStack stack, String tag) { if (stack == null) return null; Object outputObject = getNode(stack, tag); if (outputObject == null) { try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; outputObject = class_NBTTagCompound.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject); } catch (Throwable ex) { ex.printStackTrace(); } } return outputObject; } public static String getMeta(Object node, String tag, String defaultValue) { String meta = getMeta(node, tag); return meta == null || meta.length() == 0 ? defaultValue : meta; } public static String getMeta(Object node, String tag) { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; String meta = null; try { meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Byte getMetaByte(Object node, String tag) { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; Byte meta = null; try { meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Integer getMetaInt(Object node, String tag) { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; Integer meta = null; try { meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static Boolean getMetaBoolean(Object node, String tag) { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; Boolean meta = null; try { meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static void setMeta(Object node, String tag, String value) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { if (value == null || value.length() == 0) { class_NBTTagCompound_removeMethod.invoke(node, tag); } else { class_NBTTagCompound_setStringMethod.invoke(node, tag, value); } } catch (Throwable ex) { ex.printStackTrace(); } } public static void setMetaLong(Object node, String tag, long value) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { class_NBTTagCompound_setLongMethod.invoke(node, tag, value); } catch (Throwable ex) { ex.printStackTrace(); } } public static void setMetaDouble(Object node, String tag, double value) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { class_NBTTagCompound_setDoubleMethod.invoke(node, tag, value); } catch (Throwable ex) { ex.printStackTrace(); } } public static void setMetaInt(Object node, String tag, int value) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { class_NBTTagCompound_setIntMethod.invoke(node, tag, value); } catch (Throwable ex) { ex.printStackTrace(); } } public static void removeMeta(Object node, String tag) { if (node == null|| !class_NBTTagCompound.isInstance(node)) return; try { class_NBTTagCompound_removeMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } } public static void removeMeta(ItemStack stack, String tag) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; removeMeta(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } } public static void setMetaNode(Object node, String tag, Object child) { if (node == null || !class_NBTTagCompound.isInstance(node)) return; try { if (child == null) { class_NBTTagCompound_removeMethod.invoke(node, tag); } else { class_NBTTagCompound_setMethod.invoke(node, tag, child); } } catch (Throwable ex) { ex.printStackTrace(); } } public static boolean setMetaNode(ItemStack stack, String tag, Object child) { if (stack == null) return false; try { Object craft = getHandle(stack); if (craft == null) return false; Object node = getTag(craft); if (node == null) return false; if (child == null) { class_NBTTagCompound_removeMethod.invoke(node, tag); } else { class_NBTTagCompound_setMethod.invoke(node, tag, child); } } catch (Throwable ex) { ex.printStackTrace(); return false; } return true; } public static String getMeta(ItemStack stack, String tag) { if (stack == null) return null; String meta = null; try { Object craft = getHandle(stack); if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } return meta; } public static void setMeta(ItemStack stack, String tag, String value) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); } catch (Throwable ex) { ex.printStackTrace(); } } public static void addGlow(ItemStack stack) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; final Object enchList = class_NBTTagList.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList); // Testing Glow API based on ItemMetadata storage Object bukkitData = createNode(stack, "bukkit"); class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", true); } catch (Throwable ex) { } } public static void removeGlow(ItemStack stack) { if (stack == null) return; Collection<Enchantment> enchants = stack.getEnchantments().keySet(); for (Enchantment enchant : enchants) { stack.removeEnchantment(enchant); } try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; // Testing Glow API based on ItemMetadata storage Object bukkitData = getNode(stack, "bukkit"); if (bukkitData != null) { class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", false); } } catch (Throwable ex) { } } public static boolean isUnbreakable(ItemStack stack) { if (stack == null) return false; Boolean unbreakableFlag = null; try { Object craft = getHandle(stack); if (craft == null) return false; Object tagObject = getTag(craft); if (tagObject == null) return false; unbreakableFlag = getMetaBoolean(tagObject, "Unbreakable"); } catch (Throwable ex) { } return unbreakableFlag != null && unbreakableFlag; } public static void makeUnbreakable(ItemStack stack) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; Object unbreakableFlag = null; if (class_NBTTagByte_constructor != null) { unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1); } else { unbreakableFlag = class_NBTTagByte_legacy_constructor.newInstance("", (byte) 1); } class_NBTTagCompound_setMethod.invoke(tagObject, "Unbreakable", unbreakableFlag); } catch (Throwable ex) { } } public static void removeUnbreakable(ItemStack stack) { removeMeta(stack, "Unbreakable"); } public static void hideFlags(ItemStack stack, byte flags) { if (stack == null) return; try { Object craft = getHandle(stack); if (craft == null) return; Object tagObject = getTag(craft); if (tagObject == null) return; Object hideFlag = null; if (class_NBTTagByte_constructor != null) { hideFlag = class_NBTTagByte_constructor.newInstance(flags); } else { hideFlag = class_NBTTagByte_legacy_constructor.newInstance("", flags); } class_NBTTagCompound_setMethod.invoke(tagObject, "HideFlags", hideFlag); } catch (Throwable ex) { } } public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { boolean result = false; if (world == null) return false; try { Object worldHandle = getHandle(world); if (worldHandle == null) return false; Object entityHandle = entity == null ? null : getHandle(entity); Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); result = (Boolean)cancelledField.get(explosion); } catch (Throwable ex) { ex.printStackTrace(); result = false; } return result; } public static void makeTemporary(ItemStack itemStack, String message) { setMeta(itemStack, "temporary", message); } public static boolean isTemporary(ItemStack itemStack) { return hasMeta(itemStack, "temporary"); } public static void makeUnplaceable(ItemStack itemStack) { setMeta(itemStack, "unplaceable", "true"); } public static boolean isUnplaceable(ItemStack itemStack) { return hasMeta(itemStack, "unplaceable"); } public static String getTemporaryMessage(ItemStack itemStack) { return getMeta(itemStack, "temporary"); } public static void setReplacement(ItemStack itemStack, ItemStack replacement) { YamlConfiguration configuration = new YamlConfiguration(); configuration.set("item", replacement); setMeta(itemStack, "replacement", configuration.saveToString()); } public static ItemStack getReplacement(ItemStack itemStack) { String serialized = getMeta(itemStack, "replacement"); if (serialized == null || serialized.isEmpty()) { return null; } YamlConfiguration configuration = new YamlConfiguration(); ItemStack replacement = null; try { configuration.loadFromString(serialized); replacement = configuration.getItemStack("item"); } catch (Exception ex) { ex.printStackTrace(); } return replacement; } protected static Object getTagString(String value) { try { return class_NBTTagString_consructor.newInstance(value); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Object setStringList(Object nbtBase, String tag, Collection<String> values) { if (nbtBase == null) return null; Object listMeta = null; try { listMeta = class_NBTTagList.newInstance(); for (String value : values) { Object nbtString = getTagString(value); class_NBTTagList_addMethod.invoke(listMeta, nbtString); } class_NBTTagCompound_setMethod.invoke(nbtBase, tag, listMeta); } catch (Throwable ex) { ex.printStackTrace(); return null; } return listMeta; } public static ItemStack getItem(Object itemTag) { if (itemTag == null) return null; ItemStack item = null; try { Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); } catch (Exception ex) { ex.printStackTrace(); } return item; } public static ItemStack[] getItems(Object rootTag, String tagName) { try { Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList); ItemStack[] items = new ItemStack[size]; for (int i = 0; i < size; i++) { try { Object itemData = class_NBTTagList_getMethod.invoke(itemList, i); if (itemData != null) { items[i] = getItem(itemData); } } catch (Exception ex) { ex.printStackTrace(); } } return items; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Object getTileEntityData(Location location) { Object data = null; try { World world = location.getWorld(); Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (tileEntity != null) { data = class_NBTTagCompound.newInstance(); class_TileEntity_saveMethod.invoke(tileEntity, data); } } catch (Exception ex) { ex.printStackTrace(); } return data; } public static Object getTileEntity(Location location) { Object tileEntity = null; try { World world = location.getWorld(); tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); } catch (Exception ex) { ex.printStackTrace(); } return tileEntity; } public static void clearItems(Location location) { if (location == null) return; try { World world = location.getWorld(); if (world == null) return; Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (tileEntity != null) { Object entityData = class_NBTTagCompound.newInstance(); class_TileEntity_saveMethod.invoke(tileEntity, entityData); Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); if (itemList != null) { List items = (List)class_NBTTagList_list.get(itemList); items.clear(); class_TileEntity_loadMethod.invoke(tileEntity, entityData); class_TileEntity_updateMethod.invoke(tileEntity); } } } catch (Exception ex) { ex.printStackTrace(); } } public static void setTileEntityData(Location location, Object data) { if (location == null || data == null) return; try { World world = location.getWorld(); if (world == null) return; Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (tileEntity == null) return; class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX()); class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY()); class_NBTTagCompound_setIntMethod.invoke(data, "z", location.getBlockZ()); class_TileEntity_loadMethod.invoke(tileEntity, data); class_TileEntity_updateMethod.invoke(tileEntity); } catch (Exception ex) { ex.printStackTrace(); } } public static Vector getPosition(Object entityData, String tag) { try { Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0); Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1); Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2); if (x != null && y != null && z != null) { return new Vector(x, y, z); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Entity getEntity(World world, UUID uuid) { try { Object worldHandle = getHandle(world); final Map<UUID, Entity> entityMap = (Map<UUID, Entity>)class_WorldServer_entitiesByUUIDField.get(worldHandle); if (entityMap != null) { Object nmsEntity = entityMap.get(uuid); if (nmsEntity != null) { return getBukkitEntity(nmsEntity); } } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static void setEnvironment(World world, World.Environment environment) { try { class_CraftWorld_environmentField.set(world, environment); } catch (Exception ex) { ex.printStackTrace(); } } public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) { try { Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch); sendPacket(player, packet); } catch (Exception ex) { ex.printStackTrace(); } } public static Map<String, Object> getMap(ConfigurationSection section) { if (section instanceof MemorySection) { try { Object mapObject = class_MemorySection_mapField.get(section); if (mapObject instanceof Map) { return (Map<String, Object>)mapObject; } } catch (Exception ex) { ex.printStackTrace(); } } // Do it the slow way Map<String, Object> map = new HashMap<String, Object>(); Set<String> keys = section.getKeys(false); for (String key : keys) { map.put(key, section.get(key)); } return map; } }
package com.epam.ta.reportportal.entity.user; import com.epam.ta.reportportal.commons.JsonbUserType; import com.epam.ta.reportportal.entity.meta.MetaData; import com.epam.ta.reportportal.entity.project.Project; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; import java.util.Set; /** * @author Andrei Varabyeu */ @Entity @EntityListeners(AuditingEntityListener.class) @TypeDef(name = "jsonb", typeClass = JsonbUserType.class) @Table(name = "users", schema = "public") public class User implements Serializable { private static final long serialVersionUID = 923392981; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false, precision = 64) private Long id; @Column(name = "login") private String login; @Column(name = "password") private String password; @Column(name = "email") private String email; @Column(name = "role") @Enumerated(EnumType.STRING) private UserRole role; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "default_project_id") private Project defaultProject; @Column(name = "full_name") private String fullName; @Column(name = "expired") private boolean isExpired; @Type(type = "jsonb") @Column(name = "metadata") private MetaData metadata; @Column(name = "photo_path") private String photoPath; @Column(name = "type") private UserType userType; @OneToMany(fetch = FetchType.EAGER, mappedBy = "project") @Fetch(value = FetchMode.JOIN) private Set<ProjectUser> projects; public User() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public UserRole getRole() { return role; } public void setRole(UserRole role) { this.role = role; } public Set<ProjectUser> getProjects() { return projects; } public void setProjects(Set<ProjectUser> projects) { this.projects = projects; } public Project getDefaultProject() { return this.defaultProject; } public void setDefaultProject(Project defaultProjectId) { this.defaultProject = defaultProjectId; } public String getFullName() { return this.fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public boolean isExpired() { return isExpired; } public void setExpired(boolean expired) { isExpired = expired; } public String getPhotoPath() { return photoPath; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } public UserType getUserType() { return userType; } public void setUserType(UserType userType) { this.userType = userType; } public MetaData getMetadata() { return metadata; } public void setMetadata(MetaData metadata) { this.metadata = metadata; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return isExpired == user.isExpired && Objects.equals(id, user.id) && Objects.equals(login, user.login) && Objects.equals( password, user.password ) && Objects.equals(email, user.email) && role == user.role && Objects.equals(defaultProject, user.defaultProject) && Objects.equals(fullName, user.fullName) && Objects.equals(metadata, user.metadata) && Objects.equals( photoPath, user.photoPath) && userType == user.userType; } @Override public int hashCode() { return Objects.hash(id, login, password, email, role, defaultProject, fullName, isExpired, metadata, photoPath, userType); } }
package com.faforever.client.replay; import com.faforever.client.config.ClientProperties; import com.faforever.client.fx.PlatformService; import com.faforever.client.game.Game; import com.faforever.client.game.GameService; import com.faforever.client.game.KnownFeaturedMod; import com.faforever.client.i18n.I18n; import com.faforever.client.map.MapService; import com.faforever.client.mod.FeaturedMod; import com.faforever.client.mod.ModService; import com.faforever.client.notification.Action; import com.faforever.client.notification.DismissAction; import com.faforever.client.notification.ImmediateErrorNotification; import com.faforever.client.notification.ImmediateNotification; import com.faforever.client.notification.NotificationService; import com.faforever.client.notification.PersistentNotification; import com.faforever.client.notification.ReportAction; import com.faforever.client.notification.Severity; import com.faforever.client.preferences.PreferencesService; import com.faforever.client.remote.FafService; import com.faforever.client.replay.Replay.ChatMessage; import com.faforever.client.replay.Replay.GameOption; import com.faforever.client.reporting.ReportingService; import com.faforever.client.task.TaskService; import com.faforever.client.vault.search.SearchController.SortConfig; import com.faforever.commons.replay.ReplayData; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.net.UrlEscapers; import com.google.common.primitives.Bytes; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.web.util.UriComponentsBuilder; import javax.inject.Inject; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.faforever.client.notification.Severity.WARN; import static com.github.nocatch.NoCatch.noCatch; import static java.net.URLDecoder.decode; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.move; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; @Lazy @Service @Slf4j public class ReplayService { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * Byte offset at which a SupCom replay's version number starts. */ private static final int VERSION_OFFSET = 0x18; private static final int MAP_NAME_OFFSET = 0x2D; private static final String FAF_REPLAY_FILE_ENDING = ".fafreplay"; private static final String SUP_COM_REPLAY_FILE_ENDING = ".scfareplay"; private static final String FAF_LIFE_PROTOCOL = "faflive"; private static final String GPGNET_SCHEME = "gpgnet"; private static final String TEMP_SCFA_REPLAY_FILE_NAME = "temp.scfareplay"; private static final long MAX_REPLAYS = 300; private final ClientProperties clientProperties; private final PreferencesService preferencesService; private final ReplayFileReader replayFileReader; private final NotificationService notificationService; private final GameService gameService; private final TaskService taskService; private final I18n i18n; private final ReportingService reportingService; private final ApplicationContext applicationContext; private final PlatformService platformService; private final ReplayServer replayServer; private final FafService fafService; private final ModService modService; private final MapService mapService; @Inject public ReplayService(ClientProperties clientProperties, PreferencesService preferencesService, ReplayFileReader replayFileReader, NotificationService notificationService, GameService gameService, TaskService taskService, I18n i18n, ReportingService reportingService, ApplicationContext applicationContext, PlatformService platformService, ReplayServer replayServer, FafService fafService, ModService modService, MapService mapService) { this.clientProperties = clientProperties; this.preferencesService = preferencesService; this.replayFileReader = replayFileReader; this.notificationService = notificationService; this.gameService = gameService; this.taskService = taskService; this.i18n = i18n; this.reportingService = reportingService; this.applicationContext = applicationContext; this.platformService = platformService; this.replayServer = replayServer; this.fafService = fafService; this.modService = modService; this.mapService = mapService; } @VisibleForTesting static Integer parseSupComVersion(byte[] rawReplayBytes) { int versionDelimiterIndex = Bytes.indexOf(rawReplayBytes, (byte) 0x00); return Integer.parseInt(new String(rawReplayBytes, VERSION_OFFSET, versionDelimiterIndex - VERSION_OFFSET, US_ASCII)); } @VisibleForTesting static String parseMapName(byte[] rawReplayBytes) { int mapDelimiterIndex = Bytes.indexOf(rawReplayBytes, new byte[]{0x00, 0x0D, 0x0A, 0x1A}); String mapPath = new String(rawReplayBytes, MAP_NAME_OFFSET, mapDelimiterIndex - MAP_NAME_OFFSET, US_ASCII); return mapPath.split("/")[2]; } @VisibleForTesting static String guessModByFileName(String fileName) { String[] splitFileName = fileName.split("\\."); if (splitFileName.length > 2) { return splitFileName[splitFileName.length - 2]; } return KnownFeaturedMod.DEFAULT.getTechnicalName(); } /** * Loads some, but not all, local replays. Loading all local replays could result in OOME. */ @SneakyThrows public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { StreamSupport.stream(directoryStream.spliterator(), false) .sorted(Comparator.comparing(path -> noCatch(() -> Files.getLastModifiedTime((Path) path))).reversed()) .limit(MAX_REPLAYS) .forEach(replayFile -> { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).get(); mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.orElse(null)))); } catch (Exception e) { logger.warn("Could not read replay file '{}'", replayFile, e); moveCorruptedReplayFile(replayFile); } }); } return replayInfos; } private void moveCorruptedReplayFile(Path replayFile) { Path corruptedReplaysDirectory = preferencesService.getCorruptedReplaysDirectory(); noCatch(() -> createDirectories(corruptedReplaysDirectory)); Path target = corruptedReplaysDirectory.resolve(replayFile.getFileName()); logger.debug("Moving corrupted replay file from {} to {}", replayFile, target); noCatch(() -> move(replayFile, target)); notificationService.addNotification(new PersistentNotification( i18n.get("corruptedReplayFiles.notification"), WARN, singletonList( new Action(i18n.get("corruptedReplayFiles.show"), event -> platformService.reveal(replayFile)) ) )); } public void runReplay(Replay item) { if (item.getReplayFile() != null) { runReplayFile(item.getReplayFile()); } else { runOnlineReplay(item.getId()); } } public void runLiveReplay(int gameId, int playerId) { Game game = gameService.getByUid(gameId); if (game == null) { throw new RuntimeException("There's no game with ID: " + gameId); } URI uri = UriComponentsBuilder.newInstance() .scheme(FAF_LIFE_PROTOCOL) .host(clientProperties.getReplay().getRemoteHost()) .path("/" + gameId + "/" + playerId + SUP_COM_REPLAY_FILE_ENDING) .queryParam("map", UrlEscapers.urlFragmentEscaper().escape(game.getMapFolderName())) .queryParam("mod", game.getFeaturedMod()) .build() .toUri(); noCatch(() -> runLiveReplay(uri)); } public void runLiveReplay(URI uri) { logger.debug("Running replay from URL: {}", uri); if (!uri.getScheme().equals(FAF_LIFE_PROTOCOL)) { throw new IllegalArgumentException("Invalid protocol: " + uri.getScheme()); } Map<String, String> queryParams = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(uri.getQuery()); String gameType = queryParams.get("mod"); String mapName = noCatch(() -> decode(queryParams.get("map"), UTF_8.name())); Integer gameId = Integer.parseInt(uri.getPath().split("/")[1]); try { URI replayUri = new URI(GPGNET_SCHEME, null, uri.getHost(), uri.getPort(), uri.getPath(), null, null); gameService.runWithLiveReplay(replayUri, gameId, gameType, mapName) .exceptionally(throwable -> { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("liveReplayCouldNotBeStarted"), Severity.ERROR, throwable, asList(new DismissAction(i18n), new ReportAction(i18n, reportingService, throwable)) )); return null; }); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public CompletableFuture<Integer> startReplayServer(int gameUid) { return replayServer.start(gameUid); } public void stopReplayServer() { replayServer.stop(); } public void runReplay(Integer replayId) { runOnlineReplay(replayId); } public CompletableFuture<List<Replay>> getNewestReplays(int topElementCount, int page) { return fafService.getNewestReplays(topElementCount, page); } public CompletableFuture<List<Replay>> getHighestRatedReplays(int topElementCount, int page) { return fafService.getHighestRatedReplays(topElementCount, page); } public CompletableFuture<List<Replay>> findByQuery(String query, int maxResults, int page, SortConfig sortConfig) { return fafService.findReplaysByQuery(query, maxResults, page, sortConfig); } public CompletableFuture<Optional<Replay>> findById(int id) { return fafService.findReplayById(id); } public CompletableFuture<Path> downloadReplay(int id) { ReplayDownloadTask task = applicationContext.getBean(ReplayDownloadTask.class); task.setReplayId(id); return taskService.submitTask(task).getFuture(); } /** * Reads the specified replay file in order to add more information to the specified replay instance. */ public void enrich(Replay replay, Path path) { ReplayData replayData = replayFileReader.parseReplay(path); replay.getChatMessages().setAll(replayData.getChatMessages().stream() .map(chatMessage -> new ChatMessage(chatMessage.getTime(), chatMessage.getSender(), chatMessage.getMessage())) .collect(Collectors.toList()) ); replay.getGameOptions().setAll(replayData.getGameOptions().stream() .map(gameOption -> new GameOption(gameOption.getKey(), gameOption.getValue())) .collect(Collectors.toList()) ); } @SneakyThrows public CompletableFuture<Integer> getSize(int id) { return CompletableFuture.supplyAsync(() -> noCatch(() -> new URL(String.format(clientProperties.getVault().getReplayDownloadUrlFormat(), id)) .openConnection() .getContentLength())); } public boolean replayChangedRating(Replay replay) { return replay.getTeamPlayerStats().values().stream() .flatMap(Collection::stream) .anyMatch(playerStats -> playerStats.getAfterMean() != null && playerStats.getAfterDeviation() != null); } @SneakyThrows public void runReplayFile(Path path) { log.debug("Starting replay file: {}", path.toAbsolutePath()); String fileName = path.getFileName().toString(); if (fileName.endsWith(FAF_REPLAY_FILE_ENDING)) { runFafReplayFile(path); } else if (fileName.endsWith(SUP_COM_REPLAY_FILE_ENDING)) { runSupComReplayFile(path); } } private void runOnlineReplay(int replayId) { downloadReplay(replayId) .thenAccept(this::runReplayFile) .exceptionally(throwable -> { notificationService.addNotification(new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("replayCouldNotBeStarted", replayId), throwable, i18n, reportingService )); return null; }); } private void runFafReplayFile(Path path) throws IOException { byte[] rawReplayBytes = replayFileReader.readRawReplayData(path); Path tempSupComReplayFile = preferencesService.getCacheDirectory().resolve(TEMP_SCFA_REPLAY_FILE_NAME); createDirectories(tempSupComReplayFile.getParent()); Files.copy(new ByteArrayInputStream(rawReplayBytes), tempSupComReplayFile, StandardCopyOption.REPLACE_EXISTING); LocalReplayInfo replayInfo = replayFileReader.parseMetaData(path); String gameType = replayInfo.getFeaturedMod(); Integer replayId = replayInfo.getUid(); Map<String, Integer> modVersions = replayInfo.getFeaturedModVersions(); String mapName = replayInfo.getMapname(); Set<String> simMods = replayInfo.getSimMods() != null ? replayInfo.getSimMods().keySet() : emptySet(); Integer version = parseSupComVersion(rawReplayBytes); gameService.runWithReplay(tempSupComReplayFile, replayId, gameType, version, modVersions, simMods, mapName); } private void runSupComReplayFile(Path path) { byte[] rawReplayBytes = replayFileReader.readRawReplayData(path); Integer version = parseSupComVersion(rawReplayBytes); String mapName = parseMapName(rawReplayBytes); String fileName = path.getFileName().toString(); String gameType = guessModByFileName(fileName); gameService.runWithReplay(path, null, gameType, version, emptyMap(), emptySet(), mapName); } }
package com.github.davidmoten.rx.jdbc; import static com.github.davidmoten.rx.jdbc.Conditions.checkNotNull; import static com.github.davidmoten.rx.jdbc.Queries.bufferedParameters; import java.sql.ResultSet; import java.util.List; import rx.Observable; import rx.Observable.Operator; import rx.functions.Func1; import com.github.davidmoten.rx.jdbc.tuple.Tuple2; import com.github.davidmoten.rx.jdbc.tuple.Tuple3; import com.github.davidmoten.rx.jdbc.tuple.Tuple4; import com.github.davidmoten.rx.jdbc.tuple.Tuple5; import com.github.davidmoten.rx.jdbc.tuple.Tuple6; import com.github.davidmoten.rx.jdbc.tuple.Tuple7; import com.github.davidmoten.rx.jdbc.tuple.TupleN; import com.github.davidmoten.rx.jdbc.tuple.Tuples; /** * A query and its executable context. */ final public class QuerySelect implements Query { private final String sql; private final Observable<Parameter> parameters; private final QueryContext context; private Observable<?> depends = Observable.empty(); /** * Constructor. * * @param sql * @param parameters * @param depends * @param context */ private QuerySelect(String sql, Observable<Parameter> parameters, Observable<?> depends, QueryContext context) { checkNotNull(sql); checkNotNull(parameters); checkNotNull(depends); checkNotNull(context); this.sql = sql; this.parameters = parameters; this.depends = depends; this.context = context; } @Override public String sql() { return sql; } @Override public QueryContext context() { return context; } @Override public Observable<Parameter> parameters() { return parameters; } @Override public String toString() { return "QuerySelect [sql=" + sql + "]"; } @Override public Observable<?> depends() { return depends; } /** * Returns the results of running a select query with all sets of * parameters. * * @return */ public <T> Observable<T> execute(ResultSetMapper<? extends T> function) { return bufferedParameters(this) // execute once per set of parameters .concatMap(executeOnce(function)); } /** * Returns a {@link Func1} that itself returns the results of pushing one * set of parameters through a select query. * * @param query * @return */ private <T> Func1<List<Parameter>, Observable<T>> executeOnce( final ResultSetMapper<? extends T> function) { return new Func1<List<Parameter>, Observable<T>>() { @Override public Observable<T> call(List<Parameter> params) { return executeOnce(params, function); } }; } /** * Returns an Observable of the results of pushing one set of parameters * through a select query. * * @param params * one set of parameters to be run with the query * @return */ private <T> Observable<T> executeOnce(final List<Parameter> params, ResultSetMapper<? extends T> function) { return QuerySelectOperation.execute(this, params, function) .subscribeOn(context.scheduler()); } /** * Builds a {@link QuerySelect}. */ final public static class Builder { /** * Builds the standard stuff. */ private final QueryBuilder builder; /** * Constructor. * * @param sql * @param db */ public Builder(String sql, Database db) { builder = new QueryBuilder(sql, db); } /** * Appends the given parameters to the parameter list for the query. If * there are more parameters than required for one execution of the * query then more than one execution of the query will occur. * * @param parameters * @return this */ public <T> Builder parameters(Observable<T> parameters) { builder.parameters(parameters); return this; } /** * Appends the given parameter values to the parameter list for the * query. If there are more parameters than required for one execution * of the query then more than one execution of the query will occur. * * @param objects * @return this */ public Builder parameters(Object... objects) { builder.parameters(objects); return this; } /** * Appends a parameter to the parameter list for the query. If there are * more parameters than required for one execution of the query then * more than one execution of the query will occur. * * @param value * @return this */ public Builder parameter(Object value) { builder.parameter(value); return this; } /** * Appends a dependency to the dependencies that have to complete their * emitting before the query is executed. * * @param dependency * @return this */ public Builder dependsOn(Observable<?> dependency) { builder.dependsOn(dependency); return this; } /** * Appends a dependency on the result of the last transaction ( * <code>true</code> for commit or <code>false</code> for rollback) to * the dependencies that have to complete their emitting before the * query is executed. * * @return this */ public Builder dependsOnLastTransaction() { builder.dependsOnLastTransaction(); return this; } /** * Transforms the results using the given function. * * @param function * @return */ public <T> Observable<T> get(ResultSetMapper<? extends T> function) { return new QuerySelect(builder.sql(), builder.parameters(), builder.depends(), builder.context()).execute(function); } /** * <p> * Transforms each row of the {@link ResultSet} into an instance of * <code>T</code> using <i>automapping</i> of the ResultSet columns into * corresponding constructor parameters that are assignable. Beyond * normal assignable criteria (for example Integer 123 is assignable to * a Double) other conversions exist to facilitate the automapping: * </p> * <p> * They are: * <ul> * <li>java.sql.Blob &#10143; byte[]</li> * <li>java.sql.Blob &#10143; java.io.InputStream</li> * <li>java.sql.Clob &#10143; String</li> * <li>java.sql.Clob &#10143; java.io.Reader</li> * <li>java.sql.Date &#10143; java.util.Date</li> * <li>java.sql.Date &#10143; Long</li> * <li>java.sql.Timestamp &#10143; java.util.Date</li> * <li>java.sql.Timestamp &#10143; Long</li> * <li>java.sql.Time &#10143; java.util.Date</li> * <li>java.sql.Time &#10143; Long</li> * <li>java.math.BigInteger &#10143; * Short,Integer,Long,Float,Double,BigDecimal</li> * <li>java.math.BigDecimal &#10143; * Short,Integer,Long,Float,Double,BigInteger</li> * </p> * * @param cls * @return */ public <T> Observable<T> autoMap(Class<T> cls) { if (builder.sql() == null) { com.github.davidmoten.rx.jdbc.annotations.Query query = cls .getAnnotation(com.github.davidmoten.rx.jdbc.annotations.Query.class); if (query != null && query.value() != null) { String sql = query.value(); builder.setSql(sql); } else throw new RuntimeException( "Class " + cls + " must be annotated with @Query(sql) or sql must be specified to the builder.select() call"); } return get(Util.autoMap(cls)); } /** * Automaps the first column of the ResultSet into the target class * <code>cls</code>. * * @param cls * @return */ public <S> Observable<S> getAs(Class<S> cls) { return get(Tuples.single(cls)); } /** * Automaps all the columns of the {@link ResultSet} into the target * class <code>cls</code>. See {@link #autoMap(Class) autoMap()}. * * @param cls * @return */ public <S> Observable<TupleN<S>> getTupleN(Class<S> cls) { return get(Tuples.tupleN(cls)); } /** * Automaps all the columns of the {@link ResultSet} into {@link Object} * . See {@link #autoMap(Class) autoMap()}. * * @param cls * @return */ public <S> Observable<TupleN<Object>> getTupleN() { return get(Tuples.tupleN(Object.class)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @return */ public <T1, T2> Observable<Tuple2<T1, T2>> getAs(Class<T1> cls1, Class<T2> cls2) { return get(Tuples.tuple(cls1, cls2)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @return */ public <T1, T2, T3> Observable<Tuple3<T1, T2, T3>> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3) { return get(Tuples.tuple(cls1, cls2, cls3)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @return */ public <T1, T2, T3, T4> Observable<Tuple4<T1, T2, T3, T4>> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4) { return get(Tuples.tuple(cls1, cls2, cls3, cls4)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @return */ public <T1, T2, T3, T4, T5> Observable<Tuple5<T1, T2, T3, T4, T5>> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @param cls6 * @return */ public <T1, T2, T3, T4, T5, T6> Observable<Tuple6<T1, T2, T3, T4, T5, T6>> getAs( Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5, Class<T6> cls6) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @param cls6 * @param cls7 * @return */ public <T1, T2, T3, T4, T5, T6, T7> Observable<Tuple7<T1, T2, T3, T4, T5, T6, T7>> getAs( Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5, Class<T6> cls6, Class<T7> cls7) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6, cls7)); } public Observable<Integer> count() { return get(ResultSetMapperCount.INSTANCE).count(); } // Lazy singleton private static final class ResultSetMapperCount { static final ResultSetMapper<Integer> INSTANCE = new ResultSetMapper<Integer>() { @Override public Integer call(ResultSet rs) { return 1; } }; } /** * Returns an {@link Operator} to allow the query to be pushed * parameters via the {@link Observable#lift(Operator)} method. * * @return operator that acts on parameters */ public OperatorBuilder<Object> parameterOperator() { return new OperatorBuilder<Object>(this, OperatorType.PARAMETER); } /** * Returns an {@link Operator} to allow the query to be pushed * dependencies via the {@link Observable#lift(Operator)} method. * * @return operator that acts on dependencies */ public OperatorBuilder<Object> dependsOnOperator() { return new OperatorBuilder<Object>(this, OperatorType.DEPENDENCY); } /** * Returns an {@link Operator} that runs a select query for each list of * parameter objects in the source observable. * * @return */ public OperatorBuilder<Observable<Object>> parameterListOperator() { return new OperatorBuilder<Observable<Object>>(this, OperatorType.PARAMETER_LIST); } } /** * Builder pattern for select query {@link Operator}. */ public static class OperatorBuilder<R> { private final Builder builder; private final OperatorType operatorType; /** * Constructor. * * @param builder * @param operatorType */ public OperatorBuilder(Builder builder, OperatorType operatorType) { this.builder = builder; this.operatorType = operatorType; } /** * Transforms the results using the given function. * * @param function * @return */ public <T> Operator<T, R> get(ResultSetMapper<? extends T> function) { return new QuerySelectOperator<T, R>(builder, function, operatorType); } /** * See {@link Builder#autoMap(Class)}. * * @param cls * @return */ public <S> Operator<S, R> autoMap(Class<S> cls) { return get(Util.autoMap(cls)); } /** * Automaps the first column of the ResultSet into the target class * <code>cls</code>. * * @param cls * @return */ public <S> Operator<S, R> getAs(Class<S> cls) { return get(Tuples.single(cls)); } /** * Automaps all the columns of the {@link ResultSet} into the target * class <code>cls</code>. See {@link #autoMap(Class) autoMap()}. * * @param cls * @return */ public <S> Operator<TupleN<S>, R> getTupleN(Class<S> cls) { return get(Tuples.tupleN(cls)); } /** * Automaps all the columns of the {@link ResultSet} into {@link Object} * . See {@link #autoMap(Class) autoMap()}. * * @param cls * @return */ public <S> Operator<TupleN<Object>, R> getTupleN() { return get(Tuples.tupleN(Object.class)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @return */ public <T1, T2> Operator<Tuple2<T1, T2>, R> getAs(Class<T1> cls1, Class<T2> cls2) { return get(Tuples.tuple(cls1, cls2)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @return */ public <T1, T2, T3> Operator<Tuple3<T1, T2, T3>, R> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3) { return get(Tuples.tuple(cls1, cls2, cls3)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @return */ public <T1, T2, T3, T4> Operator<Tuple4<T1, T2, T3, T4>, R> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4) { return get(Tuples.tuple(cls1, cls2, cls3, cls4)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @return */ public <T1, T2, T3, T4, T5> Operator<Tuple5<T1, T2, T3, T4, T5>, R> getAs(Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @param cls6 * @return */ public <T1, T2, T3, T4, T5, T6> Operator<Tuple6<T1, T2, T3, T4, T5, T6>, R> getAs( Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5, Class<T6> cls6) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6)); } /** * Automaps the columns of the {@link ResultSet} into the specified * classes. See {@link #autoMap(Class) autoMap()}. * * @param cls1 * @param cls2 * @param cls3 * @param cls4 * @param cls5 * @param cls6 * @param cls7 * @return */ public <T1, T2, T3, T4, T5, T6, T7> Operator<Tuple7<T1, T2, T3, T4, T5, T6, T7>, R> getAs( Class<T1> cls1, Class<T2> cls2, Class<T3> cls3, Class<T4> cls4, Class<T5> cls5, Class<T6> cls6, Class<T7> cls7) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6, cls7)); } } }
package com.github.dozedoff.commonj.net; import java.io.BufferedInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for downloading binary data from the Internet. */ public class GetBinary { private long contentLenght = 0; private int offset = 0; private int failCount = 0; private int maxRetry = 3; private int readTimeoutInMilli = 10000; private ByteBuffer classBuffer; private final static Logger logger = LoggerFactory.getLogger(GetBinary.class); private final static String GET_METHOD = "GET", HEAD_METHOD = "HEAD"; public GetBinary() { classBuffer = ByteBuffer.allocate(15728640); // 15mb } public GetBinary(int size) { classBuffer = ByteBuffer.allocate(size); } @Deprecated /** * Use getViaHttp instead. * @param url * @return * @throws IOException */ public byte[] get(String url) throws IOException { return get(new URL(url)); } @Deprecated /** * Use getViaHttp instead. * @param url * @return * @throws IOException */ public byte[] get(URL url) throws IOException { BufferedInputStream binary = null; HttpURLConnection thread = null; try { thread = (HttpURLConnection) url.openConnection(); thread.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend to // be a // firefox // browser binary = new BufferedInputStream(thread.getInputStream()); classBuffer.clear(); // ByteBuffer bb = ByteBuffer.allocate(15728640); //15mb int count = 0; byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time while ((count = binary.read(c)) != -1) { classBuffer.put(c, 0, count); } classBuffer.flip(); byte[] varBuffer = new byte[classBuffer.limit()]; classBuffer.get(varBuffer); binary.close(); return varBuffer; } catch (IOException e) { throw new IOException("unable to connect to " + url.toString()); } finally { if (binary != null) binary.close(); if (thread != null) thread.disconnect(); } } public Long getLenght(URL url) throws IOException, PageLoadException { HttpURLConnection thread = null; try { thread = connect(url, HEAD_METHOD, true); thread.connect(); return Long.valueOf(thread.getHeaderField("Content-Length")); } catch (NumberFormatException nfe) { if (thread.getResponseCode() != 200) throw new PageLoadException(Integer.toString(thread.getResponseCode()), thread.getResponseCode()); throw new NumberFormatException("unable to parse " + url.toString()); } catch (SocketTimeoutException ste) { throw new SocketTimeoutException(ste.getMessage()); } catch (IOException e) { throw new IOException("unable to connect to " + url.toString()); } catch (ClassCastException cce) { logger.warn(cce.getMessage() + ", " + url.toString()); } finally { if (thread != null) thread.disconnect(); } return contentLenght; } public Map<String, List<String>> getHeader(URL url) throws IOException { HttpURLConnection thread = null; try { thread = connect(url, HEAD_METHOD, true); thread.connect(); return thread.getHeaderFields(); } catch (IOException e) { throw new IOException("unable to connect to " + url.toString()); } finally { if (thread != null) { thread.disconnect(); } } } public byte[] getRange(URL url, int start, long l) throws IOException, PageLoadException { BufferedInputStream binary = null; HttpURLConnection httpCon = null; try { httpCon = connect(url, GET_METHOD, true); httpCon.setRequestProperty("Range", "bytes=" + start + "-" + l); httpCon.connect(); binary = new BufferedInputStream(httpCon.getInputStream()); } catch (SocketTimeoutException ste) { if (httpCon != null) { httpCon.disconnect(); } throw new SocketTimeoutException(ste.getMessage()); } catch (IOException e) { if (httpCon != null) { httpCon.disconnect(); } throw new PageLoadException(Integer.toString(httpCon.getResponseCode()), httpCon.getResponseCode()); } int count = 0; byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time try { while ((count = binary.read(c)) != -1) { classBuffer.put(c, 0, count); } } catch (SocketException se) { logger.warn("SocketException, http response: " + httpCon.getResponseCode()); if (failCount < maxRetry) { try { Thread.sleep(5000); } catch (Exception ie) { } this.offset = classBuffer.position(); httpCon.disconnect(); failCount++; return getRange(url, offset, contentLenght - 1); } else { logger.warn("Buffer position at failure: " + classBuffer.position() + " URL: " + url.toString()); httpCon.disconnect(); throw new SocketException(); } } finally { if (binary != null) binary.close(); if (httpCon != null) { httpCon.disconnect(); } } if (failCount != 0) logger.info("GetBinary Successful -> " + classBuffer.position() + "/" + contentLenght + ", " + failCount + " tries, " + url.toString()); classBuffer.flip(); byte[] varBuffer = new byte[classBuffer.limit()]; classBuffer.get(varBuffer); classBuffer.clear(); return varBuffer; } public byte[] getViaHttp(String url) throws PageLoadException, IOException { return getViaHttp(new URL(url)); } public byte[] getViaHttp(URL url) throws IOException, PageLoadException { Long contentLenght = 0L; BufferedInputStream binary = null; HttpURLConnection httpCon = null; httpCon = connect(url, GET_METHOD, true); httpCon.connect(); if (httpCon.getResponseCode() != 200) { httpCon.disconnect(); throw new PageLoadException(String.valueOf(httpCon.getResponseCode()), httpCon.getResponseCode()); } contentLenght = httpCon.getContentLengthLong(); binary = new BufferedInputStream(httpCon.getInputStream()); int count = 0; byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time try { while ((count = binary.read(c)) != -1) { classBuffer.put(c, 0, count); } } catch (SocketException se) { // TODO remove this catch block, it's unused // try{Thread.sleep(5000);}catch(Exception ie){} this.offset = classBuffer.position(); if (failCount < maxRetry) { failCount++; logger.warn("GetBinary failed, reason: " + se.getLocalizedMessage() + " -> " + classBuffer.position() + "/" + contentLenght + " " + url.toString()); httpCon.disconnect(); return getRange(url, offset, contentLenght - 1); } else { throw new SocketException(); } } catch (NullPointerException npe) { logger.error("NullPointerException in GetBinary.getViaHttp"); return null; } finally { if (binary != null) binary.close(); if (httpCon != null) { httpCon.disconnect(); } } classBuffer.flip(); byte[] varBuffer = new byte[classBuffer.limit()]; classBuffer.get(varBuffer); classBuffer.clear(); return varBuffer; } private HttpURLConnection connect(URL url, String method, boolean isOutput) throws IOException, ProtocolException { HttpURLConnection httpCon; httpCon = (HttpURLConnection) url.openConnection(); // pretend to be a firefox browser httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); httpCon.setRequestMethod(method); httpCon.setDoOutput(isOutput); httpCon.setReadTimeout(readTimeoutInMilli); return httpCon; } public int getMaxRetry() { return maxRetry; } public void setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; } public boolean setReadTimeout(int milliSeconds) { if (milliSeconds >= 0) { this.readTimeoutInMilli = milliSeconds; return true; } else { return false; } } }
package com.github.fjdbc.query; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import com.github.fjdbc.util.Consumers; import com.github.fjdbc.util.FjdbcUtil; /** * Extract objects from a ResultSet. The object may map to one or many rows from the result set. */ @FunctionalInterface public interface ResultSetExtractor<T> { T extract(ResultSet rs) throws SQLException; default void extractAll(ResultSet rs, Consumer<? super T> callback) throws SQLException { while (rs.next()) { final T object = extract(rs); callback.accept(object); } } default List<T> extractAll(ResultSet rs) throws SQLException { final List<T> res = new ArrayList<>(); extractAll(rs, Consumers.toList(res)); return res; } default Iterator<T> iterator(ResultSet rs) { return new ResultSetIterator<>(rs, this); } /** * An iterator backed by a ResultSet. The ResultSet is closed when the last element is read. * * @param <T> */ public static class ResultSetIterator<T> implements Iterator<T> { private final ResultSet rs; private final ResultSetExtractor<T> extractor; private boolean _hasNext = true; /** * True if resultSet.next() has been called at least once, false otherwise. */ private boolean nextCalled = false; public ResultSetIterator(ResultSet rs, ResultSetExtractor<T> extractor) { this.rs = rs; this.extractor = extractor; } @Override public boolean hasNext() { try { // need to call next() at least once otherwise isLast doesn't work (MySql). if (!nextCalled) { final boolean next = rs.next(); nextCalled = true; if (!next) { FjdbcUtil.close(null, null, rs); _hasNext = false; return false; } } final boolean hasNext = _hasNext && !rs.isLast() && !rs.isAfterLast() && !rs.isClosed(); if (!hasNext) FjdbcUtil.close(null, null, rs); return hasNext; } catch (final SQLException e) { FjdbcUtil.close(null, null, rs); throw new RuntimeException(e); } } @Override public T next() { try { final boolean next = rs.next(); nextCalled = true; if (!next) { _hasNext = false; return null; } return extractor.extract(rs); } catch (final SQLException e) { FjdbcUtil.close(null, null, rs); throw new RuntimeException(e); } } } }
package com.github.games647.changeskin; import com.comphenix.protocol.utility.SafeCacheBuilder; import com.comphenix.protocol.wrappers.WrappedSignedProperty; import com.google.common.base.Charsets; import com.google.common.cache.CacheLoader; import com.google.common.collect.Maps; import com.google.common.io.Files; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.ParseException; public class ChangeSkin extends JavaPlugin { private static final String SKIN_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/"; private final Map<UUID, UUID> userPreferences = Maps.newHashMap(); //this is thread-safe in order to save and load from different threads like the skin download private final ConcurrentMap<UUID, WrappedSignedProperty> skinCache = SafeCacheBuilder .<UUID, WrappedSignedProperty>newBuilder() .maximumSize(1024 * 5) .expireAfterWrite(3, TimeUnit.HOURS) .build(new CacheLoader<UUID, WrappedSignedProperty>() { @Override public WrappedSignedProperty load(UUID key) throws Exception { //A key should be inserted manually on start packet throw new UnsupportedOperationException("Not supported"); } }); @Override public void onEnable() { loadPreferences(); getCommand("setskin").setExecutor(new SetSkinCommand(this)); getServer().getPluginManager().registerEvents(new PlayerLoginListener(this), this); } @Override public void onDisable() { savePreferences(); //clean up userPreferences.clear(); skinCache.clear(); } public ConcurrentMap<UUID, WrappedSignedProperty> getSkinCache() { return skinCache; } public Map<UUID, UUID> getUserPreferences() { return userPreferences; } public WrappedSignedProperty downloadSkin(UUID uuid) { //unsigned is needed in order to receive the signature String uuidString = uuid.toString().replace("-", "") + "?unsigned=false"; try { HttpURLConnection httpConnection = (HttpURLConnection) new URL(SKIN_URL + uuidString).openConnection(); httpConnection.addRequestProperty("Content-Type", "application/json"); BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String line = reader.readLine(); if (line != null && !line.equals("null")) { JSONObject userData = (JSONObject) JSONValue.parseWithException(line); JSONArray properties = (JSONArray) userData.get("properties"); JSONObject skinData = (JSONObject) properties.get(0); //base64 encoded skin data String encodedSkin = (String) skinData.get("value"); String signature = (String) skinData.get("signature"); return WrappedSignedProperty.fromValues("textures", encodedSkin, signature); } } catch (IOException ioException) { getLogger().log(Level.SEVERE, "Tried downloading skin data from Mojang", ioException); } catch (ParseException parseException) { getLogger().log(Level.SEVERE, "Tried parsing json from Mojang", parseException); } return null; } public UUID getUUID(String playerName) throws ParseException { try { HttpURLConnection httpConnection = (HttpURLConnection) new URL(UUID_URL + playerName).openConnection(); httpConnection.addRequestProperty("Content-Type", "application/json"); BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String line = reader.readLine(); if (line != null && !line.equals("null")) { JSONArray profiles = (JSONArray) JSONValue.parseWithException(line); JSONObject profile = (JSONObject) profiles.get(0); String id = (String) profile.get("id"); return parseId(id); } } catch (IOException iOException) { getLogger().log(Level.SEVERE, "Tried downloading skin data from Mojang", iOException); } catch (ParseException parseException) { getLogger().log(Level.SEVERE, "Tried parsing json from Mojang", parseException); } return null; } public void setSkin(Player player, UUID targetSkin) { userPreferences.put(player.getUniqueId(), targetSkin); if (!skinCache.containsKey(targetSkin)) { //download the skin only if it's not already in the cache Bukkit.getScheduler().runTaskAsynchronously(this, new SkinDownloader(this, player, targetSkin)); } } private UUID parseId(String withoutDashes) { return UUID.fromString(withoutDashes.substring(0, 8) + "-" + withoutDashes.substring(8, 12) + "-" + withoutDashes.substring(12, 16) + "-" + withoutDashes.substring(16, 20) + "-" + withoutDashes.substring(20, 32)); } private void savePreferences() { getDataFolder().mkdir(); File file = new File(getDataFolder(), "preferences.txt"); BufferedWriter bufferedWriter = null; try { if (!file.exists()) { file.createNewFile(); } bufferedWriter = Files.newWriter(file, Charsets.UTF_8); for (Map.Entry<UUID, UUID> entry : userPreferences.entrySet()) { bufferedWriter.write(entry.getKey().toString()); bufferedWriter.write(':'); bufferedWriter.write(entry.getValue().toString()); bufferedWriter.write(System.lineSeparator()); } bufferedWriter.flush(); } catch (IOException ioExc) { getLogger().log(Level.SEVERE, "Failed to save skin prefernces", ioExc); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException ioExc) { getLogger().log(Level.SEVERE, "Failed to close the file handle", ioExc); } } } } private void loadPreferences() { getDataFolder().mkdir(); File file = new File(getDataFolder(), "preferences.txt"); BufferedReader bufferedReader = null; try { if (!file.exists()) { file.createNewFile(); } bufferedReader = Files.newReader(file, Charsets.UTF_8); String currentLine = bufferedReader.readLine(); while (currentLine != null && !currentLine.isEmpty()) { String[] parts = currentLine.split(":"); UUID player = UUID.fromString(parts[0]); UUID target = UUID.fromString(parts[1]); userPreferences.put(player, target); currentLine = bufferedReader.readLine(); } } catch (IOException ioExc) { getLogger().log(Level.SEVERE, "Failed to load preferences", ioExc); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ioExc) { getLogger().log(Level.SEVERE, "Failed to close the file handle", ioExc); } } } } }
package com.github.horrorho.inflatabledonkey; import com.dd.plist.NSDictionary; import com.github.horrorho.inflatabledonkey.args.ArgsParser; import com.github.horrorho.inflatabledonkey.args.AuthenticationMapper; import com.github.horrorho.inflatabledonkey.args.Help; import com.github.horrorho.inflatabledonkey.args.OptionsFactory; import com.github.horrorho.inflatabledonkey.args.Property; import com.github.horrorho.inflatabledonkey.data.AccountInfo; import com.github.horrorho.inflatabledonkey.data.Auth; import com.github.horrorho.inflatabledonkey.data.Authenticator; import com.github.horrorho.inflatabledonkey.data.CKInit; import com.github.horrorho.inflatabledonkey.data.Tokens; import com.github.horrorho.inflatabledonkey.protocol.ChunkServer; import com.github.horrorho.inflatabledonkey.protocol.CloudKit; import com.github.horrorho.inflatabledonkey.protocol.ProtoBufArray; import com.github.horrorho.inflatabledonkey.requests.AccountSettingsRequestFactory; import com.github.horrorho.inflatabledonkey.requests.AuthorizeGetRequestFactory; import com.github.horrorho.inflatabledonkey.requests.CkAppInitBackupRequestFactory; import com.github.horrorho.inflatabledonkey.requests.Headers; import com.github.horrorho.inflatabledonkey.requests.M201RequestFactory; import com.github.horrorho.inflatabledonkey.requests.M211RequestFactory; import com.github.horrorho.inflatabledonkey.requests.MappedHeaders; import com.github.horrorho.inflatabledonkey.requests.ProtoBufsRequestFactory; import com.github.horrorho.inflatabledonkey.responsehandler.InputStreamResponseHandler; import com.github.horrorho.inflatabledonkey.responsehandler.JsonResponseHandler; import com.github.horrorho.inflatabledonkey.responsehandler.PropertyListResponseHandler; import com.github.horrorho.inflatabledonkey.util.PLists; import com.google.protobuf.ByteString; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); /** * @param args the command line arguments * @throws IOException */ public static void main(String[] args) throws IOException { // Command line arguments. AuthenticationMapper authenticationMapper = AuthenticationMapper.instance(); OptionsFactory optionsFactory = OptionsFactory.create(); ArgsParser<Property> argsParser = new ArgsParser<>(optionsFactory); Map<Property, String> arguments = new HashMap<>(); try { List<String> operands = argsParser.apply(args, arguments); if (arguments.containsKey(Property.ARGS_HELP)) { Help.instance().accept(optionsFactory.get().keySet()); System.exit(0); } arguments.putAll(authenticationMapper.apply(operands)); } catch (IllegalArgumentException ex) { System.out.println("Error: " + ex.getMessage()); System.out.println("Try '" + Property.APP_NAME.defaultValue() + " --help' for more information."); System.exit(0); } logger.debug("-- main() - arguments: {}", arguments); // Session constants String deviceID = new BigInteger(256, ThreadLocalRandom.current()).toString(16).toUpperCase(Locale.US); //deviceID = "51378363AF15278F992AEB76026C539217D49B2F678DB559F33B53528FAD291C"; String container = "com.apple.backup.ios"; String bundle = "com.apple.backupd"; String ckdFetchRecordZonesOperation = "CKDFetchRecordZonesOperation"; Headers coreHeaders = new MappedHeaders( new BasicHeader(Headers.userAgent, "CloudKit/479 (13A404)"), new BasicHeader(Headers.xMmeClientInfo, "<iPhone5,3> <iPhone OS;9.0.1;13A404> <com.apple.cloudkit.CloudKitDaemon/479 (com.apple.cloudd/479)>"), new BasicHeader(Headers.xCloudKitProtocolVersion, "client=1;comments=1;device=1;presence=1;records=1;sharing=1;subscriptions=1;users=1;mescal=1;"), new BasicHeader(Headers.xAppleMmcsProtoVersion, "4.0") ); CloudKit.String mbksync = CloudKit.String.newBuilder() .setValue("mbksync") .setEncoding(6) .build(); CloudKit.String defaultZone = CloudKit.String.newBuilder() .setValue("_defaultZone") .setEncoding(6) .build(); CloudKit.String backupAccount = CloudKit.String.newBuilder() .setValue("BackupAccount") .setEncoding(1) .build(); CloudKit.String seven = CloudKit.String.newBuilder() .setValue(UUID.randomUUID().toString()) // Unknown session static UUID. .setEncoding(2) .build(); CloudKit.Info info = CloudKit.Info.newBuilder() .setContainer(container) .setBundle(bundle) .setF7(seven) .setOs("9.0.1") .setApp("com.apple.cloudkit.CloudKitDaemon") .setAppVersion("479") .setLimit1(40000) .setLimit2(40000) .setVersion("4.0") .setF19(1) .setDeviceName("My iPhone") .setDeviceID(deviceID) .setF23(1) .setF25(1) .build(); // Protobuf array response handler. InputStreamResponseHandler<List<CloudKit.Response>> ckResponseHandler = new InputStreamResponseHandler<>(inputStream -> ProtoBufArray.decode(inputStream, CloudKit.Response.PARSER)); // Default HttpClient. HttpClient httpClient = HttpClients.createDefault(); /* STEP 1. Authenticate via appleId/ password or dsPrsID:mmeAuthToken. No different to iOS8. */ logger.info("-- main() - STEP 1. Authenticate via appleId/ password or dsPrsID:mmeAuthToken."); Auth auth = arguments.containsKey(Property.AUTHENTICATION_TOKEN) ? new Auth(arguments.get(Property.AUTHENTICATION_TOKEN)) : new Authenticator(coreHeaders).authenticate( httpClient, arguments.get(Property.AUTHENTICATION_APPLEID), arguments.get(Property.AUTHENTICATION_PASSWORD)); logger.debug("-- main() - auth: {}", auth); logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken()); if (arguments.containsKey(Property.ARGS_TOKEN)) { System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken()); System.exit(0); } logger.info("-- main() - STEP 2. Account settings."); HttpUriRequest accountSettingsRequest = new AccountSettingsRequestFactory(coreHeaders) .apply(auth.dsPrsID(), auth.mmeAuthToken()); NSDictionary settings = httpClient.execute(accountSettingsRequest, PropertyListResponseHandler.nsDictionaryResponseHandler()); logger.debug("-- main() - account settings: {}", settings.toASCIIPropertyList()); AccountInfo accountInfo = new AccountInfo(PLists.get(settings, "appleAccountInfo")); Tokens tokens = new Tokens(PLists.get(settings, "tokens")); logger.info("-- main() - STEP 3. CloudKit Application Initialization."); HttpUriRequest ckAppInitRequest = CkAppInitBackupRequestFactory.create() .newRequest(accountInfo.dsPrsID(), tokens.mmeAuthToken(), tokens.cloudKitToken()); JsonResponseHandler<CKInit> jsonResponseHandler = new JsonResponseHandler<>(CKInit.class); CKInit ckInit = httpClient.execute(ckAppInitRequest, jsonResponseHandler); logger.debug("-- main() - ckInit: {}", ckInit); CloudKit.String ckUserId = CloudKit.String.newBuilder() .setValue(ckInit.cloudKitUserId()) .setEncoding(7) .build(); /* STEP 4. Record zones. Url ckDatabase from ckInit + /record/retrieve ~ pXX-ckdatabase.icloud.com:443//api/client/record/retrieve Headers similar to step 3 Message type 201 request (cloud_kit.proto) This proto is encoded with Apple's protobuf array encoding (see ProtoBufArray class). Possibility of passing multiple requests not yet explored. Returns record zone data. */ logger.info("-- main() - STEP 4. Record zones."); CloudKit.Request requestA = M201RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), mbksync, ckUserId, info); logger.debug("-- main() - record zones request: {}", requestA); HttpUriRequest postA = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestA), coreHeaders); List<CloudKit.Response> responseA = httpClient.execute(postA, ckResponseHandler); logger.debug("-- main() - record zones response: {}", responseA); /* STEP 5. Backup list. Url/ headers as step 4. Message type 211 request, protobuf array encoded. Returns device data/ backups. */ logger.info("-- main() - STEP 5. Backup list."); CloudKit.Request requestB = M211RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), backupAccount, mbksync, ckUserId, info); logger.debug("-- main() - backups request: {}", requestB); HttpUriRequest postB = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestB), coreHeaders); List<CloudKit.Response> responseB = httpClient.execute(postB, ckResponseHandler); logger.debug("-- main() - backup response: {}", responseB); List<String> devices = responseB.stream() .map(CloudKit.Response::getM211Response) .map(CloudKit.M211Response::getBody) .map(CloudKit.M211ResponseBody::getContainerList) .flatMap(Collection::stream) .filter(value -> value.getName().getValue().equals("devices")) .flatMap(value -> value.getData().getDataList().stream()) .map(x -> x.getXRecordID().getRecordID().getRecordName().getValue()) // TODO refactor .collect(Collectors.toList()); logger.info("-- main() - devices: {}", devices); if (devices.isEmpty()) { logger.info("-- main() - no devices"); System.exit(0); } /* STEP 6. Snapshot list. Url/ headers as step 5. Message type 211 with the required backup uuid, protobuf array encoded. Returns device/ snapshots/ keybag information. Timestamps are hex encoded double offsets to 01 Jan 2001 00:00:00 GMT (Cocoa/ Webkit reference date). */ logger.info("-- main() - STEP 6. Snapshot list."); CloudKit.String device = CloudKit.String.newBuilder() .setValue(devices.get(0)) // First device only. .setEncoding(1) .build(); CloudKit.Request requestC = M211RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), device, mbksync, ckUserId, info); logger.debug("-- main() - snapshots request: {}", requestC); HttpUriRequest postC = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestC), coreHeaders); List<CloudKit.Response> responseC = httpClient.execute(postC, ckResponseHandler); logger.debug("-- main() - snapshots response: {}", responseC); List<String> snapshots = responseC.stream() .map(CloudKit.Response::getM211Response) .map(CloudKit.M211Response::getBody) .map(CloudKit.M211ResponseBody::getContainerList) .flatMap(Collection::stream) .filter(value -> value.getName().getValue().equals("snapshots")) .flatMap(value -> value.getData().getDataList().stream()) .map(x -> x.getXRecordID().getRecordID().getRecordName().getValue()) .collect(Collectors.toList()); logger.info("-- main() - snapshots: {}", snapshots); if (snapshots.isEmpty()) { logger.info("-- main() - no snapshots for device: {}", devices.get(0)); System.exit(0); } /* STEP 7. Manifest list. Url/ headers as step 6. Message type 211 with the required snapshot uuid, protobuf array encoded. Returns system/ backup properties (bytes ? format ?? proto), quota information and manifest details. */ logger.info("-- main() - STEP 7. Manifest list."); CloudKit.String snapshot = CloudKit.String.newBuilder() .setValue(snapshots.get(0)) // First snapshot only. .setEncoding(1) .build(); CloudKit.Request requestD = M211RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), snapshot, mbksync, ckUserId, info); logger.debug("-- main() - manifests request: {}", requestD); HttpUriRequest postD = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestD), coreHeaders); List<CloudKit.Response> responseD = httpClient.execute(postD, ckResponseHandler); logger.debug("-- main() - manifests response: {}", responseD); List<String> manifests = responseD.stream() .map(CloudKit.Response::getM211Response) .map(CloudKit.M211Response::getBody) .map(CloudKit.M211ResponseBody::getContainerList) .flatMap(Collection::stream) .filter(value -> value.getName().getValue().equals("manifestIDs")) .map(CloudKit.Container::getData) .map(CloudKit.Data::getDataList) .flatMap(Collection::stream) .map(CloudKit.Data::getString) .collect(Collectors.toList()); logger.info("-- main() - manifests: {}", manifests); if (manifests.isEmpty()) { logger.info("-- main() - no manifests for snapshot: {}", snapshots.get(0)); System.exit(0); } // TODO revisit this method, we may be able to reduce the subsequent two server calls to one. // /* // STEP 8. Retrieve list of assets // // // Url ckDatabase from ckInit + /query/retrieve // ~ pXX-ckdatabase.icloud.com:443//api/client/query/retrieve // Headers as step 7. // Message type 220 with the required manifest string + ":0" appended, protobuf array encoded. // List of required fields "fileType", "protectionClass", "encryptedAttributes", "deleted", "keybag" // // Returns a rather somewhat familiar looking set of results but with encoded bytes. // Are these protobufs in protobufs? // */ // logger.info("-- main() - STEP 8 (obsolete). Retrieve list of assets"); // CloudKit.Names columns = CloudKit.Names.newBuilder() // .addName(CloudKit.Name.newBuilder().setValue("fileType").build()) // .addName(CloudKit.Name.newBuilder().setValue("protectionClass").build()) // .addName(CloudKit.Name.newBuilder().setValue("encryptedAttributes").build()) // .addName(CloudKit.Name.newBuilder().setValue("deleted").build()) // .addName(CloudKit.Name.newBuilder().setValue("keybag").build()) // .build(); // CloudKit.Name subField = CloudKit.Name.newBuilder().setValue("PrivilegedManifestDownload").build(); // record type // CloudKit.String manifest = CloudKit.String.newBuilder() // .setValue(manifests.get(0) + ":0") // .setEncoding(1) // .build(); // CloudKit.String defaultZone = CloudKit.String.newBuilder() // .setValue("_defaultZone") // .setEncoding(6) // .build(); // CloudKit.Request requestE = M220RequestFactory.instance() // .newRequest( // container, // bundle, // "CKDQueryOperation", // UUID.randomUUID().toString(), // subField, // field, // columns, // manifest, // defaultZone, // ckUserId, // info); // logger.debug("-- main() - asset request: {}", requestE); // HttpUriRequest postE = ProtoBufsRequestFactory.defaultInstance().newRequest( // ckInit.production().url() + "/query/retrieve", // container, // bundle, // ckInit.cloudKitUserId(), // tokens.cloudKitToken(), // UUID.randomUUID().toString(), // Arrays.asList(requestE), // coreHeaders); // List<CloudKit.Response> responseE = httpClient.execute(postE, ckResponseHandler); // logger.debug("-- main() - assets response: {}", responseE); /* STEP 8. Retrieve list of files. Url/ headers as step 7. Message type 211 with the required manifest, protobuf array encoded. Returns system/ backup properties (bytes ? format ?? proto), quota information and manifest details. Returns a rather somewhat familiar looking set of results but with encoded bytes. Are these protobufs in protobufs? */ logger.info("-- main() - STEP 8. Retrieve list of assets"); CloudKit.String manifest = CloudKit.String.newBuilder() .setValue(manifests.get(0) + ":0") // Increment if this manifest contains only 0 length files in step 9. .setEncoding(1) .build(); CloudKit.Request requestF = M211RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), manifest, defaultZone, ckUserId, info); logger.debug("-- main() - assets request: {}", requestF); HttpUriRequest postF = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestF), coreHeaders); List<CloudKit.Response> responseF = httpClient.execute(postF, ckResponseHandler); logger.debug("-- main() - assets response: {}", responseF); List<String> files = responseF.stream() .map(CloudKit.Response::getM211Response) .map(CloudKit.M211Response::getBody) .map(CloudKit.M211ResponseBody::getContainerList) .flatMap(Collection::stream) .filter(c -> c.getName().getValue().equals("files")) .map(CloudKit.Container::getData) .map(CloudKit.Data::getDataList) .flatMap(Collection::stream) .map(CloudKit.Data::getXRecordID) .map(CloudKit.XRecordID::getRecordID) .map(CloudKit.RecordID::getRecordName) .map(CloudKit.String::getValue) .collect(Collectors.toList()); logger.debug("-- main() - assets: {}", files); /* STEP 9. Retrieve asset tokens. Url/ headers as step 8. Message type 211 with the required file, protobuf array encoded. */ logger.info("-- main() - STEP 9. Retrieve list of asset tokens"); // F:UUID:token:length:x // Find first file that isn't 0 length. // Not ideal, as all files might be zero length in this manifest, but allows us a flat sequence of steps. String file = files.stream() .filter(a -> { // TOFIX fragile String[] split = a.split(":"); return !split[3].equals("0"); }) .findFirst() .orElseGet(null); if (file == null) { logger.warn("-- main() - empty manifest, please manually increment code manifest at step 8"); System.exit(0); } CloudKit.String fileRecord = CloudKit.String.newBuilder() .setValue(file) .setEncoding(1) .build(); CloudKit.Request requestG = M211RequestFactory.instance() .newRequest( container, bundle, ckdFetchRecordZonesOperation, UUID.randomUUID().toString(), fileRecord, defaultZone, ckUserId, info); logger.debug("-- main() - asset tokens request: {}", requestG); HttpUriRequest postG = ProtoBufsRequestFactory.defaultInstance().newRequest( ckInit.production().url() + "/record/retrieve", container, bundle, ckInit.cloudKitUserId(), tokens.cloudKitToken(), UUID.randomUUID().toString(), Arrays.asList(requestG), coreHeaders); List<CloudKit.Response> responseG = httpClient.execute(postG, ckResponseHandler); logger.debug("-- main() - asset tokens response: {}", responseG); /* STEP 10. AuthorizeGet. Process somewhat different to iOS8. New headers/ mmcs auth token. See AuthorizeGetRequestFactory for details. Returns a ChunkServer.FileGroup protobuf which is largely identical to iOS8. */ logger.info("-- main() - STEP 10. AuthorizeGet"); // Contents are protobufs within protobufs // They parse to form a file attributes object that contains our tokens. List<ByteString> contents = responseG.stream() .map(CloudKit.Response::getM211Response) .map(CloudKit.M211Response::getBody) .map(CloudKit.M211ResponseBody::getContainerList) .flatMap(Collection::stream) .filter(c -> c.getName().getValue().equals("contents")) .map(c -> c.getData()) .map(x -> x.getProto()) .collect(Collectors.toList()); ByteString content = contents.get(0); // TODO confusing, rename to file attributes or similar CloudKit.Asset asset = CloudKit.Asset.parseFrom(content); logger.debug("-- main() - file attributes: {}", asset); // TODO these encrypted attributes needs deciphering. // TODO Without them we don't know what our binary file data represents. // TODO But where is our decryption key? // TODO Possibly AES encrypted. // List<ByteString> encryptedAttributes = responseG.stream() // .map(CloudKit.Response::getM211Response) // .map(CloudKit.M211Response::getBody) // .map(CloudKit.M211ResponseBody::getContainerList) // .flatMap(Collection::stream) // .filter(c -> c.getName().getValue().equals("encryptedAttributes")) // .map(c -> c.getData()) // .map(x -> x.getBytes()) // .collect(Collectors.toList()); CloudKit.FileTokens fileTokens = FileTokensFactory.instance().apply(Arrays.asList(asset)); // TODO check mmcsurl and com.apple.Dataclass.Content url match. But is there a reason they shouldn't? HttpUriRequest authorizeGet = new AuthorizeGetRequestFactory(coreHeaders) .newRequest(auth.dsPrsID(), asset.getMmcsurl(), container, "_defaultZone", fileTokens); logger.debug("-- main() - authorizeGet request: {}", authorizeGet); ResponseHandler<ChunkServer.FileGroups> fileGroupsResponseHandler = new InputStreamResponseHandler<>(ChunkServer.FileGroups.PARSER::parseFrom); ChunkServer.FileGroups fileGroups = httpClient.execute(authorizeGet, fileGroupsResponseHandler); logger.debug("-- main() - fileGroups: {}", fileGroups); } } // TODO info limits have not been set
package com.jaamsim.BasicObjects; import com.jaamsim.DisplayModels.ShapeModel; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Samples.SampleExpInput; import com.jaamsim.input.ColourInput; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.StringInput; import com.jaamsim.units.DimensionlessUnit; public class BooleanIndicator extends DisplayEntity { @Keyword(description = "An expression returning a boolean value: zero = FALSE, non-zero = TRUE.", exampleList = {"'[Queue1].QueueLength > 2'", "[Server1].Working"}) private final SampleExpInput expInput; @Keyword(description = "The colour of the indicator when the property is true", exampleList = {"green"}) private final ColourInput trueColor; @Keyword(description = "The colour of the indicator when the property is false", exampleList = {"red"}) private final ColourInput falseColor; @Keyword(description = "The string displayed by the Text output when the property is true.", exampleList = {"'True text'"}) private final StringInput trueText; @Keyword(description = "The string displayed by the Text output when the property is false.", exampleList = {"'False text'"}) private final StringInput falseText; { expInput = new SampleExpInput("OutputName", "Key Inputs", null); expInput.setUnitType(DimensionlessUnit.class); expInput.setRequired(true); this.addInput(expInput); trueColor = new ColourInput("TrueColour", "Graphics", ColourInput.GREEN); this.addInput(trueColor); this.addSynonym(trueColor, "TrueColor"); falseColor = new ColourInput("FalseColour", "Graphics", ColourInput.RED); this.addInput(falseColor); this.addSynonym(falseColor, "FalseColor"); trueText = new StringInput("TrueText", "Graphics", "TRUE"); this.addInput(trueText); falseText = new StringInput("FalseText", "Graphics", "FALSE"); this.addInput(falseText); } public BooleanIndicator() { } @Override public void updateGraphics(double simTime) { if (expInput.getValue() == null) return; if (expInput.getValue().getNextSample(simTime) != 0.0d) setTagColour(ShapeModel.TAG_CONTENTS, trueColor.getValue()); else setTagColour(ShapeModel.TAG_CONTENTS, falseColor.getValue()); } @Output(name = "Text", description = "If the property is true, then return TrueText. If the property is false, then return FalseText.", unitType = DimensionlessUnit.class) public String getText(double simTime) { if (expInput.getValue() == null) return ""; if (expInput.getValue().getNextSample(simTime) != 0.0d) return trueText.getValue(); else return falseText.getValue(); } }
package com.kscs.util.plugins.xjc; import java.util.Iterator; import com.kscs.util.plugins.xjc.base.AbstractPlugin; import com.kscs.util.plugins.xjc.base.Opt; import com.kscs.util.plugins.xjc.base.PluginUtil; import com.kscs.util.plugins.xjc.outline.DefinedClassOutline; import com.kscs.util.plugins.xjc.outline.PropertyOutline; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JConditional; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * XJC Plugin to make generated classes immutable */ public class ImmutablePlugin extends AbstractPlugin { @Opt private String constructorAccess = "public"; @Opt protected boolean generateModifier = true; @Opt protected String modifierClassName = "Modifier"; @Opt protected String modifierMethodName = "modifier"; @Opt protected boolean fake = false; @Opt protected boolean collectionsAsIterable = false; @Override public String getOptionName() { return "Ximmutable"; } @Override public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException { final ApiConstructs apiConstructs = new ApiConstructs(outline, opt, errorHandler); for (final ClassOutline classOutline : outline.getClasses()) { final JDefinedClass definedClass = classOutline.implClass; for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) { final JFieldVar declaredField; if (fieldOutline.getPropertyInfo().isCollection() && !((declaredField = PluginUtil.getDeclaredField(fieldOutline)).type().isArray())) { final JClass elementType = ((JClass) declaredField.type()).getTypeParameters().get(0); final JMethod oldGetter = definedClass.getMethod("get" + fieldOutline.getPropertyInfo().getName(true), new JType[0]); final JType getterType = this.collectionsAsIterable ? apiConstructs.iterableClass.narrow(elementType) : oldGetter.type(); if(fake) { oldGetter.type(getterType); } else { final JFieldVar immutableField = definedClass.field(JMod.PROTECTED | JMod.TRANSIENT, declaredField.type(), getImmutableFieldName(declaredField), JExpr._null()); definedClass.methods().remove(oldGetter); final JMethod newGetter = definedClass.method(JMod.PUBLIC, getterType, oldGetter.name()); final JConditional ifFieldNull = newGetter.body()._if(JExpr._this().ref(declaredField).eq(JExpr._null())); ifFieldNull._then().assign(JExpr._this().ref(declaredField), JExpr._new(apiConstructs.arrayListClass.narrow(elementType))); final JConditional ifImmutableFieldNull = newGetter.body()._if(JExpr._this().ref(immutableField).eq(JExpr._null())); immutableInit(apiConstructs, ifImmutableFieldNull._then(), JExpr._this(), declaredField); newGetter.body()._return(JExpr._this().ref(immutableField)); } } else { if(!fake) { final String setterName = "set" + fieldOutline.getPropertyInfo().getName(true); final JMethod setterMethod = definedClass.getMethod(setterName, new JType[]{fieldOutline.getRawType()}); if (setterMethod != null) { setterMethod.mods().setProtected(); } } } if (!fake && !"public".equalsIgnoreCase(this.constructorAccess)) { final Iterator<JMethod> constructors = definedClass.constructors(); if (!constructors.hasNext()) { // generate protected/private no-arg constructor final JMethod constructor = definedClass.constructor("private".equalsIgnoreCase(this.constructorAccess) ? JMod.PRIVATE : JMod.PROTECTED); constructor.javadoc().append(getMessage("comment.constructor")); constructor.body().directStatement("// " + getMessage("comment.constructor")); } while (constructors.hasNext()) { final JMethod constructor = constructors.next(); if (constructor.params().isEmpty() && (constructor.mods().getValue() & JMod.PUBLIC) == JMod.PUBLIC) { if ("private".equals(this.constructorAccess.toLowerCase())) { constructor.mods().setPrivate(); } else { constructor.mods().setProtected(); } } } } } if(this.generateModifier) { try { final GroupInterfacePlugin groupInterfacePlugin = apiConstructs.findPlugin(GroupInterfacePlugin.class); if(groupInterfacePlugin != null) { ModifierGenerator.generateClass(apiConstructs, new DefinedClassOutline(apiConstructs, classOutline), this.modifierClassName, this.modifierClassName, groupInterfacePlugin.getGroupInterfacesForClass(apiConstructs, classOutline.implClass.fullName()), this.modifierMethodName); } else { ModifierGenerator.generateClass(apiConstructs, new DefinedClassOutline(apiConstructs, classOutline), this.modifierClassName, this.modifierMethodName); } } catch (final JClassAlreadyExistsException e) { errorHandler.error(new SAXParseException(e.getMessage(), classOutline.target.getLocator())); } } } return true; } String getImmutableFieldName(final FieldOutline fieldVar) { return fieldVar.getPropertyInfo().getName(false) + "_RO"; } String getImmutableFieldName(final PropertyOutline fieldVar) { return fieldVar.getFieldName() + "_RO"; } String getImmutableFieldName(final JFieldVar fieldVar) { return fieldVar.name() + "_RO"; } public void immutableInit(final ApiConstructs apiConstructs, final JBlock body, final JExpression instanceRef, final FieldOutline collectionField) { body.assign(instanceRef.ref(getImmutableFieldName(collectionField)), PluginUtil.nullSafe(collectionField, apiConstructs.unmodifiableList(instanceRef.ref(collectionField.getPropertyInfo().getName(false))))); } public void immutableInit(final ApiConstructs apiConstructs, final JBlock body, final JExpression instanceRef, final PropertyOutline collectionField) { body.assign(instanceRef.ref(getImmutableFieldName(collectionField)), PluginUtil.nullSafe(collectionField, apiConstructs.unmodifiableList(instanceRef.ref(collectionField.getFieldName())))); } public void immutableInit(final ApiConstructs apiConstructs, final JBlock body, final JExpression instanceRef, final JFieldVar declaredField) { body.assign(instanceRef.ref(getImmutableFieldName(declaredField)), PluginUtil.nullSafe(declaredField, apiConstructs.unmodifiableList(instanceRef.ref(declaredField)))); } }
package org.opennms.features.topology.plugins.topo.linkd.internal; import com.google.common.collect.Lists; import org.opennms.features.topology.api.GraphContainer; import org.opennms.features.topology.api.OperationContext; import org.opennms.features.topology.api.support.VertexHopGraphProvider; import org.opennms.features.topology.api.support.VertexHopGraphProvider.VertexHopCriteria; import org.opennms.features.topology.api.topo.*; import org.opennms.netmgt.dao.api.*; import org.opennms.netmgt.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; import javax.xml.bind.JAXBException; import java.io.File; import java.net.MalformedURLException; import java.util.*; public class EnhancedLinkdTopologyProvider extends AbstractLinkdTopologyProvider implements SearchProvider { private abstract class LinkDetail<K> { private final String m_id; private final Vertex m_source; private final K m_sourceLink; private final Vertex m_target; private final K m_targetLink; public LinkDetail(String id, Vertex source, K sourceLink, Vertex target, K targetLink){ m_id = id; m_source = source; m_sourceLink = sourceLink; m_target = target; m_targetLink = targetLink; } public abstract int hashCode(); public abstract boolean equals(Object obj); public abstract int getSourceIfIndex(); public abstract int getTargetIfIndex(); public abstract String getType(); public String getId() { return m_id; } public Vertex getSource() { return m_source; } public Vertex getTarget() { return m_target; } public K getSourceLink() { return m_sourceLink; } public K getTargetLink() { return m_targetLink; } } private class LldpLinkDetail extends LinkDetail<LldpLink>{ public LldpLinkDetail(String id, Vertex source, LldpLink sourceLink, Vertex target, LldpLink targetLink) { super(id, source, sourceLink, target, targetLink); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSourceLink() == null) ? 0 : getSourceLink().getId().hashCode()) + ((getTargetLink() == null) ? 0 : getTargetLink().getId().hashCode()); result = prime * result + ((getVertexNamespace() == null) ? 0 : getVertexNamespace().hashCode()); return result; } @Override public boolean equals(Object obj) { if(obj instanceof LldpLinkDetail){ LldpLinkDetail objDetail = (LldpLinkDetail)obj; return getId().equals(objDetail.getId()); } else { return false; } } @Override public int getSourceIfIndex() { return getSourceLink().getLldpPortIfindex(); } @Override public int getTargetIfIndex() { return getTargetLink().getLldpPortIfindex(); } @Override public String getType() { return "LLDP"; } } private class OspfLinkDetail extends LinkDetail<OspfLink>{ public OspfLinkDetail(String id, Vertex source, OspfLink sourceLink, Vertex target, OspfLink targetLink) { super(id, source, sourceLink, target, targetLink); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSourceLink() == null) ? 0 : getSourceLink().getId().hashCode()) + ((getTargetLink() == null) ? 0 : getTargetLink().getId().hashCode()); result = prime * result + ((getVertexNamespace() == null) ? 0 : getVertexNamespace().hashCode()); return result; } @Override public boolean equals(Object obj) { if(obj instanceof LldpLinkDetail){ OspfLinkDetail objDetail = (OspfLinkDetail)obj; return getId().equals(objDetail.getId()); } else { return false; } } @Override public int getSourceIfIndex() { return getSourceLink().getOspfIfIndex(); } @Override public int getTargetIfIndex() { return getTargetLink().getOspfIfIndex(); } @Override public String getType() { return "OSPF"; } } private class IsIsLinkDetail extends LinkDetail<Integer>{ private final int m_sourceIfindex; private final int m_targetIfindex; private final int m_sourceLinkId; private final int m_targetLinkId; public IsIsLinkDetail(String id, Vertex source, int sourceLinkId, Integer sourceIfIndex, Vertex target, int targetLinkId, Integer targetIfIndex) { super(id, source, null, target, null); m_sourceLinkId = sourceLinkId; m_targetLinkId = targetLinkId; m_sourceIfindex = sourceIfIndex; m_targetIfindex = targetIfIndex; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSourceLink() == null) ? 0 : m_sourceLinkId) + ((getTargetLink() == null) ? 0 : m_targetLinkId); result = prime * result + ((getVertexNamespace() == null) ? 0 : getVertexNamespace().hashCode()); return result; } @Override public boolean equals(Object obj) { if(obj instanceof LldpLinkDetail){ IsIsLinkDetail objDetail = (IsIsLinkDetail)obj; return getId().equals(objDetail.getId()); } else { return false; } } @Override public int getSourceIfIndex() { return m_sourceIfindex; } @Override public int getTargetIfIndex() { return m_targetIfindex; } @Override public String getType() { return "IsIs"; } } private interface LinkState { void setParentInterfaces(OnmsSnmpInterface sourceInterface, OnmsSnmpInterface targetInterface); String getLinkStatus(); } private static Logger LOG = LoggerFactory.getLogger(EnhancedLinkdTopologyProvider.class); static final String[] OPER_ADMIN_STATUS = new String[] { "&nbsp;", //0 (not supported) "Up", "Down", "Testing", "Unknown", "Dormant", "NotPresent", "LowerLayerDown" }; private LldpLinkDao m_lldpLinkDao; private OspfLinkDao m_ospfLinkDao; private IsIsLinkDao m_isisLinkDao; public final static String LLDP_EDGE_NAMESPACE = TOPOLOGY_NAMESPACE_LINKD + "::LLDP"; public final static String OSPF_EDGE_NAMESPACE = TOPOLOGY_NAMESPACE_LINKD + "::OSPF"; public final static String ISIS_EDGE_NAMESPACE = TOPOLOGY_NAMESPACE_LINKD + "::ISIS"; public EnhancedLinkdTopologyProvider() { } /** * Used as an init-method in the OSGi blueprint * @throws JAXBException * @throws MalformedURLException */ public void onInit() throws MalformedURLException, JAXBException { LOG.debug("init: loading topology."); load(null); } @Override @Transactional public void load(String filename) throws MalformedURLException, JAXBException { if (filename != null) { LOG.warn("Filename that was specified for linkd topology will be ignored: " + filename + ", using " + getConfigurationFile() + " instead"); } try{ //TODO: change to one query from the database that will return all links plus elements joined //This reset container is set in here for the demo, don't commit resetContainer(); getLldpLinks(); getOspfLinks(); getIsIsLinks(); } catch (Exception e){ String message = e.getMessage(); } LOG.debug("loadtopology: adding nodes without links: " + isAddNodeWithoutLink()); if (isAddNodeWithoutLink()) { List<OnmsNode> allNodes; allNodes = getAllNodesNoACL(); for (OnmsNode onmsnode: allNodes) { String nodeId = onmsnode.getNodeId(); if (getVertex(getVertexNamespace(), nodeId) == null) { LOG.debug("loadtopology: adding link-less node: " + onmsnode.getLabel()); addVertices(getVertex(onmsnode)); } } } File configFile = new File(getConfigurationFile()); if (configFile.exists() && configFile.canRead()) { LOG.debug("loadtopology: loading topology from configuration file: " + getConfigurationFile()); WrappedGraph graph = getGraphFromFile(configFile); // Add all groups to the topology for (WrappedVertex eachVertexInFile: graph.m_vertices) { if (eachVertexInFile.group) { LOG.debug("loadtopology: adding group to topology: " + eachVertexInFile.id); if (eachVertexInFile.namespace == null) { eachVertexInFile.namespace = getVertexNamespace(); LoggerFactory.getLogger(this.getClass()).warn("Setting namespace on vertex to default: {}", eachVertexInFile); } if (eachVertexInFile.id == null) { LoggerFactory.getLogger(this.getClass()).warn("Invalid vertex unmarshalled from {}: {}", getConfigurationFile(), eachVertexInFile); } AbstractVertex newGroupVertex = addGroup(eachVertexInFile.id, eachVertexInFile.iconKey, eachVertexInFile.label); newGroupVertex.setIpAddress(eachVertexInFile.ipAddr); newGroupVertex.setLocked(eachVertexInFile.locked); if (eachVertexInFile.nodeID != null) newGroupVertex.setNodeID(eachVertexInFile.nodeID); if (!newGroupVertex.equals(eachVertexInFile.parent)) newGroupVertex.setParent(eachVertexInFile.parent); newGroupVertex.setSelected(eachVertexInFile.selected); newGroupVertex.setStyleName(eachVertexInFile.styleName); newGroupVertex.setTooltipText(eachVertexInFile.tooltipText); if (eachVertexInFile.x != null) newGroupVertex.setX(eachVertexInFile.x); if (eachVertexInFile.y != null) newGroupVertex.setY(eachVertexInFile.y); } } for (Vertex vertex: getVertices()) { if (vertex.getParent() != null && !vertex.equals(vertex.getParent())) { LOG.debug("loadtopology: setting parent of " + vertex + " to " + vertex.getParent()); setParent(vertex, vertex.getParent()); } } // Add all children to the specific group // Attention: We ignore all other attributes, they do not need to be merged! for (WrappedVertex eachVertexInFile : graph.m_vertices) { if (!eachVertexInFile.group && eachVertexInFile.parent != null) { final Vertex child = getVertex(eachVertexInFile); final Vertex parent = getVertex(eachVertexInFile.parent); if (child == null || parent == null) continue; LOG.debug("loadtopology: setting parent of " + child + " to " + parent); if (!child.equals(parent)) setParent(child, parent); } } } else { LOG.debug("loadtopology: could not load topology configFile:" + getConfigurationFile()); } LOG.debug("Found " + getGroups().size() + " groups"); LOG.debug("Found " + getVerticesWithoutGroups().size() + " vertices"); LOG.debug("Found " + getEdges().size() + " edges"); } private void getOspfLinks() { List<OspfLink> allLinks = getOspfLinkDao().findAll(); Set<OspfLinkDetail> combinedLinkDetails = new HashSet<OspfLinkDetail>(); for(OspfLink sourceLink : allLinks) { for (OspfLink targetLink : allLinks) { boolean ipAddrCheck = sourceLink.getOspfRemIpAddr().equals(targetLink.getOspfIpAddr()) && targetLink.getOspfRemIpAddr().equals(sourceLink.getOspfIpAddr()); if(ipAddrCheck) { String id = "ospf::" + Math.min(sourceLink.getId(), targetLink.getId()) + "||" + Math.max(sourceLink.getId(), targetLink.getId()); Vertex source = new AbstractVertex(AbstractLinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, sourceLink.getNode().getNodeId(), sourceLink.getNode().getLabel()); Vertex target = new AbstractVertex(AbstractLinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, targetLink.getNode().getNodeId(), targetLink.getNode().getLabel()); OspfLinkDetail linkDetail = new OspfLinkDetail( Math.min(sourceLink.getId(), targetLink.getId()) + "|" + Math.max(sourceLink.getId(), targetLink.getId()), source, sourceLink, target, targetLink); combinedLinkDetails.add(linkDetail); } } } for (OspfLinkDetail linkDetail : combinedLinkDetails) { AbstractEdge edge = connectVertices(linkDetail.getId(), linkDetail.getSource(), linkDetail.getTarget(), OSPF_EDGE_NAMESPACE); edge.setTooltipText(getEdgeTooltipText(linkDetail)); } } private void getLldpLinks() { List<LldpLink> allLinks = m_lldpLinkDao.findAll(); Set<LldpLinkDetail> combinedLinkDetails = new HashSet<LldpLinkDetail>(); for (LldpLink sourceLink : allLinks) { LOG.debug("loadtopology: parsing link: " + sourceLink); OnmsNode sourceNode = sourceLink.getNode(); LldpElement sourceElement = sourceNode.getLldpElement(); LOG.debug("loadtopology: found source node: " + sourceNode.getLabel()); Vertex source = getVertex(getVertexNamespace(), sourceNode.getNodeId()); if (source == null) { LOG.debug("loadtopology: adding source node as vertex: " + sourceNode.getLabel()); source = getVertex(sourceNode); addVertices(source); } for (LldpLink targetLink : allLinks) { OnmsNode targetNode = targetLink.getNode(); LldpElement targetLldpElement = targetNode.getLldpElement(); //Compare the remote data to the targetNode element data boolean bool1 = sourceLink.getLldpRemPortId().equals(targetLink.getLldpPortId()) && targetLink.getLldpRemPortId().equals(sourceLink.getLldpPortId()); boolean bool2 = sourceLink.getLldpRemPortDescr().equals(targetLink.getLldpPortDescr()) && targetLink.getLldpRemPortDescr().equals(sourceLink.getLldpPortDescr()); boolean bool3 = sourceLink.getLldpRemChassisId().equals(targetLldpElement.getLldpChassisId()) && targetLink.getLldpRemChassisId().equals(sourceElement.getLldpChassisId()); boolean bool4 = sourceLink.getLldpRemSysname().equals(targetLldpElement.getLldpSysname()) && targetLink.getLldpRemSysname().equals(sourceElement.getLldpSysname()); boolean bool5 = sourceLink.getLldpRemPortIdSubType() == targetLink.getLldpPortIdSubType() && targetLink.getLldpRemPortIdSubType() == sourceLink.getLldpPortIdSubType(); if (bool1 && bool2 && bool3 && bool4 && bool5) { Vertex target = getVertex(getVertexNamespace(), targetNode.getNodeId()); if (target == null) { target = getVertex(targetNode); } LldpLinkDetail linkDetail = new LldpLinkDetail( Math.min(sourceLink.getId(), targetLink.getId()) + "|" + Math.max(sourceLink.getId(), targetLink.getId()), source, sourceLink, target, targetLink); combinedLinkDetails.add(linkDetail); } } } for (LldpLinkDetail linkDetail : combinedLinkDetails) { AbstractEdge edge = connectVertices(linkDetail.getId(), linkDetail.getSource(), linkDetail.getTarget(), LLDP_EDGE_NAMESPACE); edge.setTooltipText(getEdgeTooltipText(linkDetail)); } } private void getIsIsLinks(){ List<Object[]> isislinks = m_isisLinkDao.getLinksForTopology(); for (Object[] linkObj : isislinks) { Integer link1Id = (Integer) linkObj[1]; Integer link1Nodeid = (Integer) linkObj[2]; Integer link1IfIndex = (Integer) linkObj[3]; Integer link2Id = (Integer) linkObj[4]; Integer link2Nodeid = (Integer) linkObj[5]; Integer link2IfIndex = (Integer) linkObj[6]; IsIsLinkDetail linkDetail = new IsIsLinkDetail( Math.min(link1Id, link2Id) + "|" + Math.max(link1Id, link2Id), getVertex(m_nodeDao.get(link1Nodeid)), link1Id, link1IfIndex, getVertex(m_nodeDao.get(link2Nodeid)), link2Id, link2IfIndex ); AbstractEdge edge = connectVertices(linkDetail.getId(), linkDetail.getSource(), linkDetail.getTarget(), ISIS_EDGE_NAMESPACE); edge.setTooltipText(getEdgeTooltipText(linkDetail)); } } @Override public void refresh() { try { load(null); } catch (MalformedURLException e) { LOG.error(e.getMessage(), e); } catch (JAXBException e) { LOG.error(e.getMessage(), e); } } private String getEdgeTooltipText(LinkDetail linkDetail) { StringBuffer tooltipText = new StringBuffer(); Vertex source = linkDetail.getSource(); Vertex target = linkDetail.getTarget(); OnmsSnmpInterface sourceInterface = getByNodeIdAndIfIndex(linkDetail.getSourceIfIndex(), source); OnmsSnmpInterface targetInterface = getByNodeIdAndIfIndex(linkDetail.getTargetIfIndex(), target); tooltipText.append(HTML_TOOLTIP_TAG_OPEN); if (sourceInterface != null && targetInterface != null && sourceInterface.getNetMask() != null && !sourceInterface.getNetMask().isLoopbackAddress() && targetInterface.getNetMask() != null && !targetInterface.getNetMask().isLoopbackAddress()) { tooltipText.append("Type of Link: " + linkDetail.getType() + " Layer3/Layer2"); } else { tooltipText.append("Type of Link: " + linkDetail.getType() + " Layer2"); } tooltipText.append(HTML_TOOLTIP_TAG_END); tooltipText.append(HTML_TOOLTIP_TAG_OPEN); tooltipText.append( "Name: &lt;endpoint1 " + source.getLabel()); if (sourceInterface != null ) tooltipText.append( ":"+sourceInterface.getIfName()); tooltipText.append( " ---- endpoint2 " + target.getLabel()); if (targetInterface != null) tooltipText.append( ":"+targetInterface.getIfName()); tooltipText.append("&gt;"); tooltipText.append(HTML_TOOLTIP_TAG_END); if ( targetInterface != null) { if (targetInterface.getIfSpeed() != null) { tooltipText.append(HTML_TOOLTIP_TAG_OPEN); tooltipText.append( "Bandwidth: " + getHumanReadableIfSpeed(targetInterface.getIfSpeed())); tooltipText.append(HTML_TOOLTIP_TAG_END); } } else if (sourceInterface != null) { if (sourceInterface.getIfSpeed() != null) { tooltipText.append(HTML_TOOLTIP_TAG_OPEN); tooltipText.append( "Bandwidth: " + getHumanReadableIfSpeed(sourceInterface.getIfSpeed())); tooltipText.append(HTML_TOOLTIP_TAG_END); } } tooltipText.append(HTML_TOOLTIP_TAG_OPEN); tooltipText.append( "End Point 1: " + source.getLabel() + ", " + source.getIpAddress()); tooltipText.append(HTML_TOOLTIP_TAG_END); tooltipText.append(HTML_TOOLTIP_TAG_OPEN); tooltipText.append( "End Point 2: " + target.getLabel() + ", " + target.getIpAddress()); tooltipText.append(HTML_TOOLTIP_TAG_END); return tooltipText.toString(); } private OnmsSnmpInterface getByNodeIdAndIfIndex(Integer ifIndex, Vertex source) { if(source.getId() != null && ifIndex != null) return getSnmpInterfaceDao().findByNodeIdAndIfIndex(Integer.parseInt(source.getId()), ifIndex); return null; } public void setLldpLinkDao(LldpLinkDao lldpLinkDao) { m_lldpLinkDao = lldpLinkDao; } public LldpLinkDao getLldpLinkDao() { return m_lldpLinkDao; } public void setOspfLinkDao(OspfLinkDao ospfLinkDao) { m_ospfLinkDao = ospfLinkDao; } public OspfLinkDao getOspfLinkDao(){ return m_ospfLinkDao; } public IsIsLinkDao getIsisLinkDao() { return m_isisLinkDao; } public void setIsisLinkDao(IsIsLinkDao isisLinkDao) { m_isisLinkDao = isisLinkDao; } //Search Provider methods @Override public String getSearchProviderNamespace() { return TOPOLOGY_NAMESPACE_LINKD; } @Override public VertexHopCriteria getDefaultCriteria() { return null; } @Override public List<SearchResult> query(SearchQuery searchQuery, GraphContainer graphContainer) { //LOG.debug("SearchProvider->query: called with search query: '{}'", searchQuery); List<Vertex> vertices = getFilteredVertices(); List<SearchResult> searchResults = Lists.newArrayList(); for(Vertex vertex : vertices){ if(searchQuery.matches(vertex.getLabel())) { searchResults.add(new SearchResult(vertex)); } } //LOG.debug("SearchProvider->query: found {} search results.", searchResults.size()); return searchResults; } @Override public void onFocusSearchResult(SearchResult searchResult, OperationContext operationContext) { } @Override public void onDefocusSearchResult(SearchResult searchResult, OperationContext operationContext) { } @Override public boolean supportsPrefix(String searchPrefix) { return AbstractSearchProvider.supportsPrefix("nodes=", searchPrefix); } @Override public Set<VertexRef> getVertexRefsBy(SearchResult searchResult, GraphContainer container) { LOG.debug("SearchProvider->getVertexRefsBy: called with search result: '{}'", searchResult); org.opennms.features.topology.api.topo.Criteria criterion = findCriterion(searchResult.getId(), container); Set<VertexRef> vertices = ((VertexHopCriteria)criterion).getVertices(); LOG.debug("SearchProvider->getVertexRefsBy: found '{}' vertices.", vertices.size()); return vertices; } @Override public void addVertexHopCriteria(SearchResult searchResult, GraphContainer container) { LOG.debug("SearchProvider->addVertexHopCriteria: called with search result: '{}'", searchResult); VertexHopCriteria criterion = LinkdHopCriteriaFactory.createCriteria(searchResult.getId(), searchResult.getLabel()); container.addCriteria(criterion); LOG.debug("SearchProvider->addVertexHop: adding hop criteria {}.", criterion); logCriteriaInContainer(container); } @Override public void removeVertexHopCriteria(SearchResult searchResult, GraphContainer container) { LOG.debug("SearchProvider->removeVertexHopCriteria: called with search result: '{}'", searchResult); Criteria criterion = findCriterion(searchResult.getId(), container); if (criterion != null) { LOG.debug("SearchProvider->removeVertexHopCriteria: found criterion: {} for searchResult {}.", criterion, searchResult); container.removeCriteria(criterion); } else { LOG.debug("SearchProvider->removeVertexHopCriteria: did not find criterion for searchResult {}.", searchResult); } logCriteriaInContainer(container); } @Override public void onCenterSearchResult(SearchResult searchResult, GraphContainer graphContainer) { LOG.debug("SearchProvider->onCenterSearchResult: called with search result: '{}'", searchResult); } @Override public void onToggleCollapse(SearchResult searchResult, GraphContainer graphContainer) { LOG.debug("SearchProvider->onToggleCollapse: called with search result: '{}'", searchResult); } private org.opennms.features.topology.api.topo.Criteria findCriterion(String resultId, GraphContainer container) { org.opennms.features.topology.api.topo.Criteria[] criteria = container.getCriteria(); for (org.opennms.features.topology.api.topo.Criteria criterion : criteria) { if (criterion instanceof LinkdHopCriteria ) { String id = ((LinkdHopCriteria) criterion).getId(); if (id.equals(resultId)) { return criterion; } } if (criterion instanceof VertexHopGraphProvider.FocusNodeHopCriteria) { String id = ((VertexHopGraphProvider.FocusNodeHopCriteria)criterion).getId(); if (id.equals(resultId)) { return criterion; } } } return null; } private void logCriteriaInContainer(GraphContainer container) { Criteria[] criteria = container.getCriteria(); LOG.debug("SearchProvider->addVertexHopCriteria: there are now {} criteria in the GraphContainer.", criteria.length); for (Criteria crit : criteria) { LOG.debug("SearchProvider->addVertexHopCriteria: criterion: '{}' is in the GraphContainer.", crit); } } }
package algorithms.imageProcessing; import algorithms.util.PairIntArray; import algorithms.util.SimpleLinkedListNode; import java.util.Arrays; import java.util.logging.Logger; public class DFSContiguousValueFinder { /** * an array to hold each group as an item. each item contains a key which is an index * to arrays indexer.x, indexer.y and this.pointToGroupIndex */ protected SimpleLinkedListNode[] groupMembership = null; protected int nGroups = 0; protected Logger log = null; // 0 = unvisited, 1 = processing, 2 = visited protected int[] color = null; /* * array holding indexes for a point to the group it belongs to. * note that the point index is relative to indexer.x and indexer.y */ protected int[] pointToGroupIndex = null; protected int minimumNumberInCluster = 3; protected boolean notValue = false; protected boolean debug = false; protected final GreyscaleImage img; public DFSContiguousValueFinder(final GreyscaleImage input) { this.img = input; this.log = Logger.getLogger(this.getClass().getName()); } public void setMinimumNumberInCluster(int n) { this.minimumNumberInCluster = n; } public void setDebug(boolean setDebugToTrue) { this.debug = setDebugToTrue; } protected void initializeVariables() { pointToGroupIndex = new int[img.getNPixels()]; Arrays.fill(pointToGroupIndex, -1); groupMembership = new SimpleLinkedListNode[10]; for (int i = 0; i < groupMembership.length; i++) { groupMembership[i] = new SimpleLinkedListNode(); } } /** * NOTE: to keep the performance reasonable, bin the image so that * the number of pixels is below 87000 pixels. * * @param pixelValue */ public void findGroups(int pixelValue) { initializeVariables(); findClusters(pixelValue); prune(); } /** * NOTE: to keep the performance reasonable, bin the image so that * the number of pixels is below 87000 pixels. * * @param pixelValue */ public void findGroupsNotThisValue(int pixelValue) { notValue = true; initializeVariables(); findClusters(pixelValue); prune(); } protected void findClusters(int pixelValue) { // traverse the data by ordered x values // so can break when exceed critical distance // 0 = unvisited, 1 = processing, 2 = visited color = new int[img.getNPixels()]; findClustersIterative(pixelValue); } /** * NOTE: to keep the performance reasonable, the use of jvm stack has to * be reduced. For default jvm settings, the size of the local array variable * within this method frame should be kept to having fewer that 128k items * in it, therefore the GreyscaleImage should be binned before use to keep * the number of pixels below 128k/1.5 (roughly keep below 87000 pixels). * If all pixels are connected, that limit has to be lowered. * * @param pixelValue */ protected void findClustersIterative(int pixelValue) { Runtime runtime = Runtime.getRuntime(); log.info("memFree=" + runtime.freeMemory()); int width = img.getWidth(); int height = img.getHeight(); java.util.Stack<Integer> stack = new java.util.Stack<Integer>(); for (int uIndex = (img.getNPixels() - 1); uIndex > -1; uIndex stack.add(Integer.valueOf(uIndex)); } color[stack.peek().intValue()] = 2; int ni = 0; while (!stack.isEmpty()) { ni++; if ((ni % 1000) == 0) { log.info("memFree=" + runtime.freeMemory()); } int uIndex = stack.pop().intValue(); int uPixValue = img.getValue(uIndex); if ((notValue && (uPixValue == pixelValue)) || (!notValue && (uPixValue != pixelValue))) { color[uIndex] = 2; continue; } /* note to speed this up a little, have copied out the index to row and col relationship from GreyscaleImage. */ int uY = uIndex/width; int uX = uIndex - (uY * width); //(1 + frac)*O(N) where frac is the fraction added back to stack for (int vX = (uX - 1); vX <= (uX + 1); vX++) { if ((vX < 0) || (vX > (width - 1))) { continue; } for (int vY = (uY - 1); vY <= (uY + 1); vY++) { if ((vY < 0) || (vY > (height - 1))) { continue; } int vIndex = (vY * width) + vX; if (color[vIndex] != 0 || (uIndex == vIndex)) { continue; } //TODO: could consider not allowing diagonal connections color[vIndex] = 2; int vPixValue = img.getValue(vIndex); if ((notValue && (vPixValue == pixelValue)) || (!notValue && (vPixValue != pixelValue))) { continue; } processPair(uIndex, vIndex); // inserting back at the top of the stack assures that the // search continues next from an associated point stack.add(Integer.valueOf(vIndex)); } } } } protected void processPair(int uIdx, int vIdx) { //log.finest("processPair " + uSortedXIndex + ":" + vSortedXIndex); int groupId; if ((pointToGroupIndex[uIdx] > -1) && (pointToGroupIndex[vIdx] == -1)) { groupId = pointToGroupIndex[uIdx]; pointToGroupIndex[vIdx] = groupId; groupMembership[groupId].insert(vIdx); } else if ((pointToGroupIndex[vIdx] > -1) && (pointToGroupIndex[uIdx] == -1)) { groupId = pointToGroupIndex[vIdx]; pointToGroupIndex[uIdx] = groupId; groupMembership[groupId].insert(uIdx); } else if ((pointToGroupIndex[uIdx] == -1) && (pointToGroupIndex[vIdx] == -1)) { checkAndExpandGroupMembershipArray(); groupId = nGroups; pointToGroupIndex[uIdx] = groupId; pointToGroupIndex[vIdx] = groupId; groupMembership[groupId].insert(uIdx); groupMembership[groupId].insert(vIdx); nGroups++; } else { groupId = -1; log.finest("not reading " + uIdx + ":" + vIdx ); } } public SimpleLinkedListNode[] getGroupMembershipList() { return Arrays.copyOf(groupMembership, nGroups); //return groupMembership; } public int getNumberOfGroups() { return nGroups; } public int[] getPointToGroupIndexes() { return pointToGroupIndex; } /** * remove groups smaller than minimumNumberInCluster */ protected void prune() { log.finest("number of groups before prune=" + nGroups); //TODO: the data structures used could be written at the expense // of space complexity to reduce changes needed when group number // changes // iterate backwards so can move items up without conflict with iterator for (int i = (nGroups - 1); i > -1; i SimpleLinkedListNode group = groupMembership[i]; int count = group.getNumberOfKeys(); log.finest(" group " + i + " has " + count + " members before prune (min=" + minimumNumberInCluster + ")"); if (count < minimumNumberInCluster) { // remove this group and move up all groups w/ index > i by one index for (int j = (i + 1); j < nGroups; j++) { int newGroupId = j - 1; groupMembership[newGroupId] = groupMembership[j]; // update members in pointToGroupIndex SimpleLinkedListNode latest = groupMembership[j]; while (latest != null) { int idx = latest.getKey(); pointToGroupIndex[idx] = newGroupId; latest = latest.getNext(); } } nGroups } } log.finest("number of groups after prune=" + nGroups); } protected void checkAndExpandGroupMembershipArray() { if (groupMembership == null) { throw new IllegalStateException("groupMembership cannot be null"); } if (groupMembership.length < (nGroups + 1)) { int oldN = groupMembership.length; int n = (oldN == 0) ? 10 : (int) (1.5f * oldN); groupMembership = Arrays.copyOf(groupMembership, n); for (int k = oldN; k < n; k++) { groupMembership[k] = new SimpleLinkedListNode(); } } } /** * estimate the amount of memory used by this class and its instance and class variables * @return the memory in bytes used by this class and its instance and class variables. */ public long approximateMemoryUsed() { String arch = System.getProperty("sun.arch.data.model"); boolean is32Bit = ((arch != null) && arch.equals("64")) ? false : true; int nbits = (is32Bit) ? 32 : 64; int overheadBytes = 16; int intBytes = (is32Bit) ? 4 : 8; int arrayBytes = 32/8; int refBytes = nbits/8; long sumBytes = 4*intBytes + 2*arrayBytes; if (groupMembership != null) { long nodeInBytes = SimpleLinkedListNode.approximateMemoryUsed(); sumBytes += (groupMembership.length * nodeInBytes); } if (pointToGroupIndex != null) { sumBytes += (pointToGroupIndex.length * intBytes); } sumBytes += overheadBytes; long padding = (sumBytes % 8); sumBytes += padding; return sumBytes; } public int getNumberofGroupMembers(int groupId) { if (nGroups == 0) { return 0; } if (groupId > (nGroups - 1) || (groupId < 0)) { throw new IllegalArgumentException("groupId=" + groupId + " is outside of range of nGroups=" + nGroups); } return groupMembership[groupId].getNumberOfKeys(); } public PairIntArray getXY(int groupId) { if (nGroups == 0) { return new PairIntArray(); } if (groupId > (nGroups - 1) || (groupId < 0)) { throw new IllegalArgumentException("groupId=" + groupId + " is outside of range of nGroups=" + nGroups); } int[] indexes = getIndexes(groupId); PairIntArray xy = new PairIntArray(); for (int i = 0; i < indexes.length; i++) { int index = indexes[i]; img.getXY(xy, index); } return xy; } public int[] getIndexes(int groupId) { if (nGroups == 0) { return new int[0]; } if (groupId > (nGroups - 1) || (groupId < 0)) { throw new IllegalArgumentException("groupId=" + groupId + " is outside of range of nGroups=" + nGroups); } int[] indexes = new int[10]; int count = 0; SimpleLinkedListNode group = groupMembership[groupId]; while (group != null) { int idx = group.getKey(); indexes = expandIfNeeded(indexes, count + 1); indexes[count] = idx; group = group.getNext(); count++; } return Arrays.copyOf(indexes, count); } protected int[] expandIfNeeded(int[] a, int nTotal) { if (nTotal > a.length) { int n = a.length + 10; if (nTotal > n) { n = nTotal; } return Arrays.copyOf(a, n); } return a; } }
package org.xwiki.test.ui; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.xwiki.extension.test.ExtensionTestUtils; import org.xwiki.repository.test.RepositoryTestUtils; /** * Base class for admin tests that need to manipulate a repository of extensions. * * @version $Id$ */ public class AbstractExtensionAdminAuthenticatedTest extends AbstractTest { @Rule public SuperAdminAuthenticationRule authenticationRule = new SuperAdminAuthenticationRule(getUtil()); @Before public void setUp() throws Exception { // Make sure to have the proper token getUtil().recacheSecretToken(); // Save admin credentials getUtil().setDefaultCredentials(TestUtils.SUPER_ADMIN_CREDENTIALS); } @BeforeClass public static void init() throws Exception { // Make sure repository and extension utils are initialized and set. RepositoryTestUtils repositoryTestUtils = getRepositoryTestUtils(); ExtensionTestUtils extensionTestUtils = getExtensionTestUtils(); // This will not be null if we are in the middle of allTests if (repositoryTestUtils == null || extensionTestUtils == null) { AllTests.initExtensions(context); } } protected static RepositoryTestUtils getRepositoryTestUtils() { return (RepositoryTestUtils) context.getProperties().get(RepositoryTestUtils.PROPERTY_KEY); } protected static ExtensionTestUtils getExtensionTestUtils() { return (ExtensionTestUtils) context.getProperties().get(ExtensionTestUtils.PROPERTY_KEY); } }
package com.pangdata.apps.redis; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.util.Pool; import com.pangdata.sdk.mqtt.PangMqtt; import com.pangdata.sdk.util.NumberUtils; import com.pangdata.sdk.util.PangProperties; public class ServerStateGetter implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ServerStateGetter.class); private Map<String, String> redis; private List<String> mItems; private AtomicBoolean running; private PangMqtt pang; private String prefix; public ServerStateGetter(Map<String, String> redis, List<String> mItems, AtomicBoolean running, PangMqtt pang) { this.redis = redis; this.mItems = mItems; this.running = running; this.pang = pang; } public void run() { JedisPoolConfig config = new JedisPoolConfig(); config.setBlockWhenExhausted(false); config.setTestOnBorrow(true); Jedis resource = null; Pool<Jedis> jedisPool = null; String host = null; try { prefix = redis.get("prefix"); if (prefix == null || prefix.length() == 0) { throw new IllegalArgumentException("'redis.[index].prefix' must not be null"); } Thread.currentThread().setName(prefix); host = redis.get("host"); String[] addr = host.split(":"); if (host == null || host.trim().length() == 0 || addr == null || addr.length == 0) { throw new IllegalArgumentException("redis.[index].host' property not configured properly"); } String master = redis.get("master"); if(master != null) { Set<String> sentinels = new HashSet<String>(); String[] split = host.split(","); for (String uri : split) { sentinels.add(uri); // default sentinel port is that! } jedisPool = new JedisSentinelPool(master, sentinels, config, 5000, redis.get("auth")); } else { jedisPool = new JedisPool(config, addr[0], addr.length == 1 ? 6379 : Integer.valueOf(addr[1]), 5000, redis.get("auth")); } } catch (Exception e) { logger.error("Connection error", e); System.exit(0); } while (running.get()) { try { resource = jedisPool.getResource(); String result = resource.info(); Map<String, Object> values = parse(mItems, result); logger.debug("Redis info: {}", values); pang.sendData(values); } catch (Throwable e) { logger.error("Error occurred", e); if (e instanceof JedisConnectionException) { logger.error("Redis Server connection failure: {}", host); } } finally { jedisPool.returnResourceObject(resource); } try { TimeUnit.MILLISECONDS.sleep(PangProperties.getPeriod()); } catch (InterruptedException e) { } } if (resource != null) { jedisPool.returnResourceObject(resource); } } private Map<String, Object> parse(List<String> mItems, String result) { String[] split = result.split("\r\n"); Map<String, Object> values = new HashMap<String, Object>(); for (int i = 0; i < split.length; i++) { String[] split2 = split[i].split(":"); if (mItems.contains(split2[0])) { values.put(prefix + "_" + split2[0], NumberUtils.toObject(split2[1])); } else if (split2[0].startsWith("db") && split2.length >= 2) { // prefix_dbindex_keys, prefix_dbindex_expires, prefix_dbindex_avg_ttl String[] split3 = split2[1].split(","); for (int j = 0; j < split3.length; j++) { String[] split4 = split3[j].split("="); if (mItems.contains(split4[0])) { values.put(prefix + "_" + split2[0] + "_" + split4[0], NumberUtils.toObject(split4[1])); } } } } return values; } }
package org.mozilla.mozstumbler.service; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build.VERSION; import android.text.TextUtils; import android.util.Log; public class Prefs { public static final String NICKNAME_PREF = "nickname"; public static final String EMAIL_PREF = "email"; public static final String WIFI_ONLY = "wifi_only"; protected static final String PREFS_FILE = Prefs.class.getSimpleName(); private static final String LOG_TAG = AppGlobals.makeLogTag(Prefs.class.getSimpleName()); private static final String USER_AGENT_PREF = "user-agent"; private static final String VALUES_VERSION_PREF = "values_version"; private static final String LAT_PREF = "lat_pref"; private static final String LON_PREF = "lon_pref"; private static final String FIREFOX_SCAN_ENABLED = "firefox_scan_on"; private static final String MOZ_API_KEY = "moz_api_key"; private static final String LAST_ATTEMPTED_UPLOAD_TIME = "last_attempted_upload_time"; // Simulation prefs private static final String SIMULATE_STUMBLE = "simulate_stumble"; private static final String SIMULATION_LAT = "simulate_lat"; private static final String SIMULATION_LON = "simulate_lon"; protected static Prefs sInstance; private final SharedPreferences mSharedPrefs; protected Prefs(Context context) { mSharedPrefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_MULTI_PROCESS | Context.MODE_PRIVATE); if (getPrefs().getInt(VALUES_VERSION_PREF, -1) != AppGlobals.appVersionCode) { Log.i(LOG_TAG, "Version of the application has changed. Updating default values."); // Remove old keys getPrefs().edit() .remove("reports") .remove("power_saving_mode") .commit(); getPrefs().edit().putInt(VALUES_VERSION_PREF, AppGlobals.appVersionCode).commit(); getPrefs().edit().commit(); } } public static synchronized Prefs createGlobalInstance(Context c) { if (sInstance == null) { sInstance = new Prefs(c); } return sInstance; } /* Only access after CreatePrefsInstance(Context) has been called at startup. */ public static synchronized Prefs getInstance() { assert (sInstance != null); return sInstance; } @TargetApi(9) protected static void apply(SharedPreferences.Editor editor) { if (VERSION.SDK_INT >= 9) { editor.apply(); } else if (!editor.commit()) { Log.e(LOG_TAG, "", new IllegalStateException("commit() failed?!")); } } /// Getters public synchronized String getUserAgent() { String s = getStringPref(USER_AGENT_PREF); return (s == null) ? AppGlobals.appName + "/" + AppGlobals.appVersionName : s; } /// Setters public synchronized void setUserAgent(String userAgent) { setStringPref(USER_AGENT_PREF, userAgent); } public synchronized boolean getFirefoxScanEnabled() { return getBoolPrefWithDefault(FIREFOX_SCAN_ENABLED, false); } public synchronized void setFirefoxScanEnabled(boolean on) { setBoolPref(FIREFOX_SCAN_ENABLED, on); } public synchronized String getMozApiKey() { String s = getStringPref(MOZ_API_KEY); return (s == null) ? "no-mozilla-api-key" : s; } public synchronized void setMozApiKey(String s) { setStringPref(MOZ_API_KEY, s); } // This is the time an upload was last attempted, not necessarily successful. // Used to ensure upload attempts aren't happening too frequently. public synchronized long getLastAttemptedUploadTime() { return getPrefs().getLong(LAST_ATTEMPTED_UPLOAD_TIME, 0); } public synchronized void setLastAttemptedUploadTime(long time) { SharedPreferences.Editor editor = getPrefs().edit(); editor.putLong(LAST_ATTEMPTED_UPLOAD_TIME, time); apply(editor); } public synchronized String getNickname() { String nickname = getStringPref(NICKNAME_PREF); if (nickname != null) { nickname = nickname.trim(); } return TextUtils.isEmpty(nickname) ? null : nickname; } public synchronized void setNickname(String nick) { if (nick != null) { nick = nick.trim(); setStringPref(NICKNAME_PREF, nick); } } public synchronized String getEmail() { String email = getStringPref(EMAIL_PREF); if (email != null) { email = email.trim(); } return TextUtils.isEmpty(email) ? null : email; } public synchronized void setEmail(String email) { if (email != null) { email = email.trim(); setStringPref(EMAIL_PREF, email); } } public synchronized boolean getUseWifiOnly() { return getBoolPrefWithDefault(WIFI_ONLY, true); } /// Privates public synchronized void setUseWifiOnly(boolean state) { setBoolPref(WIFI_ONLY, state); } protected String getStringPref(String key) { return getPrefs().getString(key, null); } protected boolean getBoolPrefWithDefault(String key, boolean def) { return getPrefs().getBoolean(key, def); } protected void setBoolPref(String key, Boolean state) { SharedPreferences.Editor editor = getPrefs().edit(); editor.putBoolean(key, state); apply(editor); } protected float getFloatPrefWithDefault(String key, float def) { return getPrefs().getFloat(key, def); } protected void setFloatPref(String key, float value) { SharedPreferences.Editor editor = getPrefs().edit(); editor.putFloat(key, value); apply(editor); } protected void setStringPref(String key, String value) { SharedPreferences.Editor editor = getPrefs().edit(); editor.putString(key, value); apply(editor); } @SuppressLint("InlinedApi") protected SharedPreferences getPrefs() { return mSharedPrefs; } private float getFloatPref(String name, float value) { return getFloatPrefWithDefault(name, value); } public boolean isSimulateStumble() { return getBoolPrefWithDefault(SIMULATE_STUMBLE, false); } public void setSimulateStumble(boolean b) { setBoolPref(SIMULATE_STUMBLE, b); } public float getSimulationLat() { return getFloatPref(SIMULATION_LAT, (float) 43.6472969); } public void setSimulationLat(float value) { setFloatPref(SIMULATION_LAT, value); } public float getSimulationLon() { return getFloatPref(SIMULATION_LON, (float) -79.3943137); } public void setSimulationLon(float value) { setFloatPref(SIMULATION_LON, value); } }
package org.xwiki.mail.internal.configuration; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.mail.MailSenderConfiguration; /** * Gets the Mail Sending configuration. The configuration is checked in the following order: * <ul> * <li>Look in Mail.SendMailConfigClass in the current wiki</li> * <li>Look in (current space).XWikiPreferences in the current wiki</li> * <li>Look in XWiki.XWikiPreferences in the current wiki</li> * <li>Look in the xwiki properties file</li> * </ul> * * @version $Id$ * @since 6.1M2 */ @Component @Singleton public class DefaultMailSenderConfiguration implements MailSenderConfiguration { /** * Java Mail SMTP property for the protocol. */ public static final String JAVAMAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol"; /** * Java Mail SMTP property for the host. */ public static final String JAVAMAIL_SMTP_HOST = "mail.smtp.host"; /** * Java Mail SMTP property for the server port. */ public static final String JAVAMAIL_SMTP_PORT = "mail.smtp.port"; /** * Java Mail SMTP property for the username. */ public static final String JAVAMAIL_SMTP_USERNAME = "mail.smtp.user"; /** * Java Mail SMTP property for the from email address. */ public static final String JAVAMAIL_SMTP_FROM = "mail.smtp.from"; /** * Java Mail SMTP property for specifying that we are authenticating. */ public static final String JAVAMAIL_SMTP_AUTH = "mail.smtp.auth"; /** * Prefix for configuration keys for the Mail Sending module. */ private static final String PREFIX = "mail.sender."; private static final int DEFAULT_PORT = 25; /** * By default we wait 8 seconds between each mail in order to throttle the mail sending and not be considered as * a spammer by mail servers. */ private static final long DEFAULT_SEND_WAIT_TIME = 8 * 1000L; private static final String FROM_PROPERTY = "from"; private static final String BCC_PROPERTY = "bcc"; private static final String HOST_PROPERTY = "host"; private static final String PORT_PROPERTY = "port"; private static final String USERNAME_PROPERTY = "username"; private static final String PASSWORD_PROPERTY = "password"; private static final String PROPERTIES_PROPERTY = "properties"; private static final String SEND_WAIT_TIME = "sendWaitTime"; @Inject private Logger logger; @Inject @Named("mailsend") private ConfigurationSource mailConfigSource; @Inject @Named("documents") private ConfigurationSource documentsSource; @Inject @Named("xwikiproperties") private ConfigurationSource xwikiPropertiesSource; @Override public String getHost() { String host; // First, look in the document sources host = this.mailConfigSource.getProperty(HOST_PROPERTY, this.documentsSource.getProperty("smtp_server", String.class)); // If not found, look in the xwiki properties source if (host == null) { host = this.xwikiPropertiesSource.getProperty(PREFIX + HOST_PROPERTY, "localhost"); } return host; } @Override public int getPort() { Integer port = null; // First, look in the document sources String portAsString = this.documentsSource.getProperty("smtp_port"); if (!StringUtils.isEmpty(portAsString)) { try { port = this.mailConfigSource.getProperty(PORT_PROPERTY, Integer.parseInt(portAsString)); } catch (NumberFormatException e) { port = DEFAULT_PORT; } } else { Long portAsLong = this.mailConfigSource.getProperty(PORT_PROPERTY, Long.class); if (portAsLong != null) { port = portAsLong.intValue(); } } // If not found, look in the xwiki properties source if (port == null) { port = this.xwikiPropertiesSource.getProperty(PREFIX + PORT_PROPERTY, DEFAULT_PORT); } return port; } @Override public String getUsername() { String username; // First, look in the document sources username = this.mailConfigSource.getProperty(USERNAME_PROPERTY, this.documentsSource.getProperty("smtp_server_username", String.class)); // If not found, look in the xwiki properties source if (username == null) { username = this.xwikiPropertiesSource.getProperty(PREFIX + USERNAME_PROPERTY, String.class); } return username; } @Override public String getPassword() { String password; // First, look in the document sources password = this.mailConfigSource.getProperty(PASSWORD_PROPERTY, this.documentsSource.getProperty("smtp_server_password", String.class)); // If not found, look in the xwiki properties source if (password == null) { password = this.xwikiPropertiesSource.getProperty(PREFIX + PASSWORD_PROPERTY, String.class); } return password; } @Override public List<String> getBCCAddresses() { List<String> bccAddresses = new ArrayList<>(); // First, look in the document source String bccAsString = this.mailConfigSource.getProperty(BCC_PROPERTY, String.class); // If not found, look in the xwiki properties source if (bccAsString == null) { bccAsString = this.xwikiPropertiesSource.getProperty(PREFIX + BCC_PROPERTY, String.class); } // Convert into a list (if property is found and not null) if (bccAsString != null) { for (String address : StringUtils.split(bccAsString, ',')) { bccAddresses.add(StringUtils.trim(address)); } } return bccAddresses; } @Override public String getFromAddress() { String from; // First, look in the document sources from = this.mailConfigSource.getProperty(FROM_PROPERTY, this.documentsSource.getProperty("admin_email", String.class)); // If not found, look in the xwiki properties source if (from == null) { from = this.xwikiPropertiesSource.getProperty(PREFIX + FROM_PROPERTY, String.class); } return from; } @Override public Properties getAdditionalProperties() { Properties properties; // First, look in the document sources String extraPropertiesAsString = this.mailConfigSource.getProperty(PROPERTIES_PROPERTY, this.documentsSource.getProperty("javamail_extra_props", String.class)); // If not found, look in the xwiki properties source if (extraPropertiesAsString == null) { properties = this.xwikiPropertiesSource.getProperty(PREFIX + PROPERTIES_PROPERTY, Properties.class); } else { // The "javamail_extra_props" property is stored in a text area and thus we need to convert it to a Map. InputStream is = new ByteArrayInputStream(extraPropertiesAsString.getBytes()); properties = new Properties(); try { properties.load(is); } catch (Exception e) { // Will happen if the user has not used the right format, in which case we log a warning but discard // the user values. this.logger.warn("Error while parsing mail properties [{}]. Root cause [{}]. Ignoring configuration...", extraPropertiesAsString, ExceptionUtils.getRootCauseMessage(e)); } } return properties; } @Override public Properties getAllProperties() { Properties properties = new Properties(); addProperty(properties, JAVAMAIL_TRANSPORT_PROTOCOL, "smtp"); addProperty(properties, JAVAMAIL_SMTP_HOST, getHost()); addProperty(properties, JAVAMAIL_SMTP_USERNAME, getUsername()); addProperty(properties, JAVAMAIL_SMTP_FROM, getFromAddress()); addProperty(properties, JAVAMAIL_SMTP_PORT, Integer.toString(getPort())); // If a username and a password have been provided consider we're authenticating against the SMTP server if (usesAuthentication()) { properties.put(JAVAMAIL_SMTP_AUTH, "true"); } // Add user-specified mail properties. // Note: We're only supporting SMTP (and not SMTPS) at the moment, which means that for sending emails to a // SMTP server requiring TLS the user will need to pass the "mail.smtp.starttls.enable=true" property and use // the proper port for TLS (587 for Gmail for example, while port 465 is used for SMTPS/SSL). properties.putAll(getAdditionalProperties()); return properties; } private void addProperty(Properties properties, String key, String value) { if (value != null) { properties.setProperty(key, value); } } @Override public boolean usesAuthentication() { return !StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword()); } @Override public String getScriptServicePermissionCheckerHint() { return this.xwikiPropertiesSource.getProperty(PREFIX + "scriptServiceCheckerHint", "programmingrights"); } @Override public long getSendWaitTime() { Long waitTime = this.mailConfigSource.getProperty(SEND_WAIT_TIME); if (waitTime == null) { waitTime = this.xwikiPropertiesSource.getProperty(PREFIX + SEND_WAIT_TIME, DEFAULT_SEND_WAIT_TIME); } return waitTime; } }
package com.pm.server.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.pm.server.datatype.Coordinate; import com.pm.server.datatype.CoordinateImpl; import com.pm.server.datatype.PlayerName; import com.pm.server.datatype.PlayerState; import com.pm.server.exceptionhttp.BadRequestException; import com.pm.server.exceptionhttp.ConflictException; import com.pm.server.exceptionhttp.InternalServerErrorException; import com.pm.server.exceptionhttp.NotFoundException; import com.pm.server.player.Player; import com.pm.server.registry.PlayerRegistry; import com.pm.server.request.LocationRequest; import com.pm.server.request.PlayerNameRequest; import com.pm.server.request.PlayerStateRequest; import com.pm.server.response.IdAndPlayerStateResponse; import com.pm.server.response.LocationResponse; import com.pm.server.response.PlayerResponse; import com.pm.server.response.PlayerStateResponse; import com.pm.server.utils.JsonUtils; import com.pm.server.utils.ValidationUtils; @RestController @RequestMapping("/player") public class PlayerController { @Autowired private PlayerRegistry playerRegistry; Coordinate locationDefault = new CoordinateImpl(0.0, 0.0); private final static Logger log = LogManager.getLogger(PlayerController.class.getName()); @RequestMapping( value = "/{playerName}", method=RequestMethod.POST, produces={ "application/json" } ) @ResponseStatus(value = HttpStatus.OK) public void selectPlayer( @PathVariable String playerName, @RequestBody(required = false) LocationRequest requestBody) throws ConflictException, BadRequestException { log.debug("Mapped POST /player/{}", playerName); log.debug("Request body: {}", JsonUtils.objectToJson(requestBody)); PlayerNameRequest playerNameRequest = new PlayerNameRequest(); playerNameRequest.name = playerName; PlayerName name = ValidationUtils.validateRequestWithName(playerNameRequest); Coordinate location = ValidationUtils .validateRequestBodyWithLocation(requestBody); log.debug("Attempting to select Player {} at ({}, {}).", name, location.getLatitude(), location.getLongitude() ); Player player = playerRegistry.getPlayerByName(name); if(player == null) { String errorMessage = name + " is not a valid Player name."; log.warn(errorMessage); throw new BadRequestException(errorMessage); } else if(player.getState() != PlayerState.UNINITIALIZED) { String errorMessage = "Player "+ name + " has already been selected."; log.warn(errorMessage); throw new ConflictException(errorMessage); } playerRegistry.setPlayerLocationByName(name, location); playerRegistry.setPlayerStateByName(name, PlayerState.READY); } @RequestMapping( value="/{playerName}", method=RequestMethod.DELETE ) @ResponseStatus(value = HttpStatus.OK) public void deselectPlayer( @PathVariable String playerName, HttpServletResponse response) throws BadRequestException, NotFoundException, InternalServerErrorException { log.debug("Mapped DELETE /player/{}", playerName); PlayerNameRequest playerNameRequest = new PlayerNameRequest(); playerNameRequest.name = playerName; PlayerName name = ValidationUtils .validateRequestWithName(playerNameRequest); Player player = playerRegistry.getPlayerByName(name); if(player == null) { String errorMessage = "Player " + name + " was not found."; log.warn(errorMessage); throw new NotFoundException(errorMessage); } else if(player.getState() == PlayerState.UNINITIALIZED) { String errorMessage = "Player "+ name + " has not yet been selected."; log.warn(errorMessage); throw new BadRequestException(errorMessage); } try { playerRegistry.setPlayerStateByName( name, PlayerState.UNINITIALIZED ); } catch(Exception e) { String errorMessage = "Player " + name + " was found but could not be deselected."; log.warn(errorMessage); throw new InternalServerErrorException(errorMessage); } log.debug("Player {} was succesfully deselected", name); log.debug("Setting Player {} to default location", name); playerRegistry.setPlayerLocationByName(name, locationDefault); } @RequestMapping( value="/{playerName}/location", method=RequestMethod.GET, produces={ "application/json" } ) @ResponseStatus(value = HttpStatus.OK) public LocationResponse getPlayerLocation( @PathVariable String playerName, HttpServletResponse response) throws BadRequestException, NotFoundException { log.debug("Mapped GET /player/{}/location", playerName); PlayerNameRequest nameRequest = new PlayerNameRequest(); nameRequest.name = playerName; PlayerName name = ValidationUtils .validateRequestWithName(nameRequest); Player player = playerRegistry.getPlayerByName(name); if(player == null) { String errorMessage = "No Player named " + name + " was found in the registry."; log.debug(errorMessage); throw new NotFoundException(errorMessage); } LocationResponse locationResponse = new LocationResponse(); if(player.getLocation() == null) { locationResponse.setLatitude(0.0); locationResponse.setLongitude(0.0); } else { locationResponse.setLatitude(player.getLocation().getLatitude()); locationResponse.setLongitude(player.getLocation().getLongitude()); } String objectString = JsonUtils.objectToJson(locationResponse); if(objectString != null) { log.debug("Returning locationResponse: {}", objectString); } return locationResponse; } @RequestMapping( value="/locations", method=RequestMethod.GET, produces={ "application/json" } ) @ResponseStatus(value = HttpStatus.OK) public List<PlayerResponse> getAllPlayerLocations() { log.debug("Mapped GET /player/locations"); List<PlayerResponse> playerResponseList = new ArrayList<PlayerResponse>(); List<Player> playerList = playerRegistry.getAllPlayers(); if(playerList != null) { for(Player player : playerList) { String objectString = JsonUtils.objectToJson(player); if(objectString != null) { log.trace("Processing Player: {}", objectString); } PlayerResponse playerResponse = new PlayerResponse(); playerResponse.setId(player.getId()); playerResponse.setLocation(player.getLocation()); playerResponseList.add(playerResponse); } } String objectString = JsonUtils.objectToJson(playerResponseList); if(objectString != null) { log.debug("Returning PlayersResponse: {}", objectString); } return playerResponseList; } @RequestMapping( value="/{id}/state", method=RequestMethod.GET, produces={ "application/json" } ) @ResponseStatus(value = HttpStatus.OK) public PlayerStateResponse getPlayerStateById( @PathVariable Integer id, HttpServletResponse response) throws NotFoundException { log.debug("Mapped GET /player/{}/state", id); Player player = playerRegistry.getPlayerByName(PlayerName.Inky); if(player == null) { String errorMessage = "No Player with id " + Integer.toString(id) + "."; log.debug(errorMessage); throw new NotFoundException(errorMessage); } PlayerStateResponse playerStateResponse = new PlayerStateResponse(); playerStateResponse.setState(player.getState()); String objectString = JsonUtils.objectToJson(playerStateResponse); if(objectString != null) { log.debug("Returning playerStateResponse: {}", objectString); } return playerStateResponse; } @RequestMapping( value="/states", method=RequestMethod.GET, produces={ "application/json" } ) @ResponseStatus(value = HttpStatus.OK) public List<IdAndPlayerStateResponse> getAllPlayerStates() { log.debug("Mapped GET /player/states"); List<IdAndPlayerStateResponse> playerResponseList = new ArrayList<IdAndPlayerStateResponse>(); List<Player> players = playerRegistry.getAllPlayers(); if(players != null) { for(Player player : players) { String objectString = JsonUtils.objectToJson(player); if(objectString != null) { log.trace("Processing Player: {}", objectString); } IdAndPlayerStateResponse PlayerResponse = new IdAndPlayerStateResponse(); PlayerResponse.id = player.getId(); PlayerResponse.state = player.getState(); playerResponseList.add(PlayerResponse); } } String objectString = JsonUtils.objectToJson(playerResponseList); if(objectString != null) { log.debug("Returning playerResponse: {}", objectString); } return playerResponseList; } @RequestMapping( value="/{id}/location", method=RequestMethod.PUT ) @ResponseStatus(value = HttpStatus.OK) public void setPlayerLocationById( @PathVariable Integer id, @RequestBody LocationRequest locationRequest) throws BadRequestException, NotFoundException { log.debug("Mapped PUT /player/{}/location", id); log.debug("Request body: {}", JsonUtils.objectToJson(locationRequest)); Coordinate location = ValidationUtils .validateRequestBodyWithLocation(locationRequest); Player player = playerRegistry.getPlayerByName(PlayerName.Inky); if(player == null) { String errorMessage = "Player with id " + Integer.toString(id) + " was not found."; log.debug(errorMessage); throw new NotFoundException(errorMessage); } log.debug( "Setting Player with id {} to ({}, {})", id, location.getLatitude(), location.getLongitude() ); playerRegistry.setPlayerLocationByName(PlayerName.Inky, location); } @RequestMapping( value="/{id}/state", method=RequestMethod.PUT ) @ResponseStatus(value = HttpStatus.OK) public void setPlayerStateById( @PathVariable Integer id, @RequestBody PlayerStateRequest stateRequest) throws BadRequestException, NotFoundException { log.debug("Mapped PUT /player/{}/state", id); log.debug("Request body: {}", JsonUtils.objectToJson(stateRequest)); PlayerState state = ValidationUtils.validateRequestBodyWithState(stateRequest); if(state == PlayerState.POWERUP) { String errorMessage = "The POWERUP state is not valid for a Player."; log.warn(errorMessage); throw new BadRequestException(errorMessage); } Player player = playerRegistry.getPlayerByName(PlayerName.Inky); if(player == null) { String errorMessage = "Player with id " + Integer.toString(id) + " was not found."; log.debug(errorMessage); throw new NotFoundException(errorMessage); } log.debug( "Changing Player with id {} from state {} to {}", id, player.getState(), state ); playerRegistry.setPlayerStateByName(PlayerName.Inky, state); } }
package edu.purdue.voltag; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Parcelable; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.util.Log; import android.util.LruCache; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.parse.Parse; import com.parse.ParsePush; import com.parse.PushService; import edu.purdue.voltag.data.ParseConstants; import edu.purdue.voltag.data.VoltagDB; import edu.purdue.voltag.fragments.CreateGameFragment; import edu.purdue.voltag.fragments.GameChoiceFragment; import edu.purdue.voltag.fragments.GameLobbyFragment; import edu.purdue.voltag.fragments.RegistrationFragment; import edu.purdue.voltag.lobby.BitmapCacheHost; import static android.nfc.NdefRecord.createMime; public class MainActivity extends Activity implements NfcAdapter.CreateNdefMessageCallback { public static final String LOG_TAG = "voltag_log"; public static final String PREFS_NAME = "voltag_prefs"; public static final String PREF_ISIT = "player_is_it"; public static final String PREF_CURRENT_GAME_ID = "current_game_id"; public static final String PREF_CURRENT_GAME_NAME = "current_game_name"; public static final String PREF_USER_ID = "user_id"; public static final String PREF_EMAIL = "user_email"; public static final String PREF_ISREGISTERED = "is_registered"; private NfcAdapter mNfcAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new Thread(new Runnable() { public void run() { Parse.initialize(MainActivity.this, ParseConstants.PARSE_APPLICATION_KEY, ParseConstants.PARSE_CLIENT_KEY); PushService.setDefaultPushCallback(getApplicationContext(),MainActivity.class); Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE); } }).start(); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show(); finish(); return; } mNfcAdapter.setNdefPushMessageCallback(this,this); setContentView(R.layout.activity_main); } @Override public void onStart() { super.onStart(); String gameId; SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME,0); gameId = settings.getString(MainActivity.PREF_CURRENT_GAME_ID,""); if(!(gameId.equals(""))){ closeSplash(); getFragmentManager().beginTransaction().replace(android.R.id.content, new GameLobbyFragment()).commit(); } } public void testClick(View view) { closeSplash(); getFragmentManager().beginTransaction().replace(android.R.id.content, new GameLobbyFragment()).commit(); } public void beginButton(View view) { SharedPreferences settings = getSharedPreferences(PREFS_NAME,0); boolean isRegistered = settings.getBoolean(PREF_ISREGISTERED,false); Log.d("debug", "isRegistered=" + isRegistered); closeSplash(); if(!isRegistered) { getFragmentManager().beginTransaction().replace(android.R.id.content, new RegistrationFragment()).commit(); } else{ getFragmentManager().beginTransaction().replace(android.R.id.content, new GameChoiceFragment()).commit(); } } private void closeSplash() { View v = (View) findViewById(R.id.splash); v.setVisibility(View.GONE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, 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(); if (id == R.id.action_settings) { return true; } else if (id == R.id.action_about) { showAboutDialog(); return true; } return super.onOptionsItemSelected(item); } private void showAboutDialog() { // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage(R.string.dialog_message) .setCancelable(true) .setTitle(R.string.dialog_title); builder.setPositiveButton( android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); dialog.show(); } public NdefMessage createNdefMessage(NfcEvent event) { SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); Boolean isIt = settings.getBoolean(MainActivity.PREF_ISIT,false); if(isIt) { String text = ("it"); Log.d("debug", "sendingNFC You are it."); NdefMessage msg = new NdefMessage( new NdefRecord[]{createMime( "application/edu.purdue.voltag", text.getBytes()), /** * The Android Application Record (AAR) is commented out. When a device * receives a push with an AAR in it, the application specified in the AAR * is guaranteed to run. The AAR overrides the tag dispatch system. * You can add it back in to guarantee that this * activity starts when receiving a beamed message. For now, this code * uses the tag dispatch system. */ NdefRecord.createApplicationRecord("edu.purdue.voltag") } ); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(MainActivity.PREF_ISIT,false); editor.commit(); return msg; } else{ String text = ("ignore"); Log.d("debug", "sendingNFC ignore."); NdefMessage msg = new NdefMessage( new NdefRecord[]{createMime( "application/edu.purdue.voltag", text.getBytes()), /** * The Android Application Record (AAR) is commented out. When a device * receives a push with an AAR in it, the application specified in the AAR * is guaranteed to run. The AAR overrides the tag dispatch system. * You can add it back in to guarantee that this * activity starts when receiving a beamed message. For now, this code * uses the tag dispatch system. */ NdefRecord.createApplicationRecord("edu.purdue.voltag") } ); return msg; } } @Override public void onResume() { super.onResume(); // Check to see that the Activity started due to an Android Beam if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { processIntent(getIntent()); } } public void onNewIntent(Intent intent) { // onResume gets called after this to handle the intent setIntent(intent); } /** * Parses the NDEF Message from the intent and prints to the TextView */ void processIntent(Intent intent) { Log.d("debug","processing sending that I am now it to server"); Toast.makeText(this, "You are it!", Toast.LENGTH_LONG).show(); VoltagDB db = VoltagDB.getDB(this); Parcelable[] rawMsgs = intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam NdefMessage msg = (NdefMessage) rawMsgs[0]; String message = new String(msg.getRecords()[0].getPayload()); Log.d("debug","message="+message); if(message.equals("it")){ db.tagThisPlayerOnParse(null); SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME,0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(MainActivity.PREF_ISIT,true); editor.commit(); ParsePush push = new ParsePush(); String test = settings.getString(MainActivity.PREF_CURRENT_GAME_ID,""); Log.d("debug","sending push to channels " + test); push.setChannel(test); String name = settings.getString(MainActivity.PREFS_NAME,""); push.setMessage("is now it!"); Log.d("debug",push.); push.sendInBackground(); } // record 0 contains the MIME type, record 1 is the AAR, if present } }
package com.qihoo.fireline; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.model.Action; import hudson.model.ProminentProjectAction; import jenkins.model.Jenkins; public class FireLineScanCodeAction implements ProminentProjectAction { @Override public String getUrlName() { return null; } @Override public String getIconFileName() { PluginWrapper wrapper = null; Jenkins jenkins=Jenkins.getInstance(); PluginManager pluginManager=jenkins.getPluginManager(); if ( jenkins!= null && pluginManager!= null) wrapper = pluginManager.getPlugin("fireline"); if (wrapper != null) return "/plugin/" + wrapper.getShortName() + "/images/fireLine_48x48.png"; return null; } @Override public String getDisplayName() { return "FireLine Static Analysis"; } }
package com.rollbar.payload.data.body; /** * Represents the context around the code where the error occurred (lines before, 'pre', and after, 'post') */ public class CodeContext { private final String[] pre; private final String[] post; /** * Constructor */ public CodeContext() { this(null, null); } /** * Constructor * @param pre the lines of code before the one that triggered the error * @param post the lines of code after the one that triggered the error */ public CodeContext(String[] pre, String[] post) { this.pre = pre == null ? null : pre.clone(); this.post = post == null ? null : post.clone(); } /** * @return the lines of code before the one that triggered the error */ public String[] pre() { return pre == null ? null : pre.clone(); } /** * Set the lines of code before the one that triggered the error in a copy of this CodeContext * @param pre the new `pre` lines of code * @return a copy of this CodeContext with pre overridden */ public CodeContext pre(String[] pre) { return new CodeContext(pre, post); } /** * @return the lines of code after the one that triggered the error */ public String[] post() { return post == null ? null : post.clone(); } /** * Set the lines of code after the one that triggered the error in a copy of this CodeContext * @param post the new `post` lines of code * @return a copy of this CodeContext with post overridden */ public CodeContext post(String[] post) { return new CodeContext(pre, post); } }
package com.royalrangers.dto.structure; import lombok.Getter; import lombok.Setter; import java.util.Date; @Getter @Setter public class PlatoonDto { private Integer name; private Long cityId; private String history; private String logoUrl; private String address; private Date meetTime; }
package com.xcx.system.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.xiaoleilu.hutool.crypto.SecureUtil; import com.xiaoleilu.hutool.util.StrUtil; @Controller @EnableAutoConfiguration public class IndexController { private static final String TOKEN = "wxa759517f581d48e8"; @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String signature = request.getParameter("signature"); if (StrUtil.isBlank(signature)) { return "signature is blank"; } String echostr = request.getParameter("echostr"); if (StrUtil.isBlank(echostr)) { return "echostr is blank"; } String timestamp = request.getParameter("timestamp"); if (StrUtil.isBlank(timestamp)) { return "timestamp is blank"; } String nonce = request.getParameter("nonce"); if (StrUtil.isBlank(nonce)) { return "nonce is blank"; } String[] str = { TOKEN, timestamp, nonce }; Arrays.sort(str); String bigStr = str[0] + str[1] + str[2]; System.out.println(bigStr); String digest = SecureUtil.sha1(bigStr); System.out.println(digest); System.out.println(signature); System.out.println(echostr); if (digest.equals(signature)) { return echostr; } return "err"; } @RequestMapping("/data") @ResponseBody Map<String, Object> data() { Map<String, Object> data = new HashMap<>(); data.put("suc", true); data.put("name", "sizhongxia"); return data; } @RequestMapping("/deploy") @ResponseBody String deploy() { InputStreamReader stdISR = null; InputStreamReader errISR = null; Process process = null; String command = "/root/shell/deploy_pro_xcx.sh"; try { process = Runtime.getRuntime().exec(command); process.waitFor(); StringBuffer sb = new StringBuffer(); String line = null; stdISR = new InputStreamReader(process.getInputStream()); BufferedReader stdBR = new BufferedReader(stdISR); while ((line = stdBR.readLine()) != null) { // System.out.println("STD line:" + line); sb.append(line); } errISR = new InputStreamReader(process.getErrorStream()); BufferedReader errBR = new BufferedReader(errISR); while ((line = errBR.readLine()) != null) { // System.out.println("ERR line:" + line); sb.append(line); } return "suc - " + sb.toString(); } catch (IOException | InterruptedException e) { return e.getMessage(); } finally { try { if (stdISR != null) { stdISR.close(); } if (errISR != null) { errISR.close(); } if (process != null) { process.destroy(); } } catch (IOException e) { return "err"; } } } }
package org.xwiki.rendering.internal.parser.pygments; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.NewLineBlock; import org.xwiki.rendering.parser.AbstractHighlightParser; import org.xwiki.rendering.parser.HighlightParser; import org.xwiki.rendering.parser.ParseException; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.syntax.SyntaxType; /** * Highlight provided source using Pygments. * * @version $Id$ * @since 1.7RC1 */ // Note that we force the Component annotation so that this component is only registered as a Highlight Parser // and not a Parser too since we don't want this parser to be visible to users as a valid standard input parser // component. @Component(roles = {HighlightParser.class }) @Singleton public class PygmentsParser extends AbstractHighlightParser implements Initializable { /** * The name of the style variable in Python code. */ private static final String PY_STYLE_VARNAME = "style"; /** * The name of the listener variable in Python code. */ private static final String PY_LISTENER_VARNAME = "listener"; /** * The name of the variable containing the source code to highlight in Python code. */ private static final String PY_CODE_VARNAME = "code"; /** * The name of the variable containing the language of the source. */ private static final String PY_LANGUAGE_VARNAME = "language"; /** * The name of the lexer variable in Python code. */ private static final String PY_LEXER_VARNAME = "pygmentLexer"; /** * The identifier of the Java Scripting engine to use. */ private static final String ENGINE_ID = "python"; /** * The syntax identifier. */ private Syntax syntax; /** * Used to parse Pygment token values into blocks. */ @Inject @Named("plain/1.0") private Parser plainTextParser; /** * Pygments highligh parser configuration. */ @Inject private PygmentsParserConfiguration configuration; /** * The JSR223 Script Engine we use to evaluate Python scripts. */ private ScriptEngine engine; /** * The Python script used to manipulate Pygments. */ private String script; /** * The logger to log. */ @Inject private Logger logger; @Override public void initialize() throws InitializationException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); // Get the script InputStream is = getClass().getResourceAsStream("/pygments/code.py"); if (is != null) { try { this.script = IOUtils.toString(is, "UTF8"); } catch (Exception e) { throw new InitializationException("Failed to read resource /pygments/code.py resource", e); } finally { IOUtils.closeQuietly(is); } } else { throw new InitializationException("Failed to find resource /pygments/code.py resource"); } // Get the Python engine this.engine = scriptEngineManager.getEngineByName(ENGINE_ID); if (this.engine == null) { throw new InitializationException("Failed to find engine for Python script language"); } String highlightSyntaxId = getSyntaxId() + "-highlight"; this.syntax = new Syntax(new SyntaxType(highlightSyntaxId, highlightSyntaxId), "1.0"); } @Override public Syntax getSyntax() { return this.syntax; } @Override public List<Block> highlight(String syntaxId, Reader source) throws ParseException { String code; try { code = IOUtils.toString(source); } catch (IOException e) { throw new ParseException("Failed to read source", e); } if (code.length() == 0) { return Collections.emptyList(); } List<Block> blocks; try { blocks = highlight(syntaxId, code); } catch (ScriptException e) { throw new ParseException("Failed to highlight code", e); } // TODO: there is a bug in Pygments that makes it always put a newline at the end of the content if (code.charAt(code.length() - 1) != '\n' && !blocks.isEmpty() && blocks.get(blocks.size() - 1) instanceof NewLineBlock) { blocks.remove(blocks.size() - 1); } return blocks; } /** * Return a highlighted version of the provided content. * * @param syntaxId the identifier of the source syntax. * @param code the content to highlight. * @return the highlighted version of the provided source. * @throws ScriptException when failed to execute the script * @throws ParseException when failed to parse the content as plain text */ private List<Block> highlight(String syntaxId, String code) throws ScriptException, ParseException { BlocksGeneratorPygmentsListener listener = new BlocksGeneratorPygmentsListener(this.plainTextParser); ScriptContext scriptContext = new SimpleScriptContext(); scriptContext.setAttribute(PY_LANGUAGE_VARNAME, syntaxId, ScriptContext.ENGINE_SCOPE); scriptContext.setAttribute(PY_CODE_VARNAME, code, ScriptContext.ENGINE_SCOPE); scriptContext.setAttribute(PY_STYLE_VARNAME, this.configuration.getStyle(), ScriptContext.ENGINE_SCOPE); scriptContext.setAttribute(PY_LISTENER_VARNAME, listener, ScriptContext.ENGINE_SCOPE); this.engine.eval(this.script, scriptContext); List<Block> blocks; if (scriptContext.getAttribute(PY_LEXER_VARNAME) != null) { blocks = listener.getBlocks(); } else { blocks = this.plainTextParser.parse(new StringReader(code)).getChildren().get(0).getChildren(); } return blocks; } }
package crazypants.enderio.machine.tank; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.ClientProxy; import crazypants.enderio.EnderIO; import crazypants.enderio.GuiHandler; import crazypants.enderio.ModObject; import crazypants.enderio.gui.IAdvancedTooltipProvider; import crazypants.enderio.gui.TooltipAddera; import crazypants.enderio.machine.AbstractMachineBlock; import crazypants.enderio.machine.AbstractMachineEntity; import crazypants.enderio.machine.power.PowerDisplayUtil; import crazypants.enderio.network.PacketHandler; import crazypants.util.FluidUtil; import crazypants.util.Lang; import crazypants.util.Util; public class BlockTank extends AbstractMachineBlock<TileTank> implements IAdvancedTooltipProvider { public static BlockTank create() { PacketHandler.INSTANCE.registerMessage(PacketTank.class, PacketTank.class, PacketHandler.nextID(), Side.CLIENT); BlockTank res = new BlockTank(); res.init(); return res; } protected BlockTank() { super(ModObject.blockTank, TileTank.class); setStepSound(Block.soundTypeGlass); } @Override protected void init() { GameRegistry.registerBlock(this, BlockItemTank.class, ModObject.blockTank.unlocalisedName); if(teClass != null) { GameRegistry.registerTileEntity(teClass, ModObject.blockTank.unlocalisedName + "TileEntity"); } EnderIO.guiHandler.registerGuiHandler(GuiHandler.GUI_ID_TANK, this); setLightOpacity(0); } @Override public int damageDropped(int par1) { return par1; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int par6, float par7, float par8, float par9) { TileEntity te = world.getTileEntity(x, y, z); if(!(te instanceof TileTank)) { return super.onBlockActivated(world, x, y, z, entityPlayer, par6, par7, par8, par9); } TileTank tank = (TileTank) te; ItemStack item = entityPlayer.inventory.getCurrentItem(); if(item == null) { return super.onBlockActivated(world, x, y, z, entityPlayer, par6, par7, par8, par9); } //check for filled fluid containers and see if we can empty them into our input tank FluidStack fluid = FluidUtil.getFluidFromItem(item); if(fluid != null) { int filled = tank.fill(ForgeDirection.UP, fluid, false); if(filled >= fluid.amount) { tank.fill(ForgeDirection.UP, fluid, true); if(!entityPlayer.capabilities.isCreativeMode) { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, Util.consumeItem(item)); } return true; } } //now check for empty fluid containers to fill FluidStack available = tank.tank.getFluid(); if(available != null) { ItemStack res = FluidContainerRegistry.fillFluidContainer(available.copy(), item); FluidStack filled = FluidContainerRegistry.getFluidForFilledItem(res); if(filled == null) { //this shouldn't be necessary but it appears to be a bug as the above method doesnt work FluidContainerData[] datas = FluidContainerRegistry.getRegisteredFluidContainerData(); for (FluidContainerData data : datas) { if(data != null && data.fluid != null && data.fluid.getFluid() != null && data.fluid.getFluid().getName() != null && data.emptyContainer != null && data.fluid.getFluid().getName().equals(available.getFluid().getName()) && data.emptyContainer.isItemEqual(item)) { res = data.filledContainer.copy(); filled = FluidContainerRegistry.getFluidForFilledItem(res); } } } if(filled != null) { tank.drain(ForgeDirection.DOWN, filled, true); if(item.stackSize > 1) { item.stackSize entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, item); for (int i = 0; i < entityPlayer.inventory.mainInventory.length; i++) { if(entityPlayer.inventory.mainInventory[i] == null) { entityPlayer.inventory.setInventorySlotContents(i, res); return true; } } if(!world.isRemote) { Util.dropItems(world, res, x, y, z, true); } } else { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, res); } return true; } } return super.onBlockActivated(world, x, y, z, entityPlayer, par6, par7, par8, par9); } @Override public TileEntity createNewTileEntity(World var1, int var2) { return new TileTank(var2); } @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); if(!(te instanceof TileTank)) { return null; } return new ContainerTank(player.inventory, (TileTank) te); } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); if(!(te instanceof TileTank)) { return null; } return new GuiTank(player.inventory, (TileTank) te); } @Override public boolean isOpaqueCube() { return false; } @Override protected int getGuiId() { return GuiHandler.GUI_ID_TANK; } @Override public IIcon getIcon(IBlockAccess world, int x, int y, int z, int blockSide) { // used to render the block in the world TileEntity te = world.getTileEntity(x, y, z); int facing = 0; if(te instanceof AbstractMachineEntity) { AbstractMachineEntity me = (AbstractMachineEntity) te; facing = me.facing; } int meta = world.getBlockMetadata(x, y, z); meta = MathHelper.clamp_int(meta, 0, 1); if(meta == 1) { return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing] + 6]; } else { return iconBuffer[0][ClientProxy.sideAndFacingToSpriteOffset[blockSide][facing]]; } } @Override public IIcon getIcon(int blockSide, int blockMeta) { int offset = MathHelper.clamp_int(blockMeta, 0, 1) == 0 ? 0 : 6; return iconBuffer[0][blockSide + offset]; } @Override protected String getMachineFrontIconKey(boolean pressurized) { if(pressurized) { return "enderio:blockTankAdvanced"; } return "enderio:blockTank"; } protected String getSideIconKey(boolean active) { return getMachineFrontIconKey(active); } protected String getBackIconKey(boolean active) { return getMachineFrontIconKey(active); } @Override protected String getTopIconKey(boolean pressurized) { if(pressurized) { return "enderio:blockTankTopAdvanced"; } return "enderio:machineTop"; } @Override @SideOnly(Side.CLIENT) public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { } @Override public float getExplosionResistance(Entity par1Entity, World world, int x, int y, int z, double explosionX, double explosionY, double explosionZ) { int meta = world.getBlockMetadata(x, y, z); meta = MathHelper.clamp_int(meta, 0, 1); if(meta == 1) { return 2000; } else { return super.getExplosionResistance(par1Entity); } } @Override @SideOnly(Side.CLIENT) public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { if(itemstack.stackTagCompound != null && itemstack.stackTagCompound.hasKey("tankContents")) { FluidStack fl = FluidStack.loadFluidStackFromNBT((NBTTagCompound) itemstack.stackTagCompound.getTag("tankContents")); if(fl != null && fl.getFluid() != null) { String str = fl.amount + " " + Lang.localize("fluid.millibucket.abr") + " " + PowerDisplayUtil.ofStr() + " " + fl.getFluid().getLocalizedName(); list.add(str); } } } @Override @SideOnly(Side.CLIENT) public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { TooltipAddera.addDetailedTooltipFromResources(list, itemstack); if(itemstack.getItemDamage() == 1) { list.add(EnumChatFormatting.ITALIC + Lang.localize("blastResistant")); } } @Override public String getUnlocalizedNameForTooltip(ItemStack stack) { System.out.println("BlockTank.getUnlocalizedNameForTooltip: "); return stack.getUnlocalizedName(); } }
package de.felixroske.jfxsupport; import static java.util.ResourceBundle.getBundle; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.StringUtils; import javafx.application.Platform; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.AnchorPane; public abstract class AbstractFxmlView implements ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFxmlView.class); private final ObjectProperty<Object> presenterProperty; private final ResourceBundle bundle; private final URL resource; private final FXMLView annotation; private FXMLLoader fxmlLoader; private ApplicationContext applicationContext; private String fxmlRoot; /** * Instantiates a new abstract fxml view. */ public AbstractFxmlView() { LOGGER.debug("AbstractFxmlView construction"); // Set the root path to package path final String filePathFromPackageName = PropertyReaderHelper.determineFilePathFromPackageName(getClass()); setFxmlRootPath(filePathFromPackageName); annotation = getFXMLAnnotation(); resource = getURLResource(annotation); presenterProperty = new SimpleObjectProperty<>(); bundle = getResourceBundle(getBundleName()); } /** * Gets the URL resource. This will be derived from applied annotation value * or from naming convention. * * @param annotation * the annotation as defined by inheriting class. * @return the URL resource */ private URL getURLResource(final FXMLView annotation) { if (annotation != null && !annotation.value().equals("")) { return getClass().getResource(annotation.value()); } else { return getClass().getResource(getFxmlPath()); } } /** * Gets the {@link FXMLView} annotation from inheriting class. * * @return the FXML annotation */ private FXMLView getFXMLAnnotation() { final Class<? extends AbstractFxmlView> theClass = this.getClass(); final FXMLView annotation = theClass.getAnnotation(FXMLView.class); return annotation; } /** * Creates the controller for type. * * @param type * the type * @return the object */ private Object createControllerForType(final Class<?> type) { return applicationContext.getBean(type); } /* * (non-Javadoc) * * @see * org.springframework.context.ApplicationContextAware#setApplicationContext * (org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { if (this.applicationContext != null) { return; } this.applicationContext = applicationContext; } /** * Sets the fxml root path. * * @param path * the new fxml root path */ private void setFxmlRootPath(final String path) { if (path.endsWith("/")) { fxmlRoot = path; } else { fxmlRoot = path + "/"; } } private FXMLLoader loadSynchronously(final URL resource, final ResourceBundle bundle) throws IllegalStateException { final FXMLLoader loader = new FXMLLoader(resource, bundle); loader.setControllerFactory(this::createControllerForType); try { loader.load(); } catch (final IOException ex) { throw new IllegalStateException("Cannot load " + getConventionalName(), ex); } return loader; } /** * Ensure fxml loader initialized. */ private void ensureFxmlLoaderInitialized() { if (fxmlLoader != null) { return; } fxmlLoader = loadSynchronously(resource, bundle); presenterProperty.set(fxmlLoader.getController()); } /** * Initializes the view by loading the FXML (if not happened yet) and * returns the top Node (parent) specified in the FXML file. * * @return the root view as determined from {@link FXMLLoader}. */ public Parent getView() { ensureFxmlLoaderInitialized(); final Parent parent = fxmlLoader.getRoot(); addCSSIfAvailable(parent); return parent; } /** * Initializes the view synchronously and invokes the consumer with the * created parent Node within the FX UI thread. * * @param consumer * - an object interested in received the {@link Parent} as * callback */ public void getView(final Consumer<Parent> consumer) { CompletableFuture.supplyAsync(this::getView, Platform::runLater).thenAccept(consumer); } /** * Scene Builder creates for each FXML document a root container. This * method omits the root container (e.g. {@link AnchorPane}) and gives you * the access to its first child. * * @return the first child of the {@link AnchorPane} or null if there are no * children available from this view. */ public Node getViewWithoutRootContainer() { final ObservableList<Node> children = getView().getChildrenUnmodifiable(); if (children.isEmpty()) { return null; } return children.listIterator().next(); } /** * Adds the CSS if available. * * @param parent * the parent */ void addCSSIfAvailable(final Parent parent) { // Read global css when available: final List<String> list = PropertyReaderHelper.get(applicationContext.getEnvironment(), "javafx.css"); if (!list.isEmpty()) { list.forEach(css -> parent.getStylesheets().add(getClass().getResource(css).toExternalForm())); } addCSSFromAnnotation(parent, annotation); final URL uri = getClass().getResource(getStyleSheetName()); if (uri == null) { return; } final String uriToCss = uri.toExternalForm(); parent.getStylesheets().add(uriToCss); } /** * Adds the CSS from annotation to parent. * * @param parent * the parent * @param annotation * the annotation */ private void addCSSFromAnnotation(final Parent parent, final FXMLView annotation) { if (annotation != null && annotation.css().length > 0) { for (final String cssFile : annotation.css()) { final URL uri = getClass().getResource(cssFile); if (uri != null) { final String uriToCss = uri.toExternalForm(); parent.getStylesheets().add(uriToCss); LOGGER.debug("css file added to parent: {}", cssFile); } else { LOGGER.warn("referenced {} css file could not be located", cssFile); } } } } /** * Gets the style sheet name. * * @return the style sheet name */ private String getStyleSheetName() { return fxmlRoot + getConventionalName(".css"); } /** * In case the view was not initialized yet, the conventional fxml * (airhacks.fxml for the AirhacksView and AirhacksPresenter) are loaded and * the specified presenter / controller is going to be constructed and * returned. * * @return the corresponding controller / presenter (usually for a * AirhacksView the AirhacksPresenter) */ public Object getPresenter() { ensureFxmlLoaderInitialized(); return presenterProperty.get(); } /** * Does not initialize the view. Only registers the Consumer and waits until * the the view is going to be created / the method FXMLView#getView or * FXMLView#getViewAsync invoked. * * @param presenterConsumer * listener for the presenter construction */ public void getPresenter(final Consumer<Object> presenterConsumer) { presenterProperty.addListener( (final ObservableValue<? extends Object> o, final Object oldValue, final Object newValue) -> { presenterConsumer.accept(newValue); }); } /** * Gets the conventional name. * * @param ending * the suffix to append * @return the conventional name with stripped ending */ private String getConventionalName(final String ending) { return getConventionalName() + ending; } /** * Gets the conventional name. * * @return the name of the view without the "View" prefix in lowerCase. For * AirhacksView just airhacks is going to be returned. */ private String getConventionalName() { return stripEnding(getClass().getSimpleName().toLowerCase()); } /** * Gets the bundle name. * * @return the bundle name */ private String getBundleName() { if (!StringUtils.isEmpty(annotation)) { final String lbundle = annotation.bundle(); LOGGER.debug("Annotated bundle: {}", lbundle); return lbundle; } else { final String lbundle = getClass().getPackage().getName() + "." + getConventionalName(); LOGGER.debug("Bundle: {} based on conventional name.", lbundle); return lbundle; } } /** * Strip ending. * * @param clazz * the clazz * @return the string */ private static String stripEnding(final String clazz) { if (!clazz.endsWith("view")) { return clazz; } return clazz.substring(0, clazz.lastIndexOf("view")); } /** * Gets the fxml file path. * * @return the relative path to the fxml file derived from the FXML view. * e.g. The name for the AirhacksView is going to be * <PATH>/airhacks.fxml. */ final String getFxmlPath() { final String fxmlPath = fxmlRoot + getConventionalName(".fxml"); LOGGER.debug("Determined fxmlPath: " + fxmlPath); return fxmlPath; } /** * Gets the resource bundle or returns null. * * @param name * the name of the resource bundle. * @return the resource bundle */ private ResourceBundle getResourceBundle(final String name) { try { LOGGER.debug("Resource bundle: " + name); return getBundle(name); } catch (final MissingResourceException ex) { LOGGER.debug("No resource bundle could be determined: " + ex.getMessage()); return null; } } /** * Gets the resource bundle. * * @return an existing resource bundle, or null */ public ResourceBundle getResourceBundle() { return bundle; } @Override public String toString() { return "AbstractFxmlView [presenterProperty=" + presenterProperty + ", bundle=" + bundle + ", resource=" + resource + ", fxmlRoot=" + fxmlRoot + "]"; } }
package de.gishmo.gwt.editor.processor; import java.util.Optional; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Types; import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; public class ModelUtils { // public static boolean containsMethod(TypeElement element, // String path, // String prefix) { // if (path.indexOf(".") == -1) { // return ElementFilter.methodsIn(element.getEnclosedElements()) // .stream() // .filter(executebleElement -> executebleElement.getConsumerSimpleName() // .toString() // .equals(prefix + ModelUtils.capatilize(path))) // .findFirst() // .isPresent(); // } else { // if (path.indexOf(".") == path.length()) { // return false; // Optional<? extends ExecutableElement> optional = ElementFilter.methodsIn(element.getEnclosedElements()) // .stream() // .filter(executebleElement -> executebleElement.getConsumerSimpleName() // .toString() // .equals("get" + ModelUtils.capatilize(path.substring(0, // path.indexOf("."))))) // .findFirst(); // if (optional.isPresent()) { // ExecutableElement executableElement = optional.get(); // return ModelUtils.containsMethod((TypeElement) MoreTypes.asDeclared(optional.get() // .getReturnType()) // .asElement(), // path.substring(path.indexOf(".") + 1), // prefix); // } else { // return false; public static ExecutableElement findGetMethod(TypeElement element, String path) { if (path.indexOf(".") == -1) { Optional<? extends ExecutableElement> optional = ElementFilter.methodsIn(element.getEnclosedElements()) .stream() .filter(executebleElement -> executebleElement.getSimpleName() .toString() .equals("get" + ModelUtils.capatilize(path))) .findFirst(); if (optional.isPresent()) { return optional.get(); } else { return null; } } else { if (path.indexOf(".") == path.length()) { return null; } Optional<? extends ExecutableElement> optional = ElementFilter.methodsIn(element.getEnclosedElements()) .stream() .filter(executebleElement -> executebleElement.getSimpleName() .toString() .equals("get" + ModelUtils.capatilize(path.substring(0, path.indexOf("."))))) .findFirst(); if (optional.isPresent()) { ExecutableElement executableElement = optional.get(); return ModelUtils.findGetMethod((TypeElement) MoreTypes.asDeclared(optional.get() .getReturnType()) .asElement(), path.substring(path.indexOf(".") + 1)); } else { return null; } } } public static ExecutableElement findSetMethod(TypeElement element, String path) { if (path.indexOf(".") == -1) { Optional<? extends ExecutableElement> optional = ElementFilter.methodsIn(element.getEnclosedElements()) .stream() .filter(executebleElement -> executebleElement.getSimpleName() .toString() .equals("set" + ModelUtils.capatilize(path))) .findFirst(); if (optional.isPresent()) { return optional.get(); } else { return null; } } else { if (path.indexOf(".") == path.length()) { return null; } Optional<? extends ExecutableElement> optional = ElementFilter.methodsIn(element.getEnclosedElements()) .stream() .filter(executebleElement -> executebleElement.getSimpleName() .toString() .equals("set" + ModelUtils.capatilize(path.substring(0, path.indexOf("."))))) .findFirst(); if (optional.isPresent()) { return optional.get(); // return ModelUtils.findSetMethod((TypeElement) MoreTypes.asDeclared(optional.get() // .getReturnType()) // .asElement(), // path.substring(path.indexOf(".") + 1)); } else { return null; } } } public static TypeMirror getInterfaceType(Types types, TypeElement element, Class<?> clazz) { Optional<? extends TypeMirror> optinals = element.getInterfaces() .stream() .filter(interfaceType -> ClassName.get(types.erasure(interfaceType)) .toString() .contains(clazz.getCanonicalName())) .findFirst(); if (optinals.isPresent()) { return optinals.get(); } else { if (element.getSuperclass() == null) { return null; } return ModelUtils.getInterfaceType(types, (TypeElement) types.asElement(element.getSuperclass()), clazz); } } private static String capatilize(String value) { return value.substring(0, 1) .toUpperCase() + value.substring(1); } }
package de.prob2.ui.consoles.groovy; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.config.Config; import de.prob2.ui.config.ConfigData; import de.prob2.ui.config.ConfigListener; import de.prob2.ui.consoles.Console; import de.prob2.ui.consoles.groovy.codecompletion.CodeCompletionEvent; import de.prob2.ui.consoles.groovy.codecompletion.CodeCompletionTriggerAction; import de.prob2.ui.internal.FXMLInjected; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import org.fxmisc.wellbehaved.event.EventPattern; import org.fxmisc.wellbehaved.event.InputMap; import org.fxmisc.wellbehaved.event.Nodes; @FXMLInjected @Singleton public class GroovyConsole extends Console { private final GroovyInterpreter groovyInterpreter; @Inject private GroovyConsole(GroovyInterpreter groovyInterpreter, ResourceBundle bundle, Config config) { super(bundle, bundle.getString("consoles.groovy.header"), bundle.getString("consoles.groovy.prompt"), groovyInterpreter); this.groovyInterpreter = groovyInterpreter; this.groovyInterpreter.setCodeCompletion(this); setCodeCompletionEvent(); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.SPACE, KeyCombination.CONTROL_DOWN), e-> this.triggerCodeCompletion(CodeCompletionTriggerAction.TRIGGER))); config.addListener(new ConfigListener() { @Override public void loadConfig(final ConfigData configData) { if (configData.groovyConsoleInstructions != null) { loadInstructions(configData.groovyConsoleInstructions); } } @Override public void saveConfig(final ConfigData configData) { configData.groovyConsoleInstructions = saveInstructions(); } }); } @Override protected void keyPressed(KeyEvent e) { if (".".equals(e.getText())) { triggerCodeCompletion(CodeCompletionTriggerAction.POINT); } super.keyPressed(e); } private void triggerCodeCompletion(CodeCompletionTriggerAction action) { if (getCaretPosition() >= this.getInputStart()) { int caretPosInLine = getCaretPosition() - getInputStart(); groovyInterpreter.triggerCodeCompletion(getInput().substring(0, caretPosInLine), action); } } private void setCodeCompletionEvent() { this.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> groovyInterpreter.triggerCloseCodeCompletion()); this.addEventHandler(CodeCompletionEvent.CODECOMPLETION, this::handleCodeCompletionEvent); } private void handleCodeCompletionEvent(CodeCompletionEvent e) { if (e.getCode() == KeyCode.ENTER || e.getEvent() instanceof MouseEvent || ";".equals(((KeyEvent)e.getEvent()).getText())) { handleChooseSuggestion(e); this.scrollYToPixel(Double.MAX_VALUE); } else if (e.getCode() == KeyCode.SPACE) { //handle Space in Code Completion keyPressed((KeyEvent)e.getEvent()); e.consume(); } } private void handleChooseSuggestion(CodeCompletionEvent e) { String choice = e.getChoice(); String suggestion = e.getCurrentSuggestion(); int indexSkipped = getIndexSkipped(this.getText(this.getCaretPosition(), this.getLength()), choice, suggestion); int indexOfRest = this.getCaretPosition() + indexSkipped; int oldLength = this.getLength(); String addition = choice + this.getText(indexOfRest, this.getLength()); this.deleteText(this.getCaretPosition() - suggestion.length(), this.getLength()); this.appendText(addition); int diff = this.getLength() - oldLength; currentPosInLine += diff + indexSkipped; charCounterInLine += diff; this.moveTo(indexOfRest + diff); } private int getIndexSkipped(String rest, String choice, String suggestion) { String restOfChoice = choice.substring(suggestion.length()); int result = 0; for (int i = 0; i < Math.min(rest.length(), restOfChoice.length()); i++) { if (restOfChoice.charAt(i) == rest.charAt(i)) { result++; } else { break; } } return result; } public void closeObjectStage() { groovyInterpreter.closeObjectStage(); } }
package org.carlspring.strongbox.storage.validation; import org.carlspring.strongbox.config.Maven2LayoutProviderTestConfig; import org.carlspring.strongbox.configuration.Configuration; import org.carlspring.strongbox.configuration.ConfigurationManager; import org.carlspring.strongbox.storage.validation.version.MavenReleaseVersionValidator; import org.carlspring.strongbox.storage.validation.version.MavenSnapshotVersionValidator; import javax.inject.Inject; import java.io.File; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /** * @author mtodorov */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Maven2LayoutProviderTestConfig.class}) public class DefaultMavenArtifactCoordinateValidatorsTest { public static final String TEST_CLASSES = "target/test-classes"; public static final String CONFIGURATION_BASEDIR = TEST_CLASSES + "/xml"; @Inject private ConfigurationManager configurationManager; @Before public void setUp() { File xmlDir = new File(CONFIGURATION_BASEDIR); if (!xmlDir.exists()) { //noinspection ResultOfMethodCallIgnored xmlDir.mkdirs(); } } @Test public void testParseConfiguration() { final Configuration configuration = configurationManager.getConfiguration(); assertNotNull(configuration); assertNotNull(configuration.getStorages()); assertNotNull(configuration.getRoutingRules()); for (String storageId : configuration.getStorages().keySet()) { assertNotNull("Storage ID was null!", storageId); } assertTrue("Unexpected number of storages!", configuration.getStorages().size() > 0); assertNotNull("Incorrect version!", configuration.getVersion()); assertEquals("Incorrect port number!", 48080, configuration.getPort()); assertTrue("Repository should have required authentication!", configuration.getStorages() .get("storage0") .getRepositories() .get("snapshots") .isSecured()); assertTrue(configuration.getStorages() .get("storage0") .getRepositories() .get("releases") .allowsDirectoryBrowsing()); Set<String> versionValidators = configuration.getStorages() .get("storage0") .getRepositories() .get("releases") .getArtifactCoordinateValidators(); assertEquals(Integer.valueOf(2), Integer.valueOf(versionValidators.size())); assertTrue(versionValidators.remove(MavenSnapshotVersionValidator.ALIAS)); assertTrue(versionValidators.remove(MavenReleaseVersionValidator.ALIAS)); assertEquals(Integer.valueOf(versionValidators.size()), Integer.valueOf(0)); } }
package de.slackspace.openkeepass; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.bouncycastle.util.encoders.Base64; import de.slackspace.openkeepass.crypto.Decrypter; import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; import de.slackspace.openkeepass.crypto.Salsa20; import de.slackspace.openkeepass.crypto.Sha256; import de.slackspace.openkeepass.domain.CompressionAlgorithm; import de.slackspace.openkeepass.domain.CrsAlgorithm; import de.slackspace.openkeepass.domain.KeePassFile; import de.slackspace.openkeepass.domain.KeePassHeader; import de.slackspace.openkeepass.domain.KeyFile; import de.slackspace.openkeepass.exception.KeePassDatabaseUnreadable; import de.slackspace.openkeepass.exception.KeePassDatabaseUnwriteable; import de.slackspace.openkeepass.stream.HashedBlockInputStream; import de.slackspace.openkeepass.stream.HashedBlockOutputStream; import de.slackspace.openkeepass.stream.SafeInputStream; import de.slackspace.openkeepass.util.ByteUtils; import de.slackspace.openkeepass.util.StreamUtils; import de.slackspace.openkeepass.xml.KeePassDatabaseXmlParser; import de.slackspace.openkeepass.xml.KeyFileXmlParser; /** * A KeePassDatabase is the central API class to read and write a KeePass * database file. * <p> * Currently the following KeePass files are supported: * * <ul> * <li>KeePass Database V2 with password</li> * <li>KeePass Database V2 with keyfile</li> * <li>KeePass Database V2 with combined password and keyfile</li> * </ul> * * A typical read use-case should use the following idiom: * * <pre> * // open database * KeePassFile database = KeePassDatabase.getInstance("keePassDatabasePath").openDatabase("secret"); * * // get password entries * List&lt;Entry&gt; entries = database.getEntries(); * ... * </pre> * * If the database could not be opened an exception of type <tt>KeePassDatabaseUnreadable</tt> will be * thrown. * <p> * A typical write use-case should use the following idiom: * * <pre> * // build an entry * Entry entryOne = new EntryBuilder("First entry").username("Carl").password("secret").build(); * * // build more entries or groups as you like * ... * * // build KeePass model * KeePassFile keePassFile = new KeePassFileBuilder("testDB").addTopEntries(entryOne).build(); * * // write KeePass database file * KeePassDatabase.write(keePassFile, "secret", new FileOutputStream("keePassDatabasePath")); * </pre> * * @see KeePassFile * */ public class KeePassDatabase { private static final String MSG_UTF8_NOT_SUPPORTED = "The encoding UTF-8 is not supported"; private static final String UTF_8 = "UTF-8"; private KeePassHeader keepassHeader = new KeePassHeader(); private byte[] keepassFile; protected Decrypter decrypter = new Decrypter(); protected KeePassDatabaseXmlParser keePassDatabaseXmlParser = new KeePassDatabaseXmlParser(); protected KeyFileXmlParser keyFileXmlParser = new KeyFileXmlParser(); private KeePassDatabase(InputStream inputStream) { try { keepassFile = StreamUtils.toByteArray(inputStream); keepassHeader.checkVersionSupport(keepassFile); keepassHeader.read(keepassFile); } catch (IOException e) { throw new KeePassDatabaseUnreadable("Could not open database file", e); } } /** * Retrieves a KeePassDatabase instance. The instance returned is based on * the given database filename and tries to parse the database header of it. * * @param keePassDatabaseFile * a KeePass database filename, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(String keePassDatabaseFile) { return getInstance(new File(keePassDatabaseFile)); } /** * Retrieves a KeePassDatabase instance. The instance returned is based on * the given database file and tries to parse the database header of it. * * @param keePassDatabaseFile * a KeePass database file, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(File keePassDatabaseFile) { if (keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } InputStream keePassDatabaseStream = null; try { keePassDatabaseStream = new FileInputStream(keePassDatabaseFile); return getInstance(keePassDatabaseStream); } catch (FileNotFoundException e) { throw new IllegalArgumentException( "The KeePass database file could not be found. You must provide a valid KeePass database file.", e); } finally { if (keePassDatabaseStream != null) { try { keePassDatabaseStream.close(); } catch (IOException e) { // Ignore } } } } /** * Retrieves a KeePassDatabase instance. The instance returned is based on * the given input stream and tries to parse the database header of it. * * @param keePassDatabaseStream * an input stream of a KeePass database, must not be NULL * @return a KeePassDatabase */ public static KeePassDatabase getInstance(InputStream keePassDatabaseStream) { if (keePassDatabaseStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass database stream."); } KeePassDatabase reader = new KeePassDatabase(keePassDatabaseStream); return reader; } /** * Opens a KeePass database with the given password and returns the * KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password an * exception will be thrown. * * @param password * the password to open the database * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(String password) { if (password == null) { throw new IllegalArgumentException( "The password for the database must not be null. Please provide a valid password."); } try { byte[] passwordBytes = password.getBytes(UTF_8); byte[] hashedPassword = Sha256.hash(passwordBytes); return decryptAndParseDatabase(hashedPassword); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException(MSG_UTF8_NOT_SUPPORTED, e); } } /** * Opens a KeePass database with the given password and keyfile and returns * the KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password and * keyfile an exception will be thrown. * * @param password * the password to open the database * @param keyFile * the password to open the database * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(String password, File keyFile) { if (password == null) { throw new IllegalArgumentException( "The password for the database must not be null. Please provide a valid password."); } if (keyFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass keyfile."); } try { return openDatabase(password, new FileInputStream(keyFile)); } catch (FileNotFoundException e) { throw new IllegalArgumentException( "The KeePass keyfile could not be found. You must provide a valid KeePass keyfile.", e); } } /** * Opens a KeePass database with the given password and keyfile stream and * returns the KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password and * keyfile stream an exception will be thrown. * * @param password * the password to open the database * @param keyFileStream * the keyfile to open the database as stream * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(String password, InputStream keyFileStream) { if (password == null) { throw new IllegalArgumentException( "The password for the database must not be null. Please provide a valid password."); } if (keyFileStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream."); } try { byte[] passwordBytes = password.getBytes(UTF_8); byte[] hashedPassword = Sha256.hash(passwordBytes); KeyFile keyFile = keyFileXmlParser.fromXml(keyFileStream); byte[] protectedBuffer = Base64.decode(keyFile.getKey().getData().getBytes(UTF_8)); if (protectedBuffer.length != 32) { protectedBuffer = Sha256.hash(protectedBuffer); } return decryptAndParseDatabase(ByteUtils.concat(hashedPassword, protectedBuffer)); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException(MSG_UTF8_NOT_SUPPORTED, e); } } /** * Opens a KeePass database with the given keyfile and returns the * KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided password an * exception will be thrown. * * @param keyFile * the password to open the database * @return a KeePassFile the keyfile to open the database * @see KeePassFile */ public KeePassFile openDatabase(File keyFile) { if (keyFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass keyfile."); } try { return openDatabase(new FileInputStream(keyFile)); } catch (FileNotFoundException e) { throw new IllegalArgumentException( "The KeePass keyfile could not be found. You must provide a valid KeePass keyfile.", e); } } /** * Opens a KeePass database with the given keyfile stream and returns the * KeePassFile for further processing. * <p> * If the database cannot be decrypted with the provided keyfile an * exception will be thrown. * * @param keyFileStream * the keyfile to open the database as stream * @return a KeePassFile * @see KeePassFile */ public KeePassFile openDatabase(InputStream keyFileStream) { if (keyFileStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream."); } try { KeyFile keyFile = keyFileXmlParser.fromXml(keyFileStream); byte[] protectedBuffer = Base64.decode(keyFile.getKey().getData().getBytes(UTF_8)); return decryptAndParseDatabase(protectedBuffer); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException(MSG_UTF8_NOT_SUPPORTED, e); } } @SuppressWarnings("resource") private KeePassFile decryptAndParseDatabase(byte[] key) { try { byte[] aesDecryptedDbFile = decrypter.decryptDatabase(key, keepassHeader, keepassFile); byte[] startBytes = new byte[32]; SafeInputStream decryptedStream = new SafeInputStream(new ByteArrayInputStream(aesDecryptedDbFile)); // Metadata must be skipped here decryptedStream.skipSafe(KeePassHeader.VERSION_SIGNATURE_LENGTH + keepassHeader.getHeaderSize()); decryptedStream.readSafe(startBytes); // Compare startBytes if (!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { throw new KeePassDatabaseUnreadable( "The keepass database file seems to be corrupt or cannot be decrypted."); } HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); byte[] decompressed = hashedBlockBytes; // Unzip if necessary if (keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); decompressed = StreamUtils.toByteArray(gzipInputStream); } ProtectedStringCrypto protectedStringCrypto; if (keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); } else { throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); } return keePassDatabaseXmlParser.fromXml(new ByteArrayInputStream(decompressed), protectedStringCrypto); } catch (IOException e) { throw new KeePassDatabaseUnreadable("Could not open database file", e); } } /** * Gets the KeePassDatabase header. * * @return the database header */ public KeePassHeader getHeader() { return keepassHeader; } /** * Encrypts a {@link KeePassFile} with the given password and writes it to * the given file location. * <p> * If the KeePassFile cannot be encrypted an exception will be thrown. * * @param keePassFile * the keePass model which should be written * @param password * the password to encrypt the database * @param keePassDatabaseFile * the target location where the database file will be written * @see KeePassFile */ public static void write(KeePassFile keePassFile, String password, String keePassDatabaseFile) { if (keePassDatabaseFile == null || keePassDatabaseFile.isEmpty()) { throw new IllegalArgumentException( "You must provide a non-empty path where the database should be written to."); } try { write(keePassFile, password, new FileOutputStream(keePassDatabaseFile)); } catch (FileNotFoundException e) { throw new KeePassDatabaseUnreadable("Could not find database file", e); } } /** * Encrypts a {@link KeePassFile} with the given password and writes it to * the given stream. * <p> * If the KeePassFile cannot be encrypted an exception will be thrown. * * @param keePassFile * the keePass model which should be written * @param password * the password to encrypt the database * @param stream * the target stream where the output will be written * @see KeePassFile * */ public static void write(KeePassFile keePassFile, String password, OutputStream stream) { if (stream == null) { throw new IllegalArgumentException("You must provide a stream to write to."); } try { if (!validateKeePassFile(keePassFile)) { throw new KeePassDatabaseUnwriteable( "The provided keePassFile is not valid. A valid keePassFile must contain of meta and root group and the root group must at least contain one group."); } KeePassHeader header = new KeePassHeader(); header.initialize(); byte[] passwordBytes = password.getBytes(UTF_8); byte[] hashedPassword = Sha256.hash(passwordBytes); // Marshall xml ProtectedStringCrypto protectedStringCrypto = Salsa20.createInstance(header.getProtectedStreamKey()); byte[] keePassFilePayload = new KeePassDatabaseXmlParser().toXml(keePassFile, protectedStringCrypto) .toByteArray(); // Unzip ByteArrayOutputStream streamToUnzip = new ByteArrayOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(streamToUnzip); gzipOutputStream.write(keePassFilePayload); gzipOutputStream.close(); // Unhash ByteArrayOutputStream streamToUnhashBlock = new ByteArrayOutputStream(); HashedBlockOutputStream hashBlockOutputStream = new HashedBlockOutputStream(streamToUnhashBlock); hashBlockOutputStream.write(streamToUnzip.toByteArray()); hashBlockOutputStream.close(); // Write Header ByteArrayOutputStream streamToEncrypt = new ByteArrayOutputStream(); streamToEncrypt.write(header.getBytes()); streamToEncrypt.write(header.getStreamStartBytes()); // Write Content streamToEncrypt.write(streamToUnhashBlock.toByteArray()); // Encrypt byte[] encryptedDatabase = new Decrypter().encryptDatabase(hashedPassword, header, streamToEncrypt.toByteArray()); // Write database to stream stream.write(encryptedDatabase); } catch (IOException e) { throw new KeePassDatabaseUnwriteable("Could not write database file", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } } } private static boolean validateKeePassFile(KeePassFile keePassFile) { if (keePassFile == null || keePassFile.getMeta() == null) { return false; } if (keePassFile.getRoot() == null || keePassFile.getRoot().getGroups().isEmpty()) { return false; } return true; } }
package com.bitdubai.fermat_dmp_plugin.layer.engine.app_runtime.developer.bitdubai.version_1; import com.bitdubai.fermat_api.CantStartPluginException; import com.bitdubai.fermat_api.FermatException; import com.bitdubai.fermat_api.Plugin; import com.bitdubai.fermat_api.Service; import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.RuntimeFernatComboBox; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.interfaces.FermatComboBox; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.enums.EventType; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.Activity; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.Fragment; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.MainMenu; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.SearchView; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.SideMenu; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.Tab; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.MenuItem; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.TabStrip; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.TitleBar; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.Wizard; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.WizardPage; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.Activities; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.WizardPageTypes; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.WizardTypes; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.Fragments; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.SubAppRuntimeManager; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.SubApp; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.Apps; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps; import com.bitdubai.fermat_api.layer.osa_android.file_system.DealsWithPluginFileSystem; import com.bitdubai.fermat_api.layer.osa_android.file_system.PluginFileSystem; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.DealsWithErrors; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.DealsWithEvents; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.EventHandler; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.EventListener; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.EventManager; import com.bitdubai.fermat_dmp_plugin.layer.engine.app_runtime.developer.bitdubai.version_1.event_handlers.WalletResourcesInstalledEventHandler; import com.bitdubai.fermat_dmp_plugin.layer.engine.app_runtime.developer.bitdubai.version_1.exceptions.CantFactoryResetException; import com.bitdubai.fermat_dmp_plugin.layer.engine.app_runtime.developer.bitdubai.version_1.structure.RuntimeApp; import com.bitdubai.fermat_dmp_plugin.layer.engine.app_runtime.developer.bitdubai.version_1.structure.RuntimeSubApp; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; /** * The App Runtime is the module in charge of the UI navigation structure. A user is always at a certain point in this * structure. */ /** * A Navigation stack is maintained by this plugin to allow the user to go back all the stack down to the root if necessary. */ public class SubAppRuntimeMiddlewarePluginRoot implements Service, SubAppRuntimeManager, DealsWithEvents, DealsWithErrors, DealsWithPluginFileSystem, Plugin { /** * Service Interface member variables. */ ServiceStatus serviceStatus = ServiceStatus.CREATED; /** * SubAppRuntimeManager Interface member variables. */ List<EventListener> listenersAdded = new ArrayList<>(); Map<SubApps, SubApp> listSubApp = new HashMap<SubApps, SubApp>(); SubApps lastSubapp; RuntimeSubApp homeScreen; /** * UsesFileSystem Interface member variables. */ PluginFileSystem pluginFileSystem; /** * DealsWithErrors Interface member variables. */ ErrorManager errorManager; /** * DealWithEvents Interface member variables. */ EventManager eventManager; /** * Plugin Interface member variables. */ UUID pluginId; public void addToNavigationStructure(/*String NavigationStructure, WalletModule*/) { } @Override public void start() throws CantStartPluginException { try { /** * I will initialize the handling of com.bitdubai.platform events. */ EventListener eventListener; EventHandler eventHandler; eventListener = eventManager.getNewListener(EventType.WALLET_RESOURCES_INSTALLED); eventHandler = new WalletResourcesInstalledEventHandler(); ((WalletResourcesInstalledEventHandler) eventHandler).setSubAppRuntimeManager(this); eventListener.setEventHandler(eventHandler); eventManager.addListener(eventListener); listenersAdded.add(eventListener); /** * At this time the only thing I can do is a factory reset. Once there should be a possibility to add * functionality based on wallets downloaded by users this wont be an option. * * * */ factoryReset(); this.serviceStatus = ServiceStatus.STARTED; } catch (CantFactoryResetException ex) { String message = CantStartPluginException.DEFAULT_MESSAGE; FermatException cause = ex; String context = "App Runtime Start"; String possibleReason = "Some null definition"; throw new CantStartPluginException(message, cause, context, possibleReason); } catch (Exception exception) { throw new CantStartPluginException(CantStartPluginException.DEFAULT_MESSAGE, FermatException.wrapException(exception), null, "Unchecked Exception occurred, check the cause"); } } @Override public void pause() { this.serviceStatus = ServiceStatus.PAUSED; } @Override public void resume() { this.serviceStatus = ServiceStatus.STARTED; } @Override public void stop() { /** * I will remove all the listeners registered with the event manager. */ for (EventListener eventListener : listenersAdded) { eventManager.removeListener(eventListener); } listenersAdded.clear(); this.serviceStatus = ServiceStatus.STOPPED; } @Override public ServiceStatus getStatus() { return this.serviceStatus; } /** * AppRuntime Interface implementation. */ @Override public SubApp getLastSubApp() { if (lastSubapp != null) { return listSubApp.get(lastSubapp); } return homeScreen; } @Override public SubApp getSubApp(SubApps subApps) { SubApp subApp = listSubApp.get(subApps); if(subApp!=null){ lastSubapp = subApps; return subApp; } return null; // Iterator<Map.Entry<SubApps, SubApp>> eSubApp = listSubApp.entrySet().iterator(); // while (eSubApp.hasNext()) { // Map.Entry<SubApps, SubApp> walletEntry = eSubApp.next(); // SubApp subApp = (SubApp) walletEntry.getValue(); // if (subApp.getType().equals(subApps)) { // lastSubapp = subApps; // return subApp; } @Override public SubApp getHomeScreen() { lastSubapp = SubApps.CWP_WALLET_MANAGER; homeScreen.getActivity(Activities.CWP_WALLET_MANAGER_MAIN); return homeScreen; } /** * UsesFileSystem Interface implementation. */ @Override public void setPluginFileSystem(PluginFileSystem pluginFileSystem) { this.pluginFileSystem = pluginFileSystem; } /** * DealWithEvents Interface implementation. */ @Override public void setEventManager(EventManager eventManager) { this.eventManager = eventManager; } /** * DealWithErrors Interface implementation. */ @Override public void setErrorManager(ErrorManager errorManager) { this.errorManager = errorManager; } /** * DealsWithPluginIdentity methods implementation. */ @Override public void setId(UUID pluginId) { this.pluginId = pluginId; } /** * The first time this plugins runs, it will setup the initial structure for the App, subApp and so on through the local * interfaces of the classes involved, */ private void firstRunCheck() { /** * First I check weather this a structure already created, if not I create the "Factory" structure. */ } /** * Here is where I actually generate the factory structure of the APP. This method is also useful to reset to the * factory structure. */ private void factoryReset() throws CantFactoryResetException { loadHomeScreen(); try { RuntimeApp runtimeApp = new RuntimeApp(); runtimeApp.setType(Apps.CRYPTO_WALLET_PLATFORM); RuntimeSubApp runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_SHELL); runtimeApp.addSubApp(runtimeSubApp); listSubApp.put(SubApps.CWP_SHELL, runtimeSubApp); Activity runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_SHELL_LOGIN); runtimeSubApp.addActivity(runtimeActivity); Fragment runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_SHELL_LOGIN.getKey()); runtimeActivity.addFragment(Fragments.CWP_SHELL_LOGIN.getKey(), runtimeFragment); TitleBar runtimeTitleBar; SideMenu runtimeSideMenu; MainMenu runtimeMainMenu; MenuItem runtimeMenuItem; TabStrip runtimeTabStrip; StatusBar statusBar; Tab runtimeTab; /** * Definition of Developer Manager App */ runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_DEVELOPER_APP); listSubApp.put(SubApps.CWP_DEVELOPER_APP, runtimeSubApp); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_SUB_APP_ALL_DEVELOPER); runtimeActivity.setColor("#b46a54"); //runtimeActivity.setStatusBarColor(); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#d07b62"); runtimeActivity.setStatusBar(statusBar); runtimeSubApp.addActivity(runtimeActivity); runtimeSubApp.setStartActivity(Activities.CWP_SUB_APP_ALL_DEVELOPER); runtimeTitleBar = new TitleBar(); //Navigation runtimeSideMenu = new SideMenu(); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Personal Wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Shops"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Commercial wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Factory Projects"); runtimeMenuItem.setLinkToActivity(Activities.CWP_WALLET_FACTORY_MAIN); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Published Wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Wallet Store"); runtimeMenuItem.setLinkToActivity(Activities.CWP_WALLET_STORE_MAIN_ACTIVITY); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Exit"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeActivity.setSideMenu(runtimeSideMenu); //fin navigation runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Developer"); //runtimeTitleBar.setColor("#d07b62"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTabStrip.setTabsColor("#d07b62"); runtimeTabStrip.setTabsTextColor("#FFFFFF"); runtimeTabStrip.setTabsIndicateColor("#b46a54"); runtimeTab = new Tab(); runtimeTab.setLabel("DataBase Tools"); runtimeTab.setFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_FRAGMENT); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Log Tools"); runtimeTab.setFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_FRAGMENT); runtimeTabStrip.addTab(runtimeTab); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_LIST_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_LIST_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_TABLE_LIST_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_LIST_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_TABLE_LIST_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_TABLE_RECORD_LIST_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_TABLE_LIST_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_DATABASE_TABLE_RECORD_LIST_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_1_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_1_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_2_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_1_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_2_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_3_FRAGMENT.getKey()); runtimeFragment.setBack(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_2_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_DEVELOPER_TOOL_LOG_LEVEL_3_FRAGMENT.getKey(), runtimeFragment); /** * End of Developer tabs. */ //wallet factory app runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_WALLET_FACTORY); runtimeApp.addSubApp(runtimeSubApp); listSubApp.put(SubApps.CWP_WALLET_FACTORY, runtimeSubApp); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_FACTORY_MAIN); runtimeActivity.setColor("#b46a54"); runtimeSubApp.setStartActivity(Activities.CWP_WALLET_FACTORY_MAIN); //runtimeActivity.setStatusBarColor(""); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#b46a54"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Factory"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTabStrip.setTabsColor("#d07b62"); runtimeTabStrip.setTabsTextColor("#FFFFFF"); runtimeTabStrip.setTabsIndicateColor("#b46a54"); runtimeTab = new Tab(); runtimeTab.setLabel("Developer Projects"); runtimeTab.setFragment(Fragments.CWP_WALLET_FACTORY_MANAGER_FRAGMENT); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Wallet Projects"); runtimeTab.setFragment(Fragments.CWP_WALLET_FACTORY_PROJECTS_FRAGMENT); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("EditMode"); runtimeTab.setFragment(Fragments.CWP_WALLET_FACTORY_EDIT_MODE); runtimeTabStrip.addTab(runtimeTab); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeSubApp.addActivity(runtimeActivity); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_FACTORY_MANAGER_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_FACTORY_MANAGER_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_FACTORY_PROJECTS_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_FACTORY_PROJECTS_FRAGMENT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_FACTORY_EDIT_MODE.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_FACTORY_EDIT_MODE.getKey(), runtimeFragment); /* Adding WizardTypes */ Wizard runtimeWizard = new Wizard(); // step 1 wizard create from scratch WizardPage runtimeWizardPage = new WizardPage(); runtimeWizardPage.setType(WizardPageTypes.CWP_WALLET_FACTORY_CREATE_STEP_1); runtimeWizard.addPage(runtimeWizardPage); //step 2 wizard runtimeWizardPage = new WizardPage(); runtimeWizardPage.setType(WizardPageTypes.CWP_WALLET_FACTORY_CREATE_STEP_2); runtimeWizard.addPage(runtimeWizardPage); /* Adding wizard */ runtimeActivity.addWizard(WizardTypes.CWP_WALLET_FACTORY_CREATE_NEW_PROJECT, runtimeWizard); /** * Edit Activity */ runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_FACTORY_EDIT_WALLET); runtimeActivity.setColor("#b46a54"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#b46a54"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Edit Wallet"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTabStrip.setTabsColor("#8bba9e"); runtimeTabStrip.setTabsTextColor("#FFFFFF"); runtimeTabStrip.setTabsIndicateColor("#72af9c"); runtimeTab = new Tab(); runtimeTab.setLabel("Balance"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_BALANCE); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Contacts"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_CONTACTS); runtimeTabStrip.addTab(runtimeTab); runtimeTabStrip.setDividerColor(0x72af9c); //runtimeTabStrip.setBackgroundColor("#72af9c"); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_BALANCE.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_BALANCE.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_CONTACTS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_BITCOIN_ALL_BITDUBAI_CONTACTS.getKey(), runtimeFragment); runtimeSubApp.addActivity(runtimeActivity); /**End Wallet Factory*/ //wallet Publisher app runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_WALLET_PUBLISHER); runtimeApp.addSubApp(runtimeSubApp); listSubApp.put(SubApps.CWP_WALLET_PUBLISHER, runtimeSubApp); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_PUBLISHER_MAIN); runtimeActivity.setColor("#b46a54"); //runtimeActivity.setStatusBarColor("#b46a54");556 runtimeSubApp.setStartActivity(Activities.CWP_WALLET_PUBLISHER_MAIN); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Publisher"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeSubApp.addActivity(runtimeActivity); runtimeSideMenu = new SideMenu(); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Personal Wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Shops"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Commercial wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Factory Projects"); runtimeMenuItem.setLinkToActivity(Activities.CWP_WALLET_FACTORY_MAIN); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Published Wallets"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Wallet Store"); runtimeMenuItem.setLinkToActivity(Activities.CWP_WALLET_STORE_MAIN_ACTIVITY); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Exit"); runtimeSideMenu.addMenuItem(runtimeMenuItem); runtimeActivity.setSideMenu(runtimeSideMenu); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_PUBLISHER_MAIN_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_PUBLISHER_MAIN_FRAGMENT.getKey(), runtimeFragment); runtimeActivity.setStartFragment(Fragments.CWP_WALLET_PUBLISHER_MAIN_FRAGMENT.getKey()); /**End Wallet Publisher*/ runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_WALLET_MANAGER); runtimeApp.addSubApp(runtimeSubApp); listSubApp.put(SubApps.CWP_WALLET_MANAGER, runtimeSubApp); //TODO: testing //lastSubapp = SubApps.CWP_WALLET_MANAGER; runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_MANAGER_MAIN); runtimeSubApp.addActivity(runtimeActivity); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_MANAGER_MAIN.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_MANAGER_MAIN.getKey(), runtimeFragment); //Desktop page Developer sub App runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_SUB_APP_DEVELOPER.getKey()); runtimeActivity.addFragment(Fragments.CWP_SUB_APP_DEVELOPER.getKey(), runtimeFragment); runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_WALLET_RUNTIME); runtimeApp.addSubApp(runtimeSubApp); listSubApp.put(SubApps.CWP_WALLET_RUNTIME, runtimeSubApp); // runtimeSubApp = new RuntimeSubApp(); // runtimeSubApp.setType(SubApps.CWP_WALLET_STORE); // runtimeApp.addSubApp(runtimeSubApp); // listSubApp.put(SubApps.CWP_WALLET_STORE, runtimeSubApp); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_STORE_MAIN_ACTIVITY); runtimeSubApp.addActivity(runtimeActivity); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_PUBLISHER_MAIN_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_PUBLISHER_MAIN_FRAGMENT.getKey(), runtimeFragment); /** * Definition of Shop Manager */ runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_ADULTS_ALL_SHOPS); runtimeActivity.setColor("#76dc4a"); runtimeSubApp.addActivity(runtimeActivity); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("My Shop"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTab = new Tab(); runtimeTab.setLabel("Shop"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_SHOP); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Products"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_PRODUCTS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Reviews"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_REVIEWS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Chat"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_CHAT); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("History"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_HISTORY); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Map"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_MAP); runtimeTabStrip.addTab(runtimeTab); runtimeTabStrip.setDividerColor(0xFFFFFFFF); runtimeTabStrip.setIndicatorColor(0xFFFFFFFF); runtimeTabStrip.setIndicatorHeight(9); runtimeTabStrip.setBackgroundColor(0xFF76dc4a); runtimeTabStrip.setTextColor(0xFFFFFFFF); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_SHOP.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_SHOP.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_PRODUCTS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_PRODUCTS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_REVIEWS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_REVIEWS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_CHAT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_CHAT.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_HISTORY.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_HISTORY.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_MAP.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_SHOP_MAP.getKey(), runtimeFragment); /** * End of SHOPS tabs. */ /*-- wallet store --*/ runtimeSubApp = new RuntimeSubApp(); runtimeSubApp.setType(SubApps.CWP_WALLET_STORE); listSubApp.put(SubApps.CWP_WALLET_STORE, runtimeSubApp); //Activity 1 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_STORE_MAIN_ACTIVITY); runtimeSubApp.setStartActivity(Activities.CWP_WALLET_STORE_MAIN_ACTIVITY); runtimeSubApp.addActivity(runtimeActivity); runtimeActivity.setColor("#b46a54"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#b46a54"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Store"); runtimeActivity.setTitleBar(runtimeTitleBar); // runtimeTabStrip = new TabStrip(); // runtimeTabStrip.setTabsColor("#d07b62"); // runtimeTabStrip.setTabsTextColor("#FFFFFF"); // runtimeTabStrip.setTabsIndicateColor("#b46a54"); //mati SearchView runtimeSearchView = new SearchView(); runtimeSearchView.setLabel("Search"); runtimeTitleBar.setRuntimeSearchView(runtimeSearchView); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey(), runtimeFragment); runtimeActivity.setStartFragment(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey()); //Activity 2 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_STORE_DETAIL_ACTIVITY); runtimeSubApp.addActivity(runtimeActivity); runtimeActivity.setColor("#00000000"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#00000000"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Store detail"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeSearchView = new SearchView(); runtimeSearchView.setLabel("Search"); runtimeTitleBar.setRuntimeSearchView(runtimeSearchView); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey(), runtimeFragment); //Activity 3 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_STORE_MORE_DETAIL_ACTIVITY); runtimeSubApp.addActivity(runtimeActivity); runtimeActivity.setColor("#FFFFFF"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#b46a54"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Store more detail"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeSearchView = new SearchView(); runtimeSearchView.setLabel("Search"); runtimeTitleBar.setRuntimeSearchView(runtimeSearchView); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey(), runtimeFragment); // runtimeTabStrip = new TabStrip(); // runtimeTab = new Tab(); // runtimeTab.setLabel("All"); // runtimeTab.setFragment(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT); // runtimeTabStrip.addTab(runtimeTab); // runtimeTab = new Tab(); // runtimeTab.setLabel("Free"); // runtimeTab.setFragment(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT); // runtimeTabStrip.addTab(runtimeTab); // runtimeTab = new Tab(); // runtimeTab.setLabel("Paid"); // runtimeTab.setFragment(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT); // runtimeTabStrip.addTab(runtimeTab); // runtimeTab = new Tab(); // runtimeTab.setLabel("Accepted nearby"); // runtimeTab.setFragment(Fragments.CWP_WALLET_STORE_ACCEPTED_NEARBY_FRAGMENT); // runtimeTabStrip.addTab(runtimeTab); /*runtimeTab = new Tab(); runtimeTab.setLabel("Search gone"); runtimeTab.setFragment(Fragments.CWP_WALLET_STORE_SEARCH_MODE); runtimeTabStrip.addTab(runtimeTab);*/ //runtimeActivity.setTabStrip(runtimeTabStrip); // runtimeFragment = new Fragment(); // runtimeFragment.setType(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey()); // runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey(), runtimeFragment); // runtimeFragment = new Fragment(); // runtimeFragment.setType(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey()); // runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey(), runtimeFragment); // runtimeFragment = new Fragment(); // runtimeFragment.setType(Fragments.CWP_WALLET_STORE_ACCEPTED_NEARBY_FRAGMENT.getKey()); // runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_ACCEPTED_NEARBY_FRAGMENT.getKey(), runtimeFragment); /*runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_SEARCH_MODE); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_SEARCH_MODE, runtimeFragment); */ /** * End of Wallet Store */ //Account Details runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_RUNTIME_ADULTS_ALL_ACCOUNT_DETAIL); runtimeActivity.setColor("#F0E173"); runtimeSubApp.addActivity(runtimeActivity); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Account details"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTab = new Tab(); runtimeTab.setLabel("Debits"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Credits"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("All"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL); runtimeTabStrip.addTab(runtimeTab); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL.getKey(), runtimeFragment); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_ADULTS_ALL_REFFILS); runtimeSubApp.addActivity(runtimeActivity); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_ADULTS_ALL_REQUESTS_RECEIVED); runtimeSubApp.addActivity(runtimeActivity); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_ADULTS_ALL_REQUESTS_RECEIVED.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_ADULTS_ALL_REQUESTS_RECEIVED.getKey(), runtimeFragment); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_ADULTS_ALL_REQUEST_SEND); runtimeSubApp.addActivity(runtimeActivity); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_ADULTS_ALL_REQUEST_SEND.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_ADULTS_ALL_REQUEST_SEND.getKey(), runtimeFragment); runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_RUNTIME_ADULTS_ALL_ACCOUNTS); runtimeSubApp.addActivity(runtimeActivity); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Account details"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeTabStrip = new TabStrip(); runtimeTab = new Tab(); runtimeTab.setLabel("Debits"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("Credits"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS); runtimeTabStrip.addTab(runtimeTab); runtimeTab = new Tab(); runtimeTab.setLabel("All"); runtimeTab.setFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL); runtimeTabStrip.addTab(runtimeTab); runtimeActivity.setTabStrip(runtimeTabStrip); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_DEBITS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNT_CREDITS.getKey(), runtimeFragment); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_RUNTIME_WALLET_ADULTS_ALL_BITDUBAI_ACCOUNTS_ALL.getKey(), runtimeFragment); /** * End of Wallet Accounts tabs. */ /** * Start Intra user sub app */ RuntimeSubApp subAppIntraUser = new RuntimeSubApp(); subAppIntraUser.setType(SubApps.CWP_INTRA_USER); listSubApp.put(SubApps.CWP_INTRA_USER, subAppIntraUser); //Activity 1 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_INTRA_USER_ACTIVITY); subAppIntraUser.setStartActivity(Activities.CWP_INTRA_USER_ACTIVITY); //runtimeSubApp.addActivity(runtimeActivity); runtimeActivity.setColor("#FF0B46F0"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#FF0B46F0"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel(""); runtimeTitleBar.setColor("#FF0B46F0"); runtimeTitleBar.setIconName("world"); RuntimeFernatComboBox comboBox = new RuntimeFernatComboBox(); comboBox.addValue("Mati"); runtimeTitleBar.setComboBox(comboBox); runtimeActivity.setTitleBar(runtimeTitleBar); // runtimeTabStrip = new TabStrip(); // runtimeTabStrip.setTabsColor("#d07b62"); // runtimeTabStrip.setTabsTextColor("#FFFFFF"); // runtimeTabStrip.setTabsIndicateColor("#b46a54"); //mati runtimeSearchView = new SearchView(); runtimeSearchView.setLabel("Search"); runtimeTitleBar.setRuntimeSearchView(runtimeSearchView); //runtimeActivity.setTitleBar(runtimeTitleBar); runtimeMainMenu = new MainMenu(); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("Settings"); runtimeMainMenu.addMenuItem(runtimeMenuItem); runtimeMenuItem = new MenuItem(); runtimeMenuItem.setLabel("New Identity"); runtimeMainMenu.addMenuItem(runtimeMenuItem); runtimeActivity.setMainMenu(runtimeMainMenu); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey(), runtimeFragment); runtimeActivity.setStartFragment(Fragments.CWP_WALLET_STORE_ALL_FRAGMENT.getKey()); subAppIntraUser.addActivity(runtimeActivity); subAppIntraUser.setStartActivity(Activities.CWP_INTRA_USER_ACTIVITY); //Activity 2 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_INTRA_USER_CREATE_ACTIVITY); subAppIntraUser.addActivity(runtimeActivity); runtimeActivity.setColor("#FF0B46F0"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#FF0B46F0"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("New identity"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey(), runtimeFragment); runtimeActivity.setStartFragment(Fragments.CWP_WALLET_STORE_FREE_FRAGMENT.getKey()); //Activity 3 runtimeActivity = new Activity(); runtimeActivity.setType(Activities.CWP_WALLET_STORE_MORE_DETAIL_ACTIVITY); subAppIntraUser.addActivity(runtimeActivity); runtimeActivity.setColor("#b46a54"); statusBar = new com.bitdubai.fermat_api.layer.all_definition.navigation_structure.StatusBar(); statusBar.setColor("#b46a54"); runtimeTitleBar = new TitleBar(); runtimeTitleBar.setLabel("Wallet Store"); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeSearchView = new SearchView(); runtimeSearchView.setLabel("Search"); runtimeTitleBar.setRuntimeSearchView(runtimeSearchView); runtimeActivity.setTitleBar(runtimeTitleBar); runtimeFragment = new Fragment(); runtimeFragment.setType(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey()); runtimeActivity.addFragment(Fragments.CWP_WALLET_STORE_PAID_FRAGMENT.getKey(), runtimeFragment); /** * End of intra user sub app */ } catch (Exception e) { String message = CantFactoryResetException.DEFAULT_MESSAGE; FermatException cause = FermatException.wrapException(e); String context = "Error on method Factory Reset, setting the structure of the apps"; String possibleReason = "some null definition"; throw new CantFactoryResetException(message, cause, context, possibleReason); } } /** * Load home screen subApp */ private void loadHomeScreen() { homeScreen = new RuntimeSubApp(); homeScreen.setType(SubApps.CWP_WALLET_MANAGER); listSubApp.put(SubApps.CWP_WALLET_MANAGER, homeScreen); Activity activity = new Activity(); /** * set type home */ activity.setType(Activities.CWP_WALLET_MANAGER_MAIN); Fragment fragment = new Fragment(); /** * Add WalletManager fragment */ fragment = new Fragment(); fragment.setType(Fragments.CWP_WALLET_MANAGER_MAIN.getKey()); activity.addFragment(Fragments.CWP_WALLET_MANAGER_MAIN.getKey(), fragment); /** * Add developer subApp fragment */ fragment = new Fragment(); fragment.setType(Fragments.CWP_SUB_APP_DEVELOPER.getKey()); activity.addFragment(Fragments.CWP_SUB_APP_DEVELOPER.getKey(), fragment); homeScreen.setStartActivity(activity.getType()); homeScreen.addActivity(activity); } }
package de.teiesti.postie.postmen; import de.teiesti.postie.Postman; import de.teiesti.postie.Recipient; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; /** * A {@link ParallelPostman} is a {@link Postman} that delivers {@link Letter}s in parallel using an {@link * ExecutorService}. For each pair of received {@link Letter} and registered {@link Recipient} a {@link Runnable} * is created and submitted to the {@link ExecutorService}. By default, this {@link ParallelPostman} observes the * {@link Letter} order: Before the next {@link Letter} is processed a {@link ParallelPostman} waits until any * {@link Recipient#accept} has return. This behaviour can be disabled with {@link #observeLetterOrder}. It is * possible to specify the {@link ExecutorService} with {@link #setExecutorService(ExecutorService)}. * * @param <Letter> type of the letters */ public class ParallelPostman<Letter> extends Postman<Letter> { private ExecutorService es = Executors.newCachedThreadPool(); private Phaser phaser = new Phaser(1); private boolean observeLetterOrder = true; /** * Controls weather this {@link ParallelPostman} should observe the {@link Letter} order. If this option is * enabled, this {@link ParallelPostman} will not submit jobs for the next {@link Letter} before the current * {@link Letter} was fully processed. This guarantees that no {@link Letter} overtake another.<br> * <br> * It is possible to change this option at any time but jobs that have already been submitted will not be revoked. * Therefore switching from the unobserved mode to the observed mode may needs some time to take effect. This * method does only guarantee that {@link Letter}s that have not been yet submitted by the opposite side will be * processed in the correct order. Anything else happens by chance. Switching from observed to unobserved mode * will take effect immediately. * * @param observeLetterOrder weather the {@link Letter} order should be observed * * @return this {@link Postman} */ public Postman<Letter> observeLetterOrder(boolean observeLetterOrder) { this.observeLetterOrder = observeLetterOrder; return this; } public Postman<Letter> setExecutorService(ExecutorService executorService) { if (executorService == null) throw new IllegalArgumentException("executorService == null"); this.es = executorService; return this; } /** * Delivers a given {@link Letter} in parallel using an {@link ExecutorService}. This method creates a {@link * Runnable} for each {@link Recipient} and submits it to the {@link ExecutorService}. If this {@link * ParallelPostman} should observe the letter order, this method blocks until any {@link Letter} from the the * preceding call is completely processed which guarantees that the order is not mixed up. * * @param letter the {@link Letter} to deliver * * @return this {@link Postman} */ @Override protected Postman<Letter> deliver(Letter letter) { if(observeLetterOrder) phaser.arriveAndAwaitAdvance(); for (Recipient<Letter> r : recipients) { phaser.register(); es.submit(new Deliverer(r, letter, this)); } return this; } /** * Reports parallel to any {@link Recipient} that a connection was established and the {@link Postman} will start * delivering {@link Letter}s now. This method creates a {@link Runnable} for each {@link Recipient} and submits it * to the {@link ExecutorService}. This method does not return before the last * {@link Recipient#noticeStart(Postman)} has returned. * * @return this {@link Postman} */ @Override protected Postman<Letter> reportStart() { // 'phaser.arriveAndAwaitAdvance();' is not needed here, because nothing happened in parallel so far. for (Recipient<Letter> r : recipients) { phaser.register(); es.submit(new StartReporter(r, this)); } phaser.arriveAndAwaitAdvance(); return this; } /** * Reports parallel to any {@link Recipient} that the last {@link Letter} was delivered and the connection will * close now. This method creates a {@link Runnable} for each {@link Recipient} and submits it to the * {@link ExecutorService}. Before it waits until any {@link Letter} was processed for any {@link Recipient}. * This method does not return before the last {@link Recipient#noticeStop(Postman)} has returned. * * @return this {@link Postman} */ @Override protected Postman<Letter> reportStop() { phaser.arriveAndAwaitAdvance(); for (Recipient<Letter> r : recipients) { phaser.register(); es.submit(new StopReporter(r, this)); } phaser.arriveAndAwaitAdvance(); return this; } private class Deliverer implements Runnable { private Recipient<Letter> recipient; private Letter letter; private Postman postman; public Deliverer(Recipient<Letter> recipient, Letter letter, Postman postman) { this.recipient = recipient; this.letter = letter; this.postman = postman; } @Override public void run() { recipient.accept(letter, postman); phaser.arriveAndDeregister(); } } private class StartReporter implements Runnable { private Recipient<Letter> recipient; private Postman postman; public StartReporter(Recipient<Letter> recipient, Postman postman) { this.recipient = recipient; this.postman = postman; } @Override public void run() { recipient.noticeStart(postman); phaser.arriveAndDeregister(); } } private class StopReporter implements Runnable { private Recipient<Letter> recipient; private Postman postman; public StopReporter(Recipient<Letter> recipient, Postman postman) { this.recipient = recipient; this.postman = postman; } @Override public void run() { recipient.noticeStop(postman); phaser.arriveAndDeregister(); } } }
package com.bitdubai.fermat_osa_addon.layer.android.database_system.developer.bitdubai.version_1.structure; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.bitdubai.fermat_api.FermatException; import com.bitdubai.fermat_api.layer.osa_android.database_system.DataBaseSelectOperatorType; import com.bitdubai.fermat_api.layer.osa_android.database_system.DataBaseTableOrder; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterOperator; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterOrder; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseSelectOperator; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableColumn; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFilter; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFilterGroup; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseVariable; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantDeleteRecordException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantSelectRecordException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantUpdateRecordException; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * This class define methods to manage a DatabaseTable object * Set filters and orders, and load records to memory. * * * */ public class AndroidDatabaseTable implements DatabaseTable { /** * DatabaseTable Member Variables. */ Context context; String tableName; SQLiteDatabase database; private List<DatabaseTableFilter> tableFilter; private List<DatabaseTableRecord> records; private DatabaseTableRecord tableRecord; private List<DataBaseTableOrder> tableOrder; private String top = ""; private String offset = ""; private DatabaseTableFilterGroup tableFilterGroup; private List<DatabaseVariable> variablesResult; private List<DatabaseSelectOperator> tableSelectOperator; // Public constructor declarations. /** * <p>DatabaseTable implementation constructor * * @param context Android Context Object * @param database name database to use * @param tableName name table to use */ public AndroidDatabaseTable (Context context,SQLiteDatabase database, String tableName){ this.tableName = tableName; this.context = context; this.database = database; } /** * DatabaseTable interface implementation. */ public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } /** * <p>This method return a new empty instance of DatabaseTableColumn object * * @return DatabaseTableColumn object */ @Override public DatabaseTableColumn newColumn(){ return new AndroidDatabaseTableColumn(); } /** * <p>This method return a list of table columns names * * @return List<String> of columns names */ @Override public List<String> getColumns() { List<String> columns = new ArrayList<String>(); Cursor c = this.database.rawQuery("SELECT * FROM "+ tableName, null); String[] columnNames = c.getColumnNames(); for (int i = 0; i < columnNames.length; ++i) { columns.add(columnNames[i].toString()); } return columns; } /** * <p>This method return a list of Database Table Record objects * * @return List<DatabaseTableRecord> List of DatabaseTableRecord objects */ @Override public List<DatabaseTableRecord> getRecords() { return this.records; } /** * * @return */ @Override public List<DatabaseVariable> getVarialbesResult(){ return this.variablesResult; } @Override public void setVarialbesResult(List<DatabaseVariable> variables){ this.variablesResult = variables; } /** * <p>This method return a new empty instance of DatabaseTableRecord object * * @return DatabaseTableRecord object */ @Override public DatabaseTableRecord getEmptyRecord() { return new AndroidDatabaseRecord() ; } @Override public DatabaseTableFilter getEmptyTableFilter() { return new AndroidDatabaseTableFilter() ; } @Override public DatabaseTableFilterGroup getEmptyTableFilterGroup() { return new AndroidDatabaseTableFilterGroup() ; } /** * <p>This method clean Filter object */ @Override public void clearAllFilters() { this.tableFilter = null; } /** * <p>This method return a list of DatabaseTableFilter objects * * @return List<DatabaseTableFilter> object */ @Override public List<DatabaseTableFilter> getFilters() { return this.tableFilter; } /** * <p>This method return a DatabaseTableFilterGroup objects * * @return DatabaseTableFilterGroup object */ @Override public DatabaseTableFilterGroup getFilterGroup() { return this.tableFilterGroup; } /** * <p>This method selects one or more fields in a table . * <p>Accepts the use of operators on select as SUM or COUNT. * <p>saves each field with its value in an array of variables to be used in other querys. * * @param record * @throws CantSelectRecordException */ @Override public void selectRecord (DatabaseTableRecord record) throws CantSelectRecordException { /** * First I get the table records with values. * and construct de ContentValues array for SqlLite */ try{ StringBuffer strRecords = new StringBuffer (""); StringBuffer strValues = new StringBuffer (""); List<DatabaseRecord> records = record.getValues(); //check if declared operators to apply on select or only define some fields if(this.tableSelectOperator != null) { for (int i = 0; i < tableSelectOperator.size(); ++i) { if (strRecords.length() > 0) strRecords.append(","); switch (tableSelectOperator.get(i).getType()) { case SUM: strRecords.append(" SUM (" + tableSelectOperator.get(i).getColumn() +") AS " + tableSelectOperator.get(i).getAliasColumn() ); break; case COUNT: strRecords.append(" COUNT (" + tableSelectOperator.get(i).getColumn() +") AS " + tableSelectOperator.get(i).getAliasColumn()); break; default: strRecords.append(" "); break; } } } else { for (int i = 0; i < records.size(); ++i) { if(strRecords.length() > 0 ) strRecords.append (","); strRecords.append(records.get(i).getName ()); } } Cursor c = this.database.rawQuery("SELECT " + strRecords + " FROM " + tableName + " " + makeFilter(),null); List<String> columns = getColumns(); int columnsCant =0; this.variablesResult = new ArrayList<>(); if (c.moveToFirst()) { do { /** * Get columns name to read values of files * */ DatabaseVariable variable = new AndroidVariable(); variable.setName("@" + c.getColumnName(columnsCant)); variable.setValue(c.getString(columnsCant)); this.variablesResult.add(variable); columnsCant++; } while (c.moveToNext()); } } catch (Exception exception) { throw new CantSelectRecordException(); } } /** * <p>This method update a table record in the database * * @param record DatabaseTableRecord object to update * @throws CantUpdateRecordException */ @Override public void updateRecord (DatabaseTableRecord record) throws CantUpdateRecordException { try { List<DatabaseRecord> records = record.getValues(); StringBuffer strRecords = new StringBuffer (""); // ContentValues recordUpdateList = new ContentValues(); /** * I update only the fields marked as modified * */ for (int i = 0; i < records.size(); ++i) { if(records.get(i).getChange()) { // recordUpdateList.put(records.get(i).getName(), records.get(i).getValue()); if(strRecords.length() > 0 ) strRecords.append (","); //I check if the value to change what I have to take a variable, // and look that at the result of the select if(records.get(i).getUseValueofVariable()) { for (int j = 0; j < variablesResult.size(); ++j) { if(variablesResult.get(j).getName().equals(records.get(i).getValue())) strRecords.append(records.get(i).getName() + " = '" + variablesResult.get(j).getValue() + "'"); } } else { strRecords.append(records.get(i).getName() +" = '" + records.get(i).getValue() + "'"); } } } this.database.execSQL("UPDATE " + tableName + " SET " + strRecords + " " + makeFilter()); // this.database.update(tableName, recordUpdateList, makeFilter().replace("WHERE", ""), null); } catch (Exception exception) { throw new CantUpdateRecordException(); } } /** * <p>This method inserts a new record in the database * * @param record DatabaseTableRecord to insert * @throws CantInsertRecordException */ @Override public void insertRecord(DatabaseTableRecord record) throws CantInsertRecordException { /** * First I get the table records with values. * and construct de ContentValues array for SqlLite */ try{ StringBuffer strRecords = new StringBuffer (""); StringBuffer strValues = new StringBuffer (""); List<DatabaseRecord> records = record.getValues(); for (int i = 0; i < records.size(); ++i) { //initialValues.put(records.get(i).getName(),records.get(i).getValue()); if(strRecords.length() > 0 ) strRecords.append (","); strRecords.append(records.get(i).getName ()); if(strValues.length() > 0 ) strValues.append (","); //I check if the value to insert what I have to take a variable, // and look that at the result of the select if(records.get(i).getUseValueofVariable()) { for (int j = 0; j < variablesResult.size(); ++j) { if(variablesResult.get(j).getName().equals(records.get(i).getValue())) strValues.append("'" + variablesResult.get(j).getValue() + "'"); } } else { strValues.append ("'" + records.get(i).getValue() + "'"); } } // this.database.insert(tableName, null, initialValues); this.database.execSQL("INSERT INTO " + tableName + "(" + strRecords + ")" + " VALUES (" + strValues + ")"); } catch (Exception exception) { throw new CantInsertRecordException(); } } /** * <p>This method load all table records in a List of DatabaseTableRecord object * <p>Then use the method getRecords() to to retrieve. * * @throws CantLoadTableToMemoryException */ @Override public void loadToMemory() throws CantLoadTableToMemoryException { this.records = new ArrayList<>(); String topSentence = ""; String offsetSentence = ""; try { if (!this.top.isEmpty()) topSentence = " LIMIT " + this.top; if (!this.offset.isEmpty()) offsetSentence = " OFFSET " + this.offset; Cursor cursor = this.database.rawQuery("SELECT * FROM " + tableName + makeFilter() + makeOrder() + topSentence + offsetSentence, null); List<String> columns = getColumns(); if (cursor.moveToFirst()) { do { /** * Get columns name to read values of files * */ DatabaseTableRecord tableRecord1 = new AndroidDatabaseRecord(); List<DatabaseRecord> recordValues = new ArrayList<>(); for (int i = 0; i < columns.size(); ++i) { DatabaseRecord recordValue = new AndroidRecord(); recordValue.setName(columns.get(i).toString()); recordValue.setValue(cursor.getString(cursor.getColumnIndex(columns.get(i).toString()))); recordValue.setChange(false); recordValue.setUseValueofVariable(false); recordValues.add(recordValue); } tableRecord1.setValues(recordValues); this.records.add(tableRecord1); } while (cursor.moveToNext()); } cursor.close(); } catch (Exception e) { throw new CantLoadTableToMemoryException(CantLoadTableToMemoryException.DEFAULT_MESSAGE, FermatException.wrapException(e), null, null); } } /** * <p>Check if the set will table in tableName variable exists * * @return boolean */ @Override public boolean isTableExists() { Cursor cursor = this.database.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ this.tableName+"'", null); if(cursor!=null) { if(cursor.getCount()>0) { cursor.close(); return true; } cursor.close(); } return false; } /** *<p>Sets the filter on a string field * * @param columName column name to filter * @param value value to filter * @param type DatabaseFilterType object */ @Override public void setStringFilter(String columName, String value,DatabaseFilterType type){ if(this.tableFilter == null) this.tableFilter = new ArrayList<DatabaseTableFilter>(); DatabaseTableFilter filter = new AndroidDatabaseTableFilter(); filter.setColumn(columName); filter.setValue(value); filter.setType(type); this.tableFilter.add(filter); } /** *<p>Sets the filter on a UUID field * * @param columName column name to filter * @param value value to filter * @param type DatabaseFilterType object */ @Override public void setUUIDFilter(String columName, UUID value,DatabaseFilterType type){ if(this.tableFilter == null) this.tableFilter = new ArrayList<DatabaseTableFilter>(); DatabaseTableFilter filter = new AndroidDatabaseTableFilter(); filter.setColumn(columName); filter.setValue(value.toString()); filter.setType(type); this.tableFilter.add(filter); } /** * <p>Sets the order in which filtering field shown in ascendent or descending * * @param columnName Name of the column to sort * @param direction DatabaseFilterOrder object */ @Override public void setFilterOrder(String columnName, DatabaseFilterOrder direction){ if(this.tableOrder == null) this.tableOrder = new ArrayList<DataBaseTableOrder>(); DataBaseTableOrder order = new AndroidDatabaseTableOrder(); order.setColumName(columnName); order.setDirection(direction); this.tableOrder.add(order); } /** * <p>Sets the operator to apply on select statement * * @param columnName Name of the column to apply operator * @param operator DataBaseSelectOperatorType type */ @Override public void setSelectOperator(String columnName, DataBaseSelectOperatorType operator, String alias){ if(this.tableSelectOperator == null) this.tableSelectOperator = new ArrayList<DatabaseSelectOperator>(); DatabaseSelectOperator selectOperator = new AndroidDatabaseSelectOperator(); selectOperator.setColumn(columnName); selectOperator.setType(operator); selectOperator.setAliasColumn(alias); this.tableSelectOperator.add(selectOperator); } /** *<p>Sets the number of records to be selected in query * * @param top number of records to select (in string) */ @Override public void setFilterTop(String top){ this.top = top; } /** *<p>Sets the records page * @param offset */ public void setFilterOffSet(String offset){ this.offset = offset; } /** *<p>Sets the filter and subgroup to filter for queries with grouped where * * @param filters list of DatabaseTableFilter object * @param subGroups list of DatabaseTableFilterGroup objects * @param operator DatabaseFilterOperator enumerator */ @Override public void setFilterGroup(List<DatabaseTableFilter> filters, List<DatabaseTableFilterGroup> subGroups, DatabaseFilterOperator operator){ DatabaseTableFilterGroup filterGroup = new AndroidDatabaseTableFilterGroup(); filterGroup.setFilters(filters); filterGroup.setSubGroups(subGroups); filterGroup.setOperator(operator); this.tableFilterGroup = filterGroup; } /** * DatabaseTable interface private void. */ /** * Sets the context for access to the device memory * @param context Android Context Object */ public void setContext(Object context) { this.context = (Context) context; } private String makeFilter(){ // I check the definition for the filter object, filter type, filter columns names // and build the WHERE statement String filter = ""; StringBuffer strFilter = new StringBuffer(); if(this.tableFilter != null) { for (int i = 0; i < tableFilter.size(); ++i) { strFilter.append(tableFilter.get(i).getColumn()); switch (tableFilter.get(i).getType()) { case EQUAL: strFilter.append(" ='" + tableFilter.get(i).getValue() + "'"); break; case GRATER_THAN: strFilter.append( " > " + tableFilter.get(i).getValue()); break; case LESS_THAN: strFilter.append( " < " + tableFilter.get(i).getValue()); break; case LIKE: strFilter.append(" Like '%" + tableFilter.get(i).getValue() + "%'"); break; default: strFilter.append(" "); break; } if(i < tableFilter.size()-1) strFilter.append(" AND "); } filter = strFilter.toString(); if(strFilter.length() > 0 ) filter = " WHERE " + filter; return filter; } else { //if set group filter if(this.tableFilterGroup != null) { return makeGroupFilters(this.tableFilterGroup); } else { return filter; } } } private String makeOrder(){ // I check the definition for the oder object, order direction, order columns names // and build the ORDER BY statement String order= ""; StringBuffer strOrder = new StringBuffer(); if(this.tableOrder != null) { for (int i = 0; i < tableOrder.size(); ++i) { switch (tableOrder.get(i).getDirection()) { case DESCENDING: strOrder.append(tableOrder.get(i).getColumName() + " DESC "); break; case ASCENDING: strOrder.append(tableOrder.get(i).getColumName()); break; default: strOrder.append(" "); break; } if(i < tableOrder.size()-1) strOrder.append(" , "); } } order = strOrder.toString(); if(strOrder.length() > 0 ) order = " ORDER BY " + order; return order; } private String makeInternalCondition(DatabaseTableFilter filter){ StringBuffer strFilter = new StringBuffer(); strFilter.append(filter.getColumn()); switch (filter.getType()) { case EQUAL: strFilter.append(" ='" + filter.getValue() + "'"); break; case GRATER_THAN: strFilter.append(" > " + filter.getValue()); break; case LESS_THAN: strFilter.append(" < " + filter.getValue()); break; case LIKE: strFilter.append(" Like '%" + filter.getValue() + "%'"); break; default: strFilter.append(" "); } return strFilter.toString(); } private String makeInternalConditionGroup(List<DatabaseTableFilter> filters, DatabaseFilterOperator operator){ StringBuffer strFilter = new StringBuffer(); for (DatabaseTableFilter filter : filters){ switch (operator) { case AND: if(strFilter.length() > 0) strFilter.append(" AND "); strFilter.append(makeInternalCondition(filter)); break; case OR: if(strFilter.length() > 0) strFilter.append(" OR "); strFilter.append(makeInternalCondition(filter)); break; default: strFilter.append(" "); } } return strFilter.toString(); } public String makeGroupFilters(DatabaseTableFilterGroup databaseTableFilterGroup){ StringBuffer strFilter = new StringBuffer(); String filter = ""; if(databaseTableFilterGroup != null && (databaseTableFilterGroup.getFilters().size() > 0 || databaseTableFilterGroup.getSubGroups().size() > 0)) { strFilter.append("("); strFilter.append(makeInternalConditionGroup(databaseTableFilterGroup.getFilters(), databaseTableFilterGroup.getOperator())); int ix = 0; for(DatabaseTableFilterGroup subGroup : databaseTableFilterGroup.getSubGroups()){ if (subGroup.getFilters().size() > 0 || ix > 0){ switch (databaseTableFilterGroup.getOperator()) { case AND: strFilter.append(" AND "); break; case OR: strFilter.append(" OR "); break; default: strFilter.append(" "); } } strFilter.append("("); strFilter.append(makeGroupFilters(subGroup)); strFilter.append(")"); ix++; } strFilter.append(")"); } filter = strFilter.toString(); if(strFilter.length() > 0 ) filter = " WHERE " + filter; return filter; } @Override public void deleteRecord(DatabaseTableRecord record) throws CantDeleteRecordException { try{ List<DatabaseRecord> records = record.getValues(); String queryWhereClause=""; if(!records.isEmpty()) { for (int i = 0; i < records.size(); ++i) { if (queryWhereClause.length() > 0) { queryWhereClause += " and "; queryWhereClause += records.get(i).getName(); } else queryWhereClause += records.get(i).getName(); queryWhereClause += "="; queryWhereClause += records.get(i).getValue(); } }else{ queryWhereClause=null; } if(queryWhereClause!=null){ this.database.execSQL("DELETE FROM " + tableName + " WHERE " + queryWhereClause); }else{ this.database.execSQL("DELETE FROM " + tableName); } }catch (Exception exception) { throw new CantDeleteRecordException(); } } @Override public DatabaseTableRecord getRecordFromPk(String pk) throws Exception { Cursor c = database.rawQuery(" SELECT * from "+tableName+" WHERE pk="+pk,null); List<String> columns = getColumns(); DatabaseTableRecord tableRecord1 = new AndroidDatabaseRecord(); if (c.moveToFirst()) { /** - * Get columns name to read values of files * */ List<DatabaseRecord> recordValues = new ArrayList<>(); for (int i = 0; i < columns.size(); ++i) { DatabaseRecord recordValue = new AndroidRecord(); recordValue.setName(columns.get(i).toString()); recordValue.setValue(c.getString(c.getColumnIndex(columns.get(i).toString()))); recordValue.setChange(false); recordValues.add(recordValue); } tableRecord1.setValues(recordValues); if(c.moveToNext()){ //si pasa esto es porque hay algo mal throw new Exception(); } }else{ return null; } return tableRecord1; } @Override public String toString(){ return tableName; } }
package edu.harvard.iq.dataverse; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.ejb.EJB; /** * * @author skraffmiller */ public class DatasetVersionUI { @EJB DataverseServiceBean dataverseService; public DatasetVersionUI() { } private Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> metadataBlocksForView = new HashMap(); private Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> metadataBlocksForEdit = new HashMap(); public Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> getMetadataBlocksForView() { return metadataBlocksForView; } public void setMetadataBlocksForView(Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> metadataBlocksForView) { this.metadataBlocksForView = metadataBlocksForView; } public Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> getMetadataBlocksForEdit() { return metadataBlocksForEdit; } public void setMetadataBlocksForEdit(Map<MetadataBlock, Map<DatasetField, List<DatasetFieldValue>>> metadataBlocksForEdit) { this.metadataBlocksForEdit = metadataBlocksForEdit; } public DatasetVersionUI(DatasetVersion datasetVersion) { /*takes in the values of a dataset version and apportions them into lists for viewing and editng in the dataset page. */ setDatasetVersion(datasetVersion); this.setDatasetAuthors(new ArrayList()); this.setDatasetKeywords(new ArrayList()); this.setDatasetRelPublications(new ArrayList()); this.setSubjects(new ArrayList()); this.setDisplaysAboveTabs(new ArrayList()); // loop through vaues to get fields for view mode for (DatasetFieldValue dsfv : datasetVersion.getDatasetFieldValues()) { if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.title)) { setTitle(dsfv); } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.descriptionText)) { setDescription(dsfv); } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.author)) { Collection childVals = dsfv.getChildDatasetFieldValues(); DatasetAuthor datasetAuthor = new DatasetAuthor(); if (childVals != null) { for (Object cv : childVals) { DatasetFieldValue cvo = (DatasetFieldValue) cv; if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.authorName)) { datasetAuthor.setName(cvo); } if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.authorAffiliation)) { datasetAuthor.setAffiliation(cvo); } } } this.getDatasetAuthors().add(datasetAuthor); } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.keyword)) { this.getDatasetKeywords().add(dsfv); } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.subject)) { this.getSubjects().add(dsfv.getStrValue()); } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.publication)) { //Special handling for Related Publications // Treated as below the tabs for editing, but must get first value for display above tabs if (this.datasetRelPublications.isEmpty()) { Collection childVals = dsfv.getChildDatasetFieldValues(); DatasetRelPublication datasetRelPublication = new DatasetRelPublication(); if (childVals != null) { for (Object cv : childVals) { DatasetFieldValue cvo = (DatasetFieldValue) cv; if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.publicationCitation)) { datasetRelPublication.setText(cvo.getStrValue()); } if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.publicationIDNumber)) { datasetRelPublication.setIdNumber(cvo.getStrValue()); } if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.publicationIDType)) { datasetRelPublication.setIdType(cvo.getStrValue()); } if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.publicationURL)) { datasetRelPublication.setUrl(null); } if (cvo.getDatasetField().getName().equals(DatasetFieldConstant.distributorURL)) { datasetRelPublication.setUrl(cvo.getStrValue()); } } } this.getDatasetRelPublications().add(datasetRelPublication); } } else if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.notesText)) { this.setNotesText(dsfv.getStrValue()); } else if (dsfv.getDatasetField().isDisplayOnCreate() && ((!dsfv.getDatasetField().isHasParent() && !dsfv.getDatasetField().isHasChildren() && dsfv.getStrValue() != null && !dsfv.getStrValue().isEmpty()) || (dsfv.getDatasetField().isHasChildren() && !dsfv.isChildEmpty()))) { //any fields designated as show on create this.getDisplaysAboveTabs().add(dsfv); if (dsfv.getChildDatasetFieldValues() != null && !dsfv.getChildDatasetFieldValues().isEmpty()) { for (DatasetFieldValue dsfvChild : dsfv.getChildDatasetFieldValues()) { this.getDisplaysAboveTabs().add(dsfvChild); } } } } setMetadataValueBlocks(datasetVersion); } private Dataset getDataset() { return this.datasetVersion.getDataset(); } private DatasetVersion datasetVersion; public DatasetVersion getDatasetVersion() { return datasetVersion; } public void setDatasetVersion(DatasetVersion datasetVersion) { this.datasetVersion = datasetVersion; } private DatasetFieldValue title; public DatasetFieldValue getTitle() { return title; } public void setTitle(DatasetFieldValue title) { this.title = title; } private List<String> subjects = new ArrayList(); public List<String> getSubjects() { return subjects; } public void setSubjects(List<String> subjects) { this.subjects = subjects; } private List<DatasetAuthor> datasetAuthors = new ArrayList(); public List<DatasetAuthor> getDatasetAuthors() { return datasetAuthors; } public void setDatasetAuthors(List<DatasetAuthor> datasetAuthors) { this.datasetAuthors = datasetAuthors; } private DatasetFieldValue description; public DatasetFieldValue getDescription() { return description; } public void setDescription(DatasetFieldValue description) { this.description = description; } private List<DatasetFieldValue> datasetKeywords = new ArrayList(); public List<DatasetFieldValue> getDatasetKeywords() { return datasetKeywords; } public void setDatasetKeywords(List<DatasetFieldValue> datasetKeywords) { this.datasetKeywords = datasetKeywords; } private List<DatasetFieldValue> displaysAboveTabs = new ArrayList(); public List<DatasetFieldValue> getDisplaysAboveTabs() { return displaysAboveTabs; } public void setDisplaysAboveTabs(List<DatasetFieldValue> displaysAboveTabs) { this.displaysAboveTabs = displaysAboveTabs; } private List<DatasetRelPublication> datasetRelPublications; public List<DatasetRelPublication> getDatasetRelPublications() { return datasetRelPublications; } public void setDatasetRelPublications(List<DatasetRelPublication> datasetRelPublications) { this.datasetRelPublications = datasetRelPublications; } private String notesText; public String getNotesText() { return notesText; } public void setNotesText(String notesText) { this.notesText = notesText; } public String getRelPublicationCitation() { if (!this.datasetRelPublications.isEmpty()) { return this.getDatasetRelPublications().get(0).getText(); } else { return ""; } } public String getUNF() { //todo get UNF to calculate and display here. return ""; } //TODO - make sure getCitation works private String getYearForCitation(String dateString) { //get date to first dash only if (dateString.indexOf("-") > -1) { return dateString.substring(0, dateString.indexOf("-")); } return dateString; } public String getCitation() { return getCitation(false); } public String getCitation(boolean isOnlineVersion) { Dataset dataset = getDataset(); String str = ""; boolean includeAffiliation = false; String authors = getAuthorsStr(includeAffiliation); if (!StringUtil.isEmpty(authors)) { str += authors; } if (!StringUtil.isEmpty(getDistributionDate())) { if (!StringUtil.isEmpty(str)) { str += ", "; } str += getYearForCitation(getDistributionDate()); } else { if (!StringUtil.isEmpty(getProductionDate())) { if (!StringUtil.isEmpty(str)) { str += ", "; } str += getYearForCitation(getProductionDate()); } } if (!StringUtil.isEmpty(getTitle().getStrValue())) { if (!StringUtil.isEmpty(str)) { str += ", "; } str += "\"" + getTitle().getStrValue() + "\""; } if (!StringUtil.isEmpty(dataset.getIdentifier())) { if (!StringUtil.isEmpty(str)) { str += ", "; } if (isOnlineVersion) { str += "<a href=\"" + dataset.getPersistentURL() + "\">" + dataset.getIdentifier() + "</a>"; } else { str += dataset.getPersistentURL(); } } //Get root dataverse name for Citation Dataverse root = getDatasetVersion().getDataset().getOwner(); while (root.getOwner() != null) { root = root.getOwner(); } String rootDataverseName = root.getName(); if (!StringUtil.isEmpty(rootDataverseName)) { if (!StringUtil.isEmpty(str)) { str += ", "; } str += " " + rootDataverseName + " [Publisher] "; } if (this.getDatasetVersion().getVersionNumber() != null) { str += " V" + this.getDatasetVersion().getVersionNumber(); str += " [Version]"; } /*UNF is not calculated yet if (!StringUtil.isEmpty(getUNF())) { if (!StringUtil.isEmpty(str)) { str += " "; } str += getUNF(); } String distributorNames = getDistributorNames(); if (distributorNames.trim().length() > 0) { str += " " + distributorNames; str += " [Distributor]"; }*/ return str; } public String getAuthorsStr() { return getAuthorsStr(true); } public String getAuthorsStr(boolean affiliation) { String str = ""; for (DatasetAuthor sa : this.getDatasetAuthors()) { if (str.trim().length() > 1) { str += "; "; } if (sa.getName() != null && !StringUtil.isEmpty(sa.getName().getStrValue())) { str += sa.getName().getStrValue(); } if (affiliation) { if (sa.getAffiliation() != null && !StringUtil.isEmpty(sa.getAffiliation().getStrValue())) { str += " (" + sa.getAffiliation().getStrValue() + ")"; } } } return str; } public String getKeywordsStr() { String str = ""; for (DatasetFieldValue sa : this.getDatasetKeywords()) { if (str.trim().length() > 1) { str += "; "; } if (sa.getStrValue() != null && sa.getStrValue().toString() != null && !sa.getStrValue().toString().trim().isEmpty()) { str += sa.getStrValue().toString().trim(); } } return str; } public String getSubjectStr() { String str = ""; for (String sa : this.getSubjects()) { if (str.trim().length() > 1) { str += "; "; } if (sa != null && sa.toString() != null && !sa.toString().trim().isEmpty()) { str += sa.toString().trim(); } } return str; } public String getProductionDate() { for (DatasetFieldValue dsfv : datasetVersion.getDatasetFieldValues()) { if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.productionDate)) { return dsfv.getStrValue(); } } return ""; } public String getDistributionDate() { for (DatasetFieldValue dsfv : datasetVersion.getDatasetFieldValues()) { if (dsfv.getDatasetField().getName().equals(DatasetFieldConstant.distributionDate)) { return dsfv.getStrValue(); } } return ""; } public void setMetadataValueBlocks(DatasetVersion datasetVersion) { //TODO: A lot of clean up on the logic of this method metadataBlocksForView.clear(); for (MetadataBlock mdb : this.datasetVersion.getDataset().getOwner().getMetadataBlocks()) { Map<DatasetField, List<DatasetFieldValue>> mdbMap = new TreeMap( new Comparator<DatasetField>() { public int compare(DatasetField d1, DatasetField d2) { int a = d1.getDisplayOrder(); int b = d2.getDisplayOrder(); return Integer.valueOf(a).compareTo(Integer.valueOf(b)); } }); boolean addBlock = false; for (DatasetFieldValue dsfv : datasetVersion.getDatasetFieldValues()) { if (dsfv.getDatasetField().isHasChildren() || (dsfv.getStrValue() != null && !dsfv.getStrValue().trim().equals(""))) { if (dsfv.getDatasetField().getMetadataBlock().equals(mdb)) { List<DatasetFieldValue> dsfvValues = mdbMap.get(dsfv.getDatasetField()); if (dsfvValues == null) { dsfvValues = new ArrayList(); } dsfvValues.add(dsfv); mdbMap.put(dsfv.getDatasetField(), dsfvValues); if (!dsfv.getDatasetField().isHasChildren()) { addBlock = true; } } } } if (addBlock) { metadataBlocksForView.put(mdb, mdbMap); } } metadataBlocksForEdit.clear(); for (MetadataBlock mdb : this.datasetVersion.getDataset().getOwner().getMetadataBlocks()) { Map<DatasetField, List<DatasetFieldValue>> mdbMap = new TreeMap( new Comparator<DatasetField>() { public int compare(DatasetField d1, DatasetField d2) { int a = d1.getDisplayOrder(); int b = d2.getDisplayOrder(); return Integer.valueOf(a).compareTo(Integer.valueOf(b)); } }); for (DatasetFieldValue dsfv : datasetVersion.getDatasetFieldValues()) { if (dsfv.getDatasetField().getMetadataBlock().equals(mdb)) { List<DatasetFieldValue> dsfvValues = mdbMap.get(dsfv.getDatasetField()); if (dsfvValues == null) { dsfvValues = new ArrayList(); } dsfvValues.add(dsfv); mdbMap.put(dsfv.getDatasetField(), dsfvValues); } } metadataBlocksForEdit.put(mdb, mdbMap); } } }
package org.xwiki.administration.test.po; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedCondition; import org.xwiki.index.tree.test.po.DocumentTreeElement; import org.xwiki.model.EntityType; import org.xwiki.model.reference.EntityReference; import org.xwiki.test.ui.po.InlinePage; import org.xwiki.test.ui.po.Select; import org.xwiki.tree.test.po.TreeElement; import org.xwiki.tree.test.po.TreeNodeElement; /** * Represents a template provider page in inline mode * * @version $Id$ * @since 4.2M1 */ public class TemplateProviderInlinePage extends InlinePage { public static final String ACTION_SAVEANDEDIT = "saveandedit"; public static final String ACTION_EDITONLY = "edit"; @FindBy(name = "XWiki.TemplateProviderClass_0_template") private WebElement templateInput; @FindBy(name = "XWiki.TemplateProviderClass_0_name") private WebElement templateNameInput; @FindBy(name = "XWiki.TemplateProviderClass_0_type") private WebElement templateTypeSelect; @FindBy(name = "XWiki.TemplateProviderClass_0_terminal") private WebElement terminalSelect; @FindBy(name = "XWiki.TemplateProviderClass_0_action") private WebElement templateActionSelect; private DocumentTreeElement spacesTree; public String getTemplateName() { return this.templateNameInput.getAttribute("value"); } public void setTemplateName(String value) { this.templateNameInput.clear(); this.templateNameInput.sendKeys(value); } public String getTemplate() { return this.templateInput.getAttribute("value"); } public void setTemplate(String value) { this.templateInput.clear(); this.templateInput.sendKeys(value); } public boolean isPageTemplate() { return this.templateTypeSelect.findElement(By.xpath("//option[@value='page']")).isSelected(); } public void setPageTemplate(boolean isPageTemplate) { Select select = new Select(this.templateTypeSelect); String value; if (isPageTemplate) { value = "page"; } else { value = "space"; } select.selectByValue(value); } public boolean isTerminal() { return this.terminalSelect.findElement(By.xpath("//option[@value='1']")).isSelected(); } public void setTerminal(boolean isTerminal) { Select select = new Select(this.terminalSelect); String value; if (isTerminal) { value = "1"; } else { value = "0"; } select.selectByValue(value); } public TreeElement getSpacesTree() { if (this.spacesTree == null) { this.spacesTree = new DocumentTreeElement(this.getDriver().findElement(By.cssSelector("#enabled-spaces .xtree"))) .waitForIt(); } return this.spacesTree; } public List<String> getSpaces() { List<String> spaces = new ArrayList<String>(); for (String nodeID : getSpacesTree().getNodeIDs()) { String space = getSpaceFromNodeID(nodeID); spaces.add(space); } return spaces; } public void setSpaces(List<String> spaces) { // Clean any existing selection. List<String> selectedNodeIDs = getSpacesTree().getSelectedNodeIDs(); for (String selectedSpaceID : selectedNodeIDs) { getSpacesTree().getNode(selectedSpaceID).deselect(); } // Open to and select the given spaces. for (final String space : spaces) { String nodeId = getNodeIDFromSpace(space); getSpacesTree().openTo(nodeId); // Wait for the selection to get registered by the template provider UI javascript code. getDriver().waitUntilCondition(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver input) { return getDriver().findElementWithoutWaiting( By.xpath("//input[@id='XWiki.TemplateProviderClass_0_spaces' and contains(@value, '" + space + "')]")); } }); } } /** * @return the list of _actually_ checked spaces. If none is checked it actually means that the template is * available in all spaces */ public List<String> getSelectedSpaces() { List<String> selectedSpaces = new ArrayList<String>(); List<String> selectedNodeIDs = getSpacesTree().getSelectedNodeIDs(); for (String selectedNodeID : selectedNodeIDs) { String spaceLocalSerializedReference = getSpaceFromNodeID(selectedNodeID); selectedSpaces.add(spaceLocalSerializedReference); } return selectedSpaces; } private String getNodeIDFromSpace(String space) { EntityReference spaceReference = getUtil().resolveDocumentReference(String.format("%s.WebHome", space)); String nodeId = getUtil().serializeReference(spaceReference); nodeId = String.format("document:%s", nodeId); return nodeId; } private String getSpaceFromNodeID(String selectedNodeId) { String selectedNodeIdReferenceString = selectedNodeId.substring("document:".length()); EntityReference nodeReference = getUtil().resolveDocumentReference(selectedNodeIdReferenceString); nodeReference = nodeReference.removeParent(nodeReference.extractReference(EntityType.WIKI)); nodeReference = nodeReference.extractReference(EntityType.SPACE); String spaceLocalSerializedReference = getUtil().serializeReference(nodeReference); return spaceLocalSerializedReference; } /** * Sets all spaces besides the ones passed in the list. * * @param spaces the spaces to exclude */ public void excludeSpaces(List<String> spaces) { List<String> selectedSpaces = getSelectedSpaces(); // Go through each (loaded) node in the tree. List<String> nodeIDs = getSpacesTree().getNodeIDs(); for (String nodeId : nodeIDs) { TreeNodeElement node = getSpacesTree().getNode(nodeId); if (spaces.contains(getSpaceFromNodeID(nodeId))) { // If its in the list, deselect it. node.deselect(); } else if (selectedSpaces.size() == 0 || spaces.containsAll(selectedSpaces)) { // If its not in the list, but if there would be no selections left in the tree after the exclusion // operation, select it, for the exclusion to still make sense. node.select(); } } } /** * The action to execute when the create button is pushed, you can configure here whether the new document is saved * before it is opened for edition or not. * * @param actionName the behavior to have on create; valid values are "saveandedit" and "edit". See * {@link #ACTION_EDITONLY} and {@link #ACTION_SAVEANDEDIT} * @since 7.2M2 */ public void setActionOnCreate(String actionName) { this.templateActionSelect.findElement(By.xpath("//option[@value='" + actionName + "']")).click(); } }
package edu.harvard.iq.dataverse; import java.io.Serializable; import java.util.Arrays; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import org.hibernate.validator.constraints.NotBlank; /** * File metadata: specifically WorldMap layer information for a specific DataFile * * @author raprasad */ @Entity @Table(indexes = {@Index(columnList="dataset_id")}) public class MapLayerMetadata implements Serializable { @Transient public final static String dataType = "MapLayerMetadata"; @Transient public final static List<String> MANDATORY_JSON_FIELDS = Arrays.asList("layerName", "layerLink", "embedMapLink", "worldmapUsername"); private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // ForeignKey to DataFile //x@ManyToOne // For now, make this unique: Each DataFile may only have one map @JoinColumn(nullable=false, unique=true) private DataFile dataFile; // ForeignKey to Dataset. // This is always reachable via the datafile.getOwner(); // However, save the Dataset itself to potentially save an extra step @ManyToOne @JoinColumn(nullable=false) private Dataset dataset; @Column(nullable=false) @NotBlank(message = "Please specify a layer name.") private String layerName; @Column(nullable=false) @NotBlank(message = "Please specify a layer link.") private String layerLink; @Column(nullable=false) @NotBlank(message = "Please specify am embedded map link.") private String embedMapLink; @Column(nullable=true) @NotBlank(message = "Please specify a map image link.") private String mapImageLink; @Column(nullable=false) @NotBlank(message = "Please specify a WorldMap username.") private String worldmapUsername; /** * Get property layerName. * @return value of property layerName. */ public String getLayerName() { return this.layerName; } /** * Set property layerName. * @param layerName new value of property layerName. */ public void setLayerName(String layerName) { this.layerName = layerName; } /** * Get property layerLink. * @return value of property layerLink. */ public String getLayerLink() { return this.layerLink; } /** * Set property layerLink. * @param layerLink new value of property layerLink. */ public void setLayerLink(String layerLink) { this.layerLink = layerLink; } /** * Get property mapImageLink. * @return value of property mapImageLink. */ public String getMapImageLink() { return this.mapImageLink; } /** * Set property mapImageLink. * @param mapImageLink new value of property layerLink. */ public void setMapImageLink(String mapImageLink) { this.mapImageLink = mapImageLink; } /** * Get property embedMapLink. * @return value of property embedMapLink. */ public String getEmbedMapLink() { return this.embedMapLink; } /** * Set property embedMapLink. * @param embedMapLink new value of property embedMapLink. */ public void setEmbedMapLink(String embedMapLink) { this.embedMapLink = embedMapLink; } /** * Get property worldmapUsername. * @return value of property worldmapUsername. */ public String getWorldmapUsername() { return this.worldmapUsername; } /** * Set property worldmapUsername. * @param worldmapUsername new value of property worldmapUsername. */ public void setWorldmapUsername(String worldmapUsername) { this.worldmapUsername = worldmapUsername; } public Dataset getDataset() { return dataset; } public void setDataset(Dataset dataset) { this.dataset = dataset; } public DataFile getDataFile() { return dataFile; } public void setDataFile(DataFile dataFile) { this.dataFile = dataFile; } /** * Getter for property id. * @return Value of property id. */ public Long getId() { return this.id; } /** * Setter for property id. * @param id New value of property id. */ public void setId(Long id) { this.id = id; } @Override public String toString() { return "edu.harvard.iq.dataverse.MaplayerMetadata[id=" + this.id + "]"; //return "WorldMap Layer: " + this.layerName + " for DataFile: " + this.dataFile.toString(); } }
package edu.ucar.unidata.rosetta.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Utilities for handling wizard-related cookies. */ public class CookieUtils { private static String APP_NAME = "rosetta"; private static int EXPIRATION = 1800; // 30 minutes. /** * Creates a cookie for a wizard session. * * @param id The unique ID associated with the session. * @param request The request object used for setting the domain name. * @return The cookie. */ public static Cookie createCookie(String id, HttpServletRequest request) { Cookie cookie = new Cookie(APP_NAME, id); cookie.setMaxAge(EXPIRATION); cookie.setDomain(request.getServerName()); return cookie; } /** * Invalidates the provided cookie. * * @param cookie The cookie to invalidate. * @param response The response in which to add the invalidated cookie. */ public static void invalidateCookie(Cookie cookie, HttpServletResponse response) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } }
package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * A table for storing visits - likely related to "pixel tracking". Where a remote * site requests an image from a web service, and we log that request. */ @Entity @Table(name="Visit") @Data @Exportable @DoNotDelete public class VisitDAO { @Id @GeneratedValue private int id; private String name; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST") private Date date; public VisitDAO() {} public VisitDAO(String name) { this.name = name; this.date = new Date(); } }
package org.carlspring.strongbox.providers.repository; import org.carlspring.strongbox.client.ArtifactTransportException; import org.carlspring.strongbox.config.Maven2LayoutProviderCronTasksTestConfig; import org.carlspring.strongbox.data.CacheManagerTestExecutionListener; import org.carlspring.strongbox.domain.ArtifactEntry; import org.carlspring.strongbox.providers.ProviderImplementationException; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.carlspring.strongbox.providers.layout.LayoutProvider; import org.carlspring.strongbox.services.ArtifactEntryService; import org.carlspring.strongbox.storage.Storage; import org.carlspring.strongbox.storage.metadata.MavenMetadataManager; import org.carlspring.strongbox.storage.repository.Repository; import org.carlspring.strongbox.testing.TestCaseWithMavenArtifactGenerationAndIndexing; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.security.NoSuchAlgorithmException; import java.util.Optional; import com.google.common.io.ByteStreams; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.repository.metadata.Metadata; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * @author carlspring */ @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles(profiles = "test") @ContextConfiguration(classes = Maven2LayoutProviderCronTasksTestConfig.class) @TestExecutionListeners(listeners = { CacheManagerTestExecutionListener.class }, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class MavenProxyRepositoryProviderTestIT extends TestCaseWithMavenArtifactGenerationAndIndexing { private static final Logger logger = LoggerFactory.getLogger(MavenProxyRepositoryProviderTestIT.class); @Inject private ArtifactEntryService artifactEntryService; @Inject private MavenMetadataManager mavenMetadataManager; @Before @After public void cleanup() throws Exception { deleteDirectoryRelativeToVaultDirectory( "storages/storage-common-proxies/maven-central/org/carlspring/maven/derby-maven-plugin"); deleteDirectoryRelativeToVaultDirectory("storages/storage-common-proxies/maven-oracle/com/oracle/jdbc/ojdbc8"); deleteDirectoryRelativeToVaultDirectory( "storages/storage-common-proxies/maven-central/org/carlspring/properties-injector"); deleteDirectoryRelativeToVaultDirectory("storages/storage-common-proxies/maven-central/javax/media/jai_core"); artifactEntryService.deleteAll(); } /* @Test public void shouldBeAbleToProvideFilesFromOracleMavenRepoWithHttpsAndAuthenticationAndRedirections() throws Exception { String providedTestOracleRepoUser = System.getProperty("strongbox.test.oracle.repo.user"); String providedTestOracleRepoPassword = System.getProperty("strongbox.test.oracle.repo.password"); if (providedTestOracleRepoUser == null || providedTestOracleRepoPassword == null) { logger.info( "System property strongbox.test.oracle.repo.user or strongbox.test.oracle.repo.password not found. Ignoring test."); return; } ImmutableRemoteRepository mavenOracleRepository = configurationManagementService.getConfiguration() .getStorage("storage-common-proxies") .getRepository("maven-oracle") .getRemoteRepository(); String initialUsername = mavenOracleRepository.getUsername(); String initialPassword = mavenOracleRepository.getPassword(); mavenOracleRepository.setUsername(providedTestOracleRepoUser); mavenOracleRepository.setPassword(providedTestOracleRepoPassword); assertStreamNotNull("storage-common-proxies", "maven-oracle", "com/oracle/jdbc/ojdbc8/12.2.0.1/ojdbc8-12.2.0.1.jar"); assertStreamNotNull("storage-common-proxies", "maven-oracle", "com/oracle/jdbc/ojdbc8/12.2.0.1/ojdbc8-12.2.0.1.pom"); mavenOracleRepository.setUsername(initialUsername); mavenOracleRepository.setPassword(initialPassword); } */ @Test public void whenDownloadingArtifactMetadaFileShouldAlsoBeResolved() throws Exception { String storageId = "storage-common-proxies"; String repositoryId = "maven-central"; assertStreamNotNull(storageId, repositoryId, "org/carlspring/properties-injector/1.7/properties-injector-1.7.jar"); Storage storage = getConfiguration().getStorage(storageId); Repository repository = storage.getRepository(repositoryId); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); assertTrue(layoutProvider.containsPath(repositoryPathResolver.resolve(repository, "org/carlspring/properties-injector/maven-metadata.xml"))); } @Ignore @Test public void whenDownloadingArtifactMetadataFileShouldBeMergedWhenExist() throws Exception { String storageId = "storage-common-proxies"; Storage storage = getConfiguration().getStorage(storageId); // 1. download the artifact and artifactId-level maven metadata-file from maven-central String repositoryId = "maven-central"; assertStreamNotNull(storageId, repositoryId, "javax/media/jai_core/1.1.3/jai_core-1.1.3-javadoc.jar"); // 2. resolve downloaded artifact base path Repository repository = storage.getRepository(repositoryId); LayoutProvider layoutProvider = layoutProviderRegistry.getProvider(repository.getLayout()); final Path mavenCentralArtifactBaseBath = repositoryPathResolver.resolve(repository, "javax/media/jai_core"); // 3. copy the content to carlspring repository repositoryId = "carlspring"; repository = storage.getRepository(repositoryId); final Path carlspringArtifactBaseBath = repositoryPathResolver.resolve(repository, "javax/media/jai_core"); FileUtils.copyDirectory(mavenCentralArtifactBaseBath.toFile(), carlspringArtifactBaseBath.toFile()); // 4. confirm maven-metadata.xml lies in the carlspring repository assertTrue(layoutProvider.containsPath(repositoryPathResolver.resolve(repository, "javax/media/jai_core/maven-metadata.xml"))); // 5. confirm some pre-merge state Path artifactBasePath = repositoryPathResolver.resolve(repository, "javax/media/jai_core/"); Metadata metadata = mavenMetadataManager.readMetadata(artifactBasePath); assertThat(metadata.getVersioning().getVersions().size(), CoreMatchers.equalTo(1)); assertThat(metadata.getVersioning().getVersions().get(0), CoreMatchers.equalTo("1.1.2_01")); // 6. download the artifact from remote carlspring repository - it contains different maven-metadata.xml file assertStreamNotNull(storageId, repositoryId, "javax/media/jai_core/1.1.3/jai_core-1.1.3.jar"); // 7. confirm the state of maven-metadata.xml file has changed metadata = mavenMetadataManager.readMetadata(artifactBasePath); assertThat(metadata.getVersioning().getVersions().size(), CoreMatchers.equalTo(2)); assertThat(metadata.getVersioning().getVersions().get(0), CoreMatchers.equalTo("1.1.2_01")); assertThat(metadata.getVersioning().getVersions().get(1), CoreMatchers.equalTo("1.1.3")); } @Test public void whenDownloadingArtifactDatabaseShouldBeAffectedByArtifactEntry() throws Exception { String storageId = "storage-common-proxies"; String repositoryId = "maven-central"; String path = "org/carlspring/properties-injector/1.6/properties-injector-1.6.jar"; Optional<ArtifactEntry> artifactEntry = Optional.ofNullable(artifactEntryService.findOneArtifact(storageId, repositoryId, path)); assertThat(artifactEntry, CoreMatchers.equalTo(Optional.empty())); assertStreamNotNull(storageId, repositoryId, path); artifactEntry = Optional.ofNullable(artifactEntryService.findOneArtifact(storageId, repositoryId, path)); assertThat(artifactEntry, CoreMatchers.not(CoreMatchers.equalTo(Optional.empty()))); } @Test public void testMavenCentral() throws Exception { assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/maven-metadata.xml"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/maven-metadata.xml.md5"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/maven-metadata.xml.sha1"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.pom"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.pom.md5"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.pom.sha1"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.jar"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.jar.md5"); assertStreamNotNull("storage-common-proxies", "maven-central", "org/carlspring/maven/derby-maven-plugin/1.10/derby-maven-plugin-1.10.jar.sha1"); assertIndexContainsArtifact("storage-common-proxies", "maven-central", "+g:org.carlspring.maven +a:derby-maven-plugin +v:1.10"); } @Ignore // Broken while Docker is being worked on, as there is no running instance of the Strongbox service. @Test public void testStrongboxAtCarlspringDotOrg() throws ProviderImplementationException, NoSuchAlgorithmException, ArtifactTransportException, IOException { RepositoryPath path = artifactResolutionService.resolvePath("public", "maven-group", "org/carlspring/commons/commons-io/1.0-SNAPSHOT/maven-metadata.xml"); try (InputStream is = artifactResolutionService.getInputStream(path)) { assertNotNull("Failed to resolve org/carlspring/commons/commons-io/1.0-SNAPSHOT/maven-metadata.xml!", is); System.out.println(ByteStreams.toByteArray(is)); } } }
package function.cohort.collapsing; import java.util.ArrayList; import java.util.List; /** * * @author nick */ public class RegionBoundary { private String name; private List<Region> regionList = new ArrayList<Region>(); public RegionBoundary(String regionBoundaryStr) { // gene/domain boundary format: name chr (start..end,start..end,start..end) length // region boundary format: name chr:start-end,chr:start-end,chr:start-end String[] tmp = regionBoundaryStr.split("\\s+"); name = tmp[0]; if (regionBoundaryStr.contains("(")) { // input gene/domain boundary format initRegionList(tmp[1], tmp[2]); } else { initRegionList(tmp[1]); } } public String getName() { return name; } public List<Region> getList() { return regionList; } private void initRegionList(String chr, String boundaryStr) { boundaryStr = boundaryStr.replace("(", "").replace(")", ""); for (String intervalStr : boundaryStr.split(",")) { regionList.add(new Region(chr, intervalStr)); } } private void initRegionList(String boundaryStr) { for (String regionStr : boundaryStr.split(",")) { regionList.add(new Region(regionStr)); } } public boolean isContained(String chr, int pos) { for (Region region : regionList) { if (region.isContained(chr, pos)) { return true; } } return false; } class Region { String chr; public int start; public int end; public Region(String chr, String intervalStr) { // chr, start..end this.chr = chr; String[] tmp = intervalStr.split("\\W"); start = Integer.valueOf(tmp[0]); end = Integer.valueOf(tmp[2]); } public Region(String regionStr) { // chr:start-end String[] tmp = regionStr.split(":|-"); chr = tmp[0]; start = Integer.valueOf(tmp[1]); end = Integer.valueOf(tmp[2]); } public boolean isContained(String chr, int pos) { if (this.chr.equalsIgnoreCase(chr) && pos >= this.start && pos <= this.end) { return true; } return false; } public String toString() { return chr + ":" + start + "-" + end; } } }
package infobip.api.model.sms.mo.reports; import infobip.api.model.Price; import java.util.Date; /** * This is a generated class and is not intended for modification! */ public class MOReport { private String cleanText; private int smsCount; private Price price; private String callbackData; private String messageId; private String from; private String to; private String text; private String keyword; private Date receivedAt; public MOReport() { } public String getCleanText() { return this.cleanText; } public MOReport setCleanText(String cleanText) { this.cleanText = cleanText; return this; } public int getSmsCount() { return this.smsCount; } public MOReport setSmsCount(int smsCount) { this.smsCount = smsCount; return this; } public Price getPrice() { return this.price; } public MOReport setPrice(Price price) { this.price = price; return this; } public String getCallbackData() { return this.callbackData; } public MOReport setCallbackData(String callbackData) { this.callbackData = callbackData; return this; } public String getMessageId() { return this.messageId; } public MOReport setMessageId(String messageId) { this.messageId = messageId; return this; } public String getFrom() { return this.from; } public MOReport setFrom(String from) { this.from = from; return this; } public String getTo() { return this.to; } public MOReport setTo(String to) { this.to = to; return this; } public String getText() { return this.text; } public MOReport setText(String text) { this.text = text; return this; } public String getKeyword() { return this.keyword; } public MOReport setKeyword(String keyword) { this.keyword = keyword; return this; } public Date getReceivedAt() { return this.receivedAt; } public MOReport setReceivedAt(Date receivedAt) { this.receivedAt = receivedAt; return this; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MOReport o = (MOReport)obj; if (this.cleanText == null) { if (o.cleanText != null){ return false; } } else if (!this.cleanText.equals(o.cleanText)) { return false; } if (this.smsCount != o.smsCount) { return false; } if (this.price == null) { if (o.price != null){ return false; } } else if (!this.price.equals(o.price)) { return false; } if (this.callbackData == null) { if (o.callbackData != null){ return false; } } else if (!this.callbackData.equals(o.callbackData)) { return false; } if (this.messageId == null) { if (o.messageId != null){ return false; } } else if (!this.messageId.equals(o.messageId)) { return false; } if (this.from == null) { if (o.from != null){ return false; } } else if (!this.from.equals(o.from)) { return false; } if (this.to == null) { if (o.to != null){ return false; } } else if (!this.to.equals(o.to)) { return false; } if (this.text == null) { if (o.text != null){ return false; } } else if (!this.text.equals(o.text)) { return false; } if (this.keyword == null) { if (o.keyword != null){ return false; } } else if (!this.keyword.equals(o.keyword)) { return false; } if (this.receivedAt == null) { if (o.receivedAt != null){ return false; } } else if (!this.receivedAt.equals(o.receivedAt)) { return false; } return true; } @Override public String toString() { return "MOReport{" + "cleanText='" + cleanText + "'" + ", smsCount=" + smsCount + ", price='" + price + "'" + ", callbackData='" + callbackData + "'" + ", messageId='" + messageId + "'" + ", from='" + from + "'" + ", to='" + to + "'" + ", text='" + text + "'" + ", keyword='" + keyword + "'" + ", receivedAt='" + receivedAt + "'" + '}'; } }
package innovimax.mixthem.join; import innovimax.mixthem.exceptions.MixException; import innovimax.mixthem.interfaces.IJoinLine; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * <p>Joins two lines on a common field.</p> * <p>This is the default implementation of IJoinLine.</p> * @see IJoinLine * @author Innovimax * @version 1.0 */ public class DefaultLineJoining implements IJoinLine { /* @Override public String join(String line1, String line2) throws MixException { if (line1 != null && line2 != null) { List<String> list1 = Arrays.asList(line1.split("\\s")); List<String> list2 = Arrays.asList(line2.split("\\s")); if (list1.size() > 0 && list2.contains(list1.get(0))) { String part1 = list1.stream().collect(Collectors.joining(" ")); String part2 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); return part1 + " " + part2; } } return null; } @Override public String join(String line1, String line2, int index) throws MixException { if (line1 != null && line2 != null) { List<String> list1 = Arrays.asList(line1.split("\\s")); List<String> list2 = Arrays.asList(line2.split("\\s")); if (list1.size() >= index && list2.size() >= index && list1.get(index - 1).equals(list2.get(index - 1))) { String part1 = list1.get(index - 1); String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(" ")); String part3 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); return part1 + " " + part2 + " " + part3; } } return null; } @Override public String join(String line1, String line2, int index1, int index2) throws MixException { System.out.println("join col1 col2 todo"); return null; } */ @Override public String join(String line1, String line2, JoinType type, List<String> params) throws MixException { String join = null; if (line1 != null && line2 != null) { List<String> list1 = Arrays.asList(line1.split("\\s")); List<String> list2 = Arrays.asList(line2.split("\\s")); switch (type) { case _DEFAULT: if (list1.size() > 0 && list2.contains(list1.get(0))) { String part1 = list1.stream().collect(Collectors.joining(" ")); String part2 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); join = part1 + " " + part2; } break; case _SAME_COL: int index = new Integer(params.get(0)).intValue(); if (list1.size() >= index && list2.size() >= index && list1.get(index - 1).equals(list2.get(index - 1))) { String part1 = list1.get(index - 1); String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(" ")); String part3 = list2.stream().filter(s -> !list1.contains(s)).collect(Collectors.joining(" ")); join = part1 + " " + part2 + " " + part3; } break; case _DIFF_COL: System.out.println("join col1 col2 todo"); break; } } return join; } }
package io.fabric8.che.starter.client; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import io.fabric8.che.starter.client.keycloak.KeycloakRestTemplate; import io.fabric8.che.starter.exception.StackNotFoundException; import io.fabric8.che.starter.model.stack.Stack; import io.fabric8.che.starter.model.stack.StackProjectMapping; import io.fabric8.che.starter.util.CheServerUrlProvider; @Component public class StackClient { @Autowired CheServerUrlProvider cheServerUrlProvider; public List<Stack> listStacks(String keycloakToken) { String url = CheRestEndpoints.LIST_STACKS.generateUrl(cheServerUrlProvider.getUrl(keycloakToken)); RestTemplate template = new KeycloakRestTemplate(keycloakToken); ResponseEntity<List<Stack>> response = template.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<Stack>>() { }); return response.getBody(); } /** * Gets stack for specified stack ID. Throws StackNotFoundException if there is * no such stack on the Che server. * * @param stackId stack ID * @param keycloakToken Keycloak token * @return image name for stack * @throws StackNotFoundException if no image name exists for such stack ID or * call to Che server was not successful */ public Stack getStack(String stackId, String keycloakToken) throws StackNotFoundException { List<Stack> stacks = listStacks(keycloakToken); if (stacks != null && !stacks.isEmpty()) { return stacks.stream().filter(s -> stackId.equals(s.getId())).findFirst() .orElseThrow(() -> new StackNotFoundException("Stack with id '" + stackId + "' was not found")); } throw new StackNotFoundException("No stacks were returned from Che server"); } public String getProjectTypeByStackId(final String stackId) { return StackProjectMapping.get().getOrDefault(stackId, StackProjectMapping.BLANK_PROJECT_TYPE); } }
package io.github.trevornelson.service; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import io.github.trevornelson.Account; /** * Custom Objectify Service that this application should use. */ public class OfyService { /** * This static block ensure the entity registration. */ static { factory().register(Account.class); } /** * Use this static method for getting the Objectify service object in order to make sure the * above static block is executed before using Objectify. * @return Objectify service object. */ public static Objectify ofy() { return ObjectifyService.ofy(); } /** * Use this static method for getting the Objectify service factory. * @return ObjectifyFactory. */ public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
package it.polito.tellmefirst.classify; import it.polito.tellmefirst.classify.threads.ClassiThread; import it.polito.tellmefirst.lucene.IndexesUtil; import it.polito.tellmefirst.lucene.LuceneManager; import it.polito.tellmefirst.lucene.SimpleSearcher; import it.polito.tellmefirst.util.TMFUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Optional; import static java.util.Optional.ofNullable; import java.util.TreeMap; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; public class Classifier { LuceneManager contextLuceneManager; SimpleSearcher searcher; static Log LOG = LogFactory.getLog(Classifier.class); public Classifier(String lang) { LOG.debug("[constructor] - BEGIN"); if (lang.equals("it")) { LOG.info("Initializing italian Classifier..."); searcher = IndexesUtil.ITALIAN_CORPUS_INDEX_SEARCHER; } else { LOG.info("Initializing english Classifier..."); searcher = IndexesUtil.ENGLISH_CORPUS_INDEX_SEARCHER; } contextLuceneManager = searcher.getLuceneManager(); LOG.debug("[constructor] - END"); } public ArrayList<String[]> classify(String textString, int numOfTopics, String lang) throws InterruptedException, IOException, ParseException { LOG.debug("[classify] - BEGIN"); ArrayList<String[]> result; Text text = new Text(textString); int totalNumWords = TMFUtils.countWords(textString); LOG.debug("TOTAL WORDS: " + totalNumWords); if (totalNumWords > 1000) { LOG.debug("Text contains " + totalNumWords + " words. We'll use Classify for long texts."); result = classifyLongText(text, numOfTopics, lang); } else { LOG.debug("Text contains " + totalNumWords + " words. We'll use Classify for short texts."); result = classifyShortText(text, numOfTopics, lang); } LOG.debug("[classify] - END"); return result; } public ArrayList<String[]> classifyLongText(Text text, int numOfTopics, String lang) throws InterruptedException, IOException { LOG.debug("[classifyLongText] - BEGIN"); ArrayList<String[]> result; LOG.debug("[classifyLongText] - We're using as analyzer: " + contextLuceneManager.getLuceneDefaultAnalyzer()); String longText = text.getText(); ArrayList<String> pieces = new ArrayList<String>(); // split long text in smaller parts and call // getContextQueryForKBasedDisambiguator() for each one int n = 0; while (TMFUtils.countWords(longText) > 1000) { String firstPart = StringUtils.join(longText.split(" "), " ", 0, 1000); String secondPart = StringUtils.join(longText.split(" "), " ", 1000, TMFUtils.countWords(longText)); pieces.add(firstPart); LOG.debug("Piece n°" + n + " analyzing..."); longText = secondPart; if (TMFUtils.countWords(longText) < 300) { LOG.debug("Final piece contains " + TMFUtils.countWords(longText) + " words. Discarded, because < " + "300 words."); } else if (TMFUtils.countWords(longText) < 1000) { LOG.debug("Final piece contains " + TMFUtils.countWords(longText) + " words."); pieces.add(longText); } n++; } ArrayList<ScoreDoc> mergedHitList = new ArrayList<ScoreDoc>(); ArrayList<ClassiThread> threadList = new ArrayList<ClassiThread>(); for (String textPiece : pieces) { ClassiThread thread = new ClassiThread(contextLuceneManager, searcher, textPiece); thread.start(); threadList.add(thread); } for (ClassiThread thread : threadList) { thread.join(); ScoreDoc[] hits = thread.getHits(); ArrayList<ScoreDoc> hitList = new ArrayList<ScoreDoc>(); for (int b = 0; b < numOfTopics && b < hits.length; b++) { hitList.add(hits[b]); } mergedHitList.addAll(hitList); } HashMap<Integer, Integer> scoreDocCount = new HashMap<Integer, Integer>(); for (ScoreDoc scoreDoc : mergedHitList) { Integer count = scoreDocCount.get(scoreDoc.doc); scoreDocCount.put(scoreDoc.doc, (count == null) ? 1 : count + 1); } HashMap<Integer, Integer> sortedMap = TMFUtils .sortHashMapIntegers(scoreDocCount); LinkedHashMap<ScoreDoc, Integer> sortedMapWithScore = new LinkedHashMap<ScoreDoc, Integer>(); for (int docnum : sortedMap.keySet()) { Document doc = searcher.getFullDocument(docnum); // XXX boolean flag = true; for (ScoreDoc sdoc : mergedHitList) { if (flag && sdoc.doc == docnum) { sortedMapWithScore.put(sdoc, sortedMap.get(docnum)); flag = false; } } } ArrayList<ScoreDoc> finalHitsList = sortByRank(sortedMapWithScore); ScoreDoc[] hits = new ScoreDoc[finalHitsList.size()]; for (int i = 0; i < finalHitsList.size(); i++) { hits[i] = finalHitsList.get(i); } result = classifyCore(hits, numOfTopics, lang); LOG.debug("[classifyLongText] - END"); return result; } /** * Classify a short piece of text. This function is used to bypass * the policy by which TMF triggers the long or the short classification * process depending on the text length. Note that if the text passed * to this function is too long, lucene may throw an exception. * * @param textString the input piece of text. * @param numOfTopics maximum number of topics to be returned (less * topics may be returned. * @param lang the classifier language (yes, this argument is * redundant and will be removed in the future). * @return A list of vectors of strings. Each vector shall be composed * of seven strings: the URI, the label, the title, the * score, the merged type, the image, and the wiki link. * * @since 2.0.0.0. */ public List<String[]> classifyShortText(String textString, int numOfTopics, String lang) throws InterruptedException, IOException, ParseException { return classifyShortText(new Text(textString), numOfTopics, lang); } public ArrayList<String[]> classifyShortText(Text text, int numOfTopics, String lang) throws ParseException, IOException { LOG.debug("[classifyShortText] - BEGIN"); ArrayList<String[]> result; LOG.debug("[classifyShortText] - We're using as analyzer: " + contextLuceneManager.getLuceneDefaultAnalyzer()); Query query = contextLuceneManager.getQueryForContext(text); ScoreDoc[] hits = searcher.getHits(query); result = classifyCore(hits, numOfTopics, lang); LOG.debug("[classifyShortText] - END"); return result; } public ArrayList<String[]> classifyCore(ScoreDoc[] hits, int numOfTopics, String lang) throws IOException { LOG.debug("[classifyCore] - BEGIN"); ArrayList<String[]> result = new ArrayList<String[]>(); if (hits.length == 0) { LOG.error("No results given by Lucene query from Classify!!"); } else { for (int i = 0; i < numOfTopics; i++) { String[] arrayOfFields = new String[7]; Document doc = searcher.getFullDocument(hits[i].doc); String uri = ""; String visLabel = ""; String title = ""; String mergedTypes = ""; String image; String wikilink = ""; if (lang.equals("italian")) { String italianUri = "http://it.dbpedia.org/resource/" + doc.getField("URI").stringValue(); wikilink = "http://it.wikipedia.org/wiki/" + doc.getField("URI").stringValue(); // Italian: resource without a corresponding in English DBpedia if (doc.getField("SAMEAS") == null) { uri = italianUri; title = doc.getField("TITLE").stringValue(); visLabel = title.replaceAll("\\(.+?\\)", "").trim(); Field[] types = doc.getFields("TYPE"); StringBuilder typesString = new StringBuilder(); for (Field value : types) { typesString.append(value.stringValue() + " } mergedTypes = typesString.toString(); image = ofNullable(doc.getField("IMAGE")) .flatMap(y -> ofNullable(y.stringValue())) .orElse(""); // Italian: resource with a corresponding in English DBpedia. // Note: in this case we use getImage() to get the image URL, rather // than the "IMAGE" field, under the assumption that the english // version of DBPedia is more rich. } else { uri = doc.getField("SAMEAS").stringValue(); title = IndexesUtil.getTitle(uri, "en"); visLabel = doc.getField("TITLE").stringValue() .replaceAll("\\(.+?\\)", "").trim(); image = IndexesUtil.getImage(uri, "en"); ArrayList<String> typesArray = IndexesUtil.getTypes(uri, "en"); StringBuilder typesString = new StringBuilder(); for (String type : typesArray) { typesString.append(type + " } mergedTypes = typesString.toString(); } // English } else { uri = "http://dbpedia.org/resource/" + doc.getField("URI").stringValue(); wikilink = "http://en.wikipedia.org/wiki/" + doc.getField("URI").stringValue(); title = doc.getField("TITLE").stringValue(); visLabel = title.replaceAll("\\(.+?\\)", "").trim(); image = ofNullable(doc.getField("IMAGE")) .flatMap(y -> ofNullable(y.stringValue())) .orElse(""); Field[] types = doc.getFields("TYPE"); StringBuilder typesString = new StringBuilder(); for (Field value : types) { typesString.append(value.stringValue() + " } mergedTypes = typesString.toString(); } LOG.debug("[classifyCore] - uri = " + uri); LOG.debug("[classifyCore] - title = " + title); LOG.debug("[classifyCore] - wikilink = " + wikilink); // LOG.debug("[classifyCore] - getWikiHtmlUrl = " + // getWikiHtmlUrl); String score = String.valueOf(hits[i].score); arrayOfFields[0] = uri; arrayOfFields[1] = visLabel; arrayOfFields[2] = title; arrayOfFields[3] = score; arrayOfFields[4] = mergedTypes; arrayOfFields[5] = image; arrayOfFields[6] = wikilink; result.add(arrayOfFields); } } LOG.debug("[classifyCore] - END size=" + result.size()); return result; } public ArrayList<ScoreDoc> sortByRank(LinkedHashMap<ScoreDoc, Integer> inputList) { LOG.debug("[sortByRank] - BEGIN"); ArrayList<ScoreDoc> result = new ArrayList<ScoreDoc>(); LinkedMap apacheMap = new LinkedMap(inputList); for (int i = 0; i < apacheMap.size() - 1; i++) { TreeMap<Float, ScoreDoc> treeMap = new TreeMap<Float, ScoreDoc>( Collections.reverseOrder()); do { i++; treeMap.put(((ScoreDoc) apacheMap.get(i - 1)).score, (ScoreDoc) apacheMap.get(i - 1)); } while (i < apacheMap.size() && apacheMap.getValue(i) == apacheMap.getValue(i - 1)); i for (Float score : treeMap.keySet()) { result.add(treeMap.get(score)); } } LOG.debug("[sortByRank] - END"); return result; } }
package land.face.strife.data.effects; import land.face.strife.data.StrifeMob; import land.face.strife.util.TargetingUtil; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Mob; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.util.Vector; public class ForceTarget extends Effect { private boolean casterTargetsTarget; private boolean overwrite; @Override public void apply(StrifeMob caster, StrifeMob target) { LivingEntity fromTarget = casterTargetsTarget ? caster.getEntity() : target.getEntity(); LivingEntity toTarget = casterTargetsTarget ? target.getEntity() : caster.getEntity(); if (fromTarget instanceof Mob) { if (overwrite) { ((Mob) fromTarget).setTarget(toTarget); return; } LivingEntity mobTarget = TargetingUtil.getMobTarget(fromTarget); if (mobTarget == null) { ((Mob) fromTarget).setTarget(toTarget); } } Location newLoc = fromTarget.getLocation().clone(); Vector savedVelocity = fromTarget.getVelocity(); newLoc.setDirection(toTarget.getEyeLocation().subtract(fromTarget.getEyeLocation()).toVector().normalize()); fromTarget.teleport(newLoc, TeleportCause.PLUGIN); fromTarget.setVelocity(savedVelocity); } public void setOverwrite(boolean overwrite) { this.overwrite = overwrite; } public void setCasterTargetsTarget(boolean casterTargetsTarget) { this.casterTargetsTarget = casterTargetsTarget; } }
package lodVader.invalidLinks; import java.util.ArrayList; import java.util.HashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import lodVader.mongodb.collections.DatasetDB; import lodVader.mongodb.collections.gridFS.ObjectsBucket; import lodVader.mongodb.collections.gridFS.SubjectsBucket; import lodVader.mongodb.collections.gridFS.SuperBucket; import lodVader.threads.ProcessNSFromTuple; public class InvalidLinksFilters { final static Logger logger = LoggerFactory.getLogger(InvalidLinksFilters.class); HashMap<Integer, ArrayList<SuperBucket>> datasetSubjectFilters = new HashMap<Integer, ArrayList<SuperBucket>>(); HashMap<Integer, ArrayList<SuperBucket>> datasetObjectFilters = new HashMap<Integer, ArrayList<SuperBucket>>(); public void loadDatasetObjectFilter(int datasetID) { if(!datasetObjectFilters.containsKey(datasetID)){ datasetObjectFilters.put(datasetID, new ObjectsBucket().getFiltersFromDataset(datasetID)); } } public void loadDatasetSubjectFilter(int datasetID) { if(!datasetSubjectFilters.containsKey(datasetID)){ logger.info("Loading dataset"+new DatasetDB(datasetID).getTitle()+" to filter..."); datasetSubjectFilters.put(datasetID, new SubjectsBucket().getFiltersFromDataset(datasetID)); } } public boolean queryDatasetSubject(String resource, int datasetID){ for(SuperBucket buket: datasetSubjectFilters.get(datasetID)){ if(buket.filter.compare(resource)) return true; } return false; } public boolean queryDatasetObject(String resource, int datasetID){ for(SuperBucket buket: datasetObjectFilters.get(datasetID)){ if(buket.filter.compare(resource)) return true; } return false; } }
package mcjty.gearswap.blocks; import net.minecraft.item.ItemStack; class OriginalStackSource implements Source { private final ItemStack[] currentStacks; public OriginalStackSource(ItemStack[] currentStacks) { this.currentStacks = currentStacks; } @Override public int getStackCount() { return currentStacks.length; } @Override public ItemStack getStack(int index) { return currentStacks[index]; } @Override public ItemStack extractAmount(int index, int amount) { ItemStack current = currentStacks[index]; if (amount < current.stackSize) { current = current.copy(); currentStacks[index].stackSize -= amount; current.stackSize = amount; } else { currentStacks[index] = null; } return current; } }
package me.coley.recaf.command; import me.coley.recaf.command.impl.*; import me.coley.recaf.parse.assembly.parsers.NumericParser; import me.coley.recaf.search.SearchCollector; import me.coley.recaf.search.SearchResult; import org.apache.commons.io.FileUtils; import org.tinylog.Logger; import picocli.CommandLine; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.Callable; import java.util.function.Consumer; /** * Command line controller. * * @author Matt */ public class HeadlessController extends Controller { private final Map<String, Class<?>> lookup = new HashMap<>(); private final Map<Class<?>, Consumer<?>> handlers = new HashMap<>(); private final File script; private boolean running = true; /** * @param workspace * Initial workspace file. Can point to a file to load <i>(class, jar)</i> or a workspace * configuration <i>(json)</i>. * @param script * Script to run. May be {@code null}. If not {@code null} the commands will be executed * then Recaf will terminate. */ public HeadlessController(File workspace, File script) { super(workspace); this.script = script; } @Override public void run() { // Try to load passed workspace try { loadInitialWorkspace(); if (getWorkspace() != null) Logger.info("Loaded workspace from: " + initialWorkspace); } catch(Exception ex) { Logger.error("Error loading workspace from file: " + initialWorkspace, ex); } // Start if(script != null) { // Script means no user input if(getWorkspace() == null) throw new IllegalArgumentException("No workspace was provided"); //Parse script List<String> lines; try { lines = FileUtils.readLines(script, StandardCharsets.UTF_8); } catch(IOException ex) { throw new IllegalArgumentException("Script file could not be read: " + script, ex); } // Run script for(String line : lines) handle(line); } else { // Interactive input Scanner scanner = new Scanner(System.in); do { // Ensure a workspace is open if(getWorkspace() == null) { Logger.info("Please input the path to a java program (class, jar) " + "or workspace file (json).\nSee documentation below:\n"); usage(get(LoadWorkspace.class)); } // Prompt & run commands from user input System.out.print("\n$ "); String in = scanner.nextLine(); if (!in.isEmpty()) handle(in); } while(running); scanner.close(); } } /** * Handle user input string. * * @param in * Line of input. */ private void handle(String in) { // Fetch command class int argsOffset = 1; String[] split = in.trim().split(" "); String name = split[0]; Class<?> key = getClass(name); if (key == null) { Logger.error("No such command: '" + name + "'"); return; } // Check for subcommand if(key.getDeclaredClasses().length > 0 && split.length > 1) { String tmpName = name + " " + split[argsOffset]; Class<?> tmpKey = getClass(tmpName); if(tmpKey != null) { key = tmpKey; argsOffset++; } } Callable<?> command = get(key); String[] args = Arrays.copyOfRange(split, argsOffset, split.length); // Picocli command handling CommandLine cmd = new CommandLine(command); cmd.registerConverter(Number.class, s -> (Number) new NumericParser("value").parse(s)); try { // Verify command can execute if (command instanceof WorkspaceCommand) { WorkspaceCommand wsCommand = (WorkspaceCommand)command; wsCommand.setWorkspace(getWorkspace()); wsCommand.verify(); } // Have picocli auto-populate annotated fields. cmd.parseArgs(args); // Meta commands should be fed command info after field population for some reason... odd if (command instanceof MetaCommand) ((MetaCommand) command).setContext(cmd); // Give help command access to all other commands if (command instanceof Help) for (Map.Entry<String, Class<?>> subCommEntry : lookup.entrySet()) if (!subCommEntry.getKey().contains(" ")) cmd.addSubcommand(new CommandLine(get(subCommEntry.getValue()))); // Invoke the command cmd.setExecutionResult(command.call()); // Handle result if (handlers.containsKey(key)) handlers.get(key).accept(cmd.getExecutionResult()); } catch (CommandLine.ParameterException ex) { // Raised from invalid user input, show usage and error. Logger.error(ex.getMessage() + "\nSee 'help " + name + "' for usage."); //ex.printStackTrace(); } catch (Exception ex) { // Raised from callable command Logger.error(ex); } } /** * Print usage of command. * * @param command * Command to show usage of. */ private void usage(Callable<?> command) { CommandLine cmd = new CommandLine(command); cmd.usage(cmd.getOut()); } /** * @param name * Command name. * @param <R> * Return type of callable. * @param <T> * Callable implementation. * * @return Class of command. */ @SuppressWarnings("unchecked") private <R, T extends Callable<R>> Class<T> getClass(String name) { return (Class<T>) lookup.get(name); } @Override protected <R, T extends Callable<R>> void register(Class<T> clazz) { super.register(clazz); // Add name lookup CommandLine.Command comm = clazz.getDeclaredAnnotation(CommandLine.Command.class); if (comm == null) throw new IllegalStateException("Callable class does not have required command annotation: " + clazz.getName()); String name = comm.name(); lookup.put(name, clazz); // Add name lookup for sub-commands for(Class<?> subclass : comm.subcommands()) { comm = subclass.getDeclaredAnnotation(CommandLine.Command.class); if(comm == null) throw new IllegalStateException("Callable class does not have required command annotation: " + subclass.getName()); String subname = comm.name(); lookup.put(name + " " + subname, subclass); } } /** * @param clazz * Command class. * @param consumer * Consumer that handles the return value of the command. * @param <R> * Return type of callable. * @param <T> * Callable implementation. */ private <R, T extends Callable<R>> void registerHandler(Class<T> clazz, Consumer<R> consumer) { handlers.put(clazz, consumer); } @Override protected void setup() { super.setup(); Consumer<SearchCollector> printResults = r -> { for (SearchResult res : r.getAllResults()) Logger.info(res.getContext()); }; registerHandler(LoadWorkspace.class, this::setWorkspace); registerHandler(Decompile.class, Logger::info); registerHandler(Search.ClassInheritance.class, printResults); registerHandler(Search.ClassName.class, printResults); registerHandler(Search.Member.class, printResults); registerHandler(Search.ClassUsage.class, printResults); registerHandler(Search.MemberUsage.class, printResults); registerHandler(Search.Text.class, printResults); registerHandler(Search.Value.class, printResults); registerHandler(Quit.class, v -> running = false); } }
package net.glowstone.block.blocktype; import net.glowstone.block.GlowBlock; import net.glowstone.block.GlowBlockState; import net.glowstone.block.entity.BlockEntity; import net.glowstone.block.entity.ContainerEntity; import net.glowstone.block.entity.HopperEntity; import net.glowstone.block.state.GlowHopper; import net.glowstone.chunk.GlowChunk; import net.glowstone.entity.GlowPlayer; import net.glowstone.entity.objects.GlowItem; import net.glowstone.inventory.MaterialMatcher; import net.glowstone.inventory.ToolType; import org.bukkit.Location; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.material.*; import org.bukkit.util.Vector; import java.util.HashMap; public class BlockHopper extends BlockContainer { public void setFacingDirection(BlockState bs, BlockFace face) { byte data; switch (face) { case DOWN: data = 0; break; case UP: data = 1; break; case NORTH: data = 2; break; case SOUTH: data = 3; break; case WEST: data = 4; break; case EAST: default: data = 5; break; } bs.setRawData(data); } @Override public BlockEntity createBlockEntity(GlowChunk chunk, int cx, int cy, int cz) { return new HopperEntity(chunk.getBlock(cx, cy, cz)); } @Override public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { super.placeBlock(player, state, face, holding, clickedLoc); setFacingDirection(state, face.getOppositeFace()); state.getBlock().getWorld().requestPulse(state.getBlock()); } @Override protected MaterialMatcher getNeededMiningTool(GlowBlock block) { return ToolType.PICKAXE; } @Override public void receivePulse(GlowBlock block) { if (block.getBlockEntity() == null) { return; } HopperEntity hopper = (HopperEntity) block.getBlockEntity(); if (!((Hopper) block.getState().getData()).isPowered()) { pushItems(block, hopper); } pullItems(block, hopper); } @Override public void onRedstoneUpdate(GlowBlock block) { ((Hopper) block.getState().getData()).setActive(!block.isBlockPowered()); } private void pullItems(GlowBlock block, HopperEntity hopper) { GlowBlock source = block.getRelative(BlockFace.UP); MaterialData data = source.getState().getData(); if (!source.getType().isSolid() || (data instanceof Step && !((Step) data).isInverted()) || (data instanceof WoodenStep && !((WoodenStep) data).isInverted()) || (data instanceof Sign) || (data instanceof Rails)) { GlowItem item = getFirstDroppedItem(source.getLocation()); if (item == null) { return; } ItemStack stack = item.getItemStack(); HashMap<Integer, ItemStack> add = hopper.getInventory().addItem(stack); if (add.size() > 0) { item.setItemStack(add.get(0)); } else { item.remove(); } } else if (source.getBlockEntity() != null && source.getBlockEntity() instanceof ContainerEntity) { ContainerEntity sourceContainer = (ContainerEntity) source.getBlockEntity(); if (sourceContainer.getInventory() == null || sourceContainer.getInventory().getContents().length == 0) { return; } ItemStack item = getFirstItem(sourceContainer); if (item == null) { return; } ItemStack clone = item.clone(); clone.setAmount(1); if (hopper.getInventory().addItem(clone).size() > 0) { return; } if (item.getAmount() - 1 == 0) { sourceContainer.getInventory().remove(item); } else { item.setAmount(item.getAmount() - 1); } } } private boolean pushItems(GlowBlock block, HopperEntity hopper) { if (hopper.getInventory() == null || hopper.getInventory().getContents().length == 0) { return false; } GlowBlock target = block.getRelative(((Hopper) block.getState().getData()).getFacing()); if (target.getType() != null && target.getBlockEntity() instanceof ContainerEntity) { if (target.getState() instanceof GlowHopper) { if (((Hopper) block.getState().getData()).getFacing() == BlockFace.DOWN) { // If the hopper is facing downwards, the target hopper can do the pulling task itself return false; } } ItemStack item = getFirstItem(hopper); if (item == null) { return false; } ItemStack clone = item.clone(); clone.setAmount(1); if (((ContainerEntity) target.getBlockEntity()).getInventory().addItem(clone).size() > 0) { return false; } if (item.getAmount() - 1 == 0) { hopper.getInventory().remove(item); } else { item.setAmount(item.getAmount() - 1); } return true; } return false; } private GlowItem getFirstDroppedItem(Location location) { for (Entity entity : location.getChunk().getEntities()) { if (location.getBlockX() != entity.getLocation().getBlockX() || location.getBlockY() != entity.getLocation().getBlockY() || location.getBlockZ() != entity.getLocation().getBlockZ()) { continue; } if (entity.getType() != EntityType.DROPPED_ITEM) { continue; } return ((GlowItem) entity); } return null; } private ItemStack getFirstItem(ContainerEntity container) { Inventory inventory = container.getInventory(); for (int i = 0; i < inventory.getSize(); i++) { if (inventory.getItem(i) == null || inventory.getItem(i).getType() == null) { continue; } return inventory.getItem(i); } return null; } @Override public boolean isPulseOnce(GlowBlock block) { return false; } @Override public int getPulseTickSpeed(GlowBlock block) { return 8; } }
package net.malisis.core.renderer; import java.util.Arrays; import java.util.Set; import javax.vecmath.Matrix4f; import org.lwjgl.opengl.GL11; import com.google.common.collect.Sets; import net.malisis.core.MalisisCore; import net.malisis.core.asm.AsmUtils; import net.malisis.core.block.BoundingBoxType; import net.malisis.core.block.IBoundingBox; import net.malisis.core.block.IComponent; import net.malisis.core.block.ISmartCull; import net.malisis.core.registry.MalisisRegistry; import net.malisis.core.renderer.element.Face; import net.malisis.core.renderer.element.Shape; import net.malisis.core.renderer.element.Vertex; import net.malisis.core.renderer.element.shape.Cube; import net.malisis.core.renderer.font.FontOptions; import net.malisis.core.renderer.font.MalisisFont; import net.malisis.core.renderer.icon.Icon; import net.malisis.core.renderer.icon.provider.IBlockIconProvider; import net.malisis.core.renderer.icon.provider.IIconProvider; import net.malisis.core.renderer.icon.provider.IItemIconProvider; import net.malisis.core.renderer.model.MalisisModel; import net.malisis.core.util.AABBUtils; import net.malisis.core.util.BlockPosUtils; import net.malisis.core.util.EnumFacingUtils; import net.malisis.core.util.ItemUtils; import net.malisis.core.util.Silenced; import net.malisis.core.util.Utils; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.DestroyBlockProgress; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.registry.ClientRegistry; /** * Base class for rendering. Handles the rendering. Provides easy registration of the renderer, and automatically sets up the context for * the rendering. * * @author Ordinastie * */ public class MalisisRenderer<T extends TileEntity> extends TileEntitySpecialRenderer<T> implements IBlockRenderer, IRenderWorldLast { /** Batched buffer reference. */ protected static final BufferBuilder batchedBuffer = ((Tessellator) Silenced.get(() -> AsmUtils .changeFieldAccess( TileEntityRendererDispatcher.class, "batchBuffer") .get(TileEntityRendererDispatcher.instance))).getBuffer(); public static VertexFormat malisisVertexFormat = new VertexFormat() { { addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.POSITION, 3)); addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.UBYTE, VertexFormatElement.EnumUsage.COLOR, 4)); addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.UV, 2)); addElement(new VertexFormatElement(1, VertexFormatElement.EnumType.SHORT, VertexFormatElement.EnumUsage.UV, 2)); addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.NORMAL, 3)); addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.PADDING, 1)); } }; /** Whether this {@link MalisisRenderer} initialized. (initialize() already called) */ private boolean initialized = false; /** Currently used buffer. */ protected BufferBuilder buffer = null; /** Current used vertex format. */ protected VertexFormat vertexFormat = malisisVertexFormat; /** Current world reference (BLOCK/TESR/IRWL). */ protected IBlockAccess world; /** Position of the block (BLOCK/TESR). */ protected BlockPos pos; /** Block to render (BLOCK/TESR). */ protected Block block; /** Metadata of the block to render (BLOCK/TESR). */ protected IBlockState blockState; /** TileEntity currently drawing (TESR). */ protected T tileEntity; /** Partial tick time (TESR/IRWL). */ protected float partialTick = 0; /** ItemStack to render (ITEM). */ protected ItemStack itemStack; /** Item to render (ITEM) */ protected Item item; /** Type of render for item (ITEM) **/ protected TransformType tranformType; /** RenderGlobal reference (IRWL) */ protected RenderGlobal renderGlobal; /** Type of rendering. */ protected RenderType renderType; /** Mode of rendering (GL constant). */ protected int drawMode = GL11.GL_QUADS; /** Base brightness of the block. */ protected int baseBrightness; /** Whether the rendering is batched (TESR/ANIMATED). **/ private boolean isBatched = false; /** Vertex positions offset. **/ protected Vec3d posOffset = null; /** List of classes the Block is allowed to be. */ private Set<Class<?>> ensureBlocks = Sets.newHashSet(); /** Whether the damage for the blocks should be handled by this {@link MalisisRenderer} (for TESR). */ protected boolean getBlockDamage = false; /** Current block destroy progression (for TESR). */ protected DestroyBlockProgress destroyBlockProgress = null; /** Whether at least one vertex has been drawn. */ protected boolean vertexDrawn = false; /** * Instantiates a new {@link MalisisRenderer}. */ public MalisisRenderer() { //this.renderId = RenderingRegistry.getNextAvailableRenderId(); } //#region Getters public RenderType getRenderType() { return renderType; } public IBlockAccess getWorldAccess() { return world; } public BlockPos getPos() { return pos; } public IBlockState getBlockState() { return blockState; } public ItemStack getItemStack() { return itemStack; } public T getTileEntity() { return tileEntity; } //#region // #region set() /** * Resets data so this {@link MalisisRenderer} can be reused. */ public void reset() { this.buffer = null; this.renderType = RenderType.UNSET; this.drawMode = 0; this.world = null; this.pos = null; this.block = null; this.blockState = null; this.tileEntity = null; this.item = null; this.itemStack = null; this.destroyBlockProgress = null; this.tranformType = null; this.posOffset = null; } /** * Sets informations for this {@link MalisisRenderer}. * * @param world the world * @param block the block * @param pos the pos * @param blockState the block state */ @SuppressWarnings("unchecked") public void set(IBlockAccess world, Block block, BlockPos pos, IBlockState blockState) { this.world = world; this.pos = new BlockPos(pos); this.block = block; this.blockState = blockState; this.tileEntity = (T) world.getTileEntity(pos); } public void set(IBlockAccess world, BlockPos pos) { this.world = world; this.pos = pos; set(world.getBlockState(pos)); } /** * Sets informations for this {@link MalisisRenderer}. * * @param world the world */ public void set(IBlockAccess world) { this.world = world; } /** * Sets informations for this {@link MalisisRenderer}. * * @param block the block */ public void set(Block block) { this.block = block; this.blockState = block.getDefaultState(); } /** * Sets informations for this {@link MalisisRenderer}. * * @param blockState the block state */ public void set(IBlockState blockState) { this.block = blockState.getBlock(); this.blockState = blockState; } /** * Sets informations for this {@link MalisisRenderer}. * * @param pos the pos */ public void set(BlockPos pos) { this.pos = new BlockPos(pos); } /** * Sets informations for this {@link MalisisRenderer}. * * @param te the te * @param partialTick the partial tick */ public void set(T te, float partialTick) { set(te.getWorld(), te.getBlockType(), te.getPos(), te.getWorld().getBlockState(te.getPos())); this.partialTick = partialTick; this.tileEntity = te; } /** * Sets informations for this {@link MalisisRenderer}. * * @param itemStack the item stack */ public void set(ItemStack itemStack) { this.itemStack = itemStack; this.item = itemStack.getItem(); IBlockState state = ItemUtils.getStateFromItemStack(itemStack); if (state != null) this.set(state); } /** * Limits the classes the block can be for this {@link MalisisRenderer}. * * @param blockClasses the block classes */ protected void ensureBlock(Class<?>... blockClasses) { ensureBlocks.clear(); ensureBlocks.addAll(Arrays.asList(blockClasses)); } /** * Check if the current block is allowed. If not, no rendering will be done. * * @return true, if successful */ private boolean checkBlock() { //AIR allows render because of Items if (block == Blocks.AIR || ensureBlocks.size() == 0) return true; return ensureBlocks.contains(block.getClass()); } protected void setBatched() { if (!FMLClientHandler.instance().hasOptifine()) this.isBatched = true; } protected boolean isBatched() { return isBatched; } // #end //#region IBlockRenderer @Override public synchronized boolean renderBlock(BufferBuilder wr, IBlockAccess world, BlockPos pos, IBlockState state) { this.buffer = wr; set(world, state.getBlock(), pos, state); prepare(RenderType.BLOCK); if (checkBlock()) render(); clean(); return vertexDrawn; } //#end IBlockRenderer //#region IItemRenderer @Override public synchronized boolean renderItem(ItemStack itemStack, float partialTick) { if (tranformType == TransformType.FIRST_PERSON_RIGHT_HAND || tranformType == TransformType.FIRST_PERSON_LEFT_HAND) { ItemStack stackInv = Utils .getClientPlayer() .getHeldItem(tranformType == TransformType.FIRST_PERSON_RIGHT_HAND ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND); if (itemStack != stackInv && stackInv != null && stackInv.getItem() == itemStack.getItem()) itemStack = stackInv; } this.buffer = Tessellator.getInstance().getBuffer(); set(itemStack); prepare(RenderType.ITEM); if (checkBlock()) render(); clean(); return true; } @Override public void setTransformType(TransformType transformType) { this.tranformType = transformType; } @Override public boolean isGui3d() { return true; } @Override public Matrix4f getTransform(Item item, TransformType tranformType) { this.tranformType = tranformType; return null; } //#end IItemRenderer // #region TESR /** * Renders a {@link TileEntitySpecialRenderer}. * * @param te the TileEntity * @param x the x * @param y the y * @param z the z * @param partialTick the partial tick */ @Override public synchronized void renderTileEntityAt(T te, double x, double y, double z, float partialTick, int destroyStage, float f) { if (te.getWorld().getBlockState(te.getPos()).getBlock() == Blocks.AIR) return; this.buffer = isBatched() ? batchedBuffer : Tessellator.getInstance().getBuffer(); set(te, partialTick); prepare(RenderType.TILE_ENTITY, x, y, z); if (checkBlock()) render(); //TODO // if (getBlockDamage) // destroyBlockProgress = getBlockDestroyProgress(); // if (destroyBlockProgress != null) // next(); // GL11.glEnable(GL11.GL_BLEND); // OpenGlHelper.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO); // GL11.glAlphaFunc(GL11.GL_GREATER, 0); // GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); // t.disableColor(); // renderDestroyProgress(); // next(); // GL11.glDisable(GL11.GL_BLEND); clean(); } // #end TESR // #region IRenderWorldLast @Override public boolean shouldSetViewportPosition() { return true; } @Override public boolean shouldRender(RenderWorldLastEvent event, IBlockAccess world) { return true; } @Override public void renderWorldLastEvent(RenderWorldLastEvent event, IBlockAccess world) { set(world); buffer = Tessellator.getInstance().getBuffer(); partialTick = event.getPartialTicks(); renderGlobal = event.getContext(); double x = 0, y = 0, z = 0; if (shouldSetViewportPosition()) { EntityPlayer p = Utils.getClientPlayer(); x = -(p.lastTickPosX + (p.posX - p.lastTickPosX) * partialTick); y = -(p.lastTickPosY + (p.posY - p.lastTickPosY) * partialTick); z = -(p.lastTickPosZ + (p.posZ - p.lastTickPosZ) * partialTick); } prepare(RenderType.WORLD_LAST, x, y, z); render(); clean(); } // #end IRenderWorldLast // #region prepare() /** * Prepares the {@link Tessellator} and the GL states for the <b>renderType</b>. <b>data</b> is only used for TESR and IRWL.<br> * TESR and IRWL rendering are surrounded by glPushAttrib(GL_LIGHTING_BIT) and block texture sheet is bound. * * @param renderType the render type * @param data the data */ public void prepare(RenderType renderType, double... data) { _initialize(); vertexDrawn = false; this.renderType = renderType; if (renderType == RenderType.BLOCK) { vertexFormat = DefaultVertexFormats.BLOCK; //when drawing a block, the position to draw is relative to current chunk BlockPos chunkPos = BlockPosUtils.chunkPosition(pos); posOffset = new Vec3d(chunkPos.getX(), chunkPos.getY(), chunkPos.getZ()); } else if (renderType == RenderType.ITEM) { startDrawing(malisisVertexFormat); } else if (renderType == RenderType.TILE_ENTITY) { if (isBatched()) { posOffset = new Vec3d(data[0], data[1], data[2]); vertexFormat = FMLClientHandler.instance().hasOptifine() ? DefaultVertexFormats.BLOCK : malisisVertexFormat; } else { GlStateManager.pushAttrib(); GlStateManager.pushMatrix(); GlStateManager.disableLighting(); GlStateManager.translate(data[0], data[1], data[2]); bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); startDrawing(FMLClientHandler.instance().hasOptifine() ? DefaultVertexFormats.BLOCK : malisisVertexFormat); enableBlending(); } } else if (renderType == RenderType.WORLD_LAST) { GlStateManager.pushAttrib(); GlStateManager.pushMatrix(); Minecraft.getMinecraft().entityRenderer.enableLightmap(); GlStateManager.translate(data[0], data[1], data[2]); bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); startDrawing(malisisVertexFormat); enableBlending(); } else throw new IllegalArgumentException("Unknow renderType to handle for " + getClass().getSimpleName() + " : " + renderType); } /** * Cleans the current renderer state. */ public void clean() { if (renderType == RenderType.ITEM) { draw(); // GlStateManager.enableLighting(); // GlStateManager.popMatrix(); // GlStateManager.popAttrib(); } else if (renderType == RenderType.TILE_ENTITY) { if (isBatched()) buffer.setTranslation(0, 0, 0); else { draw(); disableBlending(); GlStateManager.enableLighting(); GlStateManager.popMatrix(); GlStateManager.popAttrib(); } } else if (renderType == RenderType.WORLD_LAST) { draw(); disableBlending(); Minecraft.getMinecraft().entityRenderer.disableLightmap(); GlStateManager.popMatrix(); GlStateManager.popAttrib(); } reset(); } /** * Tells the {@link Tessellator} to start drawing with GL11.GL_QUADS and {@link #malisisVertexFormat}. */ public void startDrawing() { startDrawing(GL11.GL_QUADS, vertexFormat); } /** * Tells the {@link Tessellator} to start drawing with specified <b>drawMode</b> and {@link #malisisVertexFormat}. * * @param drawMode the draw mode */ public void startDrawing(int drawMode) { startDrawing(drawMode, vertexFormat); } /** * Tells the {@link Tessellator} to start drawing with GL11.GL_QUADS and specified {@link VertexFormat}. * * @param vertexFormat the vertex format */ public void startDrawing(VertexFormat vertexFormat) { startDrawing(GL11.GL_QUADS, vertexFormat); } /** * Tells the {@link Tessellator} to start drawing with specified <b>drawMode and specified {@link VertexFormat}. * * @param drawMode the draw mode * @param vertexFormat the vertex format */ public void startDrawing(int drawMode, VertexFormat vertexFormat) { if (!canDraw()) return; draw(); buffer.begin(drawMode, vertexFormat); this.drawMode = drawMode; this.vertexFormat = vertexFormat; } /** * Checks if the {@link Tessellator} is currently drawing. * * @return true, if is drawing */ public boolean isDrawing() { if (buffer == null) throw new NullPointerException("[MalisisRenderer] WorldRenderer not set for " + renderType); return buffer.isDrawing; } /** * Triggers a draw and restart drawing with current {@link MalisisRenderer#drawMode}. */ public void next() { next(drawMode); } /** * Triggers a draw and restart drawing with <b>drawMode</b> and current {@link VertexFormat}. * * @param drawMode the draw mode */ public void next(int drawMode) { next(drawMode, vertexFormat); } /** * Triggers a draw and restart drawing with current {@link MalisisRenderer#drawMode} and specified {@link VertexFormat} * * @param vertexFormat the vertex format */ public void next(VertexFormat vertexFormat) { next(GL11.GL_QUADS, vertexFormat); } /** * Triggers a draw and restart drawing with current {@link MalisisRenderer#drawMode} and {@link VertexFormat} * * @param drawMode the draw mode * @param vertexFormat the vertex format */ public void next(int drawMode, VertexFormat vertexFormat) { draw(); startDrawing(drawMode, vertexFormat); } /** * Triggers a draw. */ public void draw() { if (canDraw() && isDrawing()) Tessellator.getInstance().draw(); } private boolean canDraw() { if (renderType == RenderType.BLOCK || renderType == RenderType.ANIMATED) return false; if (renderType == RenderType.TILE_ENTITY && isBatched()) return false; return true; } /** * Enables the blending for the rendering. Ineffective for BLOCK renderType. */ public void enableBlending() { if (renderType == RenderType.BLOCK) return; GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F); GlStateManager.shadeModel(GL11.GL_SMOOTH); GlStateManager.enableColorMaterial(); } /** * Disables blending for the rendering. Ineffective for BLOCK renderType. */ public void disableBlending() { if (renderType == RenderType.BLOCK) return; GlStateManager.disableColorMaterial(); GlStateManager.shadeModel(GL11.GL_FLAT); GlStateManager.disableBlend(); } /** * Enables textures */ public void enableTextures() { GL11.glEnable(GL11.GL_TEXTURE_2D); } /** * Disables textures. */ public void disableTextures() { GL11.glDisable(GL11.GL_TEXTURE_2D); } @Override protected void bindTexture(ResourceLocation resourceLocaltion) { Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocaltion); } /** * Sets billboard mode.<br> * Contents drawn will always be facing the player. * * @param x the x * @param y the y * @param z the z */ public void setBillboard(float x, float y, float z) { EntityPlayer player = Utils.getClientPlayer(); GlStateManager.pushMatrix(); GlStateManager.translate(x, y, z); GlStateManager.rotate(180 - player.rotationYaw, 0, 1, 0); } /** * End billboard mode. */ public void endBillboard() { GlStateManager.popMatrix(); } // #end prepare() /** * _initialize. */ protected final void _initialize() { if (initialized) return; initialize(); initialized = true; } /** * Initializes this {@link MalisisRenderer}. Does nothing by default.<br> * Called the first time a rendering is done and should be overridden if some setup is needed for the rendering (building shape and * parameters). */ protected void initialize() {} /** * Renders the blocks using the default Minecraft rendering system. */ public void renderStandard() { Minecraft.getMinecraft().getBlockRendererDispatcher().renderBlock(blockState, pos, world, buffer); } /** * Main rendering method. Draws simple cube by default.<br> * Should be overridden to handle the rendering. */ public void render() { drawShape(new Cube()); } protected void drawModel(MalisisModel model, RenderParameters params) { for (Shape s : model) drawShape(s, params); } /** * Draws a {@link Shape} without {@link RenderParameters} (default will be used). * * @param shape the shape */ public void drawShape(Shape shape) { drawShape(shape, null); } /** * Draws a {@link Shape} with specified {@link RenderParameters}. * * @param s the s * @param params the params */ public void drawShape(Shape s, RenderParameters params) { if (s == null) return; s.applyMatrix(); for (Face f : s.getFaces()) drawFace(f, params); } /** * Draws a {@link Face} with its own {@link RenderParameters}. * * @param face the face */ protected void drawFace(Face face) { drawFace(face, null); } /** * Draws a {@link Face} with specified {@link RenderParameters}. * * @param face the f * @param params the face params */ protected void drawFace(Face face, RenderParameters params) { if (face == null) return; int vertexCount = face.getVertexes().length; if (vertexCount != 4 && renderType == RenderType.BLOCK) { MalisisCore.log.error( "[MalisisRenderer] Attempting to render a face containing {} vertexes in BLOCK for {}. Ignored", vertexCount, block); return; } if (params == null) params = face.getParameters(); if (params.deductParameters.get()) face.deductParameters(); params = RenderParameters.merge(params, face.getParameters()); if (!shouldRenderFace(face, params)) return; if (params.applyTexture.get()) applyTexture(face, params); baseBrightness = getBaseBrightness(params); //debug // if (vertexCount != 4) // params.colorMultiplier.set(0xFF0000); for (int i = 0; i < face.getVertexes().length; i++) drawVertex(face.getVertexes()[i], i, params); //use normals if available // if ((renderType == RenderType.ITEM || params.useNormals.get()) && params.direction.get() != null) // buffer.putNormal(params.direction.get().getFrontOffsetX(), // params.direction.get().getFrontOffsetY(), // params.direction.get().getFrontOffsetZ()); //we need to separate each face if (drawMode == GL11.GL_POLYGON || drawMode == GL11.GL_LINE || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP) next(); } /** * Draws a single {@link Vertex}. * * @param vertex the vertex * @param number the offset inside the face. (Used for AO) */ protected void drawVertex(Vertex vertex, int number, RenderParameters params) { if (vertex == null) vertex = new Vertex(0, 0, 0); // brightness int brightness = calcVertexBrightness(vertex, number, params); //brightness = 255; vertex.setBrightness(brightness); // color int color = calcVertexColor(vertex, number, params); vertex.setColor(color); // alpha if (params != null && !params.usePerVertexAlpha.get()) vertex.setAlpha(params.alpha.get()); if (params != null && renderType == RenderType.ITEM) vertex.setNormal(params.direction.get()); buffer.addVertexData(vertex.getVertexData(vertexFormat, posOffset)); vertexDrawn = true; } /** * Draws a string at the specified coordinates, with color and shadow. The string gets translated. Uses FontRenderer.drawString(). * * @param font the font * @param text the text * @param x the x * @param y the y * @param z the z * @param fro the fro */ public void drawText(MalisisFont font, String text, float x, float y, float z, FontOptions fro) { if (font == null) font = MalisisFont.minecraftFont; if (fro == null) fro = FontOptions.builder().build(); font.render(this, text, x, y, z, fro); } /** * Checks if a {@link Face} should be rendered. {@link RenderParameters#direction} needs to be defined for the <b>face</b>. * * @param face the face * @return true, if successful */ protected boolean shouldRenderFace(Face face, RenderParameters params) { if (renderType != RenderType.BLOCK || world == null || block == null) return true; if (params != null && params.renderAllFaces.get()) return true; RenderParameters p = face.getParameters(); if (p.direction.get() == null || p.renderAllFaces.get()) return true; if (ISmartCull.shouldSmartCull(block)) return smartCull(face, params); boolean b = blockState.shouldSideBeRendered(world, pos, p.direction.get()); return b; } /** * Culls a face based on the actual render bounds used and not block bounding box. * * @param face the face * @param params the params * @return true, if successful */ protected boolean smartCull(Face face, RenderParameters params) { EnumFacing side = params.direction.get(); AxisAlignedBB bounds = getRenderBounds(params); if (side == EnumFacing.DOWN && bounds.minY > 0) return true; if (side == EnumFacing.UP && bounds.maxY < 1) return true; if (side == EnumFacing.NORTH && bounds.minZ > 0) return true; if (side == EnumFacing.SOUTH && bounds.maxZ < 1) return true; if (side == EnumFacing.WEST && bounds.minX > 0) return true; if (side == EnumFacing.EAST && bounds.maxX < 1) return true; return !world.getBlockState(pos.offset(side)).isOpaqueCube(); } /** * Applies the texture to the {@link Shape}.<br> * Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to * <code>false</code> to prevent reapplying texture when rendering. * * @param shape the shape */ public void applyTexture(Shape shape) { applyTexture(shape, null); } /** * Applies the texture to the {@link Shape} with specified {@link RenderParameters}.<br> * Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to * <code>false</code> to prevent reapplying texture when rendering. * * @param shape the shape * @param params the parameters */ public void applyTexture(Shape shape, RenderParameters params) { //shape.applyMatrix(); for (Face f : shape.getFaces()) { RenderParameters rp = RenderParameters.merge(params, f.getParameters()); applyTexture(f, rp); } } /** * Applies the texture to the {@link Face} with specified {@link RenderParameters}.<br> * * @param face the face * @param params the parameters */ public void applyTexture(Face face, RenderParameters params) { Icon icon = getIcon(face, params); if (icon == null) icon = Icon.missing; if (shouldRotateIcon(params)) { if (params.textureSide.get() != null && params.textureSide.get().getAxis() == Axis.Y) icon.setRotation(EnumFacingUtils.getRotationCount(blockState)); else icon.setRotation(0); } boolean flipU = params.flipU.get(); //if parameters are deducted, do not flip because the new direction can now NORTH from the last frame if (!params.deductParameters.get() && (params.direction.get() == EnumFacing.NORTH || params.direction.get() == EnumFacing.EAST)) flipU = !flipU; face.setTexture(icon, flipU, params.flipV.get(), params.interpolateUV.get()); } /** * Gets the {@link Icon} corresponding to the specified {@link RenderParameters}.<br> * If {@link #block} or {@link #item} is an {@link IIconProvider} and give the right provider for the current context, gets the icon * from that provider. * * @param face the face * @param params the params * @return the icon */ protected Icon getIcon(Face face, RenderParameters params) { if (params != null && params.icon.get() != null) return params.icon.get(); IIconProvider iconProvider = getIconProvider(params); if (iconProvider instanceof IItemIconProvider && itemStack != null) return ((IItemIconProvider) iconProvider).getIcon(itemStack); if (iconProvider instanceof IBlockIconProvider && block != null) { EnumFacing side = params != null ? params.textureSide.get() : EnumFacing.SOUTH; if (params != null && shouldRotateIcon(params)) side = EnumFacingUtils.getRealSide(blockState, side); IBlockIconProvider iblockp = (IBlockIconProvider) iconProvider; if (renderType == RenderType.BLOCK || renderType == RenderType.TILE_ENTITY) return iblockp.getIcon(world, pos, blockState, side); else if (renderType == RenderType.ITEM) return iblockp.getIcon(itemStack, side); } return iconProvider != null ? iconProvider.getIcon() : Icon.missing; } /** * Gets the {@link IIconProvider} either from parameters, the block or the item. * * @return the icon provider */ protected IIconProvider getIconProvider(RenderParameters params) { if (params != null && params.iconProvider.get() != null) return params.iconProvider.get(); IIconProvider provider = IComponent.getComponent(IIconProvider.class, item); if (provider == null) provider = IComponent.getComponent(IIconProvider.class, block); return provider; } protected boolean shouldRotateIcon(RenderParameters params) { return blockState != null && params.rotateIcon.get(); } /** * Calculates the ambient occlusion for a {@link Vertex} and also applies the side dependent shade.<br> * <b>aoMatrix</b> is the list of block coordinates necessary to compute AO. If it's empty, only the global face shade is applied.<br> * Also, <i>params.colorMultiplier</i> is applied as well. * * @param vertex the vertex * @param number the number * @param params the params * @return the int */ protected int calcVertexColor(Vertex vertex, int number, RenderParameters params) { int color = 0xFFFFFF; if (params == null) return color; if (params.usePerVertexColor.get()) //vertex should use their own colors color = vertex.getColor(); else if (params.colorMultiplier.get() != null) //global color multiplier is set color = params.colorMultiplier.get(); else if (block != null) //use block color multiplier color = Minecraft.getMinecraft().getBlockColors().colorMultiplier(blockState, world, pos, 0); //color = world != null ? block.colorMultiplier(world, pos, 0) : block.getRenderColor(blockState); if (drawMode == GL11.GL_LINES) //no AO for lines return color; if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //no AO for item/inventories return color; int[][] aoMatrix = (int[][]) params.aoMatrix.get(number); float factor = 1; //calculate AO if (params.calculateAOColor.get() && aoMatrix != null && Minecraft.isAmbientOcclusionEnabled() && blockState.getLightValue(world, pos) == 0 && params.direction.get() != null) { factor = getBlockAmbientOcclusion(world, pos.offset(params.direction.get())); for (int i = 0; i < aoMatrix.length; i++) factor += getBlockAmbientOcclusion(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2])); factor /= (aoMatrix.length + 1); } //apply face dependent shading factor *= params.colorFactor.get(); int r = (int) ((color >> 16 & 255) * factor); int g = (int) ((color >> 8 & 255) * factor); int b = (int) ((color & 255) * factor); color = r << 16 | g << 8 | b; return color; } /** * Gets the base brightness for the current {@link Face}.<br> * If <i>params.useBlockBrightness</i> = false, <i>params.brightness</i>. Else, the brightness is determined based on * <i>params.offset</i> and <i>getBlockBounds()</i> * * @param params the params * @return the base brightness */ @SuppressWarnings("deprecation") protected int getBaseBrightness(RenderParameters params) { if (!params.useEnvironmentBrightness.get()) return params.brightness.get(); if (block != null) { if (world != null && blockState.getLightValue(world, pos) != 0) return blockState.getLightValue(world, pos) << 4; else if (blockState.getLightValue() != 0) return blockState.getLightValue() << 4; } if (renderType == RenderType.ITEM) return Utils.getClientPlayer().getBrightnessForRender(); //not in world if (world == null || block == null) return params.brightness.get(); //no direction, we can only use current block brightness if (params.direction.get() == null && block != null) return blockState.getPackedLightmapCoords(world, pos); AxisAlignedBB bounds = getRenderBounds(params); EnumFacing dir = params.direction.get(); BlockPos p = pos; //use the brightness of the block next to it //TODO: check if face is actually at bounds if (bounds != null) { if (dir == EnumFacing.WEST && bounds.minX <= 0) p = p.west(); else if (dir == EnumFacing.EAST && bounds.maxX >= 1) p = p.east(); else if (dir == EnumFacing.NORTH && bounds.minZ <= 0) p = p.north(); else if (dir == EnumFacing.SOUTH && bounds.maxZ >= 1) p = p.south(); else if (dir == EnumFacing.DOWN && bounds.minY <= 0) p = p.down(); else if (dir == EnumFacing.UP && bounds.maxY >= 1) p = p.up(); } return getMixedBrightnessForBlock(world, p); } /** * Calculates the ambient occlusion brightness for a {@link Vertex}. <b>aoMatrix</b> is the list of block coordinates necessary to * compute AO. Only first 3 blocks are used.<br> * * @param vertex the vertex * @param number the number * @param params the params * @return the int */ protected int calcVertexBrightness(Vertex vertex, int number, RenderParameters params) { if (params == null) return baseBrightness; if (params.usePerVertexBrightness.get()) return vertex.getBrightness(); if (drawMode == GL11.GL_LINE) //no AO for lines return baseBrightness; if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //not in world return baseBrightness; int[][] aoMatrix = (int[][]) params.aoMatrix.get(number); if (!params.calculateBrightness.get() || aoMatrix == null) //no data return baseBrightness; if (!Minecraft.isAmbientOcclusionEnabled() || blockState.getLightValue(world, pos) != 0) // emit light return baseBrightness; int[] b = new int[Math.max(3, aoMatrix.length)]; for (int i = 0; i < b.length; i++) b[i] += getMixedBrightnessForBlock(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2])); int brightness = getAoBrightness(b[0], b[1], b[2], baseBrightness); return brightness; } /** * Does the actual brightness calculation (copied from net.minecraft.client.renderer.BlocksRenderer.java) * * @param b1 the b1 * @param b2 the b2 * @param b3 the b3 * @param base the base * @return the ao brightness */ protected int getAoBrightness(int b1, int b2, int b3, int base) { if (b1 == 0) b1 = base; if (b2 == 0) b2 = base; if (b3 == 0) b3 = base; return b1 + b2 + b3 + base >> 2 & 16711935; } /** * Gets the block ambient occlusion value. Contrary to base Minecraft code, it's the actual block at the <b>x</b>, <b>y</b> and <b>z</b> * coordinates which is used to get the value, and not value of the block drawn. This allows to have different logic behaviors for AO * values for a block. * * @param world the world * @param pos the pos * @return the block ambient occlusion */ protected float getBlockAmbientOcclusion(IBlockAccess world, BlockPos pos) { return world.getBlockState(pos).getAmbientOcclusionLightValue(); } /** * Gets the mix brightness for a block (sky + block source). * * @param world the world * @param pos the pos * @return the mixed brightness for block */ protected int getMixedBrightnessForBlock(IBlockAccess world, BlockPos pos) { // return world.getLightBrightnessForSkyBlocks(x, y, z, 0); return world.getBlockState(pos).getPackedLightmapCoords(world, pos); } /** * Gets the rendering bounds. If <i>params.useBlockBounds</i> = false, <i>params.renderBounds</i> is used instead of the actual block * bounds. * * @param params the params * @return the render bounds */ protected AxisAlignedBB getRenderBounds(RenderParameters params) { if (params != null && !params.useBlockBounds.get()) return params.renderBounds.get(); if (block instanceof IBoundingBox) return ((IBoundingBox) block).getBoundingBox(world, pos, blockState, BoundingBoxType.RENDER); if (blockState != null && world != null) return blockState.getBoundingBox(world, pos); return AABBUtils.identity(); } public static float getPartialTick() { return Minecraft.getMinecraft().func_193989_ak(); } /** * Gets the current {@link BlockRenderLayer}. * * @return the render layer */ public static BlockRenderLayer getRenderLayer() { return MinecraftForgeClient.getRenderLayer(); } /** * Registers this {@link MalisisRenderer} to be used for rendering the {@link Block}.<br> * * @param block the block */ public void registerFor(Block block) { MalisisRegistry.registerBlockRenderer(block, this); } /** * Registers this {@link MalisisRenderer} to be used for rendering the {@link Item}.<br> * * @param item the item */ public void registerFor(Item item) { MalisisRegistry.registerItemRenderer(item, this); } /** * Registers this {@link MalisisRenderer} to be used for rendering the {@link TileEntity}. * * @param clazz the clazz */ public void registerFor(Class<? extends T> clazz) { ClientRegistry.bindTileEntitySpecialRenderer(clazz, this); } /** * Registers this {@link MalisisRenderer} to be used for {@link RenderWorldLastEvent}. */ public void registerForRenderWorldLast() { MalisisRegistry.registerRenderWorldLast(this); } public static int colorMultiplier(IBlockAccess world, BlockPos pos, IBlockState state) { return Minecraft.getMinecraft().getBlockColors().colorMultiplier(state, world, pos, 0); } }
package net.ossindex.version.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.zafarkhaja.semver.Version; import com.github.zafarkhaja.semver.expr.LexerException; import com.github.zafarkhaja.semver.expr.UnexpectedTokenException; import net.ossindex.version.IVersion; public class SemanticVersion implements Comparable<IVersion>, IVersion { private static final Logger LOG = LoggerFactory.getLogger(SemanticVersion.class); private Version v; /** Use an external library for parsing. * * @param buf Version we are trying to parse */ public SemanticVersion(String buf) { setVersion(buf); } // Used by subclasses only protected SemanticVersion() { } /** Set the version * * @param buf Version we are trying to parse */ protected void setVersion(String buf) { v = Version.valueOf(buf); } /* * (non-Javadoc) * @see net.ossindex.version.IVersion#getMajor() */ @Override public int getMajor() { if(v == null) return 0; return v.getMajorVersion(); } /* * (non-Javadoc) * @see net.ossindex.version.IVersion#getMinor() */ @Override public int getMinor() { if(v == null) return 0; return v.getMinorVersion(); } /* * (non-Javadoc) * @see net.ossindex.version.IVersion#getPatch() */ @Override public int getPatch() { if(v == null) return 0; return v.getPatchVersion(); } /* * (non-Javadoc) * @see net.ossindex.version.IVersion#satisfies(java.lang.String) */ @Override public boolean satisfies(String range) { if(v == null) return false; // Convert some range variants to what the Version class expects if(range.endsWith(".x")) range = range.substring(0, range.length() - 2); try { return v.satisfies(range); } catch(LexerException | UnexpectedTokenException e) { LOG.warn("Exception checking range [" + range + "] against version [" + v + "]: " + e.getMessage()); } return false; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if(o instanceof SemanticVersion) { SemanticVersion v = (SemanticVersion)o; if(this.v != null) { return this.v.equals(v.v); } else { return super.equals(v); } } return false; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { if(v != null) { return v.hashCode(); } return super.hashCode(); } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(IVersion other) { if(other instanceof SemanticVersion) { SemanticVersion sv = (SemanticVersion)other; // If neither is named, then compare them as semantic values return this.v.compareTo(sv.v); } else { throw new UnsupportedOperationException(); } } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return v.toString(); } /** Returns true if this represents a stable release. We take this to mean * unnamed and no suffix. * * @return True if this is a stable release. */ public boolean isStable() { return true; } }
package no.uio.ifi.trackfind.frontend; import com.vaadin.server.VaadinRequest; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.ui.*; import no.uio.ifi.trackfind.backend.services.TrackFindService; import no.uio.ifi.trackfind.frontend.data.TreeNode; import no.uio.ifi.trackfind.frontend.providers.TrackDataProvider; import org.springframework.beans.factory.annotation.Autowired; @SpringUI public class TrackFindUI extends UI { private final TrackFindService trackFindService; @Autowired public TrackFindUI(TrackFindService trackFindService) { this.trackFindService = trackFindService; } @Override protected void init(VaadinRequest vaadinRequest) { Tree<TreeNode> tree = new Tree<>(); tree.setSelectionMode(Grid.SelectionMode.MULTI); tree.setWidth(30, Unit.PERCENTAGE); TrackDataProvider trackDataProvider = new TrackDataProvider(new TreeNode(trackFindService.getMetamodelTree())); tree.setDataProvider(trackDataProvider); HorizontalLayout headerLayout = new HorizontalLayout(); Panel treePanel = new Panel("Metamodel", tree); treePanel.setSizeFull(); VerticalLayout treeLayout = new VerticalLayout(treePanel); treeLayout.setSizeFull(); treeLayout.setExpandRatio(treePanel, 1f); Panel midPanel = new Panel("Something"); VerticalLayout midLayout = new VerticalLayout(midPanel); Panel dataPanel = new Panel("Data"); VerticalLayout dataLayout = new VerticalLayout(dataPanel); HorizontalLayout mainLayout = new HorizontalLayout(treeLayout, midLayout, dataLayout); mainLayout.setSizeFull(); HorizontalLayout footerLayout = new HorizontalLayout(); VerticalLayout outerLayout = new VerticalLayout(headerLayout, mainLayout, footerLayout); outerLayout.setSizeFull(); outerLayout.setExpandRatio(mainLayout, 1f); setContent(outerLayout); } }
package org.blockartistry.mod.Pathways; import org.apache.commons.lang3.StringUtils; import net.minecraftforge.common.config.Configuration; public final class ModOptions { private ModOptions() { } protected static final String CATEGORY_LOGGING_CONTROL = "logging"; protected static final String CONFIG_ENABLE_DEBUG_LOGGING = "Enable Debug Logging"; protected static boolean enableDebugLogging = false; protected static final String CONFIG_ENABLE_ONLINE_VERSION_CHECK = "Enable Online Version Check"; protected static boolean enableVersionChecking = true; protected static final String CATEGORY_GLOBAL = "global"; protected static final String CONFIG_MAX_TELEPORT_ATTEMPTS = "Max Teleport Attempts"; protected static int maxTeleportAttempts = 5; protected static final String CONFIG_TIME_BETWEEN_ATTEMPTS = "Wait Between Attempts"; protected static int timeBetweenAttempts = 10; protected static final String CONFIG_ALLOW_WATER_LANDING = "Allow Water Landings"; protected static boolean allowWaterLandings = false; protected static final String CATEGORY_COMMANDS = "commands"; protected static final String CONFIG_COMMAND_ALIAS = "Command Alias"; protected static final String CONFIG_COMMAND_OP_ONLY = "Op Only"; protected static final String CATEGORY_TELEPORT = "commands.teleport"; protected static String commandTeleportAlias = "port,tele"; protected static boolean commandTeleportOpOnly = true; protected static final String CATEGORY_CONFIGURE = "commands.configure"; protected static String commandConfigureAlias = "tconfig,tc"; protected static boolean commandConfigureOpOnly = true; public static void load(final Configuration config) { // CATEGORY: Logging String comment = "Enables/disables debug logging of the mod"; enableDebugLogging = config.getBoolean(CONFIG_ENABLE_DEBUG_LOGGING, CATEGORY_LOGGING_CONTROL, enableDebugLogging, comment); comment = "Enables/disables online version checking"; enableVersionChecking = config.getBoolean(CONFIG_ENABLE_ONLINE_VERSION_CHECK, CATEGORY_LOGGING_CONTROL, enableVersionChecking, comment); // CATEGORY: Global comment = "Max attempts at teleport for a given execution"; maxTeleportAttempts = config.getInt(CONFIG_MAX_TELEPORT_ATTEMPTS, CATEGORY_GLOBAL, maxTeleportAttempts, 1, 100, comment); comment = "Wait time between attempts in seconds"; timeBetweenAttempts = config.getInt(CONFIG_TIME_BETWEEN_ATTEMPTS, CATEGORY_GLOBAL, timeBetweenAttempts, 0, 60 * 15, comment); comment = "Allow teleport landings in water"; allowWaterLandings = config.getBoolean(CONFIG_ALLOW_WATER_LANDING, CATEGORY_GLOBAL, allowWaterLandings, comment); // CATEGORY: command.teleport comment = "Alias names for the /teleport command"; commandTeleportAlias = config.getString(CONFIG_COMMAND_ALIAS, CATEGORY_TELEPORT, commandTeleportAlias, comment); comment = "Restrict teleport command to ops"; commandTeleportOpOnly = config.getBoolean(CONFIG_COMMAND_OP_ONLY, CATEGORY_TELEPORT, commandTeleportOpOnly, comment); // CATEGORY: command.configure comment = "Alias names for the /tconfigure command"; commandConfigureAlias = config.getString(CONFIG_COMMAND_ALIAS, CATEGORY_CONFIGURE, commandConfigureAlias, comment); comment = "Restrict configure command to ops"; commandConfigureOpOnly = config.getBoolean(CONFIG_COMMAND_OP_ONLY, CATEGORY_CONFIGURE, commandConfigureOpOnly, comment); } public static boolean getEnableDebugLogging() { return enableDebugLogging; } public static boolean getOnlineVersionChecking() { return enableVersionChecking; } public static int getMaxTeleportAttempts() { return maxTeleportAttempts; } public static int getTimeBetweenAttempts() { return timeBetweenAttempts; } public static boolean getAllowWaterLandings() { return allowWaterLandings; } public static String[] getTeleportCommandAlias() { return StringUtils.split(commandTeleportAlias, ','); } public static boolean getCommandTeleportOpOnly() { return commandTeleportOpOnly; } public static String[] getConfigureCommandAlias() { return StringUtils.split(commandConfigureAlias, ','); } public static boolean getCommandConfigureOpOnly() { return commandConfigureOpOnly; } }
package org.bouncycastle.crypto.tls; public class ExtensionType { /* * RFC 6066 1.1. */ public static final int server_name = 0; public static final int max_fragment_length = 1; public static final int client_certificate_url = 2; public static final int trusted_ca_keys = 3; public static final int truncated_hmac = 4; public static final int status_request = 5; /* * RFC 4492 5.1. */ public static final int elliptic_curves = 10; public static final int ec_point_formats = 11; /* * RFC 5054 2.8.1. */ public static final int srp = 12; /* * RFC 5246 7.4.1.4. */ public static final int signature_algorithms = 13; /* * RFC 5746 3.2. */ public static final int renegotiation_info = 0xff01; }
package org.codehaus.plexus.util; import java.io.File; import java.io.IOException; import java.util.Vector; /** * Class for scanning a directory for files/directories which match certain * criteria. * <p> * These criteria consist of selectors and patterns which have been specified. * With the selectors you can select which files you want to have included. * Files which are not selected are excluded. With patterns you can include * or exclude files based on their filename. * <p> * The idea is simple. A given directory is recursively scanned for all files * and directories. Each file/directory is matched against a set of selectors, * including special support for matching against filenames with include and * and exclude patterns. Only files/directories which match at least one * pattern of the include pattern list or other file selector, and don't match * any pattern of the exclude pattern list or fail to match against a required * selector will be placed in the list of files/directories found. * <p> * When no list of include patterns is supplied, "**" will be used, which * means that everything will be matched. When no list of exclude patterns is * supplied, an empty list is used, such that nothing will be excluded. When * no selectors are supplied, none are applied. * <p> * The filename pattern matching is done as follows: * The name to be matched is split up in path segments. A path segment is the * name of a directory or file, which is bounded by * <code>File.separator</code> ('/' under UNIX, '\' under Windows). * For example, "abc/def/ghi/xyz.java" is split up in the segments "abc", * "def","ghi" and "xyz.java". * The same is done for the pattern against which should be matched. * <p> * The segments of the name and the pattern are then matched against each * other. When '**' is used for a path segment in the pattern, it matches * zero or more path segments of the name. * <p> * There is a special case regarding the use of <code>File.separator</code>s * at the beginning of the pattern and the string to match:<br> * When a pattern starts with a <code>File.separator</code>, the string * to match must also start with a <code>File.separator</code>. * When a pattern does not start with a <code>File.separator</code>, the * string to match may not start with a <code>File.separator</code>. * When one of these rules is not obeyed, the string will not * match. * <p> * When a name path segment is matched against a pattern path segment, the * following special characters can be used:<br> * '*' matches zero or more characters<br> * '?' matches one character. * <p> * Examples: * <p> * "**\*.class" matches all .class files/dirs in a directory tree. * <p> * "test\a??.java" matches all files/dirs which start with an 'a', then two * more characters and then ".java", in a directory called test. * <p> * "**" matches everything in a directory tree. * <p> * "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where * there is a parent directory called test (e.g. "abc\test\def\ghi\XYZ123"). * <p> * Case sensitivity may be turned off if necessary. By default, it is * turned on. * <p> * Example of usage: * <pre> * String[] includes = {"**\\*.class"}; * String[] excludes = {"modules\\*\\**"}; * ds.setIncludes(includes); * ds.setExcludes(excludes); * ds.setBasedir(new File("test")); * ds.setCaseSensitive(true); * ds.scan(); * * System.out.println("FILES:"); * String[] files = ds.getIncludedFiles(); * for (int i = 0; i < files.length; i++) { * System.out.println(files[i]); * } * </pre> * This will scan a directory called test for .class files, but excludes all * files in all proper subdirectories of a directory called "modules" * * @author Arnout J. Kuiper * <a href="mailto:ajkuiper@wxs.nl">ajkuiper@wxs.nl</a> * @author Magesh Umasankar * @author <a href="mailto:bruce@callenish.com">Bruce Atherton</a> * @author <a href="mailto:levylambert@tiscali-dsl.de">Antoine Levy-Lambert</a> */ public class DirectoryScanner { /** * Patterns which should be excluded by default. * * @see #addDefaultExcludes() */ public static final String[] DEFAULTEXCLUDES = { // Miscellaneous typical temporary files "**/*~", "**/ "**/. "**/%*%", "**/._*", // CVS "**/CVS", "**/CVS/**", "**/.cvsignore", // SCCS "**/SCCS", "**/SCCS/**", // Visual SourceSafe "**/vssver.scc", // Subversion "**/.svn", "**/.svn/**", // Arch/Bazaar "**/.arch-ids", "**/.arch-ids/**", // Mac "**/.DS_Store" }; /** The base directory to be scanned. */ protected File basedir; /** The patterns for the files to be included. */ protected String[] includes; /** The patterns for the files to be excluded. */ protected String[] excludes; /** The files which matched at least one include and no excludes * and were selected. */ protected Vector filesIncluded; /** The files which did not match any includes or selectors. */ protected Vector filesNotIncluded; /** * The files which matched at least one include and at least * one exclude. */ protected Vector filesExcluded; /** The directories which matched at least one include and no excludes * and were selected. */ protected Vector dirsIncluded; /** The directories which were found and did not match any includes. */ protected Vector dirsNotIncluded; /** * The directories which matched at least one include and at least one * exclude. */ protected Vector dirsExcluded; /** The files which matched at least one include and no excludes and * which a selector discarded. */ protected Vector filesDeselected; /** The directories which matched at least one include and no excludes * but which a selector discarded. */ protected Vector dirsDeselected; /** Whether or not our results were built by a slow scan. */ protected boolean haveSlowResults = false; /** * Whether or not the file system should be treated as a case sensitive * one. */ protected boolean isCaseSensitive = true; /** * Whether or not symbolic links should be followed. * * @since Ant 1.5 */ private boolean followSymlinks = true; /** Whether or not everything tested so far has been included. */ protected boolean everythingIncluded = true; /** * Sole constructor. */ public DirectoryScanner() { } /** * Tests whether or not a given path matches the start of a given * pattern up to the first "**". * <p> * This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * * @return whether or not a given path matches the start of a given * pattern up to the first "**". */ protected static boolean matchPatternStart( String pattern, String str ) { return SelectorUtils.matchPatternStart( pattern, str ); } /** * Tests whether or not a given path matches the start of a given * pattern up to the first "**". * <p> * This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * @return whether or not a given path matches the start of a given * pattern up to the first "**". */ protected static boolean matchPatternStart( String pattern, String str, boolean isCaseSensitive ) { return SelectorUtils.matchPatternStart( pattern, str, isCaseSensitive ); } /** * Tests whether or not a given path matches a given pattern. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * * @return <code>true</code> if the pattern matches against the string, * or <code>false</code> otherwise. */ protected static boolean matchPath( String pattern, String str ) { return SelectorUtils.matchPath( pattern, str ); } /** * Tests whether or not a given path matches a given pattern. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * @return <code>true</code> if the pattern matches against the string, * or <code>false</code> otherwise. */ protected static boolean matchPath( String pattern, String str, boolean isCaseSensitive ) { return SelectorUtils.matchPath( pattern, str, isCaseSensitive ); } /** * Tests whether or not a string matches against a pattern. * The pattern may contain two special characters:<br> * '*' means zero or more characters<br> * '?' means one and only one character * * @param pattern The pattern to match against. * Must not be <code>null</code>. * @param str The string which must be matched against the pattern. * Must not be <code>null</code>. * * @return <code>true</code> if the string matches against the pattern, * or <code>false</code> otherwise. */ public static boolean match( String pattern, String str ) { return SelectorUtils.match( pattern, str ); } /** * Tests whether or not a string matches against a pattern. * The pattern may contain two special characters:<br> * '*' means zero or more characters<br> * '?' means one and only one character * * @param pattern The pattern to match against. * Must not be <code>null</code>. * @param str The string which must be matched against the pattern. * Must not be <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * * @return <code>true</code> if the string matches against the pattern, * or <code>false</code> otherwise. */ protected static boolean match( String pattern, String str, boolean isCaseSensitive ) { return SelectorUtils.match( pattern, str, isCaseSensitive ); } /** * Sets the base directory to be scanned. This is the directory which is * scanned recursively. All '/' and '\' characters are replaced by * <code>File.separatorChar</code>, so the separator used need not match * <code>File.separatorChar</code>. * * @param basedir The base directory to scan. * Must not be <code>null</code>. */ public void setBasedir( String basedir ) { setBasedir( new File( basedir.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ) ) ); } /** * Sets the base directory to be scanned. This is the directory which is * scanned recursively. * * @param basedir The base directory for scanning. * Should not be <code>null</code>. */ public void setBasedir( File basedir ) { this.basedir = basedir; } /** * Returns the base directory to be scanned. * This is the directory which is scanned recursively. * * @return the base directory to be scanned */ public File getBasedir() { return basedir; } /** * Sets whether or not the file system should be regarded as case sensitive. * * @param isCaseSensitive whether or not the file system should be * regarded as a case sensitive one */ public void setCaseSensitive( boolean isCaseSensitive ) { this.isCaseSensitive = isCaseSensitive; } /** * Sets whether or not symbolic links should be followed. * * @param followSymlinks whether or not symbolic links should be followed */ public void setFollowSymlinks( boolean followSymlinks ) { this.followSymlinks = followSymlinks; } /** * Sets the list of include patterns to use. All '/' and '\' characters * are replaced by <code>File.separatorChar</code>, so the separator used * need not match <code>File.separatorChar</code>. * <p> * When a pattern ends with a '/' or '\', "**" is appended. * * @param includes A list of include patterns. * May be <code>null</code>, indicating that all files * should be included. If a non-<code>null</code> * list is given, all elements must be * non-<code>null</code>. */ public void setIncludes( String[] includes ) { if ( includes == null ) { this.includes = null; } else { this.includes = new String[includes.length]; for ( int i = 0; i < includes.length; i++ ) { String pattern; pattern = includes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); if ( pattern.endsWith( File.separator ) ) { pattern += "**"; } this.includes[i] = pattern; } } } /** * Sets the list of exclude patterns to use. All '/' and '\' characters * are replaced by <code>File.separatorChar</code>, so the separator used * need not match <code>File.separatorChar</code>. * <p> * When a pattern ends with a '/' or '\', "**" is appended. * * @param excludes A list of exclude patterns. * May be <code>null</code>, indicating that no files * should be excluded. If a non-<code>null</code> list is * given, all elements must be non-<code>null</code>. */ public void setExcludes( String[] excludes ) { if ( excludes == null ) { this.excludes = null; } else { this.excludes = new String[excludes.length]; for ( int i = 0; i < excludes.length; i++ ) { String pattern; pattern = excludes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); if ( pattern.endsWith( File.separator ) ) { pattern += "**"; } this.excludes[i] = pattern; } } } /** * Returns whether or not the scanner has included all the files or * directories it has come across so far. * * @return <code>true</code> if all files and directories which have * been found so far have been included. */ public boolean isEverythingIncluded() { return everythingIncluded; } public void scan() throws IllegalStateException { if ( basedir == null ) { throw new IllegalStateException( "No basedir set" ); } if ( !basedir.exists() ) { throw new IllegalStateException( "basedir " + basedir + " does not exist" ); } if ( !basedir.isDirectory() ) { throw new IllegalStateException( "basedir " + basedir + " is not a directory" ); } if ( includes == null ) { // No includes supplied, so set it to 'matches all' includes = new String[1]; includes[0] = "**"; } if ( excludes == null ) { excludes = new String[0]; } filesIncluded = new Vector(); filesNotIncluded = new Vector(); filesExcluded = new Vector(); filesDeselected = new Vector(); dirsIncluded = new Vector(); dirsNotIncluded = new Vector(); dirsExcluded = new Vector(); dirsDeselected = new Vector(); if ( isIncluded( "" ) ) { if ( !isExcluded( "" ) ) { if ( isSelected( "", basedir ) ) { dirsIncluded.addElement( "" ); } else { dirsDeselected.addElement( "" ); } } else { dirsExcluded.addElement( "" ); } } else { dirsNotIncluded.addElement( "" ); } scandir( basedir, "", true ); } /** * Top level invocation for a slow scan. A slow scan builds up a full * list of excluded/included files/directories, whereas a fast scan * will only have full results for included files, as it ignores * directories which can't possibly hold any included files/directories. * <p> * Returns immediately if a slow scan has already been completed. */ protected void slowScan() { if ( haveSlowResults ) { return; } String[] excl = new String[dirsExcluded.size()]; dirsExcluded.copyInto( excl ); String[] notIncl = new String[dirsNotIncluded.size()]; dirsNotIncluded.copyInto( notIncl ); for ( int i = 0; i < excl.length; i++ ) { if ( !couldHoldIncluded( excl[i] ) ) { scandir( new File( basedir, excl[i] ), excl[i] + File.separator, false ); } } for ( int i = 0; i < notIncl.length; i++ ) { if ( !couldHoldIncluded( notIncl[i] ) ) { scandir( new File( basedir, notIncl[i] ), notIncl[i] + File.separator, false ); } } haveSlowResults = true; } /** * Scans the given directory for files and directories. Found files and * directories are placed in their respective collections, based on the * matching of includes, excludes, and the selectors. When a directory * is found, it is scanned recursively. * * @param dir The directory to scan. Must not be <code>null</code>. * @param vpath The path relative to the base directory (needed to * prevent problems with an absolute path when using * dir). Must not be <code>null</code>. * @param fast Whether or not this call is part of a fast scan. * * @see #filesIncluded * @see #filesNotIncluded * @see #filesExcluded * @see #dirsIncluded * @see #dirsNotIncluded * @see #dirsExcluded * @see #slowScan */ protected void scandir( File dir, String vpath, boolean fast ) { String[] newfiles = dir.list(); if ( newfiles == null ) { /* * two reasons are mentioned in the API docs for File.list * (1) dir is not a directory. This is impossible as * we wouldn't get here in this case. * (2) an IO error occurred (why doesn't it throw an exception * then???) */ //throw new Exception( "IO error scanning directory " + dir.getAbsolutePath() ); } if ( !followSymlinks ) { Vector noLinks = new Vector(); for ( int i = 0; i < newfiles.length; i++ ) { try { if ( isSymbolicLink( dir, newfiles[i] ) ) { String name = vpath + newfiles[i]; File file = new File( dir, newfiles[i] ); if ( file.isDirectory() ) { dirsExcluded.addElement( name ); } else { filesExcluded.addElement( name ); } } else { noLinks.addElement( newfiles[i] ); } } catch ( IOException ioe ) { String msg = "IOException caught while checking " + "for links, couldn't get cannonical path!"; // will be caught and redirected to Ant's logging system System.err.println( msg ); noLinks.addElement( newfiles[i] ); } } newfiles = new String[noLinks.size()]; noLinks.copyInto( newfiles ); } for ( int i = 0; i < newfiles.length; i++ ) { String name = vpath + newfiles[i]; File file = new File( dir, newfiles[i] ); if ( file.isDirectory() ) { if ( isIncluded( name ) ) { if ( !isExcluded( name ) ) { if ( isSelected( name, file ) ) { dirsIncluded.addElement( name ); if ( fast ) { scandir( file, name + File.separator, fast ); } } else { everythingIncluded = false; dirsDeselected.addElement( name ); if ( fast && couldHoldIncluded( name ) ) { scandir( file, name + File.separator, fast ); } } } else { everythingIncluded = false; dirsExcluded.addElement( name ); if ( fast && couldHoldIncluded( name ) ) { scandir( file, name + File.separator, fast ); } } } else { everythingIncluded = false; dirsNotIncluded.addElement( name ); if ( fast && couldHoldIncluded( name ) ) { scandir( file, name + File.separator, fast ); } } if ( !fast ) { scandir( file, name + File.separator, fast ); } } else if ( file.isFile() ) { if ( isIncluded( name ) ) { if ( !isExcluded( name ) ) { if ( isSelected( name, file ) ) { filesIncluded.addElement( name ); } else { everythingIncluded = false; filesDeselected.addElement( name ); } } else { everythingIncluded = false; filesExcluded.addElement( name ); } } else { everythingIncluded = false; filesNotIncluded.addElement( name ); } } } } /** * Tests whether or not a name matches against at least one include * pattern. * * @param name The name to match. Must not be <code>null</code>. * @return <code>true</code> when the name matches against at least one * include pattern, or <code>false</code> otherwise. */ protected boolean isIncluded( String name ) { for ( int i = 0; i < includes.length; i++ ) { if ( matchPath( includes[i], name, isCaseSensitive ) ) { return true; } } return false; } /** * Tests whether or not a name matches the start of at least one include * pattern. * * @param name The name to match. Must not be <code>null</code>. * @return <code>true</code> when the name matches against the start of at * least one include pattern, or <code>false</code> otherwise. */ protected boolean couldHoldIncluded( String name ) { for ( int i = 0; i < includes.length; i++ ) { if ( matchPatternStart( includes[i], name, isCaseSensitive ) ) { return true; } } return false; } /** * Tests whether or not a name matches against at least one exclude * pattern. * * @param name The name to match. Must not be <code>null</code>. * @return <code>true</code> when the name matches against at least one * exclude pattern, or <code>false</code> otherwise. */ protected boolean isExcluded( String name ) { for ( int i = 0; i < excludes.length; i++ ) { if ( matchPath( excludes[i], name, isCaseSensitive ) ) { return true; } } return false; } /** * Tests whether a name should be selected. * * @param name the filename to check for selecting * @param file the java.io.File object for this filename * @return <code>false</code> when the selectors says that the file * should not be selected, <code>true</code> otherwise. */ protected boolean isSelected( String name, File file ) { return true; } /** * Returns the names of the files which matched at least one of the * include patterns and none of the exclude patterns. * The names are relative to the base directory. * * @return the names of the files which matched at least one of the * include patterns and none of the exclude patterns. */ public String[] getIncludedFiles() { String[] files = new String[filesIncluded.size()]; filesIncluded.copyInto( files ); return files; } /** * Returns the names of the files which matched none of the include * patterns. The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed. * * @return the names of the files which matched none of the include * patterns. * * @see #slowScan */ public String[] getNotIncludedFiles() { slowScan(); String[] files = new String[filesNotIncluded.size()]; filesNotIncluded.copyInto( files ); return files; } /** * Returns the names of the files which matched at least one of the * include patterns and at least one of the exclude patterns. * The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed. * * @return the names of the files which matched at least one of the * include patterns and at at least one of the exclude patterns. * * @see #slowScan */ public String[] getExcludedFiles() { slowScan(); String[] files = new String[filesExcluded.size()]; filesExcluded.copyInto( files ); return files; } /** * <p>Returns the names of the files which were selected out and * therefore not ultimately included.</p> * * <p>The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed.</p> * * @return the names of the files which were deselected. * * @see #slowScan */ public String[] getDeselectedFiles() { slowScan(); String[] files = new String[filesDeselected.size()]; filesDeselected.copyInto( files ); return files; } /** * Returns the names of the directories which matched at least one of the * include patterns and none of the exclude patterns. * The names are relative to the base directory. * * @return the names of the directories which matched at least one of the * include patterns and none of the exclude patterns. */ public String[] getIncludedDirectories() { String[] directories = new String[dirsIncluded.size()]; dirsIncluded.copyInto( directories ); return directories; } /** * Returns the names of the directories which matched none of the include * patterns. The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed. * * @return the names of the directories which matched none of the include * patterns. * * @see #slowScan */ public String[] getNotIncludedDirectories() { slowScan(); String[] directories = new String[dirsNotIncluded.size()]; dirsNotIncluded.copyInto( directories ); return directories; } /** * Returns the names of the directories which matched at least one of the * include patterns and at least one of the exclude patterns. * The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed. * * @return the names of the directories which matched at least one of the * include patterns and at least one of the exclude patterns. * * @see #slowScan */ public String[] getExcludedDirectories() { slowScan(); String[] directories = new String[dirsExcluded.size()]; dirsExcluded.copyInto( directories ); return directories; } /** * <p>Returns the names of the directories which were selected out and * therefore not ultimately included.</p> * * <p>The names are relative to the base directory. This involves * performing a slow scan if one has not already been completed.</p> * * @return the names of the directories which were deselected. * * @see #slowScan */ public String[] getDeselectedDirectories() { slowScan(); String[] directories = new String[dirsDeselected.size()]; dirsDeselected.copyInto( directories ); return directories; } /** * Adds default exclusions to the current exclusions set. */ public void addDefaultExcludes() { int excludesLength = excludes == null ? 0 : excludes.length; String[] newExcludes; newExcludes = new String[excludesLength + DEFAULTEXCLUDES.length]; if ( excludesLength > 0 ) { System.arraycopy( excludes, 0, newExcludes, 0, excludesLength ); } for ( int i = 0; i < DEFAULTEXCLUDES.length; i++ ) { newExcludes[i + excludesLength] = DEFAULTEXCLUDES[i].replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); } excludes = newExcludes; } /** * Checks whether a given file is a symbolic link. * * <p>It doesn't really test for symbolic links but whether the * canonical and absolute paths of the file are identical - this * may lead to false positives on some platforms.</p> * * @param parent the parent directory of the file to test * @param name the name of the file to test. * * @since Ant 1.5 */ public boolean isSymbolicLink( File parent, String name ) throws IOException { File resolvedParent = new File( parent.getCanonicalPath() ); File toTest = new File( resolvedParent, name ); return !toTest.getAbsolutePath().equals( toTest.getCanonicalPath() ); } }
package org.embulk.input.hdfs; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathNotFoundException; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigInject; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; import org.embulk.spi.BufferAllocator; import org.embulk.spi.Exec; import org.embulk.spi.FileInputPlugin; import org.embulk.spi.TransactionalFileInput; import org.embulk.spi.util.InputStreamTransactionalFileInput; import org.jruby.embed.ScriptingContainer; import org.slf4j.Logger; import javax.annotation.Nullable; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class HdfsFileInputPlugin implements FileInputPlugin { private static final Logger logger = Exec.getLogger(HdfsFileInputPlugin.class); private static FileSystem fs; public interface PluginTask extends Task { @Config("config_files") @ConfigDefault("[]") public List<String> getConfigFiles(); @Config("config") @ConfigDefault("{}") public Map<String, String> getConfig(); @Config("path") public String getPath(); @Config("rewind_seconds") @ConfigDefault("0") public int getRewindSeconds(); @Config("partition") @ConfigDefault("true") public boolean getPartition(); @Config("num_partitions") // this parameter is the approximate value. @ConfigDefault("-1") // Default: Runtime.getRuntime().availableProcessors() public long getApproximateNumPartitions(); @Config("skip_header_lines") // Skip this number of lines first. Set 1 if the file has header line. @ConfigDefault("0") // The reason why the parameter is configured is that this plugin splits files. public int getSkipHeaderLines(); public List<HdfsPartialFile> getFiles(); public void setFiles(List<HdfsPartialFile> hdfsFiles); @ConfigInject public BufferAllocator getBufferAllocator(); } @Override public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); // listing Files String pathString = strftime(task.getPath(), task.getRewindSeconds()); try { List<String> originalFileList = buildFileList(getFs(task), pathString); if (originalFileList.isEmpty()) { throw new PathNotFoundException(pathString); } logger.debug("embulk-input-hdfs: Loading target files: {}", originalFileList); task.setFiles(allocateHdfsFilesToTasks(task, getFs(task), originalFileList)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } // log the detail of partial files. for (HdfsPartialFile partialFile : task.getFiles()) { logger.debug("embulk-input-hdfs: target file: {}, start: {}, end: {}", partialFile.getPath(), partialFile.getStart(), partialFile.getEnd()); } // number of processors is same with number of targets int taskCount = task.getFiles().size(); logger.info("embulk-input-hdfs: task size: {}", taskCount); return resume(task.dump(), taskCount, control); } @Override public ConfigDiff resume(TaskSource taskSource, int taskCount, FileInputPlugin.Control control) { control.run(taskSource, taskCount); ConfigDiff configDiff = Exec.newConfigDiff(); // usually, yo use last_path //if (task.getFiles().isEmpty()) { // if (task.getLastPath().isPresent()) { // configDiff.set("last_path", task.getLastPath().get()); //} else { // List<String> files = new ArrayList<String>(task.getFiles()); // Collections.sort(files); // configDiff.set("last_path", files.get(files.size() - 1)); return configDiff; } @Override public void cleanup(TaskSource taskSource, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalFileInput open(TaskSource taskSource, int taskIndex) { final PluginTask task = taskSource.loadTask(PluginTask.class); InputStream input; final HdfsPartialFile file = task.getFiles().get(taskIndex); try { if (file.getStart() > 0 && task.getSkipHeaderLines() > 0) { input = new SequenceInputStream(getHeadersInputStream(task, file), openInputStream(task, file)); } else { input = openInputStream(task, file); } } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } return new InputStreamTransactionalFileInput(task.getBufferAllocator(), input) { @Override public void abort() { } @Override public TaskReport commit() { return Exec.newTaskReport(); } }; } private InputStream getHeadersInputStream(PluginTask task, HdfsPartialFile partialFile) throws IOException { FileSystem fs = getFs(task); ByteArrayOutputStream header = new ByteArrayOutputStream(); int skippedHeaders = 0; try (BufferedInputStream in = new BufferedInputStream(fs.open(new Path(partialFile.getPath())))) { while (true) { int c = in.read(); if (c < 0) { break; } header.write(c); if (c == '\n') { skippedHeaders++; } else if (c == '\r') { int c2 = in.read(); if (c2 == '\n') { header.write(c2); } skippedHeaders++; } if (skippedHeaders >= task.getSkipHeaderLines()) { break; } } } header.close(); return new ByteArrayInputStream(header.toByteArray()); } private static HdfsPartialFileInputStream openInputStream(PluginTask task, HdfsPartialFile partialFile) throws IOException { FileSystem fs = getFs(task); InputStream original = fs.open(new Path(partialFile.getPath())); return new HdfsPartialFileInputStream(original, partialFile.getStart(), partialFile.getEnd()); } private static FileSystem getFs(final PluginTask task) throws IOException { if (fs == null) { setFs(task); return fs; } else { return fs; } } private static FileSystem setFs(final PluginTask task) throws IOException { Configuration configuration = new Configuration(); for (String configFile : task.getConfigFiles()) { File file = new File(configFile); configuration.addResource(file.toURI().toURL()); } for (Map.Entry<String, String> entry : task.getConfig().entrySet()) { configuration.set(entry.getKey(), entry.getValue()); } // For debug for (Map.Entry<String, String> entry : configuration) { logger.trace("{}: {}", entry.getKey(), entry.getValue()); } logger.debug("Resource Files: {}", configuration); return FileSystem.get(configuration); } private String strftime(final String raw, final int rewindSeconds) { ScriptingContainer jruby = new ScriptingContainer(); Object resolved = jruby.runScriptlet( String.format("(Time.now - %s).strftime('%s')", String.valueOf(rewindSeconds), raw)); return resolved.toString(); } private List<String> buildFileList(final FileSystem fs, final String pathString) throws IOException { List<String> fileList = new ArrayList<>(); Path rootPath = new Path(pathString); final FileStatus[] entries = fs.globStatus(rootPath); // `globStatus` does not throw PathNotFoundException. // return null instead. // see: https://github.com/apache/hadoop/blob/branch-2.7.0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/Globber.java#L286 if (entries == null) { return fileList; } for (FileStatus entry : entries) { if (entry.isDirectory()) { fileList.addAll(lsr(fs, entry)); } else { fileList.add(entry.getPath().toString()); } } return fileList; } private List<String> lsr(final FileSystem fs, FileStatus status) throws IOException { List<String> fileList = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus entry : fs.listStatus(status.getPath())) { fileList.addAll(lsr(fs, entry)); } } else { fileList.add(status.getPath().toString()); } return fileList; } private List<HdfsPartialFile> allocateHdfsFilesToTasks(final PluginTask task, final FileSystem fs, final List<String> fileList) throws IOException { List<Path> pathList = Lists.transform(fileList, new Function<String, Path>() { @Nullable @Override public Path apply(@Nullable String input) { return new Path(input); } }); long totalFileLength = 0; for (Path path : pathList) { totalFileLength += fs.getFileStatus(path).getLen(); } // TODO: optimum allocation of resources long approximateNumPartitions = (task.getApproximateNumPartitions() <= 0) ? Runtime.getRuntime().availableProcessors() : task.getApproximateNumPartitions(); long partitionSizeByOneTask = totalFileLength / approximateNumPartitions; if (partitionSizeByOneTask <= 0) { partitionSizeByOneTask = 1; } List<HdfsPartialFile> hdfsPartialFiles = new ArrayList<>(); for (Path path : pathList) { long fileLength = fs.getFileStatus(path).getLen(); // declare `fileLength` here because this is used below. if (fileLength <= 0) { logger.info("embulk-input-hdfs: Skip the 0 byte target file: {}", path); continue; } long numPartitions; if (path.toString().endsWith(".gz") || path.toString().endsWith(".bz2") || path.toString().endsWith(".lzo")) { numPartitions = 1; } else if (!task.getPartition()) { numPartitions = 1; } else { numPartitions = ((fileLength - 1) / partitionSizeByOneTask) + 1; } HdfsFilePartitioner partitioner = new HdfsFilePartitioner(fs, path, numPartitions); hdfsPartialFiles.addAll(partitioner.getHdfsPartialFiles()); } return hdfsPartialFiles; } }
package org.fiteagle.api.core.usermanagement; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Pattern; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; @Entity @Table(name="USERS", uniqueConstraints=@UniqueConstraint(name="EMAIL", columnNames={"email"})) public class User implements Serializable{ private static final long serialVersionUID = -8580256972066486588L; public enum Role { FEDERATION_ADMIN, NODE_ADMIN, CLASSOWNER, STUDENT } @Id @Column(updatable = false) private String username; private String firstName; private String lastName; private String email; private String affiliation; private Role role; @Temporal(TemporalType.TIMESTAMP) @Column(updatable = false) private Date created; @Temporal(TemporalType.TIMESTAMP) private Date lastModified; private String password; @JsonView(VIEW.INTERNAL.class) private String passwordHash; @JsonView(VIEW.INTERNAL.class) private String passwordSalt; public static class VIEW { public static class PUBLIC{}; static class INTERNAL extends PUBLIC{}; } @JoinColumn(name="node_id") @ManyToOne private Node node; @OneToMany(cascade = CascadeType.PERSIST, orphanRemoval = true, mappedBy="owner") private List<UserPublicKey> publicKeys; @JsonIgnore @ManyToMany(mappedBy="participants", fetch=FetchType.EAGER) private List<Class> joinedClasses; @JsonIgnore @OneToMany(cascade = CascadeType.PERSIST, orphanRemoval = true, mappedBy="owner", fetch=FetchType.EAGER) private List<Class> ownedClasses; private final static Pattern USERNAME_PATTERN = Pattern.compile("[\\w|-|@|.]{3,200}"); private final static Pattern EMAIL_PATTERN = Pattern.compile("[^@]+@{1}[^@]+\\.+[^@]+"); private final static int MINIMUM_FIRST_AND_LASTNAME_LENGTH = 2; private final static int MINIMUM_AFFILITAION_LENGTH = 2; protected User(){ } public User(String username, String firstName, String lastName, String email, String affiliation, Node node, String passwordHash, String passwordSalt, List<UserPublicKey> publicKeys){ this.username = username; this.firstName = firstName; this.lastName = lastName; this.email = email; this.affiliation = affiliation; this.role = Role.STUDENT; this.node = node; this.passwordSalt = passwordSalt; this.passwordHash = passwordHash; this.publicKeys = publicKeys; if(publicKeys == null){ this.publicKeys = new ArrayList<>(); } this.joinedClasses = new ArrayList<>(); this.ownedClasses = new ArrayList<>(); checkAttributes(); } public static User createDefaultUser(String username, String passwordHash, String passwordSalt) { return new User(username, "default", "default", createDefaultEmail(username), "default", Node.defaultNode, passwordHash, passwordSalt, new ArrayList<UserPublicKey>()); } private static String createDefaultEmail(String username) { if(!EMAIL_PATTERN.matcher(username).matches()){ return username+"@test.org"; }else { return username; } } public static User createAdminUser(String username, String passwordHash, String passwordSalt) throws NotEnoughAttributesException, InValidAttributeException{ User admin = new User(username, "default", "default", "default", "default", Node.defaultNode, passwordHash, passwordSalt, null); admin.setRole(Role.FEDERATION_ADMIN); return admin; } private void setOwnersOfPublicKeys(){ if(this.publicKeys != null){ for(UserPublicKey publicKey : this.publicKeys){ publicKey.setOwner(this); } } } private void checkAttributes() throws NotEnoughAttributesException, InValidAttributeException { if(username == null){ throw new NotEnoughAttributesException("no username given"); } if(firstName == null){ this.firstName = "default"; } if(lastName == null){ this.lastName = "default"; } if(email == null){ this.email = "default"; } if(affiliation == null){ this.affiliation = "default"; } if(passwordHash == null || passwordSalt == null || passwordHash.equals("") || passwordSalt.equals("")){ throw new NotEnoughAttributesException("no password given or password too short"); } if(!USERNAME_PATTERN.matcher(username).matches()){ throw new InValidAttributeException("invalid username, only letters, numbers, \"@\", \".\", \"_\", and \"-\" is allowed and the username has to be from 3 to 200 characters long"); } if(firstName.length() < MINIMUM_FIRST_AND_LASTNAME_LENGTH){ throw new InValidAttributeException("firstName too short"); } if(lastName.length() < MINIMUM_FIRST_AND_LASTNAME_LENGTH){ throw new InValidAttributeException("lastName too short"); } if(!EMAIL_PATTERN.matcher(email).matches() && !email.equals("default")){ throw new InValidAttributeException("an email needs to contain \"@\" and \".\""); } if(affiliation.length() < MINIMUM_AFFILITAION_LENGTH){ throw new InValidAttributeException("affiliation too short"); } } @PreUpdate @PrePersist public void updateTimeStampsAndPublicKeys() { setOwnersOfPublicKeys(); lastModified = new Date(); if(created == null) { created = new Date(); } } @PreRemove private void deleteParticipantInClassesAndNode(){ for(Class joinedClass : joinedClasses){ joinedClass.removeParticipant(this); } this.node.removeUser(this); } @SuppressWarnings("unchecked") public void updateAttributes(String firstName, String lastName, String email, String affiliation, String passwordHash, String passwordSalt, List<UserPublicKey> publicKeys) { if(firstName != null){ this.firstName = firstName; } if(lastName != null){ this.lastName = lastName; } if(publicKeys != null && publicKeys.size() != 0){ this.publicKeys = (List<UserPublicKey>)(List<?>) publicKeys; } if(email != null){ this.email = email; } if(affiliation != null){ this.affiliation = affiliation; } if(passwordHash != null && passwordSalt != null && !passwordHash.equals("") && !passwordSalt.equals("")){ this.passwordHash = passwordHash; this.passwordSalt = passwordSalt; } checkAttributes(); } public void addPublicKey(UserPublicKey publicKey){ publicKey.setOwner(this); this.publicKeys.add((UserPublicKey) publicKey); } public void deletePublicKey(String description){ UserPublicKey keyToRemove = null; for(UserPublicKey key : this.publicKeys){ if(key.getDescription().equals(description)){ keyToRemove = key; } } if(keyToRemove != null){ this.publicKeys.remove(keyToRemove); } } public void renamePublicKey(String description, String newDescription){ for(UserPublicKey key : publicKeys){ if(key.getDescription().equals(description)){ key.setDescription(newDescription); return; } } throw new PublicKeyNotFoundException(); } public UserPublicKey getPublicKey(String description){ for(UserPublicKey key : publicKeys){ if(key.getDescription().equals(description)){ return key; } } throw new PublicKeyNotFoundException(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (affiliation == null) { if (other.affiliation != null) return false; } else if (!affiliation.equals(other.affiliation)) return false; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (publicKeys == null) { if (other.publicKeys != null) return false; } else if (!publicKeys.containsAll(other.publicKeys) || publicKeys.size() != other.publicKeys.size()) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "User [username=" + username + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", affiliation=" + affiliation + ", role=" + role + ", created=" + created + ", lastModified=" + lastModified + ", node=" + node + ", publicKeys=" + publicKeys + "]"; } public String getUsername() { return username; } public void setUsername(String username) { if(username == null || !USERNAME_PATTERN.matcher(username).matches()){ throw new InValidAttributeException("invalid username, only letters, numbers, \"@\", \".\", \"_\" and \"-\" is allowed and the username has to be from 3 to 200 characters long"); } this.username = username; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public void setEmail(String email) { if(email == null || (!EMAIL_PATTERN.matcher(email).matches() && !email.equals("default"))){ throw new InValidAttributeException("an email needs to contain \"@\" and \".\""); } this.email = email; } public String getAffiliation() { return affiliation; } public Node getNode() { return node; } public void setNode(Node node) { this.node = node; } public String getPasswordHash(){ return passwordHash; } public void setPasswordHash(String hash){ this.passwordHash = hash; } public String getPasswordSalt(){ return passwordSalt; } public void setPasswordSalt(String salt){ this.passwordSalt = salt; } @JsonIgnore public String getPassword() { return password; } @JsonProperty protected void setPassword(String password) { this.password = password; } public Role getRole() { return role; } public void setRole(Role role) { if(role != null){ this.role = role; } } public Date getCreated() { return created; } public Date getLastModified() { return lastModified; } public List<UserPublicKey> getPublicKeys() { return publicKeys; } public List<Class> getOwnedClasses() { return ownedClasses; } public List<Class> getJoinedClasses() { return joinedClasses; } public void setJoinedClasses(List<Class> targetClasses) { this.joinedClasses = targetClasses; } public boolean hasKeyWithDescription(String description){ for(UserPublicKey key: publicKeys){ if(key.getDescription().equals(description)){ return true; } } return false; } public void addOwnedClass(Class targetClass){ targetClass.setOwner(this); this.ownedClasses.add(targetClass); } public void removeOwnedClass(Class targetClass){ this.ownedClasses.remove(targetClass); } protected void addClass(Class targetClass){ this.joinedClasses.add(targetClass); } protected void removeClass(Class targetClass){ this.joinedClasses.remove(targetClass); } public class PublicKeyNotFoundException extends RuntimeException { private static final long serialVersionUID = 4906415519200726744L; public PublicKeyNotFoundException(){ super("no public key with this description could be found in the database"); } } public static class NotEnoughAttributesException extends RuntimeException { private static final long serialVersionUID = -8279867183643310351L; public NotEnoughAttributesException(){ super(); } public NotEnoughAttributesException(String message){ super(message); } } public static class InValidAttributeException extends RuntimeException { private static final long serialVersionUID = -1299121776233955847L; public InValidAttributeException(){ super(); } public InValidAttributeException(String message){ super(message); } } }
package org.jabref.gui.actions; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.undo.UndoableEdit; import org.jabref.Globals; import org.jabref.gui.BasePanel; import org.jabref.gui.JabRefFrame; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import com.jgoodies.forms.builder.ButtonBarBuilder; import com.jgoodies.forms.builder.FormBuilder; import com.jgoodies.forms.layout.FormLayout; /** * An Action for launching mass field. * * Functionality: * * Defaults to selected entries, or all entries if none are selected. * * Input field name * * Either set field, or clear field. */ public class MassSetFieldAction extends SimpleCommand { private final JabRefFrame frame; private JDialog diag; private JRadioButton all; private JRadioButton selected; private JRadioButton clear; private JRadioButton set; private JRadioButton append; private JRadioButton rename; private JComboBox<String> field; private JTextField textFieldSet; private JTextField textFieldAppend; private JTextField textFieldRename; private boolean canceled = true; private JCheckBox overwrite; public MassSetFieldAction(JabRefFrame frame) { this.frame = frame; } /** * Set a given field to a given value for all entries in a Collection. This method DOES NOT update any UndoManager, * but returns a relevant CompoundEdit that should be registered by the caller. * * @param entries The entries to set the field for. * @param field The name of the field to set. * @param textToSet The value to set. This value can be null, indicating that the field should be cleared. * @param overwriteValues Indicate whether the value should be set even if an entry already has the field set. * @return A CompoundEdit for the entire operation. */ private static UndoableEdit massSetField(Collection<BibEntry> entries, String field, String textToSet, boolean overwriteValues) { NamedCompound compoundEdit = new NamedCompound(Localization.lang("Set field")); for (BibEntry entry : entries) { Optional<String> oldValue = entry.getField(field); // If we are not allowed to overwrite values, check if there is a // nonempty // value already for this entry: if (!overwriteValues && (oldValue.isPresent()) && !oldValue.get().isEmpty()) { continue; } if (textToSet == null) { entry.clearField(field); } else { entry.setField(field, textToSet); } compoundEdit.addEdit(new UndoableFieldChange(entry, field, oldValue.orElse(null), textToSet)); } compoundEdit.end(); return compoundEdit; } private void prepareDialog(boolean selection) { selected.setEnabled(selection); if (selection) { selected.setSelected(true); } else { all.setSelected(true); } // Make sure one of the following ones is selected: if (!set.isSelected() && !clear.isSelected() && !rename.isSelected()) { set.setSelected(true); } } @Override public void execute() { BasePanel bp = frame.getCurrentBasePanel(); if (bp == null) { return; } List<BibEntry> entries = bp.getSelectedEntries(); // Lazy creation of the dialog: if (diag == null) { createDialog(); } canceled = true; prepareDialog(!entries.isEmpty()); if (diag != null) { diag.setVisible(true); } if (canceled) { return; } Collection<BibEntry> entryList; // If all entries should be treated, change the entries array: if (all.isSelected()) { entryList = bp.getDatabase().getEntries(); } else { entryList = entries; } String toSet = textFieldSet.getText(); if (toSet.isEmpty()) { toSet = null; } String[] fields = getFieldNames(((String) field.getSelectedItem()).trim().toLowerCase(Locale.ROOT)); NamedCompound compoundEdit = new NamedCompound(Localization.lang("Set field")); if (rename.isSelected()) { if (fields.length > 1) { frame.getDialogService().showErrorDialogAndWait(Localization.lang("You can only rename one field at a time")); return; // Do not close the dialog. } else { compoundEdit.addEdit(MassSetFieldAction.massRenameField(entryList, fields[0], textFieldRename.getText(), overwrite.isSelected())); } } else if (append.isSelected()) { for (String field : fields) { compoundEdit.addEdit(MassSetFieldAction.massAppendField(entryList, field, textFieldAppend.getText())); } } else { for (String field : fields) { compoundEdit.addEdit(MassSetFieldAction.massSetField(entryList, field, set.isSelected() ? toSet : null, overwrite.isSelected())); } } compoundEdit.end(); bp.getUndoManager().addEdit(compoundEdit); bp.markBaseChanged(); } /** * Append a given value to a given field for all entries in a Collection. This method DOES NOT update any UndoManager, * but returns a relevant CompoundEdit that should be registered by the caller. * * @param entries The entries to process the operation for. * @param field The name of the field to append to. * @param textToAppend The value to set. A null in this case will simply preserve the current field state. * @return A CompoundEdit for the entire operation. */ private static UndoableEdit massAppendField(Collection<BibEntry> entries, String field, String textToAppend) { String newValue = ""; if (textToAppend != null) { newValue = textToAppend; } NamedCompound compoundEdit = new NamedCompound(Localization.lang("Append field")); for (BibEntry entry : entries) { Optional<String> oldValue = entry.getField(field); entry.setField(field, oldValue.orElse("") + newValue); compoundEdit.addEdit(new UndoableFieldChange(entry, field, oldValue.orElse(null), newValue)); } compoundEdit.end(); return compoundEdit; } /** * Move contents from one field to another for a Collection of entries. * * @param entries The entries to do this operation for. * @param field The field to move contents from. * @param newField The field to move contents into. * @param overwriteValues If true, overwrites any existing values in the new field. If false, makes no change for * entries with existing value in the new field. * @return A CompoundEdit for the entire operation. */ private static UndoableEdit massRenameField(Collection<BibEntry> entries, String field, String newField, boolean overwriteValues) { NamedCompound compoundEdit = new NamedCompound(Localization.lang("Rename field")); for (BibEntry entry : entries) { Optional<String> valToMove = entry.getField(field); // If there is no value, do nothing: if ((!valToMove.isPresent()) || valToMove.get().isEmpty()) { continue; } // If we are not allowed to overwrite values, check if there is a // non-empty value already for this entry for the new field: Optional<String> valInNewField = entry.getField(newField); if (!overwriteValues && (valInNewField.isPresent()) && !valInNewField.get().isEmpty()) { continue; } entry.setField(newField, valToMove.get()); compoundEdit.addEdit(new UndoableFieldChange(entry, newField, valInNewField.orElse(null), valToMove.get())); entry.clearField(field); compoundEdit.addEdit(new UndoableFieldChange(entry, field, valToMove.get(), null)); } compoundEdit.end(); return compoundEdit; } private void createDialog() { diag = new JDialog((JFrame) null, Localization.lang("Set/clear/append/rename fields"), true); field = new JComboBox<>(); field.setEditable(true); textFieldSet = new JTextField(); textFieldSet.setEnabled(false); textFieldAppend = new JTextField(); textFieldAppend.setEnabled(false); textFieldRename = new JTextField(); textFieldRename.setEnabled(false); JButton ok = new JButton(Localization.lang("OK")); JButton cancel = new JButton(Localization.lang("Cancel")); all = new JRadioButton(Localization.lang("All entries")); selected = new JRadioButton(Localization.lang("Selected entries")); clear = new JRadioButton(Localization.lang("Clear fields")); set = new JRadioButton(Localization.lang("Set fields")); append = new JRadioButton(Localization.lang("Append to fields")); rename = new JRadioButton(Localization.lang("Rename field to") + ":"); rename.setToolTipText(Localization.lang("Move contents of a field into a field with a different name")); Set<String> allFields = frame.getCurrentBasePanel().getDatabase().getAllVisibleFields(); for (String f : allFields) { field.addItem(f); } set.addChangeListener(e -> // Entering a setText is only relevant if we are setting, not clearing: textFieldSet.setEnabled(set.isSelected())); append.addChangeListener(e -> { // Text to append is only required if we are appending: textFieldAppend.setEnabled(append.isSelected()); // Overwrite protection makes no sense if we are appending to a field: overwrite.setEnabled(!clear.isSelected() && !append.isSelected()); }); clear.addChangeListener(e -> // Overwrite protection makes no sense if we are clearing the field: overwrite.setEnabled(!clear.isSelected() && !append.isSelected())); rename.addChangeListener(e -> // Entering a setText is only relevant if we are renaming textFieldRename.setEnabled(rename.isSelected())); overwrite = new JCheckBox(Localization.lang("Overwrite existing field values"), true); ButtonGroup bg = new ButtonGroup(); bg.add(all); bg.add(selected); bg = new ButtonGroup(); bg.add(clear); bg.add(set); bg.add(append); bg.add(rename); FormBuilder builder = FormBuilder.create().layout(new FormLayout( "left:pref, 4dlu, fill:100dlu:grow", "pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref")); builder.addSeparator(Localization.lang("Field name")).xyw(1, 1, 3); builder.add(Localization.lang("Field name")).xy(1, 3); builder.add(field).xy(3, 3); builder.addSeparator(Localization.lang("Include entries")).xyw(1, 5, 3); builder.add(all).xyw(1, 7, 3); builder.add(selected).xyw(1, 9, 3); builder.addSeparator(Localization.lang("New field value")).xyw(1, 11, 3); builder.add(set).xy(1, 13); builder.add(textFieldSet).xy(3, 13); builder.add(clear).xyw(1, 15, 3); builder.add(append).xy(1, 17); builder.add(textFieldAppend).xy(3, 17); builder.add(rename).xy(1, 19); builder.add(textFieldRename).xy(3, 19); builder.add(overwrite).xyw(1, 21, 3); ButtonBarBuilder bb = new ButtonBarBuilder(); bb.addGlue(); bb.addButton(ok); bb.addButton(cancel); bb.addGlue(); builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER); diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH); diag.pack(); ok.addActionListener(e -> { // Check that any field name is set String fieldText = (String) field.getSelectedItem(); if ((fieldText == null) || fieldText.trim().isEmpty()) { frame.getDialogService().showErrorDialogAndWait(Localization.lang("You must enter at least one field name")); return; // Do not close the dialog. } // Check if the user tries to rename multiple fields: if (rename.isSelected()) { String[] fields = getFieldNames(fieldText); if (fields.length > 1) { frame.getDialogService().showErrorDialogAndWait(Localization.lang("You can only rename one field at a time")); return; // Do not close the dialog. } } canceled = false; diag.dispose(); }); Action cancelAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { canceled = true; diag.dispose(); } }; cancel.addActionListener(cancelAction); // Key bindings: ActionMap am = builder.getPanel().getActionMap(); InputMap im = builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close"); am.put("close", cancelAction); } private static String[] getFieldNames(String s) { return s.split("[\\s;,]"); } }
package org.jenkinsci.plugins; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; import hudson.model.User; import hudson.security.GroupDetails; import hudson.security.SecurityRealm; import hudson.security.UserMayOrMayNotExistException; import hudson.tasks.Mailer; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.acegisecurity.AuthenticationException; import org.acegisecurity.AuthenticationManager; import org.acegisecurity.BadCredentialsException; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.jfree.util.Log; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHUser; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.Header; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.StaplerRequest; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataRetrievalFailureException; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; /** * * Implementation of the AbstractPasswordBasedSecurityRealm that uses github * oauth to verify the user can login. * * This is based on the MySQLSecurityRealm from the mysql-auth-plugin written by * Alex Ackerman. */ public class GithubSecurityRealm extends SecurityRealm { private static final String DEFAULT_WEB_URI = "https://github.com"; private static final String DEFAULT_API_URI = "https://api.github.com"; private static final String DEFAULT_ENTERPRISE_API_SUFFIX = "/api/v3"; @Deprecated private static final String DEFAULT_URI = DEFAULT_WEB_URI; private String githubWebUri; private String githubApiUri; private String clientID; private String clientSecret; /** * @param githubWebUri The URI to the root of the web UI for GitHub or GitHub Enterprise, * including the protocol (e.g. https). * @param githubApiUri The URI to the root of the API for GitHub or GitHub Enterprise, * including the protocol (e.g. https). * @param clientID The client ID for the created OAuth Application. * @param clientSecret The client secret for the created GitHub OAuth Application. */ @DataBoundConstructor public GithubSecurityRealm(String githubWebUri, String githubApiUri, String clientID, String clientSecret) { super(); this.githubWebUri = Util.fixEmptyAndTrim(githubWebUri); this.githubApiUri = Util.fixEmptyAndTrim(githubApiUri); this.clientID = Util.fixEmptyAndTrim(clientID); this.clientSecret = Util.fixEmptyAndTrim(clientSecret); } /** * @deprecated Use {@link GithubSecurityRealm#GithubSecurityRealm(String, String, String, String)} * instead. * * @param githubWebUri The URI to the root of the web UI for GitHub or GitHub Enterprise. * @param clientID The client ID for the created OAuth Application. * @param clientSecret The client secret for the created GitHub OAuth Application. */ @Deprecated public GithubSecurityRealm(String githubWebUri, String clientID, String clientSecret) { super(); this.githubWebUri = Util.fixEmptyAndTrim(githubWebUri); this.githubApiUri = determineApiUri(this.githubWebUri); this.clientID = Util.fixEmptyAndTrim(clientID); this.clientSecret = Util.fixEmptyAndTrim(clientSecret); } private GithubSecurityRealm() { } /** * Tries to automatically determine the GitHub API URI based on * a GitHub Web URI. * * @param githubWebUri The URI to the root of the Web UI for GitHub or GitHub Enterprise. * @return The expected API URI for the given Web UI */ private String determineApiUri(String githubWebUri) { if(githubWebUri.equals(DEFAULT_WEB_URI)) { return DEFAULT_API_URI; } else { return githubWebUri + DEFAULT_ENTERPRISE_API_SUFFIX; } } /** * @param githubWebUri * the string representation of the URI to the root of the Web UI for * GitHub or GitHub Enterprise. */ private void setGithubWebUri(String githubWebUri) { this.githubWebUri = githubWebUri; } /** * @param githubWebUri * the string representation of the URI to the root of the Web UI for * GitHub or GitHub Enterprise. * @deprecated Use {@link GithubSecurityRealm#setGithubWebUri(String)} instead. */ @Deprecated private void setGithubUri(String githubWebUri) { setGithubWebUri(githubWebUri); } /** * @param clientID the clientID to set */ private void setClientID(String clientID) { this.clientID = clientID; } /** * @param clientSecret the clientSecret to set */ private void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } /** * * @return the URI to the API root of GitHub or GitHub Enterprise. */ public String getGithubApiUri() { return githubApiUri; } /** * @param githubApiUri the URI to the API root of GitHub or GitHub Enterprise. */ private void setGithubApiUri(String githubApiUri) { this.githubApiUri = githubApiUri; } public static final class ConverterImpl implements Converter { public boolean canConvert(Class type) { return type == GithubSecurityRealm.class; } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { GithubSecurityRealm realm = (GithubSecurityRealm) source; writer.startNode("githubWebUri"); writer.setValue(realm.getGithubWebUri()); writer.endNode(); writer.startNode("githubApiUri"); writer.setValue(realm.getGithubApiUri()); writer.endNode(); writer.startNode("clientID"); writer.setValue(realm.getClientID()); writer.endNode(); writer.startNode("clientSecret"); writer.setValue(realm.getClientSecret()); writer.endNode(); } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { GithubSecurityRealm realm = new GithubSecurityRealm(); String node; String value; while (reader.hasMoreChildren()) { reader.moveDown(); node = reader.getNodeName(); value = reader.getValue(); setValue(realm, node, value); reader.moveUp(); } if (realm.getGithubWebUri() == null) { realm.setGithubWebUri(DEFAULT_WEB_URI); } if (realm.getGithubApiUri() == null) { realm.setGithubApiUri(DEFAULT_API_URI); } return realm; } private void setValue(GithubSecurityRealm realm, String node, String value) { if (node.toLowerCase().equals("clientid")) { realm.setClientID(value); } else if (node.toLowerCase().equals("clientsecret")) { realm.setClientSecret(value); } else if (node.toLowerCase().equals("githubweburi")) { realm.setGithubWebUri(value); } else if (node.toLowerCase().equals("githuburi")) { // backwards compatibility for old field realm.setGithubWebUri(value); String apiUrl = realm.determineApiUri(value); realm.setGithubApiUri(apiUrl); } else if (node.toLowerCase().equals("githubapiuri")) { realm.setGithubApiUri(value); } else throw new ConversionException("Invalid node value = " + node); } } /** * @return the uri to the web root of Github (varies for Github Enterprise Edition) */ public String getGithubWebUri() { return githubWebUri; } /** * @deprecated use {@link org.jenkinsci.plugins.GithubSecurityRealm#getGithubWebUri()} instead. * @return the uri to the web root of Github (varies for Github Enterprise Edition) */ @Deprecated public String getGithubUri() { return getGithubWebUri(); } /** * @return the clientID */ public String getClientID() { return clientID; } /** * @return the clientSecret */ public String getClientSecret() { return clientSecret; } // @Override // public Filter createFilter(FilterConfig filterConfig) { // return new GithubOAuthAuthenticationFilter(); public HttpResponse doCommenceLogin(StaplerRequest request, @Header("Referer") final String referer) throws IOException { request.getSession().setAttribute(REFERER_ATTRIBUTE,referer); Set<String> scopes = new HashSet<String>(); for (GitHubOAuthScope s : Jenkins.getInstance().getExtensionList(GitHubOAuthScope.class)) { scopes.addAll(s.getScopesToRequest()); } String suffix=""; if (!scopes.isEmpty()) { suffix = "&scope="+Util.join(scopes,","); } return new HttpRedirect(githubWebUri + "/login/oauth/authorize?client_id=" + clientID + suffix); } /** * This is where the user comes back to at the end of the OpenID redirect * ping-pong. */ public HttpResponse doFinishLogin(StaplerRequest request) throws IOException { String code = request.getParameter("code"); if (code == null || code.trim().length() == 0) { Log.info("doFinishLogin: missing code."); return HttpResponses.redirectToContextRoot(); } Log.info("test"); HttpPost httpost = new HttpPost(githubWebUri + "/login/oauth/access_token?" + "client_id=" + clientID + "&" + "client_secret=" + clientSecret + "&" + "code=" + code); DefaultHttpClient httpclient = new DefaultHttpClient(); org.apache.http.HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); String accessToken = extractToken(content); if (accessToken != null && accessToken.trim().length() > 0) { // only set the access token if it exists. GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, getGithubApiUri()); SecurityContextHolder.getContext().setAuthentication(auth); GHUser self = auth.getGitHub().getMyself(); User u = User.current(); u.setFullName(self.getName()); // Set email from github only if empty if (!u.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) { u.addProperty(new Mailer.UserProperty(self.getEmail())); } } else { Log.info("Github did not return an access token."); } String referer = (String)request.getSession().getAttribute(REFERER_ATTRIBUTE); if (referer!=null) return HttpResponses.redirectTo(referer); return HttpResponses.redirectToContextRoot(); // referer should be always there, but be defensive } private String extractToken(String content) { String parts[] = content.split("&"); for (String part : parts) { if (content.contains("access_token")) { String tokenParts[] = part.split("="); return tokenParts[1]; } // fall through } return null; } /* * (non-Javadoc) * * @see hudson.security.SecurityRealm#allowsSignup() */ @Override public boolean allowsSignup() { return false; } @Override public SecurityComponents createSecurityComponents() { return new SecurityComponents(new AuthenticationManager() { public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication instanceof GithubAuthenticationToken) return authentication; throw new BadCredentialsException( "Unexpected authentication type: " + authentication); } }, new UserDetailsService() { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { return GithubSecurityRealm.this.loadUserByUsername(username); } }); } @Override public String getLoginUrl() { return "securityRealm/commenceLogin"; } @Extension public static final class DescriptorImpl extends Descriptor<SecurityRealm> { @Override public String getHelpFile() { return "/plugin/github-oauth/help/help-security-realm.html"; } @Override public String getDisplayName() { return "Github Authentication Plugin"; } public DescriptorImpl() { super(); // TODO Auto-generated constructor stub } public DescriptorImpl(Class<? extends SecurityRealm> clazz) { super(clazz); // TODO Auto-generated constructor stub } } /** * * @param username * @return * @throws UsernameNotFoundException * @throws DataAccessException */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { GHUser user = null; GithubAuthenticationToken authToken = (GithubAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); if (authToken == null) { throw new UserMayOrMayNotExistException("Could not get auth token."); } try { GroupDetails group = null; try { group = loadGroupByGroupname(username); } catch (DataRetrievalFailureException e) { LOGGER.config("No group found with name: " + username); } catch (UsernameNotFoundException e) { LOGGER.config("No group found with name: " + username); } if (group != null) { throw new UsernameNotFoundException ("user("+username+") is also an organization"); } user = authToken.loadUser(username); if (user != null) return new GithubOAuthUserDetails(user); else throw new UsernameNotFoundException("No known user: " + username); } catch (IOException e) { throw new DataRetrievalFailureException("loadUserByUsername (username=" + username +")", e); } } /** * * @param groupName * @return * @throws UsernameNotFoundException * @throws DataAccessException */ @Override public GroupDetails loadGroupByGroupname(String groupName) throws UsernameNotFoundException, DataAccessException { GithubAuthenticationToken authToken = (GithubAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); if(authToken == null) throw new UsernameNotFoundException("No known group: " + groupName); try { GHOrganization org = authToken.loadOrganization(groupName); if (org != null) return new GithubOAuthGroupDetails(org); else throw new UsernameNotFoundException("No known group: " + groupName); } catch (IOException e) { throw new DataRetrievalFailureException("loadGroupByGroupname (groupname=" + groupName +")", e); } } /** * Logger for debugging purposes. */ private static final Logger LOGGER = Logger.getLogger(GithubSecurityRealm.class.getName()); private static final String REFERER_ATTRIBUTE = GithubSecurityRealm.class.getName()+".referer"; }
package org.myrobotlab.framework.repo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.slf4j.Logger; /** * ServiceData class contains all of the Services meta data. This includes : 1. * Dependency information - what libraries are needed to run the class 2. * Categories of the service 3. Peers of the service * * All this information is Service "type" related - non of it is instance * specific. ServiceData has to be created during "build" time since most of the * services contain dependencies which might not be fulfilled during runtime. * * ServiceData.generate() creates serviceData.json which is packaged by the * build in : /resource/framework/serviceData.json * * When MyRobotLab runs for the first time, it will extract this file into the * .myrobotlab directory. * * @author GroG * */ public class ServiceData implements Serializable { private static final long serialVersionUID = 1L; transient public final static Logger log = LoggerFactory.getLogger(ServiceData.class); /** * all services meta data is contained here */ TreeMap<String, ServiceType> serviceTypes = new TreeMap<String, ServiceType>(); /** * the set of all categories */ TreeMap<String, Category> categoryTypes = new TreeMap<String, Category>(); static private ServiceData localInstance = null; static private String serviceDataCacheFileName = String.format("%s%sserviceData.json", FileIO.getCfgDir(), File.separator); static public ServiceData getLocalInstance() { if (localInstance == null) { // step 1 - try local file in the .myrobotlab directory // step 2 - extract the file from the jar // WE CAN NOT GENERATE THIS FILE DURING RUNTIME !!! // step 3 - if 1 & 2 fail - then we can 'assume' were in develop // time (we'll isJar check and error if not) // - generate it and put it in // getRoot()/resource/framework/serviceData.json File jsonFile = new File(serviceDataCacheFileName); try { log.info("try #1 loading local file {}", jsonFile); String data = FileIO.toString(jsonFile); if (data == null || data.length() == 0) { throw new IOException("service data file [{}] contains no data"); } localInstance = CodecUtils.fromJson(data, ServiceData.class); return localInstance; } catch (FileNotFoundException fe) { try { log.info("could not find {}", serviceDataCacheFileName); jsonFile.getParentFile().mkdirs(); String extractFrom = "/resource/framework/serviceData.json"; log.info("try #2 {} not found - extracting from {}", jsonFile.getName(), extractFrom); FileIO.extract(extractFrom, jsonFile.getAbsolutePath()); String data = FileIO.toString(jsonFile); localInstance = CodecUtils.fromJson(data, ServiceData.class); } catch (Exception e) { log.info("could not extract from {}", "/resource/framework/serviceData.json"); String newJson = FileIO.gluePaths(FileIO.getRoot(), "/resource/framework/serviceData.json"); log.info("try #3 serviceData.json not found in resource ! - generating and putting it in {}", newJson); if (FileIO.isJar()) { log.error("we are in a jar! This is very bad!"); } else { log.info("we are not in a jar ... ok I guess we are doing a \"refresh\" on serviceData.json"); } try { ServiceData sd = ServiceData.generate(); String json = CodecUtils.toJson(sd); log.info("saving generated serviceData.json to {}", newJson); FileOutputStream fos = new FileOutputStream(newJson); fos.write(json.getBytes()); fos.close(); log.info("saved -- goodtimes"); localInstance = sd; } catch (Exception e2) { log.error("I've tried everything! .. I give up"); Logging.logError(e2); } } localInstance.save(); } catch (Exception e) { log.error("retrieving service data failed", e); } } return localInstance; } /** * This method has to check the environment first in order to tell if its * Develop-Time or Run-Time because the method of generating a service list is * different depending on current environment * * Develop-Time can simply filter and process the files on the file system * given by the code source location * * Run-Time must extract itself and scan/filter zip entries which is * potentially a lengthy process, and should only have to be done once for the * lifetime of the version or mrl * * @return the service data description * @throws IOException * e */ static public ServiceData generate() throws IOException { log.info("================ generating serviceData.json begin ================"); ServiceData sd = new ServiceData(); // get services - all this could be done during Runtime // although running through zip entries would be a bit of a pain // Especially if you have to spin through 50 megs of data List<String> services = FileIO.getServiceList(); log.info("found {} services", services.size()); for (int i = 0; i < services.size(); ++i) { String fullClassName = services.get(i); log.info("querying {}", fullClassName); try { Class<?> theClass = Class.forName(fullClassName); Method method = theClass.getMethod("getMetaData"); ServiceType serviceType = (ServiceType) method.invoke(null); if (!fullClassName.equals(serviceType.getName())) { log.error(String.format("Class name %s not equal to the ServiceType's name %s", fullClassName, serviceType.getName())); } sd.add(serviceType); for (String cat : serviceType.categories) { Category category = null; if (serviceType.isAvailable()) { if (sd.categoryTypes.containsKey(cat)) { category = sd.categoryTypes.get(cat); } else { category = new Category(); category.name = cat; } category.serviceTypes.add(serviceType.getName()); sd.categoryTypes.put(cat, category); } } } catch (Exception e) { log.error(String.format("%s does not have a static getMetaData method", fullClassName)); } } log.info("================ generating serviceData.json end ================"); return sd; } public ServiceData() { } public void add(ServiceType serviceType) { serviceTypes.put(serviceType.getName(), serviceType); } public boolean containsServiceType(String fullServiceName) { return serviceTypes.containsKey(fullServiceName); } public List<ServiceType> getAvailableServiceTypes() { ArrayList<ServiceType> ret = new ArrayList<ServiceType>(); for (Map.Entry<String, ServiceType> o : serviceTypes.entrySet()) { if (o.getValue().isAvailable()) { ret.add(o.getValue()); } } return ret; } public Category getCategory(String filter) { if (filter == null) { return null; } if (categoryTypes.containsKey(filter)) { return categoryTypes.get(filter); } return null; } public String[] getCategoryNames() { String[] cat = new String[categoryTypes.size()]; int i = 0; for (Map.Entry<String, Category> o : categoryTypes.entrySet()) { cat[i] = o.getKey(); ++i; } return cat; } public HashSet<ServiceDependency> getServiceTypeDependencyKeys() { HashSet<ServiceDependency> uniqueKeys = new HashSet<ServiceDependency>(); for (Map.Entry<String, ServiceType> o : serviceTypes.entrySet()) { ServiceType st = o.getValue(); if (st.dependencies != null) { for (ServiceDependency library : st.dependencies) { uniqueKeys.add(library); } } } return uniqueKeys; } public String[] getServiceTypeNames() { return getServiceTypeNames(null); } public String[] getServiceTypeNames(String categoryFilterName) { if (categoryFilterName == null || categoryFilterName.length() == 0 || categoryFilterName.equals("all")) { String[] ret = serviceTypes.keySet().toArray(new String[0]); Arrays.sort(ret); return ret; } if (!categoryTypes.containsKey(categoryFilterName)) { return new String[] {}; } Category cat = categoryTypes.get(categoryFilterName); return cat.serviceTypes.toArray(new String[cat.serviceTypes.size()]); } public ServiceType getServiceType(String fullTypeName) { if (!fullTypeName.contains(".")) { fullTypeName = String.format("org.myrobotlab.service.%s", fullTypeName); } return serviceTypes.get(fullTypeName); } public List<ServiceType> getServiceTypes() { return getServiceTypes(true); } public List<ServiceType> getServiceTypes(boolean showUnavailable) { ArrayList<ServiceType> ret = new ArrayList<ServiceType>(); for (Map.Entry<String, ServiceType> o : serviceTypes.entrySet()) { if (!o.getValue().isAvailable() && !showUnavailable) { log.info("getServiceTypes ignore : " + o.getValue().getSimpleName()); } else { ret.add(o.getValue()); } } return ret; } public boolean save() { log.info("saving {}", serviceDataCacheFileName); return save(serviceDataCacheFileName); } public boolean save(String filename) { try { FileOutputStream fos = new FileOutputStream(filename); String json = CodecUtils.toJson(this); fos.write(json.getBytes()); fos.close(); return true; } catch (Exception e) { Logging.logError(e); } return false; } // TWO LEVELS !!! 1. Run-time checking & Build-time checking // Built-time checking // build time has access to the repo - can cross check dependencies to make // sure they are in the library // Runtime checking // for all Peers - do ALL THERE TYPES CURRENTLY EXIST ??? // FIXME - TODO - FIND public List<Category> getCategories() { ArrayList<Category> categories = new ArrayList<Category>(); for (Category category : categoryTypes.values()) { categories.add(category); } return categories; } static public List<ServiceDependency> getDependencyKeys(String fullTypeName) { List<ServiceDependency> keys = new ArrayList<ServiceDependency>(); ServiceData sd = getLocalInstance(); if (!sd.serviceTypes.containsKey(fullTypeName)) { log.error("{} not defined in service types"); return keys; } ServiceType st = localInstance.serviceTypes.get(fullTypeName); return st.getDependencies(); } public static void main(String[] args) { try { LoggingFactory.init(); // LoggingFactory.getInstance().setLevel("INFO"); // LoggingFactory.getInstance().addAppender(Appender.FILE); String path = ""; if (args.length > 0) { path = args[0]; } else { path = "."; } String filename = FileIO.gluePaths(path, "serviceData.json"); log.info("generating {}", filename); if (path.length() > 0) { new File(path).mkdirs(); } // remove pre-existing filename File removeExisting = new File(filename); removeExisting.delete(); // remove .myrobotlab/serviceData.json removeExisting = new File(System.getProperty("user.dir") + File.separatorChar + ".myrobotlab" + File.separatorChar + "serviceData.json"); removeExisting.delete(); ServiceData sd = generate(); FileOutputStream fos = new FileOutputStream(filename); fos.write(CodecUtils.toJson(sd).getBytes()); fos.close(); } catch (Exception e) { Logging.logError(e); System.exit(-1); } // System.exit(0); } }
package org.objectstyle.japp.worker; import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.FileSet; import com.oracle.appbundler.AppBundlerTask; import com.oracle.appbundler.Option; /** * Packages OS X apps for Java 1.7+ using Oracle appbundler. */ class JAppMacWorker extends AbstractAntWorker { JAppMacWorker(JApp parent) { super(parent); } public void execute() { validateJavaVersion(); createDirectories(); bundle(); } private void validateJavaVersion() { // not using commons SystemUtils... They are replying on static enums // and will become obsolete eventually String classVersion = System.getProperty("java.class.version"); int dot = classVersion.indexOf('.'); classVersion = dot > 0 ? classVersion.substring(0, dot) : classVersion; int classVersionInt; try { classVersionInt = Integer.parseInt(classVersion); } catch (Exception e) { // hmm.. return; } if (classVersionInt < 51) { throw new BuildException("Minimal JDK requirement is 1.7. Got : " + System.getProperty("java.version")); } } void createDirectories() { File baseDir = parent.getDestDir(); if (!baseDir.isDirectory() && !baseDir.mkdirs()) { throw new BuildException("Can't create directory " + baseDir.getAbsolutePath()); } } void bundle() { String[] jvmOptions = parent.getJvmOptions() != null ? parent.getJvmOptions().split("\\s") : new String[0]; AppBundlerTask bundler = createTask(AppBundlerTask.class); // TODO: hardcoded keys that are nice to support... // bundler.setApplicationCategory("public.app-category.developer-tools"); bundler.setDisplayName(parent.getLongName()); bundler.setIcon(parent.getIcon()); bundler.setIdentifier(parent.getName()); bundler.setMainClassName(parent.getMainClass()); bundler.setName(parent.getName()); bundler.setOutputDirectory(parent.getDestDir()); bundler.setShortVersion(parent.getVersion()); for (String op : jvmOptions) { Option option = new Option(); option.setValue(op); bundler.addConfiguredOption(option); } for (FileSet fs : parent.getLibs()) { bundler.addConfiguredClassPath(fs); } bundler.execute(); } }
package org.pac4j.jee.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.pac4j.core.config.Config; import org.pac4j.core.config.ConfigBuilder; import org.pac4j.core.config.ConfigSingleton; import org.pac4j.core.context.JEEContext; import org.pac4j.core.context.Pac4jConstants; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.http.adapter.HttpActionAdapter; import org.pac4j.core.http.adapter.JEEHttpActionAdapter; import org.pac4j.core.util.CommonHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An abstract filter which handles configuration. * * @author Jerome Leleu * @since 1.0.0 */ public abstract class AbstractConfigFilter implements Filter { protected final Logger logger = LoggerFactory.getLogger(getClass()); protected Config config; public void init(final FilterConfig filterConfig) throws ServletException { final String configFactoryParam = filterConfig.getInitParameter(Pac4jConstants.CONFIG_FACTORY); if (configFactoryParam != null) { final Config config = ConfigBuilder.build(configFactoryParam); setConfig(config); } } protected String getStringParam(final FilterConfig filterConfig, final String name, final String defaultValue) { final String param = filterConfig.getInitParameter(name); final String value; if (param != null) { value = param; } else { value = defaultValue; } logger.debug("String param: {}: {}", name, value); return value; } protected Boolean getBooleanParam(final FilterConfig filterConfig, final String name, final Boolean defaultValue) { final String param = filterConfig.getInitParameter(name); final Boolean value; if (param != null) { value = Boolean.parseBoolean(param); } else { value = defaultValue; } logger.debug("Boolean param: {}: {}", name, value); return value; } protected void checkForbiddenParameter(final FilterConfig filterConfig, final String name) { final String parameter = getStringParam(filterConfig, name, null); if (CommonHelper.isNotBlank(parameter)) { final String message = "the " + name + " servlet parameter is no longer supported"; logger.error(message); throw new TechnicalException(message); } } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse resp = (HttpServletResponse) response; internalFilter(req, resp, chain); } protected HttpActionAdapter<Object, JEEContext> retrieveHttpActionAdapter() { if (getConfig() != null) { final HttpActionAdapter<Object, JEEContext> configHttpActionAdapter = getConfig().getHttpActionAdapter(); if (configHttpActionAdapter != null) { return configHttpActionAdapter; } } return JEEHttpActionAdapter.INSTANCE; } protected abstract void internalFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException; public void destroy() {} public Config getConfig() { if (this.config == null) { return ConfigSingleton.getConfig(); } return this.config; } public void setConfig(final Config config) { CommonHelper.assertNotNull("config", config); this.config = config; ConfigSingleton.setConfig(config); } public void setConfigOnly(final Config config) { CommonHelper.assertNotNull("config", config); this.config = config; } }
package org.pfaa.chemica.processing; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.pfaa.chemica.fluid.IndustrialFluids; import org.pfaa.chemica.item.IndustrialItems; import org.pfaa.chemica.item.IngredientStack; import org.pfaa.chemica.model.IndustrialMaterial; import org.pfaa.chemica.model.MaterialState; import org.pfaa.chemica.model.State; import org.pfaa.chemica.processing.Form.Forms; import org.pfaa.chemica.registration.OreDictUtils; import com.google.common.collect.Sets; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; public class MaterialStack implements IngredientStack { private Form form; private MaterialState<?> materialState; private int size; private float chance; public MaterialStack(int size, MaterialState<?> materialState, Form form, float chance) { this.form = form; this.materialState = materialState; this.size = size; this.chance = chance; } public Form getForm() { return this.form; } public IndustrialMaterial getMaterial() { return this.materialState.material; } public State getState() { return this.materialState.state; } public String getOreDictKey() { return OreDictUtils.makeKey(this.form, this.getMaterial()); } public Set<ItemStack> getItemStacks() { List<ItemStack> itemStacks = IndustrialItems.getItemStacks(this); return Sets.newHashSet(itemStacks); } public boolean hasItemStack() { return !this.getItemStacks().isEmpty(); } public float getChance() { return this.chance; } @Override public int getSize() { return this.size; } public ItemStack getBestItemStack() { return IndustrialItems.getBestItemStack(this); } public FluidStack getFluidStack() { return IndustrialFluids.getFluidStack(this); } @Override public Object getCraftingIngredient() { return this.getOreDictKey(); } public static MaterialStack of(IndustrialMaterial material) { return of(material, null); } public static MaterialStack of(IndustrialMaterial material, Form form) { return of(1, material, form); } public static MaterialStack of(MaterialState<?> materialState, Form form) { return of(1, materialState, form); } public static MaterialStack of(int size, IndustrialMaterial material, Form form) { return of(size, material.getStandardState().of(material), form); } public static MaterialStack of(int size, MaterialState<?> materialState, Form form) { return of(size, materialState, form, 1F); } public static MaterialStack of(int size, MaterialState<?> materialState, Form form, float chance) { return new MaterialStack(size, materialState, form, chance); } private static float roundScalar(float scalar) { float precision = (float)Math.pow(10, -Math.floor(Math.log10(scalar))); return Math.round(scalar * precision) / precision; } public static MaterialStack of(MaterialStoich<?> stoich, Form form) { float weight = stoich.stoich; if (stoich.state().isFluid()) { weight *= form.scaleTo(Forms.MILLIBUCKET); form = Forms.MILLIBUCKET; } while (weight < 1) { Form unstacked = form.unstack(); if (unstacked == null) { break; } weight *= roundScalar(form.scaleTo(unstacked)); form = unstacked; } Form stacked; double ratio; while((stacked = form.stack()) != null && Math.rint(weight) >= (ratio = roundScalar(stacked.scaleTo(form)))) { weight /= ratio; form = stacked; } return of((int)Math.max(Math.rint(weight), 1), stoich.state().of(stoich.material()), form, Math.min(weight, 1F)); } public static List<MaterialStack> of(Stream<MaterialStoich<?>> stoichs, Form form) { return stoichs.map((stoich) -> of(stoich, form)).collect(Collectors.toList()); } }
package org.twuni.xmppt.xmpp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Stack; import org.twuni.Logger; import org.twuni.xmppt.client.SocketFactory; import org.twuni.xmppt.xmpp.bind.Bind; import org.twuni.xmppt.xmpp.core.Features; import org.twuni.xmppt.xmpp.core.IQ; import org.twuni.xmppt.xmpp.core.Presence; import org.twuni.xmppt.xmpp.sasl.SASLFailure; import org.twuni.xmppt.xmpp.sasl.SASLMechanisms; import org.twuni.xmppt.xmpp.sasl.SASLPlainAuthentication; import org.twuni.xmppt.xmpp.sasl.SASLSuccess; import org.twuni.xmppt.xmpp.session.Session; import org.twuni.xmppt.xmpp.stream.Acknowledgment; import org.twuni.xmppt.xmpp.stream.AcknowledgmentRequest; import org.twuni.xmppt.xmpp.stream.Enable; import org.twuni.xmppt.xmpp.stream.Enabled; import org.twuni.xmppt.xmpp.stream.Resume; import org.twuni.xmppt.xmpp.stream.Resumed; import org.twuni.xmppt.xmpp.stream.Stream; import org.twuni.xmppt.xmpp.stream.StreamError; import org.twuni.xmppt.xmpp.stream.StreamManagement; public class XMPPClientConnection { public static interface AcknowledgmentListener { public void onFailedAcknowledgment( XMPPClientConnection connection, int expected, int actual ); public void onSuccessfulAcknowledgment( XMPPClientConnection connection ); } public static class Builder { private SocketFactory socketFactory = SocketFactory.getInstance(); private String host = "localhost"; private int port = 5222; private int sessionResumptionTimeout = 300; private boolean secure = false; private Logger logger; private boolean log = true; private String serviceName = "localhost"; private String resourceName = "default"; private String userName; private String password; private InputStream state; private AcknowledgmentListener acknowledgmentListener; private PacketListener packetListener; private ConnectionListener connectionListener; public Builder acknowledgmentListener( AcknowledgmentListener acknowledgmentListener ) { this.acknowledgmentListener = acknowledgmentListener; return this; } public XMPPClientConnection build() throws IOException { XMPPClientConnection connection = new XMPPClientConnection(); connection.setAcknowledgmentListener( acknowledgmentListener ); connection.setConnectionListener( connectionListener ); if( logger != null ) { connection.connect( socketFactory, host, port, secure, serviceName, logger ); } else { connection.connect( socketFactory, host, port, secure, serviceName, log ); } connection.login( userName, password ); if( state != null ) { connection.restoreState( state ); } else { connection.bind( resourceName, sessionResumptionTimeout ); } connection.startListening( packetListener ); return connection; } public Builder connectionListener( ConnectionListener connectionListener ) { this.connectionListener = connectionListener; return this; } public Builder host( String host ) { this.host = host; return this; } public Builder log( boolean log ) { this.log = log; return log ? this : logger( null ); } public Builder logger( Logger logger ) { this.logger = logger; return log( logger != null ); } public Builder packetListener( PacketListener packetListener ) { this.packetListener = packetListener; return this; } public Builder password( String password ) { this.password = password; return this; } public Builder port( int port ) { this.port = port; return this; } public Builder resourceName( String resourceName ) { this.resourceName = resourceName; return this; } public Builder secure( boolean secure ) { this.secure = secure; return this; } public Builder serviceName( String serviceName ) { this.serviceName = serviceName; return this; } public Builder sessionResumptionTimeout( int timeout ) { sessionResumptionTimeout = timeout; return this; } public Builder socketFactory( SocketFactory socketFactory ) { this.socketFactory = socketFactory; return this; } public Builder state( byte [] state ) throws IOException { return state != null ? state( state, 0, state.length ) : state( (InputStream) null ); } public Builder state( byte [] state, int offset, int length ) throws IOException { return state( state != null ? new ByteArrayInputStream( state, offset, length ) : null ); } public Builder state( InputStream state ) throws IOException { this.state = state; return this; } public Builder userName( String userName ) { this.userName = userName; return this; } } public static interface ConnectionListener { public void onConnected( XMPPClientConnection connection ); public void onDisconnected( XMPPClientConnection connection ); } public static class Context { private static final int VERSION = 1; private static String readUTF( DataInputStream in ) throws IOException { int length = in.readInt(); return length > 0 ? in.readUTF() : null; } private static void writeUTF( DataOutputStream d, String in ) throws IOException { if( in == null ) { d.writeInt( 0 ); } else { d.writeInt( in.length() ); d.writeUTF( in ); } } public Stream stream; public Features features; public int sequence; public int sent; public int received; public int sessionResumptionTimeout; public String streamManagementID; public boolean streamManagementEnabled; public String userName; public String serviceName; public String resourceName; public String fullJID; public void load( InputStream in ) throws IOException { DataInputStream d = new DataInputStream( in ); int version = d.readInt(); switch( version ) { case 1: sequence = d.readInt(); sent = d.readInt(); received = d.readInt(); sessionResumptionTimeout = d.readInt(); streamManagementID = readUTF( d ); resourceName = readUTF( d ); fullJID = readUTF( d ); break; } } public String nextID() { sequence++; return String.format( "%s-%d", stream.id(), Integer.valueOf( sequence ) ); } public void save( OutputStream out ) throws IOException { DataOutputStream d = new DataOutputStream( out ); d.writeInt( VERSION ); d.writeInt( sequence ); d.writeInt( sent ); d.writeInt( received ); d.writeInt( sessionResumptionTimeout ); writeUTF( d, streamManagementID ); writeUTF( d, resourceName ); writeUTF( d, fullJID ); } } public static interface PacketListener { public void onException( XMPPClientConnection connection, Throwable exception ); public void onPacketReceived( XMPPClientConnection connection, Object packet ); } private final Stack<Context> contexts = new Stack<Context>(); private XMPPSocket socket; private Thread packetListenerThread; private AcknowledgmentListener acknowledgmentListener; private ConnectionListener connectionListener; public void bind( String resourceName ) throws IOException { bind( resourceName, 0 ); } public void bind( String resourceName, int sessionResumptionTimeout ) throws IOException { String id = null; if( isFeatureAvailable( Bind.class ) ) { id = generatePacketID(); send( new IQ( id, IQ.TYPE_SET, null, null, Bind.resource( resourceName ) ) ); IQ bindIQ = nextPacket(); Bind bind = bindIQ.getContent( Bind.class ); getContext().fullJID = bind.jid(); enableStreamManagement( sessionResumptionTimeout ); if( isFeatureAvailable( Session.class ) ) { id = generatePacketID(); send( new IQ( id, IQ.TYPE_SET, null, null, new Session() ) ); nextPacket( IQ.class ); } id = generatePacketID(); send( new Presence( id ) ); getContext().resourceName = resourceName; dispatchOnConnected(); } } public void connect( SocketFactory socketFactory, String host, int port, boolean secure ) throws IOException { prepareConnect(); socket = new XMPPSocket( socketFactory, host, port, secure ); } public void connect( SocketFactory socketFactory, String host, int port, boolean secure, String serviceName ) throws IOException { connect( socketFactory, host, port, secure, serviceName, true ); } public void connect( SocketFactory socketFactory, String host, int port, boolean secure, String serviceName, boolean loggingEnabled ) throws IOException { connect( socketFactory, host, port, secure ); if( !loggingEnabled ) { socket.setLogger( null ); } connect( serviceName ); } public void connect( SocketFactory socketFactory, String host, int port, boolean secure, String serviceName, Logger logger ) throws IOException { connect( socketFactory, host, port, secure ); socket.setLogger( logger ); connect( serviceName ); } private void connect( String serviceName ) throws IOException { send( new Stream( serviceName ) ); Context context = new Context(); context.serviceName = serviceName; context.stream = nextPacket(); Object packet = next(); if( packet instanceof StreamError ) { throw new IOException( ( (StreamError) packet ).content.toString() ); } if( packet instanceof Features ) { context.features = (Features) packet; } contexts.push( context ); } public void connect( String host, int port, boolean secure ) throws IOException { prepareConnect(); socket = new XMPPSocket( host, port, secure ); } public void connect( String host, int port, boolean secure, String serviceName ) throws IOException { connect( host, port, secure, serviceName, false ); } public void connect( String host, int port, boolean secure, String serviceName, boolean loggingEnabled ) throws IOException { connect( host, port, secure ); if( !loggingEnabled ) { socket.setLogger( null ); } connect( serviceName ); } public void disconnect() throws IOException { stopListening(); if( isAuthenticated() ) { logout(); } while( !contexts.isEmpty() ) { if( socket != null ) { try { send( getStream().close() ); } catch( IOException exception ) { // Socket must be closed. That's fine. } } contexts.pop(); } terminate(); } private void dispatchFailedAcknowledgment( int expected, int actual ) { if( acknowledgmentListener != null ) { acknowledgmentListener.onFailedAcknowledgment( this, expected, actual ); } } protected void dispatchOnConnected() { if( connectionListener != null ) { connectionListener.onConnected( this ); } } protected void dispatchOnDisconnected() { if( connectionListener != null ) { connectionListener.onDisconnected( this ); } } private void dispatchSuccessfulAcknowledgment() { if( acknowledgmentListener != null ) { acknowledgmentListener.onSuccessfulAcknowledgment( this ); } } protected void enableStreamManagement( int sessionResumptionTimeout ) throws IOException { if( isFeatureAvailable( StreamManagement.class ) ) { send( new Enable( sessionResumptionTimeout, sessionResumptionTimeout != 0 ) ); Enabled enabled = nextPacket(); Context context = getContext(); context.streamManagementID = enabled.id(); context.streamManagementEnabled = true; context.received = 0; context.sent = 0; } } protected String generatePacketID() { Context context = getContext(); return context != null ? context.nextID() : Long.toHexString( System.currentTimeMillis() ); } private Context getContext() { return contexts.isEmpty() ? null : contexts.peek(); } protected Features getFeatures() { Context context = getContext(); return context != null ? context.features : null; } protected Stream getStream() { Context context = getContext(); return context != null ? context.stream : null; } public boolean isAuthenticated() { Context context = getContext(); return context != null && context.fullJID != null; } public boolean isConnected() { return socket != null && socket.isConnected(); } public boolean isFeatureAvailable( Class<?> feature ) { Features features = getFeatures(); return features != null && features.hasFeature( feature ); } private boolean isResumable() { Context context = getContext(); return context != null && context.streamManagementID != null; } private boolean isStreamManagementEnabled() { Context context = getContext(); return isFeatureAvailable( StreamManagement.class ) && context != null && context.streamManagementEnabled; } public void login( String username, String password ) throws IOException { if( isFeatureAvailable( SASLMechanisms.class ) ) { SASLMechanisms mechanisms = getFeatures().getFeature( SASLMechanisms.class ); if( mechanisms.hasMechanism( SASLPlainAuthentication.MECHANISM ) ) { send( new SASLPlainAuthentication( username, password ) ); Object result = next(); if( result instanceof SASLFailure ) { throw new IOException( ( (SASLFailure) result ).reason ); } if( result instanceof SASLSuccess ) { String serviceName = getStream().from(); send( new Stream( serviceName ) ); Context context = new Context(); context.serviceName = serviceName; context.stream = nextPacket(); context.features = nextPacket(); context.userName = username; contexts.push( context ); } } } } public void logout() throws IOException { stopListening(); if( !contexts.isEmpty() ) { send( new Presence( generatePacketID(), Presence.Type.UNAVAILABLE ) ); send( getStream().close() ); contexts.pop(); } } protected Object next() throws IOException { return ok( socket.next() ); } protected <T> T nextPacket() throws IOException { T packet = socket.nextPacket(); return ok( packet ); } protected <T> T nextPacket( Class<T> type ) throws IOException { return ok( socket.nextPacket( type ) ); } private <T> T ok( T packet ) { Context context = getContext(); if( context != null ) { if( context.streamManagementEnabled ) { if( isFeatureAvailable( StreamManagement.class ) ) { if( !StreamManagement.is( packet ) ) { context.received++; } } } } return packet; } private void prepareConnect() throws IOException { if( isConnected() ) { if( isAuthenticated() ) { logout(); } disconnect(); } } protected void processPacket( PacketListener packetListener, Object packet ) throws IOException { if( StreamManagement.is( packet ) && isStreamManagementEnabled() ) { if( packet instanceof AcknowledgmentRequest ) { send( new Acknowledgment( getContext().received ) ); } else if( packet instanceof Acknowledgment ) { Acknowledgment ack = (Acknowledgment) packet; if( getContext().sent != ack.getH() ) { dispatchFailedAcknowledgment( getContext().sent, ack.getH() ); } else { dispatchSuccessfulAcknowledgment(); } } return; } packetListener.onPacketReceived( this, packet ); } public void restoreState( byte [] state ) throws IOException { restoreState( state, 0, state.length ); } public void restoreState( byte [] state, int offset, int length ) throws IOException { restoreState( new ByteArrayInputStream( state, offset, length ) ); } public void restoreState( InputStream in ) throws IOException { Context context = getContext(); if( context == null || context.userName == null ) { throw new IllegalStateException( "The stream must be authenticated before attempting to restore state." ); } context.load( in ); resume( context ); } private void resume( Context previousContext ) throws IOException { if( isFeatureAvailable( StreamManagement.class ) ) { if( previousContext != null ) { send( new Resume( previousContext.streamManagementID, previousContext.received ) ); Object response = nextPacket(); if( !( response instanceof Resumed ) ) { bind( previousContext.resourceName, previousContext.sessionResumptionTimeout ); return; } Context context = getContext(); Resumed resumed = (Resumed) response; context.streamManagementEnabled = true; context.streamManagementID = resumed.getPreviousID(); context.received = previousContext.received; context.sent = previousContext.sent; dispatchOnConnected(); if( context.sent != resumed.getH() ) { dispatchFailedAcknowledgment( context.sent, resumed.getH() ); } else { dispatchSuccessfulAcknowledgment(); } } } } public byte [] saveState() throws IOException { if( !isResumable() ) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); saveState( out ); return out.toByteArray(); } public void saveState( OutputStream out ) throws IOException { if( !isResumable() ) { return; } Context context = getContext(); if( context == null ) { context = new Context(); } context.save( out ); } public void send( Object... packets ) throws IOException { for( Object packet : packets ) { socket.write( packet ); if( isStreamManagementEnabled() ) { if( !StreamManagement.is( packet ) ) { getContext().sent++; } } } } public void sendAcknowledgment() throws IOException { send( new Acknowledgment( getContext().received ) ); } public void setAcknowledgmentListener( AcknowledgmentListener acknowledgmentListener ) { this.acknowledgmentListener = acknowledgmentListener; } public void setConnectionListener( ConnectionListener connectionListener ) { this.connectionListener = connectionListener; } public void startListening( final PacketListener packetListener ) { if( !( isConnected() && isAuthenticated() ) ) { throw new IllegalStateException(); } stopListening(); packetListenerThread = new Thread( String.format( "%s:%s", packetListener.getClass().getName(), getContext().fullJID ) ) { @Override public void run() { while( !interrupted() ) { try { Object packet = next(); if( packet == null ) { disconnect(); dispatchOnDisconnected(); break; } if( !isInterrupted() ) { processPacket( packetListener, packet ); } } catch( IOException exception ) { if( !isInterrupted() ) { packetListener.onException( XMPPClientConnection.this, exception ); } try { terminate(); } catch( IOException ignore ) { // Ignore. } if( !isConnected() ) { dispatchOnDisconnected(); } break; } } } }; packetListenerThread.start(); } public void stopListening() { if( packetListenerThread != null ) { packetListenerThread.interrupt(); packetListenerThread = null; } } public void terminate() throws IOException { if( socket != null ) { socket.flush(); socket.close(); socket = null; } } }
package org.webbitserver.sitemesh; import org.sitemesh.config.PathMapper; import org.sitemesh.content.Content; import org.sitemesh.content.ContentProcessor; import org.sitemesh.tagprocessor.util.CharSequenceList; import org.webbitserver.HttpControl; import org.webbitserver.HttpHandler; import org.webbitserver.HttpRequest; import org.webbitserver.HttpResponse; import org.webbitserver.sitemesh.contentbuffer.BasicSelector; import org.webbitserver.sitemesh.contentbuffer.BufferedResponse; import org.webbitserver.sitemesh.contentbuffer.ContentBufferingHandler; import org.webbitserver.sitemesh.contentbuffer.Selector; import org.webbitserver.wrapper.HttpResponseWrapper; import java.io.IOException; import java.nio.CharBuffer; import java.util.Arrays; public class SiteMeshHandler extends ContentBufferingHandler { private final ContentProcessor contentProcessor; private final PathMapper<HttpHandler[]> decorators; public SiteMeshHandler(Selector selector, ContentProcessor contentProcessor, PathMapper<HttpHandler[]> decorators) { super(selector); this.contentProcessor = contentProcessor; this.decorators = decorators; } protected void postProcessBuffer(HttpRequest httpRequest, HttpResponse httpResponse, HttpControl httpControl, CharBuffer buffer) throws IOException { if (buffer == null) { httpResponse.end(); return; } WebbitSiteMeshContext context = createContext(httpRequest, httpControl, contentProcessor); applyDecorator( context, buffer, contentProcessor.build(buffer, context), decorators.get(context.getPath()), 0, httpRequest, httpResponse, httpControl); } private void applyDecorator(final WebbitSiteMeshContext context, final CharBuffer original, final Content content, final HttpHandler[] decoratorHandlers, final int currentDecorator, final HttpRequest httpRequest, final HttpResponse httpResponse, final HttpControl httpControl) { if (content == null) { // Content could not be parsed: Write original content httpResponse.content(original.toString()).end(); } else { // Apply decorator... HttpHandler decoratorHandler = decoratorHandlers[currentDecorator]; try { Selector selector = new BasicSelector() { @Override public boolean shouldBufferForContentType(String contentType, String mimeType, String encoding) { return true; // We know we should buffer. } }; decoratorHandler.handleHttpRequest(httpRequest, new BufferedResponse(selector, httpResponse) { { enableBuffering(); } @Override public HttpResponseWrapper header(String name, String value) { if (name.equalsIgnoreCase("content-type")) { return this; } else { return super.header(name, value); } } @Override protected void postProcess(CharBuffer buffer) { try { context.setContentToMerge(content); Content decoratedContent = contentProcessor.build(buffer, context); int nextDecorator = currentDecorator + 1; if (nextDecorator < decoratorHandlers.length) { // There are more decorators to be applied. Recurse... applyDecorator( context, original, decoratedContent, decoratorHandlers, nextDecorator, httpRequest, httpResponse, httpControl); } else { // No more decorators to apply: Write the decorated result CharSequenceList chars = new CharSequenceList(); decoratedContent.getData().writeValueTo(chars); httpResponse.content(chars.toString()).end(); } } catch (IOException e) { httpResponse.error(e); return; } } }, httpControl); } catch (Exception e) { httpResponse.error(new IOException("Could not process decorator", e).fillInStackTrace()); } } } protected WebbitSiteMeshContext createContext(HttpRequest request, HttpControl httpControl, ContentProcessor contentProcessor) { return new WebbitSiteMeshContext(request, httpControl, contentProcessor); } }
package org.wiztools.restclient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.security.KeyStore; import java.util.Map; import junit.framework.TestSuite; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpTrace; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.ClientPNames; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.message.AbstractHttpMessage; import org.apache.http.message.BasicHeader; import org.wiztools.restclient.test.TestException; import org.wiztools.restclient.test.TestUtil; /** * * @author subwiz */ public class HTTPRequestThread extends Thread { private RequestBean request; private View view; public HTTPRequestThread(final RequestBean request, final View view) { this.request = request; this.view = view; } @Override public void run() { view.doStart(request); URL url = request.getUrl(); String urlHost = url.getHost(); int urlPort = url.getPort()==-1?url.getDefaultPort():url.getPort(); String urlProtocol = url.getProtocol(); String urlStr = url.toString(); DefaultHttpClient httpclient = new DefaultHttpClient(); // Set request timeout (default 1 minute--60000 milliseconds) GlobalOptions options = GlobalOptions.getInstance(); options.acquire(); httpclient.getParams().setLongParameter(ClientPNames.CONNECTION_MANAGER_TIMEOUT, options.getRequestTimeoutInMillis()); options.release(); // Set proxy ProxyConfig proxy = ProxyConfig.getInstance(); proxy.acquire(); if (proxy.isEnabled()) { final HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), "http"); if (proxy.isAuthEnabled()) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(proxy.getHost(), proxy.getPort()), new UsernamePasswordCredentials(proxy.getUsername(), new String(proxy.getPassword()))); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } proxy.release(); // HTTP Authentication boolean authEnabled = request.getAuthMethods().size() > 0 ? true : false; if (authEnabled) { String uid = request.getAuthUsername(); String pwd = new String(request.getAuthPassword()); String host = Util.isStrEmpty(request.getAuthHost()) ? urlHost : request.getAuthHost(); String realm = Util.isStrEmpty(request.getAuthRealm()) ? AuthScope.ANY_REALM : request.getAuthRealm(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(host, urlPort, realm), new UsernamePasswordCredentials(uid, pwd)); // preemptive mode if (request.isAuthPreemptive()) { httpclient.getParams().setBooleanParameter(ClientPNames.PREEMPTIVE_AUTHENTICATION, true); } } AbstractHttpMessage method = null; String httpMethod = request.getMethod(); try { if ("GET".equals(httpMethod)) { method = new HttpGet(urlStr); } else if ("HEAD".equals(httpMethod)) { method = new HttpHead(urlStr); } else if ("POST".equals(httpMethod)) { method = new HttpPost(urlStr); } else if ("PUT".equals(httpMethod)) { method = new HttpPut(urlStr); } else if ("DELETE".equals(httpMethod)) { method = new HttpDelete(urlStr); } else if ("OPTIONS".equals(httpMethod)) { method = new HttpOptions(urlStr); } else if ("TRACE".equals(httpMethod)) { method = new HttpTrace(urlStr); } // Get request headers Map<String, String> header_data = request.getHeaders(); for (String key : header_data.keySet()) { String value = header_data.get(key); Header header = new BasicHeader(key, value); method.addHeader(header); } // POST/PUT method specific logic if (method instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest eeMethod = (HttpEntityEnclosingRequest) method; // Create and set RequestEntity ReqEntityBean bean = request.getBody(); if (bean != null) { try { HttpEntity entity = new StringEntity( bean.getBody(), bean.getCharSet()); eeMethod.setEntity(entity); } catch (UnsupportedEncodingException ex) { view.doError(Util.getStackTrace(ex)); view.doEnd(); return; } } } // SSL String trustStorePath = request.getSslTrustStore(); char[] trustStorePassword = request.getSslTrustStorePassword(); if(urlProtocol.equalsIgnoreCase("https") && !Util.isStrEmpty(trustStorePath)){ System.out.println("inside https"); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File(trustStorePath)); try{ trustStore.load(instream, trustStorePassword); } finally{ instream.close(); } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme(urlProtocol, socketFactory, urlPort); httpclient.getConnectionManager().getSchemeRegistry().register(sch); } httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler()); // Now Execute: HttpResponse http_res = httpclient.execute((HttpUriRequest) method); ResponseBean response = new ResponseBean(); response.setStatusCode(http_res.getStatusLine().getStatusCode()); response.setStatusLine(http_res.getStatusLine().toString()); final Header[] responseHeaders = http_res.getAllHeaders(); for (Header header : responseHeaders) { response.addHeader(header.getName(), header.getValue()); } InputStream is = http_res.getEntity().getContent(); String responseBody = Util.inputStream2String(is); if (responseBody != null) { response.setResponseBody(responseBody); } // Now execute tests: try { TestSuite suite = TestUtil.getTestSuite(request, response); if (suite != null) { // suite will be null if there is no associated script String testResult = TestUtil.execute(suite); response.setTestResult(testResult); } } catch (TestException ex) { view.doError(Util.getStackTrace(ex)); } view.doResponse(response); } catch (HttpException ex) { view.doError(Util.getStackTrace(ex)); } catch (IOException ex) { view.doError(Util.getStackTrace(ex)); } catch (Exception ex) { view.doError(Util.getStackTrace(ex)); } finally { if (method != null) { httpclient.getConnectionManager().shutdown(); } view.doEnd(); } } }
package permafrost.tundra.flow; import com.wm.data.IData; import com.wm.data.IDataFactory; import com.wm.lang.flow.ExpressionEvaluator; import com.wm.lang.flow.MalformedExpressionException; import org.w3c.dom.Node; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.xml.dom.NodeHelper; import permafrost.tundra.xml.dom.Nodes; import permafrost.tundra.xml.xpath.XPathHelper; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; /** * Performs webMethods Integration Server flow language conditional statement evaluation against a specified scope. */ public class ConditionEvaluator { /** * Regular expression pattern for matching an IData node XPath expression. */ public static final Pattern CONDITION_NODE_XPATH_REGULAR_EXPRESSION_PATTERN = Pattern.compile("(?i)%([^%\\/]+)(\\/[^%]+)%"); /** * The conditional statement to be evaluated by this object. */ protected String condition; /** * Compiled node XPath expression. */ protected Map<Integer, XPathExpression> expressions; /** * Constructs a new flow condition. * * @param condition The conditional statement to be evaluated. */ public ConditionEvaluator(String condition) { this(condition, null); } /** * Constructs a new flow condition. * * @param condition The conditional statement to be evaluated. * @param namespaceContext An optional namespace context used when resolving XPath expressions. */ public ConditionEvaluator(String condition, NamespaceContext namespaceContext) { this.condition = condition; if (condition != null) { Matcher matcher = CONDITION_NODE_XPATH_REGULAR_EXPRESSION_PATTERN.matcher(condition); Map<Integer, XPathExpression> expressions = new TreeMap<Integer, XPathExpression>(); int i = 0; while (matcher.find()) { try { expressions.put(i, XPathHelper.compile(matcher.group(2), namespaceContext)); } catch(XPathExpressionException ex) { // do nothing, assume a normal IData fully-qualified key was specified rather than an XPath expression } finally { i++; } } if (expressions.size() > 0) this.expressions = Collections.unmodifiableMap(expressions); } } /** * Returns the condition that is evaluated by this object. * * @return The condition that is evaluated by this object. */ public String getCondition() { return condition; } /** * Evaluates the conditional statement against the given scope. * * @param scope The scope against which the conditional statement is evaluated. * @return True if the conditional statement evaluates to true, otherwise false. */ public synchronized boolean evaluate(IData scope) { String condition = this.condition; boolean result = true; if (condition != null) { if (scope == null) { scope = IDataFactory.create(); } else if (expressions != null) { Matcher matcher = CONDITION_NODE_XPATH_REGULAR_EXPRESSION_PATTERN.matcher(condition); StringBuffer buffer = new StringBuffer(); int i = 0; while (matcher.find()) { String key = matcher.group(1); XPathExpression expression = expressions.get(i); if (expression != null) { Object node = IDataHelper.get(scope, key); if (node instanceof Node) { try { Nodes nodes = XPathHelper.get((Node)node, expression); if (nodes != null && nodes.size() > 0) { matcher.appendReplacement(buffer, Matcher.quoteReplacement("\"" + NodeHelper.getValue(nodes.get(0)) + "\"")); } else { matcher.appendReplacement(buffer, Matcher.quoteReplacement("$null")); } } catch (XPathExpressionException ex) { throw new RuntimeException(ex); } } } i++; } matcher.appendTail(buffer); condition = buffer.toString(); } try { result = ExpressionEvaluator.evalToBoolean(condition, scope); } catch (MalformedExpressionException ex) { throw new IllegalArgumentException(ex); } } return result; } /** * Evaluates the conditional statement against the given scope. This is a convenience method which constructs a new * Condition object and evaluates it. * * @param condition The conditional statement to be evaluated. * @param scope The scope against which the conditional statement is evaluated. * @return True if the conditional statement evaluates to true, otherwise false. */ public static boolean evaluate(String condition, IData scope) { ConditionEvaluator evaluator = new ConditionEvaluator(condition); return evaluator.evaluate(scope); } }
package ru.r2cloud.satellite; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import ru.r2cloud.FilenameComparator; import ru.r2cloud.model.ObservationFull; import ru.r2cloud.model.ObservationRequest; import ru.r2cloud.model.ObservationResult; import ru.r2cloud.util.Configuration; import ru.r2cloud.util.Util; public class ObservationResultDao { private static final String SPECTOGRAM_FILENAME = "spectogram.png"; private static final String OUTPUT_WAV_FILENAME = "output.wav"; private static final String OUTPUT_RAW_FILENAME = "output.raw.gz"; private static final Logger LOG = LoggerFactory.getLogger(ObservationResultDao.class); private final Path basepath; private final Integer maxCount; public ObservationResultDao(Configuration config) { this.basepath = config.getSatellitesBasePath(); this.maxCount = config.getInteger("scheduler.data.retention.count"); } public List<ObservationFull> findAllBySatelliteId(String satelliteId) { Path dataRoot = basepath.resolve(satelliteId).resolve("data"); if (!Files.exists(dataRoot)) { return Collections.emptyList(); } List<Path> observations; try { observations = Util.toList(Files.newDirectoryStream(dataRoot)); } catch (IOException e) { LOG.error("unable to load observations", e); return Collections.emptyList(); } Collections.sort(observations, FilenameComparator.INSTANCE_DESC); List<ObservationFull> result = new ArrayList<ObservationFull>(observations.size()); for (Path curDirectory : observations) { ObservationFull cur = find(satelliteId, curDirectory); // some directories might be corrupted if (cur == null) { continue; } result.add(cur); } return result; } public ObservationFull find(String satelliteId, String observationId) { Path baseDirectory = basepath.resolve(satelliteId).resolve("data").resolve(observationId); if (!Files.exists(baseDirectory)) { return null; } return find(satelliteId, baseDirectory); } private static ObservationFull find(String satelliteId, Path curDirectory) { Path dest = curDirectory.resolve("meta.json"); if (!Files.exists(dest)) { return null; } ObservationFull full; try (BufferedReader r = Files.newBufferedReader(dest)) { JsonObject meta = Json.parse(r).asObject(); full = ObservationFull.fromJson(meta); } catch (Exception e) { LOG.error("unable to load meta", e); return null; } ObservationResult result = full.getResult(); Path a = curDirectory.resolve("a.jpg"); if (Files.exists(a)) { result.setaPath(a.toFile()); result.setaURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/a.jpg"); } Path data = curDirectory.resolve("data.bin"); if (Files.exists(data)) { result.setDataPath(data.toFile()); result.setDataURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/data.bin"); } Path wav = curDirectory.resolve(OUTPUT_WAV_FILENAME); if (Files.exists(wav)) { result.setWavPath(wav.toFile()); } Path tarGz = curDirectory.resolve(OUTPUT_RAW_FILENAME); if (Files.exists(tarGz)) { result.setIqPath(tarGz.toFile()); } Path spectogram = curDirectory.resolve(SPECTOGRAM_FILENAME); if (Files.exists(spectogram)) { result.setSpectogramPath(spectogram.toFile()); result.setSpectogramURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/" + SPECTOGRAM_FILENAME); } return full; } public File saveImage(String satelliteId, String observationId, File a) { Path dest = getObservationBasepath(satelliteId, observationId).resolve("a.jpg"); if (Files.exists(dest)) { LOG.info("unable to save. dest already exist: {}", dest.toAbsolutePath()); return null; } if (!a.renameTo(dest.toFile())) { return null; } return dest.toFile(); } public File saveData(String satelliteId, String observationId, File a) { Path dest = getObservationBasepath(satelliteId, observationId).resolve("data.bin"); if (Files.exists(dest)) { LOG.info("unable to save. dest already exist: {}", dest.toAbsolutePath()); return null; } if (!a.renameTo(dest.toFile())) { return null; } return dest.toFile(); } public boolean saveSpectogram(String satelliteId, String observationId, File a) { Path dest = getObservationBasepath(satelliteId, observationId).resolve(SPECTOGRAM_FILENAME); if (Files.exists(dest)) { LOG.info("unable to save. dest already exist: {}", dest.toAbsolutePath()); return false; } return a.renameTo(dest.toFile()); } public File insert(ObservationRequest observation, File dataFile) { try { Path satelliteBasePath = basepath.resolve(observation.getSatelliteId()).resolve("data"); if (Files.exists(satelliteBasePath)) { List<Path> dataDirs = Util.toList(Files.newDirectoryStream(satelliteBasePath)); if (dataDirs.size() > maxCount) { Collections.sort(dataDirs, FilenameComparator.INSTANCE_ASC); for (int i = 0; i < (dataDirs.size() - maxCount); i++) { Util.deleteDirectory(dataDirs.get(i)); } } } } catch (IOException e) { LOG.error("unable to cleanup old observations", e); } Path observationBasePath = getObservationBasepath(observation); if (!Util.initDirectory(observationBasePath)) { return null; } ObservationFull full = new ObservationFull(observation); if (!update(full)) { return null; } return insertData(observation, dataFile); } private File insertData(ObservationRequest observation, File dataFile) { String filename; if (dataFile.getName().endsWith("wav")) { filename = OUTPUT_WAV_FILENAME; } else { filename = OUTPUT_RAW_FILENAME; } Path dest = getObservationBasepath(observation).resolve(filename); if (!Util.initDirectory(dest.getParent())) { return null; } if (Files.exists(dest)) { LOG.info("unable to save. dest already exist: {}", dest.toAbsolutePath()); return null; } if (!dataFile.renameTo(dest.toFile())) { LOG.error("unable to save file from {} to {}. Check src and dst are on the same filesystem", dataFile.getAbsolutePath(), dest.toFile().getAbsolutePath()); return null; } return dest.toFile(); } public boolean update(ObservationFull cur) { JsonObject meta = cur.toJson(null); Path dest = getObservationBasepath(cur.getReq()).resolve("meta.json"); try (BufferedWriter w = Files.newBufferedWriter(dest)) { w.append(meta.toString()); return true; } catch (IOException e) { LOG.error("unable to write meta", e); return false; } } private Path getObservationBasepath(ObservationRequest observation) { return getObservationBasepath(observation.getSatelliteId(), observation.getId()); } private Path getObservationBasepath(String satelliteId, String observationId) { return basepath.resolve(satelliteId).resolve("data").resolve(observationId); } }
package uk.ac.gla.atanaspam.pcapj; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; /** * This class implements the capability to introduce patterns into the already exported * data set. This is done by injecting a packet that has pre-defined values for fields * at a varying frequency, thus creating the pattern. * @author atanaspam * @created 15/11/2015 * @version 0.6 */ public class PacketGenerator { private static final Logger LOG = LoggerFactory.getLogger(PacketGenerator.class); int signature; int anomalousTrafficPercentage; ArrayList<TCPFlags> flags; ArrayList<InetAddress> srcAddresses; ArrayList<InetAddress> dstAddresses; ArrayList<Integer> srcPorts; ArrayList<Integer> dstPorts; ArrayList<BasicPacket> packets; int packetsTillAnomaly; int nextFlag; int nextSrcAddress; int nextDstAddress; int nextSrcPort; int nextDstPort; int nextPacket; /** * A constructor that sets default values for all settings. */ public PacketGenerator(String path, boolean vlanEnabled, boolean verbose){ packets = new ArrayList<BasicPacket>(); this.signature = 0; this.anomalousTrafficPercentage = 10; packetsTillAnomaly = 100 / anomalousTrafficPercentage; this.flags = new ArrayList<TCPFlags>(); TCPFlags flag = new TCPFlags(false,false,false,true,false,false,true,false); flags.add(flag); this.srcAddresses = new ArrayList<InetAddress>(); this.dstAddresses = new ArrayList<InetAddress>(); try { srcAddresses.add(InetAddress.getByName("192.168.1.1")); dstAddresses.add(InetAddress.getByName("192.168.0.1")); } catch (UnknownHostException e) { e.printStackTrace(); } this.srcPorts = new ArrayList<Integer>(); this.dstPorts = new ArrayList<Integer>(); srcPorts.add(80); dstPorts.add(80); nextDstAddress = 0; nextSrcAddress = 0; nextFlag = 0; nextDstPort = 0; nextSrcPort = 0; nextPacket = 0; PcapParser pcapParser = new PcapParser(); pcapParser.setVlanEnabled(vlanEnabled); pcapParser.setVerbose(verbose); if(pcapParser.openFile(path) < 0) { LOG.error("Failed to open file" + ", exiting."); System.exit(-1); } BasicPacket packet = pcapParser.getPacket(); while(packet != BasicPacket.EOF){ if(!(packet instanceof IPPacket)){ //LOG.warn("Processed an unknown packet"); packet = pcapParser.getPacket(); continue; } packets.add(packet); packet = pcapParser.getPacket(); } LOG.info("Added "+ packets.size() + " packets"); } /** * This method customizes the PacketGenerator mode and settings. * @param srcIP an ArrayList of possible Source IP addresses * @param dstIP an ArrayList of possible Destination IP addresses * @param srcPort an ArrayList of possible Source ports * @param dstPort an ArrayList of possible Destination ports * @param flags an ArrayList of possible TCP flags * @param sig The integer representation of the current attack (pattern) simulated */ public void configure(ArrayList<InetAddress> srcIP, ArrayList<InetAddress> dstIP, ArrayList<Integer> srcPort, ArrayList<Integer> dstPort, ArrayList<boolean[]> flags, int sig){ for (boolean[] a : flags){ flags.add(a);} for (InetAddress a : srcIP){ srcAddresses.add(a);} for (InetAddress a : dstIP){ dstAddresses.add(a);} for(Integer n : srcPort){ srcPorts.add(n);} for(Integer n : dstPort){ dstPorts.add(n);} switch (sig) { case 0: { // Disable anomalousTrafficPercentage = 1; return; } case 1: { // Simulate a DOS attack signature = 1; return; } case 2: { // Simulate a DDOS attack signature = 2; try { for (byte i = 0; i < 127; i++) { byte[] ipAddr = new byte[]{0, 0, 0, i}; InetAddress addr = InetAddress.getByAddress(ipAddr); srcAddresses.add(addr); } } catch (UnknownHostException e) { e.printStackTrace(); } return; } case 3: { // Simulate a SYN flood attack signature = 3; flags.clear(); flags.add(new boolean[]{false,false,false,false,false,false,true,false}); return; } case 4: { // Simulate Invalid flags flags.clear(); // Since no flag is set, this is an invalid combination. flags.add(new boolean[]{false,false,false,false,false,false,false,false}); } case 5: { // Simulate an Application layer attack () } default: { // Disable anomalousTrafficPercentage = 1; return; } } } /** * This method sets new values to the field choices * @param srcIP an ArrayList of possible Source IP addresses * @param dstIP an ArrayList of possible Destination IP addresses * @param srcPort an ArrayList of possible Source ports * @param dstPort an ArrayList of possible Destination ports * @param flags an ArrayList of possible TCP flags * @param sig The integer representation of the current attack (pattern) simulated * @param anomalyPercent the percentage of anomalous data in the data generated */ public void set(ArrayList<InetAddress> srcIP, ArrayList<InetAddress> dstIP, ArrayList<Integer> srcPort, ArrayList<Integer> dstPort, ArrayList<TCPFlags> flags, int sig, int anomalyPercent) { this.anomalousTrafficPercentage = anomalyPercent; packetsTillAnomaly = 100 / anomalousTrafficPercentage; this.srcAddresses = srcIP; this.dstAddresses = dstIP; this.srcPorts = srcPort; this.dstPorts = dstPort; this.flags = flags; this.signature = sig; } /** * This method returns a single packet that is part of a specific pattern * If anomalousTrafficPercentage is set to 1 this method iterates over the statically imported * data and does not introduce any patterns. * @return A packet object */ public BasicPacket getPacket(){ if (packetsTillAnomaly == 1 && anomalousTrafficPercentage != 1){ return getAnomalousPacket(); } else{ return getOrdinaryPacket(); } } public void setAnomalousTrafficPercentage(int anomalousTrafficPercentage) { this.anomalousTrafficPercentage = anomalousTrafficPercentage; } private BasicPacket getAnomalousPacket(){ //IPPacket sample = (IPPacket) packets.get(nextPacket); TCPPacket p = new TCPPacket(1445457108, "FF:FF:FF:FF:FF", "FF:FF:FF:FF:FF", srcAddresses.get(nextSrcAddress), dstAddresses.get(nextDstAddress), srcPorts.get(nextSrcPort), dstPorts.get(nextDstPort), flags.get(nextFlag), new PacketContents(new byte[1])); nextSrcAddress = ++nextSrcAddress % srcAddresses.size(); nextDstAddress = ++nextDstAddress % dstAddresses.size(); nextSrcPort = ++nextSrcPort % srcPorts.size(); nextDstPort = ++nextDstPort % dstPorts.size(); nextFlag = ++nextFlag % flags.size(); packetsTillAnomaly = 100 /anomalousTrafficPercentage; return p; } private BasicPacket getOrdinaryPacket(){ packetsTillAnomaly nextPacket = ++nextPacket % packets.size(); return packets.get(nextPacket); } /** * An example to test the functionality * @param args */ public static void main (String[] args){ PacketGenerator p = new PacketGenerator("/Users/atanaspam/Documents/Versoned Projects/RTDCONN/partial.pcap", true, true); p.configure(new ArrayList<InetAddress>(), new ArrayList<InetAddress>(), new ArrayList<Integer>(), new ArrayList<Integer>(), new ArrayList<boolean[]>(), 2); for (int i=0; i<400; i++){ System.out.println(p.getPacket()); } } }
package net.ssehub.kernel_haven.code_model; import java.io.File; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.ssehub.kernel_haven.util.FormatException; import net.ssehub.kernel_haven.util.FormulaCache; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.logic.parser.Parser; /** * An element of an AST representing the code. * * @author Adam */ public class SyntaxElement implements CodeElement { private List<SyntaxElement> nested; private List<String> relations; private int lineStart; private int lineEnd; private File sourceFile; private Formula condition; private Formula presenceCondition; private ISyntaxElementType type; /** * Creates a new syntax element. * * @param type The type of syntax element. * @param condition The immediate condition of this syntax element. * @param presencCondition The presence condition of this node. */ public SyntaxElement(ISyntaxElementType type, Formula condition, Formula presencCondition) { this.nested = new LinkedList<>(); this.relations = new LinkedList<>(); this.lineStart = -1; this.lineEnd = -1; this.sourceFile = new File("<unknown>"); this.condition = condition; this.presenceCondition = presencCondition; this.type = type; } /** * Sets the line that this node starts on. * @param lineStart The start line of this node. */ public void setLineStart(int lineStart) { this.lineStart = lineStart; } /** * Sets the line that this node ends on. * * @param lineEnd The end line of this node. */ public void setLineEnd(int lineEnd) { this.lineEnd = lineEnd; } /** * Sets the source file relative to the source tree that this node originates from. * * @param sourceFile The source file. Not null. */ public void setSourceFile(File sourceFile) { this.sourceFile = sourceFile; } @Override public int getNestedElementCount() { return nested.size(); } @Override public SyntaxElement getNestedElement(int index) throws IndexOutOfBoundsException { return nested.get(index); } /** * Returns the first nested element with the given relation. * * @param relation The relation of the nested element to this node. * @return The first nested element with the given relation. <code>null</code> if none found. */ public SyntaxElement getNestedElement(String relation) { int i; for (i = 0; i < nested.size(); i++) { if (relations.get(i).equals(relation)) { break; } } return i == nested.size() ? null : nested.get(i); } /** * Adds a nested element with an empty string as the relation. {@link #addNestedElement(SyntaxElement, String)} * should be used instead. */ @Override public void addNestedElement(CodeElement element) { if (!(element instanceof SyntaxElement)) { throw new IllegalArgumentException("Can only add SyntaxElements as child of SyntaxElement"); } nested.add((SyntaxElement) element); // if relations.size() >= nested.size(), then we already had a pre-defined relation for this lement // (e.g. from CSV deserializtaion). if (relations.size() < nested.size()) { relations.add(""); } } /** * Adds a nested element with the given relation to this node. * * @param element The element to nest inside of this. * @param relation The relation of the nested element. */ public void addNestedElement(SyntaxElement element, String relation) { this.nested.add(element); this.relations.add(relation); } @Override public int getLineStart() { return lineStart; } @Override public int getLineEnd() { return lineEnd; } @Override public File getSourceFile() { return sourceFile; } @Override public Formula getCondition() { return condition; } @Override public Formula getPresenceCondition() { return presenceCondition; } /** * Returns the type of this AST node. * * @return The type of syntax element. */ public ISyntaxElementType getType() { return type; } /** * Returns the relation of the given nested syntax element to this element. * * @param index The index of the nested element to get the relation for. * @return A string describing the relation of the nested element to this node. */ public String getRelation(int index) { return relations.get(index); } /** * For deserialization: set the list of relations for the children. We first get this, and after this the * cache calls addNestedElement() a bunch of times. Package visibility; should only be used by * {@link SyntaxElementCsvUtil}. * * @param relation The relations of the children elements. */ void setDeserializedRelations(List<String> relation) { this.relations = relation; } @Override public List<String> serializeCsv() { return SyntaxElementCsvUtil.elementToCsv(this); } /** * Serializes this element, like {@link #serializeCsv()}, but uses a {@link FormulaCache} to reduce the overhead * while serializing formulas of this element. * TODO SE: @Adam I think a visitor would be much more beautiful. * @param cache The formula cache to cache the serialized formulas. * @return The CSV parts representing this element. */ public List<String> serializeCsv(FormulaCache cache) { return SyntaxElementCsvUtil.elementToCsv(this, cache); } /** * Deserializes the given CSV into a syntax element. * * @param csv The csv. * @param parser The parser to parse boolean formulas. * @return The deserialized syntax element. * * @throws FormatException If the CSV is malformed. */ public static SyntaxElement createFromCsv(String[] csv, Parser<Formula> parser) throws FormatException { return SyntaxElementCsvUtil.csvToElement(csv, parser); } /** * Iterates over the elements nested inside this element. Not recursively. * * @return An iterable over the nested elements */ public Iterable<SyntaxElement> iterateNestedSyntaxElements() { return new Iterable<SyntaxElement>() { @Override public Iterator<SyntaxElement> iterator() { return new Iterator<SyntaxElement>() { private int index = 0; @Override public boolean hasNext() { return index < getNestedElementCount(); } @Override public SyntaxElement next() { return getNestedElement(index++); } }; } }; } @Override public String toString() { return toString("", ""); } /** * Turns this node into a string with the given indentation. Recursively walks through its children with increased * indentation. * * @param relation The relation of this node to its parent. * @param indentation The indentation. Contains only tabs. Never null. * * @return This element as a string. Never null. */ private String toString(String relation, String indentation) { StringBuilder result = new StringBuilder(); String conditionStr = condition == null ? "<null>" : condition.toString(); if (conditionStr.length() > 64) { conditionStr = "..."; } result.append(indentation).append(relation).append(" [").append(conditionStr).append("] "); result.append('[').append(sourceFile.getName()).append(':').append(lineStart).append("] "); result.append(type.toString()).append('\n'); indentation += '\t'; for (int i = 0; i < nested.size(); i++) { result.append(nested.get(i).toString(relations.get(i), indentation)); } return result.toString(); } }
package org.bdgp.OpenHiCAMM.Modules; import java.awt.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.ValidationError; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.ROI; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration; import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.json.JSONException; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.MDUtils; import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import ij.measure.ResultsTable; import ij.plugin.filter.Analyzer; import ij.process.ImageProcessor; import mmcorej.TaggedImage; public class CustomMacroROIFinder extends ROIFinder implements Module, ImageLogger { public CustomMacroROIFinder() { super(); } @Override public List<ROI> process(Image image, TaggedImage taggedImage, Logger logger, ImageLogRunner imageLog, Map<String, Config> config) { // get the image label String positionName = null; try { positionName = MDUtils.getPositionName(taggedImage.tags); } catch (JSONException e) {throw new RuntimeException(e);} String imageLabel = image.getLabel(); String label = String.format("%s (%s)", positionName, imageLabel); Config roiImageScaleFactorConf = config.get("roiImageScaleFactor"); if (roiImageScaleFactorConf == null) throw new RuntimeException("Config value roiImageScaleFactor not found!"); Double roiImageScaleFactor = new Double(roiImageScaleFactorConf.getValue()); Config customMacroConf = config.get("customMacro"); if (customMacroConf == null) throw new RuntimeException("Config value customMacro not found!"); String customMacro = customMacroConf.getValue(); ImageProcessor processor = ImageUtils.makeProcessor(taggedImage); ImagePlus imp = new ImagePlus(image.toString(), processor); if (roiImageScaleFactor != 1.0) { logger.fine(String.format("%s: Resizing", label)); imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR); imp.setProcessor(imp.getTitle(), imp.getProcessor().resize( (int)Math.floor(imp.getWidth() * roiImageScaleFactor), (int)Math.floor(imp.getHeight() * roiImageScaleFactor))); } imageLog.addImage(imp, "Resized"); logger.info(String.format("Running custom macro macro:%n%s", customMacro)); imp.show(); IJ.runMacro(customMacro); ImagePlus modifiedImage1 = WindowManager.getImage(imp.getTitle()); if (modifiedImage1 != null) { imp = modifiedImage1; } imageLog.addImage(imp, "Running macro"); List<ROI> rois = new ArrayList<ROI>(); ResultsTable rt = Analyzer.getResultsTable(); // Get the objects and iterate through them logger.fine(String.format("ResultsTable Column Headings: %s", rt.getColumnHeadings())); for (int i=0; i < rt.getCounter(); i++) { double area = rt.getValue("Area", i) / (roiImageScaleFactor*roiImageScaleFactor); // area of the object double bx = rt.getValue("BX", i) / roiImageScaleFactor; // x of bounding box double by = rt.getValue("BY", i) / roiImageScaleFactor; // y of bounding box double width = rt.getValue("Width", i) / roiImageScaleFactor; // width of bounding box double height = rt.getValue("Height", i) / roiImageScaleFactor; // height of bounding box logger.finest(String.format( "Found object: area=%.2f, bx=%.2f, by=%.2f, width=%.2f, height=%.2f", area, bx, by, width, height)); ROI roi = new ROI(image.getId(), (int)Math.floor(bx), (int)Math.floor(by), (int)Math.floor(bx+width), (int)Math.floor(by+height)); rois.add(roi); // Draw the ROI rectangle try { imp.setRoi((int)Math.floor(rt.getValue("BX", i)), (int)Math.floor(rt.getValue("BY", i)), (int)Math.floor(rt.getValue("Width", i)), (int)Math.floor(rt.getValue("Height", i))); IJ.setForegroundColor(255, 255, 0); IJ.run(imp, "Draw", ""); } catch (Throwable e) { // Sometimes this fails, but it's not really important, so ignore it logger.warning(String.format("Couldn't draw the ROI rectangle!: %s", e.getMessage())); } } // close the image imageLog.addImage(imp, "Adding ROIs"); return rois; } @Override public Configuration configure() { return new Configuration() { CustomMacroROIFinderDialog dialog = new CustomMacroROIFinderDialog(CustomMacroROIFinder.this); @Override public Config[] retrieve() { List<Config> configs = new ArrayList<Config>(); Double hiResPixelSize = (Double)dialog.hiResPixelSize.getValue(); if (hiResPixelSize != null) { configs.add(new Config(workflowModule.getId(), "hiResPixelSize", hiResPixelSize.toString())); } Double overlapPct = (Double)dialog.overlapPct.getValue(); if (overlapPct != null) { configs.add(new Config(workflowModule.getId(), "overlapPct", overlapPct.toString())); } Double roiMarginPct = (Double)dialog.roiMarginPct.getValue(); if (roiMarginPct != null) { configs.add(new Config(workflowModule.getId(), "roiMarginPct", roiMarginPct.toString())); } Double roiImageScaleFactor = (Double)dialog.roiImageScaleFactor.getValue(); if (roiImageScaleFactor != null) { configs.add(new Config(workflowModule.getId(), "roiImageScaleFactor", roiImageScaleFactor.toString())); } Integer imageWidth = (Integer)dialog.imageWidth.getValue(); if (imageWidth != null) { configs.add(new Config(workflowModule.getId(), "imageWidth", imageWidth.toString())); } Integer imageHeight = (Integer)dialog.imageHeight.getValue(); if (imageHeight != null) { configs.add(new Config(workflowModule.getId(), "imageHeight", imageHeight.toString())); } if (!dialog.customMacro.getText().replaceAll("\\s+","").isEmpty()) { configs.add(new Config(workflowModule.getId(), "customMacro", dialog.customMacro.getText())); } return configs.toArray(new Config[0]); } @Override public Component display(Config[] configs) { Map<String,Config> confs = new HashMap<String,Config>(); for (Config c : configs) { confs.put(c.getKey(), c); } if (confs.containsKey("hiResPixelSize")) { dialog.hiResPixelSize.setValue(new Double(confs.get("hiResPixelSize").getValue())); } if (confs.containsKey("overlapPct")) { dialog.overlapPct.setValue(new Double(confs.get("overlapPct").getValue())); } if (confs.containsKey("roiMarginPct")) { dialog.roiMarginPct.setValue(new Double(confs.get("roiMarginPct").getValue())); } if (confs.containsKey("roiImageScaleFactor")) { dialog.roiImageScaleFactor.setValue(new Double(confs.get("roiImageScaleFactor").getValue())); } if (confs.containsKey("imageWidth")) { dialog.imageWidth.setValue(new Integer(confs.get("imageWidth").getValue())); } if (confs.containsKey("imageHeight")) { dialog.imageHeight.setValue(new Integer(confs.get("imageHeight").getValue())); } if (confs.containsKey("customMacro")) { dialog.customMacro.setText(confs.get("customMacro").getValue()); } return dialog; } @Override public ValidationError[] validate() { List<ValidationError> errors = new ArrayList<ValidationError>(); Double hiResPixelSize = (Double)dialog.hiResPixelSize.getValue(); if (hiResPixelSize == null || hiResPixelSize == 0.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a nonzero value for hiResPixelSize")); } Double overlapPct = (Double)dialog.overlapPct.getValue(); if (overlapPct == null || overlapPct < 0.0 || overlapPct > 100.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a value between 0 and 100 for Tile Percent Overlap")); } Double roiMarginPct = (Double)dialog.roiMarginPct.getValue(); if (roiMarginPct == null || roiMarginPct < 0.0 || roiMarginPct > 100.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a value between 0 and 100 for ROI Margin Percent")); } Double roiImageScaleFactor = (Double)dialog.roiImageScaleFactor.getValue(); if (roiImageScaleFactor == null || roiImageScaleFactor <= 0.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a value greater than 0.0 ROI Image Scale Factor")); } Integer imageWidth = (Integer)dialog.imageWidth.getValue(); if (imageWidth == null || imageWidth <= 0.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a value greater than 0 for the HiRes Image Width")); } Integer imageHeight = (Integer)dialog.imageHeight.getValue(); if (imageHeight == null || imageHeight <= 0.0) { errors.add(new ValidationError(workflowModule.getName(), "Please enter a value greater than 0 for the HiRes Image Height")); } if (dialog.customMacro.getText().replaceAll("\\s+","").isEmpty()) { errors.add(new ValidationError(workflowModule.getName(), "Please fill in the custom macro code!")); } return errors.toArray(new ValidationError[0]); } }; } }
package org.callimachusproject.server.chain; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.cache.ResourceFactory; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.client.cache.CacheConfig; import org.apache.http.impl.client.cache.CachingHttpAsyncClient; import org.apache.http.impl.client.cache.ManagedHttpCacheStorage; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.conn.ClientAsyncConnectionManager; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.callimachusproject.server.AsyncExecChain; import org.callimachusproject.server.helpers.AutoClosingAsyncClient; import org.callimachusproject.server.helpers.CalliContext; import org.callimachusproject.server.helpers.ResponseCallback; import org.callimachusproject.server.util.HTTPDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CacheHandler implements AsyncExecChain { private final class DelegatingClient extends CloseableHttpAsyncClient { private final AsyncExecChain delegate; private final boolean maxAgeHeuristic; private boolean running; public DelegatingClient(AsyncExecChain delegate) { this.delegate = delegate; boolean enabled = config.isHeuristicCachingEnabled(); long lifetime = config.getHeuristicDefaultLifetime(); this.maxAgeHeuristic = enabled && lifetime > 0 && lifetime < Integer.MAX_VALUE; } public void start() { running = true; } public void close() { shutdown(); } public void shutdown() { running = false; } public boolean isRunning() { return running; } public IOReactorStatus getStatus() { return null; } public HttpParams getParams() { return null; } public ClientAsyncConnectionManager getConnectionManager() { return null; } public <T> Future<T> execute(HttpAsyncRequestProducer arg0, HttpAsyncResponseConsumer<T> arg1, HttpContext arg2, FutureCallback<T> arg3) { throw new UnsupportedOperationException("CachingHttpAsyncClient does not caching for streaming HTTP exchanges"); } public Future<HttpResponse> execute(HttpHost target, final HttpRequest request, final HttpContext context, FutureCallback<HttpResponse> callback) { if (maxAgeHeuristic) { return delegate.execute(target, request, context, new ResponseCallback(callback) { public void completed(HttpResponse result) { setCacheControlIfCacheable(request, result, context); super.completed(result); } }); } else { return delegate.execute(target, request, context, callback); } } } private final Logger logger = LoggerFactory.getLogger(CacheHandler.class); private final HTTPDateFormat modifiedformat = new HTTPDateFormat(); private final AsyncExecChain delegate; private final ResourceFactory resourceFactory; private final CacheConfig config; private final Map<HttpHost, HttpAsyncClient> clients = new HashMap<HttpHost, HttpAsyncClient>(); public CacheHandler(AsyncExecChain delegate, ResourceFactory resourceFactory, CacheConfig config) { this.delegate = delegate; this.resourceFactory = resourceFactory; this.config = config; } public synchronized void reset() { clients.clear(); } @Override public Future<HttpResponse> execute(HttpHost target, HttpRequest request, final HttpContext context, FutureCallback<HttpResponse> callback) { return getClient(target).execute(target, request, context, callback); } private synchronized HttpAsyncClient getClient(HttpHost target) { if (clients.containsKey(target)) return clients.get(target); logger.debug("Initializing server side cache for {}", target); ManagedHttpCacheStorage storage = new ManagedHttpCacheStorage(config); CachingHttpAsyncClient cachingClient = new CachingHttpAsyncClient(new DelegatingClient(delegate), resourceFactory, storage, config); HttpAsyncClient client = new AutoClosingAsyncClient(cachingClient, storage); clients.put(target, client); return client; } void setCacheControlIfCacheable(final HttpRequest request, HttpResponse response, final HttpContext context) { String method = request.getRequestLine().getMethod(); int sc = response.getStatusLine().getStatusCode(); if ("GET".equals(method)) { switch (sc) { case 200: case 203: case 206: case 300: case 301: case 302: case 303: case 307: case 308: case 410: setCacheControl(response, context); case 304: if (response.getFirstHeader("Cache-Control") != null) { setCacheControl(response, context); } } } } private void setCacheControl(HttpResponse response, final HttpContext context) { long now = CalliContext.adapt(context).getReceivedOn(); Header lastMod = response.getLastHeader("Last-Modified"); Header[] headers = response.getHeaders("Cache-Control"); if (headers != null && headers.length > 0 && now > 0 && lastMod != null) { String cc = getCacheControl(headers, lastMod, now); if (cc != null) { response.removeHeaders("Cache-Control"); response.setHeader("Cache-Control", cc); } } } private String getCacheControl(Header[] cache, Header lastMod, long now) { StringBuilder sb = new StringBuilder(); for (Header hd : cache) { if (sb.length() > 0) { sb.append(","); } sb.append(hd.getValue()); } if (sb.length() == 0 || sb.indexOf("max-age") < 0 && sb.indexOf("s-maxage") < 0 && sb.indexOf("no-cache") < 0 && sb.indexOf("no-store") < 0) { int maxage = getMaxAgeHeuristic(lastMod, now); if (maxage > 0) { if (sb.length() > 0) { sb.append(","); } sb.append("max-age=").append(maxage); return sb.toString(); } } return null; } private int getMaxAgeHeuristic(Header lastModified, long now) { long lm = lastModified(lastModified); int fraction = (int) ((now - lm) / 10000); return Math.min(fraction, (int) config.getHeuristicDefaultLifetime()); } private long lastModified(Header lastModified) { return modifiedformat.parseHeader(lastModified); } }
package org.pentaho.di.trans.steps.fixedinput; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.commons.io.FileUtils; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Read a simple fixed width file * Just output fields found in the file... * * @author Matt * @since 2007-07-06 */ public class FixedInput extends BaseStep implements StepInterface { private static Class<?> PKG = FixedInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private FixedInputMeta meta; private FixedInputData data; public FixedInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(FixedInputMeta)smi; data=(FixedInputData)sdi; if (first) { first=false; data.outputRowMeta = new RowMeta(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // The conversion logic for when the lazy conversion is turned of is simple: // Pretend it's a lazy conversion object anyway and get the native type during conversion. data.convertRowMeta = data.outputRowMeta.clone(); for (ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList()) { valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); } if (meta.isHeaderPresent()) { readOneRow(false); // skip this row. } } Object[] outputRowData=readOneRow(true); if (outputRowData==null) // no more input to be expected... { setOutputDone(); return false; } putRow(data.outputRowMeta, outputRowData); // copy row to possible alternate rowset(s). if (checkFeedback(getLinesInput())) logBasic(BaseMessages.getString(PKG, "FixedInput.Log.LineNumber", Long.toString(getLinesInput()))); //$NON-NLS-1$ return true; } /** Read a single row of data from the file... * * @param doConversions if you want to do conversions, set to false for the header row. * @return a row of data... * @throws KettleException */ private Object[] readOneRow(boolean doConversions) throws KettleException { try { // See if we need to call it a day... if (meta.isRunningInParallel()) { if (getLinesInput()>=data.rowsToRead) { return null; // We're done. The rest is for the other steps in the cluster } } Object[] outputRowData = RowDataUtil.allocateRowData(data.convertRowMeta.size()); int outputIndex=0; // The strategy is as follows... // We read a block of byte[] from the file. // Then we scan that block of data. // We keep a byte[] that we extend if needed.. // At the end of the block we read another, etc. // Let's start by looking where we left off reading. if (data.stopReading) { return null; } FixedFileInputField[] fieldDefinitions = meta.getFieldDefinition(); for (int i=0;i<fieldDefinitions.length;i++) { int fieldWidth = fieldDefinitions[i].getWidth(); data.endBuffer = data.startBuffer+fieldWidth; if (data.endBuffer>data.bufferSize) { // Oops, we need to read more data... // Better resize this before we read other things in it... data.resizeByteBuffer(); // Also read another chunk of data, now that we have the space for it... // Ignore EOF, there might be other stuff in the buffer. data.readBufferFromFile(); } // re-verify the buffer after we tried to read extra data from file... if (data.endBuffer>data.bufferSize) { // still a problem? // We hit an EOF and are trying to read beyond the EOF... // If we are on the first field and there // is nothing left in the buffer, don't return // a row because we're done. if ((0 == i) && data.bufferSize <= 0) { return null; } // This is the last record of data in the file. data.stopReading = true; // Just take what's left for the current field. fieldWidth=data.bufferSize; } byte[] field = new byte[fieldWidth]; System.arraycopy(data.byteBuffer, data.startBuffer, field, 0, fieldWidth); if (doConversions) { if (meta.isLazyConversionActive()) { outputRowData[outputIndex++] = field; } else { // We're not lazy so we convert the data right here and now. // The convert object uses binary storage as such we just have to ask the native type from it. // That will do the actual conversion. ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(outputIndex); outputRowData[outputIndex++] = sourceValueMeta.convertBinaryStringToNativeType(field); } } else { outputRowData[outputIndex++] = null; // nothing for the header, no conversions here. } // OK, onto the next field... data.startBuffer=data.endBuffer; } // Now that we have all the data, see if there are any linefeed characters to remove from the buffer... if (meta.isLineFeedPresent()) { data.endBuffer+=2; if (data.endBuffer>=data.bufferSize) { // Oops, we need to read more data... // Better resize this before we read other things in it... data.resizeByteBuffer(); // Also read another chunk of data, now that we have the space for it... data.readBufferFromFile(); } // CR + Line feed in the worst case. if (data.byteBuffer[data.startBuffer]=='\n' || data.byteBuffer[data.startBuffer]=='\r') { data.startBuffer++; if (data.byteBuffer[data.startBuffer]=='\n' || data.byteBuffer[data.startBuffer]=='\r') { data.startBuffer++; } } data.endBuffer = data.startBuffer; } incrementLinesInput(); return outputRowData; } catch (Exception e) { throw new KettleFileException("Exception reading line using NIO: " + e.toString(), e); } } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(FixedInputMeta)smi; data=(FixedInputData)sdi; if (super.init(smi, sdi)) { try { data.preferredBufferSize = Integer.parseInt(environmentSubstitute(meta.getBufferSize())); data.lineWidth = Integer.parseInt(environmentSubstitute(meta.getLineWidth())); data.filename = environmentSubstitute(meta.getFilename()); if (Const.isEmpty(data.filename)) { logError(BaseMessages.getString(PKG, "FixedInput.MissingFilename.Message")); return false; } FileObject fileObject = KettleVFS.getFileObject(data.filename, getTransMeta()); try { FileInputStream fileInputStream = new FileInputStream(FileUtils.toFile(fileObject.getURL())); data.fc = fileInputStream.getChannel(); data.bb = ByteBuffer.allocateDirect( data.preferredBufferSize ); } catch(IOException e) { logError(e.toString()); return false; } // Add filename to result filenames ? if(meta.isAddResultFile()) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, getTransMeta().getName(), toString()); resultFile.setComment("File was read by a Fixed input step"); addResultFile(resultFile); } logBasic("Opened file with name ["+data.filename+"]"); data.stopReading = false; if (meta.isRunningInParallel()) { data.stepNumber = getUniqueStepNrAcrossSlaves(); data.totalNumberOfSteps = getUniqueStepCountAcrossSlaves(); data.fileSize = fileObject.getContent().getSize(); } // OK, now we need to skip a number of bytes in case we're doing a parallel read. if (meta.isRunningInParallel()) { int totalLineWidth = data.lineWidth + meta.getLineSeparatorLength(); // including line separator bytes long nrRows = data.fileSize / totalLineWidth; // 100.000 / 100 = 1000 rows long rowsToSkip = Math.round( data.stepNumber * nrRows / (double)data.totalNumberOfSteps ); // 0, 333, 667 long nextRowsToSkip = Math.round( (data.stepNumber+1) * nrRows / (double)data.totalNumberOfSteps ); // 333, 667, 1000 data.rowsToRead = nextRowsToSkip - rowsToSkip; long bytesToSkip = rowsToSkip * totalLineWidth; logBasic("Step #"+data.stepNumber+" is skipping "+bytesToSkip+" to position in file, then it's reading "+data.rowsToRead+" rows."); data.fc.position(bytesToSkip); } return true; } catch (Exception e) { logError("Error opening file '"+meta.getFilename()+"'", e); } } return false; } @Override public void dispose(StepMetaInterface smi, StepDataInterface sdi) { try { if (data.fc!=null) { data.fc.close(); } } catch (IOException e) { logError("Unable to close file channel for file '"+meta.getFilename()+"' : "+e.toString()); logError(Const.getStackTracker(e)); } super.dispose(smi, sdi); } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; /** * Binary implementation of Vector. * * @author cohen */ public class BinaryVector extends Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); private static final int DEBUG_PRINT_LENGTH = 64; private final int dimension; /** * Elemental representation for binary vectors. */ private OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. this.bitSet.xor(binaryOther.bitSet); double hammingDistance = this.bitSet.cardinality(); this.bitSet.xor(binaryOther.bitSet); return 1 - (hammingDistance / (double) dimension); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = 2; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Returns a bitset with a "1" in the position of every dimension * that exactly matches the target number. */ private OpenBitSet exact(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); return tempSet; } String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length()) if (inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } // TODO(widdows): Figure out if there's a good reason for returning a member variable. // Seems redundant to do this. return tempSet; } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } //Voting record insufficient to hold half the votes (unlikely unless unbalanced vectors used), so return zero vector // if (votingRecord.size() < 1+ Math.log(target2)/Math.log(2)) // return new OpenBitSet(dimension); boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { tempSet = exact(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selected_decrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selected_decrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ public int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. */ public void normalize() { if (isSparse) elementalToSemantic(); this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tryied to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } this.votingRecord = new ArrayList<OpenBitSet>(); this.tempSet = new OpenBitSet(dimension); this.isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] new_coordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; new_coordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(new_coordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { return votingRecord.size(); } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; /** * Binary implementation of Vector. * * Uses an "elemental" representation which is a single bit string (Lucene OpenBitSet). * * Superposes on this a "semantic" representation which contains the weights with which different * vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the * voting record to be updated, but for performance the votes are not tallied back into the * elemental bit set representation until {@link #normalize} or one of the writing functions * is called. * * @author Trevor Cohen */ public class BinaryVector implements Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); // TODO: Determing proper interface for default constants. /** * Number of decimal places to consider in weighted superpositions of binary vectors. * Higher precision requires additional memory during training. */ public static final int BINARY_VECTOR_DECIMAL_PLACES = 2; public static final boolean BINARY_BINDING_WITH_PERMUTE = false; private static final int DEBUG_PRINT_LENGTH = 64; private Random random; private final int dimension; /** * Elemental representation for binary vectors. */ protected OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; this.random = new Random(); } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. double hammingDistance = OpenBitSet.xorCount(binaryOther.bitSet, this.bitSet); return 2*(0.5 - (hammingDistance / (double) dimension)); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (weight == 0d) return; if (other.isZeroVector()) return; BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = BINARY_VECTOR_DECIMAL_PLACES; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension * in the {@link #votingRecord} that exactly matches the target number. */ private void setTempSetToExactMatches(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); } else { String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length() && inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } } } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { setTempSetToExactMatches(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selectedDecrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selectedDecrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ protected int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Implements binding using permutations and XOR. */ public void bind(Vector other, int direction) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other.copy(); if (direction > 0) { //as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C //this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A) this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B } else { //as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A this.bitSet.xor(binaryOther.bitSet); //C XOR B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A } } @Override /** * Implements inverse of binding using permutations and XOR. */ public void release(Vector other, int direction) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind (other, direction); } @Override /** * Implements binding using exclusive OR. */ public void bind(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (!BINARY_BINDING_WITH_PERMUTE) { BinaryVector binaryOther = (BinaryVector) other; this.bitSet.xor(binaryOther.bitSet); } else { bind(other, 1); } } @Override /** * Implements inverse binding using exclusive OR. */ public void release(Vector other) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind(other, -1); } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. This approach deviates from the "majority rule" * approach that is standard in the Binary Spatter Code(). Rather, the probability of assigning a one in a particular dimension * is a function of the probability of encountering the number of votes in the voting record in this dimension. * * This will be slower than normalizeBSC() below, but discards less information with positive effects on accuracy in preliminary experiments * * As a simple example to illustrate why this would be the case, consider the superposition of vectors for the terms "jazz","jazz" and "rock" * With the BSC normalization, the vector produced is identical to "jazz" (as jazz wins the vote in each case). With probabilistic normalization, * the vector produced is somewhat similar to both "jazz" and "rock", with a similarity that is proportional to the weights assigned to the * superposition, e.g. 0.624000:jazz; 0.246000:rock * */ public void normalize() { if (votingRecord == null) return; if (votingRecord.size() == 1) { this.bitSet = votingRecord.get(0); return; } //clear bitset; this.bitSet.xor(this.bitSet); //Ensure that the same set of superposed vectors will always produce the same result long theSuperpositionSeed = 0; for (int q =0; q < votingRecord.size(); q++) theSuperpositionSeed += votingRecord.get(q).getBits()[0]; random.setSeed(theSuperpositionSeed); //Determine value above the universal minimum for each dimension of the voting record int[] counts = new int[dimension]; int max = totalNumberOfVotes; //Determine the maximum possible votes on the voting record int maxpossiblevotesonrecord = 0; for (int q=0; q < votingRecord.size(); q++) maxpossiblevotesonrecord += Math.pow(2, q); //For each possible value on the record, get a BitSet with a "1" in the //position of the dimensions that match this value for (int x = 1; x <= maxpossiblevotesonrecord; x++) { this.setTempSetToExactMatches(x); //no exact matches if (this.tempSet.cardinality() == 0) continue; //For each y==1 on said BitSet (indicating votes in dimension[y] == x) int y = tempSet.nextSetBit(0); //determine total number of votes double votes = minimum+x; //calculate standard deviations above/below the mean of max/2 double z = (votes - (max/2)) / (Math.sqrt(max)/2); //find proportion of data points anticipated within z standard deviations of the mean (assuming approximately normal distribution) double proportion = erf(z/Math.sqrt(2)); //convert into a value between 0 and 1 (i.e. centered on 0.5 rather than centered on 0) proportion = (1+proportion) /2; while (y != -1) { //probabilistic normalization if ((random.nextDouble()) <= proportion) this.bitSet.fastSet(y); y++; y = tempSet.nextSetBit(y); } } //housekeeping votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } // approximation of error function, equation 7.1.27 from //in Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, //9th printing. New York: Dover, pp. 299-300, 1972. // error of approximation <= 5*10^-4 public double erf(double z) { //erf(-x) == -erf(x) double sign = Math.signum(z); z = Math.abs(z); double a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108; double sumterm = 1 + a1*z + a2*Math.pow(z,2) + a3*Math.pow(z,3) + a4*Math.pow(z,4); return sign * ( 1-1/(Math.pow(sumterm, 4))); } /** * Faster normalization according to the Binary Spatter Code's "majority" rule */ public void normalizeBSC() { if (!isSparse) this.bitSet = concludeVote(); votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } /** * Counts votes without normalizing vector (i.e. voting record is not altered). Used in SemanticVectorCollider. */ public void tallyVotes() { if (!isSparse) this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tried to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); tempSet = new OpenBitSet(dimension); isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] newCoordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; newCoordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(newCoordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { if (isSparse) return 0; return votingRecord.size(); } }
package org.runestar.client.game.api; public final class FontId { private FontId() {} public static final int PLAIN_11 = 494; public static final int PLAIN_12 = 495; public static final int BOLD_12 = 496; public static final int QUILL_8 = 497; public static final int QUILL = 645; }
package io.graceland; import javax.servlet.Filter; import org.junit.Test; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import com.google.common.collect.ImmutableList; import io.dropwizard.Bundle; import io.dropwizard.cli.Command; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.Managed; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.servlets.tasks.Task; import io.dropwizard.setup.AdminEnvironment; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.graceland.application.Application; import io.graceland.application.SimpleApplication; import io.graceland.dropwizard.Configurator; import io.graceland.dropwizard.Initializer; import io.graceland.plugin.AbstractPlugin; import io.graceland.plugin.Plugin; import io.graceland.testing.TestBundle; import io.graceland.testing.TestCommand; import io.graceland.testing.TestConfigurator; import io.graceland.testing.TestFilter; import io.graceland.testing.TestHealthCheck; import io.graceland.testing.TestInitializer; import io.graceland.testing.TestManaged; import io.graceland.testing.TestResource; import io.graceland.testing.TestTask; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PlatformTest { protected Platform newPlatform(Application application) { return new Platform(application); } @Test(expected = NullPointerException.class) public void start_must_be_called_with_args() throws Exception { Application application = mock(Application.class); Platform platform = newPlatform(application); platform.start(null); } @Test public void can_build_with_application() { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); Platform.forApplication(application); } @Test(expected = NullPointerException.class) public void cannot_build_with_null_application() { Platform.forApplication(null); } @Test(expected = NullPointerException.class) public void constructed_with_valid_application() { new Platform(null); } @Test public void start_with_no_args() throws Exception { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); String[] args = new String[]{}; new Platform(application).start(args); } @Test public void run_adds_jersey_components() throws Exception { final Object jerseyComponent = new Object(); final Class<TestResource> jerseyComponentClass = TestResource.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindJerseyComponent(jerseyComponent); bindJerseyComponent(jerseyComponentClass); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(jerseyEnvironment).register(eq(jerseyComponent)); verify(jerseyEnvironment).register(isA(TestResource.class)); } @Test public void run_adds_managed() throws Exception { final Managed managed = mock(Managed.class); final Class<TestManaged> managedClass = TestManaged.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindManaged(managed); bindManaged(managedClass); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(lifecycleEnvironment).manage(eq(managed)); verify(lifecycleEnvironment).manage(isA(TestManaged.class)); } @Test public void run_adds_healthchecks() throws Exception { final HealthCheck healthCheck = mock(HealthCheck.class); final Class<TestHealthCheck> healthCheckClass = TestHealthCheck.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindHealthCheck(healthCheck); bindHealthCheck(healthCheckClass); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(healthCheckRegistry).register(anyString(), eq(healthCheck)); verify(healthCheckRegistry).register(anyString(), isA(TestHealthCheck.class)); } @Test public void run_adds_tasks() throws Exception { final Task task = mock(Task.class); final Class<TestTask> taskClass = TestTask.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindTask(task); bindTask(taskClass); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(adminEnvironment).addTask(eq(task)); verify(adminEnvironment).addTask(isA(TestTask.class)); } @Test public void run_adds_configurators() throws Exception { final Configurator configurator = mock(Configurator.class); final Class<TestConfigurator> configuratorClass = TestConfigurator.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindConfigurator(configurator); bindConfigurator(configuratorClass); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(configurator).configure(configuration, environment); // TODO: Figure out how to check for the class generated configurator } @Test public void run_adds_filters() throws Exception { final String filterName = "my-filter-name"; final Filter filter = mock(Filter.class); final Class<TestFilter> filterClass = TestFilter.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { buildFilter(filter).withName(filterName).withPriority(999).bind(); buildFilter(filterClass).withPriority(0).bind(); } }); } }; PlatformConfiguration configuration = mock(PlatformConfiguration.class); Environment environment = mock(Environment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); new Platform(application).run(configuration, environment); verify(servletEnvironment).addFilter(eq(filterClass.getSimpleName()), isA(filterClass)); verify(servletEnvironment).addFilter(eq(filterName), eq(filter)); } @Test public void initialize_adds_bundles() { final Bundle bundle = mock(Bundle.class); final Class<TestBundle> bundleClass = TestBundle.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindBundle(bundle); bindBundle(bundleClass); } }); } }; Bootstrap<PlatformConfiguration> bootstrap = mock(Bootstrap.class); new Platform(application).initialize(bootstrap); verify(bootstrap).addBundle(eq(bundle)); verify(bootstrap).addBundle(isA(TestBundle.class)); } @Test public void initialize_adds_commands() { final Command command = mock(Command.class); final Class<TestCommand> commandClass = TestCommand.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindCommand(command); bindCommand(commandClass); } }); } }; Bootstrap<PlatformConfiguration> bootstrap = mock(Bootstrap.class); new Platform(application).initialize(bootstrap); verify(bootstrap).addCommand(eq(command)); verify(bootstrap).addCommand(isA(TestCommand.class)); } @Test public void initialize_adds_initializers() { final Initializer initializer = mock(Initializer.class); final Class<TestInitializer> initializerClass = TestInitializer.class; Application application = new SimpleApplication() { @Override protected void configure() { loadPlugin(new AbstractPlugin() { @Override protected void configure() { bindInitializer(initializer); bindInitializer(initializerClass); } }); } }; Bootstrap<PlatformConfiguration> bootstrap = mock(Bootstrap.class); new Platform(application).initialize(bootstrap); // TODO: Add a verification for the class-generated Initializer verify(initializer).initialize(eq(bootstrap)); } }
package edu.colorado.csdms.wmt.client.control; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Window; import edu.colorado.csdms.wmt.client.Constants; import edu.colorado.csdms.wmt.client.data.ComponentJSO; import edu.colorado.csdms.wmt.client.data.ComponentListJSO; import edu.colorado.csdms.wmt.client.data.LabelJSO; import edu.colorado.csdms.wmt.client.data.LabelQueryJSO; import edu.colorado.csdms.wmt.client.data.ModelJSO; import edu.colorado.csdms.wmt.client.data.ModelListJSO; import edu.colorado.csdms.wmt.client.data.ModelMetadataJSO; import edu.colorado.csdms.wmt.client.ui.ComponentSelectionMenu; import edu.colorado.csdms.wmt.client.ui.handler.AddNewUserHandler; import edu.colorado.csdms.wmt.client.ui.handler.DialogCancelHandler; import edu.colorado.csdms.wmt.client.ui.widgets.DesensitizingPopupPanel; import edu.colorado.csdms.wmt.client.ui.widgets.NewUserDialogBox; import edu.colorado.csdms.wmt.client.ui.widgets.RunInfoDialogBox; /** * A class that defines static methods for accessing, modifying and deleting, * through asynchronous HTTP GET and POST requests, the JSON files used to set * up, configure and run WMT. * * @author Mark Piper (mark.piper@colorado.edu) */ public class DataTransfer { // Labels. If I make a spelling error, at least it'll be consistent. private static final String NEW = "new"; private static final String OPEN = "open"; private static final String SHOW = "show"; private static final String LOGIN = "login"; private static final String LOGOUT = "logout"; private static final String ADD = "add"; private static final String DELETE = "delete"; private static final String EDIT = "edit"; private static final String INIT = "init"; private static final String STAGE = "stage"; private static final String LAUNCH = "launch"; private static final String LIST = "list"; private static final String ATTACH = "attach"; private static final String QUERY = "query"; private static final String GET = "get"; public final native static <T> String stringify(T jso) /*-{ return JSON.stringify(jso, function(key, value) { if (key == '__gwt_ObjectId') { return; } return value; }); }-*/; public final native static <T> T parse(String jsonStr) /*-{ return JSON.parse(jsonStr); }-*/; /** * Returns a deep copy of the input JavaScriptObject. * <p> * This is the public interface to {@link #copyImpl(JavaScriptObject)}, which * does the heavy lifting. * * @param jso a JavaScriptObject */ @SuppressWarnings("unchecked") public static <T extends JavaScriptObject> T copy(T jso) { return (T) copyImpl(jso); } private static native JavaScriptObject copyImpl(JavaScriptObject obj) /*-{ if (obj == null) return obj; var copy; if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); } else if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i]; else copy[i] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]); } } else { copy = {}; for ( var attr in obj) { if (obj.hasOwnProperty(attr)) { if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr]; else copy[attr] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]); } } } return copy; }-*/; /** * A worker that builds a HTTP query string from a HashMap of key-value * entries. * * @param entries a HashMap of key-value pairs * @return the query, as a String */ private static String buildQueryString(HashMap<String, String> entries) { StringBuilder sb = new StringBuilder(); Integer entryCount = 0; for (Entry<String, String> entry : entries.entrySet()) { if (entryCount > 0) { sb.append("&"); } String encodedName = URL.encodeQueryString(entry.getKey()); sb.append(encodedName); sb.append("="); String encodedValue = URL.encodeQueryString(entry.getValue()); sb.append(encodedValue); entryCount++; } return sb.toString(); } /** * Makes an asynchronous HTTPS POST request to create a new user login to WMT. * * @param data the DataManager object for the WMT session */ public static void newUserLogin(DataManager data) { String url = DataURL.newUserLogin(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("username", data.security.getWmtUsername()); entries.put("password", data.security.getWmtPassword()); entries.put("password2", data.security.getWmtPassword()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new AuthenticationRequestCallback( data, url, NEW)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to login to WMT. * * @param data the DataManager object for the WMT session */ public static void login(DataManager data) { String url = DataURL.login(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("username", data.security.getWmtUsername()); entries.put("password", data.security.getWmtPassword()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new AuthenticationRequestCallback( data, url, LOGIN)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to logout from WMT. * * @param data the DataManager object for the WMT session */ public static void logout(DataManager data) { String url = DataURL.logout(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(null, new AuthenticationRequestCallback(data, url, LOGOUT)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS GET request to get the WMT login state from the * server. * * @param data the DataManager object for the WMT session */ public static void getLoginState(DataManager data) { String url = DataURL.loginState(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(null, new AuthenticationRequestCallback(data, url, LIST)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to retrieve the list of components * stored in the WMT database. * <p> * Note that on completion of the request, * {@link #getComponent(DataManager, String)} starts pulling data for * individual components from the server. * * @param data the DataManager object for the WMT session */ public static void getComponentList(DataManager data) { String url = DataURL.listComponents(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder .sendRequest(null, new ComponentListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to the server to retrieve the data * for a single component. * * @param data the DataManager object for the WMT session * @param componentId the identifier of the component in the database, a * String */ public static void getComponent(DataManager data, String componentId) { String url = DataURL.showComponent(data, componentId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ComponentRequestCallback(data, url, componentId)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to retrieve the list of models * stored in the WMT database. * * @param data the DataManager object for the WMT session */ public static void getModelList(DataManager data) { String url = DataURL.listModels(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ModelListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes a pair of asynchronous HTTP GET requests to retrieve model data and * metadata from a server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database, an * Integer */ public static void getModel(DataManager data, Integer modelId) { // The "open" URL returns metadata (name, owner) in a ModelMetadataJSO, // while the "show" URL returns data in a ModelJSO. String openURL = DataURL.openModel(data, modelId); GWT.log(openURL); String showURL = DataURL.showModel(data, modelId); GWT.log(showURL); RequestBuilder openBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(openURL)); try { @SuppressWarnings("unused") Request openRequest = openBuilder.sendRequest(null, new ModelRequestCallback(data, openURL, OPEN)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } RequestBuilder showBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(showURL)); try { @SuppressWarnings("unused") Request showRequest = showBuilder.sendRequest(null, new ModelRequestCallback(data, showURL, SHOW)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to save a new model, or edits to an * existing model, to the server. * * @param data the DataManager object for the WMT session */ public static void postModel(DataManager data) { Integer modelId = data.getMetadata().getId(); GWT.log("all model ids: " + data.modelIdList.toString()); GWT.log("this model id: " + modelId.toString()); String url, type; if (data.modelIdList.contains(modelId)) { url = DataURL.editModel(data, modelId); type = EDIT; } else { url = DataURL.newModel(data); type = NEW; } GWT.log(type + ": " + url); GWT.log(data.getModelString()); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("json", data.getModelString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new ModelRequestCallback(data, url, type)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to delete a single model from the * WMT server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database */ public static void deleteModel(DataManager data, Integer modelId) { String url = DataURL.deleteModel(data, modelId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder .sendRequest(null, new ModelRequestCallback(data, url, DELETE)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to initialize a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void initModelRun(DataManager data) { String url = DataURL.newModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("description", "A model submitted from the WMT GUI."); // XXX entries.put("model_id", ((Integer) data.getMetadata().getId()).toString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, INIT)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to stage a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void stageModelRun(DataManager data) { String url = DataURL.stageModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, STAGE)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to launch a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void launchModelRun(DataManager data) { String url = DataURL.launchModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); entries.put("host", data.security.getHpccHostname()); entries.put("username", data.security.getHpccUsername()); entries.put("password", data.security.getHpccPassword()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, LAUNCH)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to add a label to WMT. * * @param data the DataManager object for the WMT session * @param label the label to add, a String */ public static void addLabel(DataManager data, String label) { String url = DataURL.addLabel(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("tag", label); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new LabelRequestCallback(data, url, ADD)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to delete a label from WMT. * * @param data the DataManager object for the WMT session * @param labelId the id of the label to delete, an Integer */ public static void deleteLabel(DataManager data, Integer labelId) { String url = DataURL.deleteLabel(data, labelId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder .sendRequest(null, new LabelRequestCallback(data, url, DELETE)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS GET request to list all labels belonging to the * current user, as well as all public labels, in WMT. * * @param data the DataManager object for the WMT session */ public static void listLabels(DataManager data) { String url = DataURL.listLabels(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new LabelRequestCallback(data, url, LIST)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to attach a label to a model. * * @param data the DataManager object for the WMT session * @param modelId the id of the model, an Integer * @param labelId the id of the label to add, an Integer */ public static void addModelLabel(DataManager data, Integer modelId, Integer labelId) { String url = DataURL.addModelLabel(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("model", modelId.toString()); // type="text" in API entries.put("tag", labelId.toString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new LabelRequestCallback(data, url, ATTACH)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS GET request to query what models use the given * labels, input as an List of Integer ids. * * @param data the DataManager object for the WMT session * @param labelIds a List of Integer label ids */ public static void queryModelLabels(DataManager data, List<Integer> labelIds) { String url = DataURL.queryModelLabel(data); // Build the URL parameters from the list of input labelIds. url += "?tags="; for (int i = 0; i < labelIds.size(); i++) { if (i > 0) { url += ","; } url += labelIds.get(i); } GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new LabelRequestCallback(data, url, QUERY)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS GET request to query what models use the given * labels, input as an List of Integer ids. * * @param data the DataManager object for the WMT session * @param labelIds a List of Integer label ids */ public static void getModelLabels(DataManager data, Integer modelId) { String url = DataURL.getModelLabel(data, modelId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new LabelRequestCallback(data, url, GET)); } catch (RequestException e) { Window.alert(Constants.REQUEST_ERR_MSG + e.getMessage()); } } /** * A RequestCallback handler class that processes WMT login and logout * requests. */ public static class AuthenticationRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public AuthenticationRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } /* * A helper that performs actions on login. */ private void loginActions() { data.security.isLoggedIn(true); data.getPerspective().getLoginPanel().getLoginName().setText( data.security.getWmtUsername()); data.getPerspective().getLoginPanel().showStatusPanel(); data.getPerspective().getLoginPanel().getSignInButton().setFocus(false); // Get all labels belonging to the user, as well as all public labels. listLabels(data); // Set a cookie to store the most recent username. // TODO Replace with the browser's login autocomplete mechanism. String currentCookie = Cookies.getCookie(Constants.USERNAME_COOKIE); if (!data.security.getWmtUsername().equals(currentCookie)) { Date expires = new Date(System.currentTimeMillis() + Constants.COOKIE_DURATION); Cookies.setCookie(Constants.USERNAME_COOKIE, data.security .getWmtUsername(), expires); } } /* * A helper that performs actions on logout. */ private void logoutActions() { data.security.isLoggedIn(false); data.getPerspective().getLoginPanel().showInputPanel(); data.getPerspective().reset(); // Clear any user-owned labels from list. Locate first, then remove. List<String> toRemove = new ArrayList<String>(); for (Map.Entry<String, LabelJSO> entry : data.modelLabels.entrySet()) { if (data.security.getWmtUsername().equals(entry.getValue().getOwner())) { toRemove.add(entry.getKey()); } } for (String key : toRemove) { GWT.log("Remove label: " + key); data.modelLabels.remove(key); } // Remind the user to sign in to use WMT. (Grays out the entire window.) DesensitizingPopupPanel signInPopup = new DesensitizingPopupPanel(Constants.SIGN_IN_MSG); signInPopup.center(); } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); // Need to refresh the model list on login and logout. getModelList(data); if (type.matches(NEW)) { loginActions(); addLabel(data, data.security.getWmtUsername()); } else if (type.matches(LOGIN)) { loginActions(); } else if (type.matches(LOGOUT)) { logoutActions(); } else if (type.matches(LIST)) { String username = rtxt.replace("\"", ""); // strip quote marks if (username.isEmpty()) { logoutActions(); } else { data.security.setWmtUsername(username); loginActions(); } } else { Window.alert(Constants.RESPONSE_ERR_MSG); } } else if (Response.SC_BAD_REQUEST == response.getStatusCode()) { // Display the NewUserDialogBox if the email address isn't recognized. final NewUserDialogBox box = new NewUserDialogBox(); box.getChoicePanel().getCancelButton().addClickHandler( new DialogCancelHandler(box)); box.getChoicePanel().getOkButton().addClickHandler( new AddNewUserHandler(data, box)); box.center(); } else if (Response.SC_UNAUTHORIZED == response.getStatusCode()) { // Display message if email address is valid, but password is not. Window.alert(Constants.PASSWORD_ERR); } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available components in the WMT database. On * success, the list of component ids are stored in the {@link DataManager} * object for the WMT session. Concurrently, * {@link DataTransfer#getComponent(DataManager, String)} is called to * download and store information on the listed components. */ public static class ComponentListRequestCallback implements RequestCallback { private DataManager data; private String url; public ComponentListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentListJSO jso = parse(rtxt); // Load the list of components into the DataManager. At the same time, // start pulling down data for the components. Asynchronicity is cool! for (int i = 0; i < jso.getComponents().length(); i++) { String componentId = jso.getComponents().get(i); data.componentIdList.add(componentId); data.retryComponentLoad.put(componentId, 0); getComponent(data, componentId); } // Show the list of components (id only) as placeholders in the // ComponentSelectionMenu. ((ComponentSelectionMenu) data.getPerspective().getModelTree() .getDriverComponentCell().getComponentMenu()) .initializeComponents(); } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of a component. On success, * {@link DataManager#addComponent(ComponentJSO)} and * {@link DataManager#addModelComponent(ComponentJSO)} are called to store the * (class) component and the model component in the DataManager object for the * WMT session. */ public static class ComponentRequestCallback implements RequestCallback { private DataManager data; private String url; private String componentId; public ComponentRequestCallback(DataManager data, String url, String componentId) { this.data = data; this.url = url; this.componentId = componentId; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentJSO jso = parse(rtxt); data.addComponent(jso); // "class" component data.addModelComponent(copy(jso)); // "instance" component, for model data.nComponents++; if (data.nComponents == data.componentIdList.size()) { data.showDefaultCursor(); } // Replace the associated placeholder ComponentSelectionMenu item. ((ComponentSelectionMenu) data.getPerspective().getModelTree() .getDriverComponentCell().getComponentMenu()).replaceMenuItem(jso .getId()); } else { // If the component didn't load, try to reload it RETRY_ATTEMPTS times. // If that fails, display an error message in a window. Integer attempt = data.retryComponentLoad.get(componentId); data.retryComponentLoad.put(componentId, attempt++); if (attempt < Constants.RETRY_ATTEMPTS) { getComponent(data, componentId); } else { data.nComponents++; String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available models in the WMT database. On success, * the list of model names and ids are stored in the {@link DataManager} * object for the WMT session. */ public static class ModelListRequestCallback implements RequestCallback { private DataManager data; private String url; public ModelListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ModelListJSO jso = parse(rtxt); // Start with clean lists of model names and ids. data.modelIdList.clear(); data.modelNameList.clear(); // Load the list of models into the DataManager. for (int i = 0; i < jso.getModels().length(); i++) { data.modelIdList.add(jso.getModels().get(i).getModelId()); data.modelNameList.add(jso.getModels().get(i).getName()); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a model GET * or POST request. * <p> * On a successful GET, {@link DataManager#deserialize()} is called to * populate the WMT GUI. On a successful POST, * {@link DataTransfer#getModelList(DataManager)} is called to refresh the * list of models available on the server. */ public static class ModelRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public ModelRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } /* * A helper for processing the return from models/show. */ private void showActions(String rtxt) { ModelJSO jso = parse(rtxt); data.setModel(jso); data.modelIsSaved(true); data.deserialize(); } /* * A helper for processing the return from models/open. */ private void openActions(String rtxt) { ModelMetadataJSO jso = parse(rtxt); data.setMetadata(jso); getModelLabels(data, data.getMetadata().getId()); } /* * A helper for processing the return from models/new and models/edit. */ private void editActions() { data.updateModelSaveState(true); DataTransfer.getModelList(data); addSelectedLabels(data.getMetadata().getId()); } /* * A helper for adding all selected labels to a model. */ private void addSelectedLabels(Integer modelId) { for (Map.Entry<String, LabelJSO> entry : data.modelLabels.entrySet()) { if (entry.getValue().isSelected()) { addModelLabel(data, modelId, entry.getValue().getId()); } } } @Override public void onResponseReceived(Request request, Response response) { data.showDefaultCursor(); if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches(SHOW)) { showActions(rtxt); } else if (type.matches(OPEN)) { openActions(rtxt); } else if (type.matches(NEW)) { Integer modelId = Integer.valueOf(rtxt); data.getMetadata().setId(modelId); editActions(); } else if (type.matches(EDIT)) { editActions(); } else if (type.matches(DELETE)) { DataTransfer.getModelList(data); } else { Window.alert(Constants.RESPONSE_ERR_MSG); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that handles the initialization, staging * and launching of a model run. */ public static class RunRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public RunRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches(INIT)) { String uuid = rtxt.replaceAll("^\"|\"$", ""); data.setSimulationId(uuid); // store the run's uuid DataTransfer.stageModelRun(data); } else if (type.matches(STAGE)) { DataTransfer.launchModelRun(data); } else if (type.matches(LAUNCH)) { RunInfoDialogBox runInfo = new RunInfoDialogBox(data); runInfo.center(); runInfo.getChoicePanel().getOkButton().setFocus(true); } else { Window.alert(Constants.RESPONSE_ERR_MSG); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that handles listing, adding, and deleting * labels. */ public static class LabelRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public LabelRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } /* * A helper for adding a new label. */ private void addActions(String rtxt) { LabelJSO jso = parse(rtxt); data.modelLabels.put(jso.getLabel(), jso); data.getPerspective().getLabelsMenu().populateMenu(); } /* * A helper for deleting a label. */ private void deleteActions(String rtxt) { Integer labelId = Integer.valueOf(rtxt.replaceAll("^\"|\"$", "")); for (Map.Entry<String, LabelJSO> entry : data.modelLabels.entrySet()) { LabelJSO jso = entry.getValue(); if (jso.getId() == labelId) { data.modelLabels.remove(jso.getLabel()); break; } } data.getPerspective().getLabelsMenu().populateMenu(); } /* * A helper for listing all labels. */ private void listActions(String rtxt) { LabelJSO jso = parse(rtxt); Integer nLabels = jso.getLabels().length(); if (nLabels > 0) { for (int i = 0; i < nLabels; i++) { LabelJSO labelJSO = jso.getLabels().get(i); String label = labelJSO.getLabel(); Boolean isUser = data.security.getWmtUsername().matches(label); labelJSO.isSelected(isUser); data.modelLabels.put(label, labelJSO); } } } /* * A helper for acting on a query of models associated with a given label. */ private void queryActions(String rtxt) { LabelQueryJSO jso = parse(rtxt); // Window.alert(jso.getIds().join()); // Populate the droplist with the restricted list of models. data.getPerspective().getOpenDialogBox().getDroplistPanel().getDroplist() .clear(); for (int i = 0; i < jso.getIds().length(); i++) { Integer modelId = jso.getIds().get(i); Integer modelIndex = data.modelIdList.indexOf(modelId); if (modelIndex == -1) { // the API shouldn't return nonexistent models, continue; // but just in case... } String modelName = data.modelNameList.get(modelIndex); data.getPerspective().getOpenDialogBox().getDroplistPanel() .getDroplist().addItem(modelName); } } /* * A helper for selecting the labels attached to a model. */ private void getActions(String rtxt) { LabelQueryJSO jso = parse(rtxt); for (Map.Entry<String, LabelJSO> entry : data.modelLabels.entrySet()) { for (int i = 0; i < jso.getIds().length(); i++) { GWT.log("Entry : " + entry.getValue().getId()); GWT.log("JSO : " + jso.getIds().get(i)); if (entry.getValue().getId() == jso.getIds().get(i)) { entry.getValue().isSelected(true); } } } } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches(ADD)) { addActions(rtxt); } else if (type.matches(DELETE)) { deleteActions(rtxt); } else if (type.matches(LIST)) { listActions(rtxt); } else if (type.matches(ATTACH)) { ; // Do nothing } else if (type.matches(QUERY)) { queryActions(rtxt); } else if (type.matches(GET)) { getActions(rtxt); } else { Window.alert(Constants.RESPONSE_ERR_MSG); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(Constants.REQUEST_ERR_MSG + exception.getMessage()); } } }
package com.akjava.gwt.three.client.js.textures; import com.akjava.gwt.three.client.js.core.EventDispatcher; import com.akjava.gwt.three.client.js.math.Vector2; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.ImageElement; public class Texture extends EventDispatcher{ protected Texture(){} /** * @deprecated * @return */ public final native int getGWTImageWidth()/*-{ return this.image.width; }-*/; public final native int getId()/*-{ return this.id; }-*/; public final native String getUuid()/*-{ return this.uuid; }-*/; public final native String getName()/*-{ return this.name; }-*/; public final native void setName(String name)/*-{ this.name = name; }-*/; public final native ImageElement getImage()/*-{ return this.image; }-*/; //get image as array,it's possible public final native JsArray<ImageElement> getGwtImages()/*-{ return this.image; }-*/; public final native void setImage(ImageElement image)/*-{ this.image = image; }-*/; public final native JsArray<JavaScriptObject> getMipmaps()/*-{ return this.mipmaps; }-*/; public final native void setMipmaps(JsArray<JavaScriptObject> mipmaps)/*-{ this.mipmaps = mipmaps; }-*/; public final native JavaScriptObject getMapping()/*-{ return this.mapping; }-*/; public final native void setMapping(JavaScriptObject mapping)/*-{ this.mapping = mapping; }-*/; public final native int getWrapS()/*-{ return this.wrapS; }-*/; public final native void setWrapS(int wrapS)/*-{ this.wrapS = wrapS; }-*/; public final native int getWrapT()/*-{ return this.wrapT; }-*/; public final native void setWrapT(int wrapT)/*-{ this.wrapT = wrapT; }-*/; public final native int getMagFilter()/*-{ return this.magFilter; }-*/; public final native void setMagFilter(int magFilter)/*-{ this.magFilter = magFilter; }-*/; public final native int getMinFilter()/*-{ return this.minFilter; }-*/; public final native void setMinFilter(int minFilter)/*-{ this.minFilter = minFilter; }-*/; /** * i'm not sure * @return */ public final native int getAnisotropy()/*-{ return this.anisotropy; }-*/; public final native void setAnisotropy(int anisotropy)/*-{ this.anisotropy = anisotropy; }-*/; public final native int getFormat()/*-{ return this.format; }-*/; public final native void setFormat(int format)/*-{ this.format = format; }-*/; public final native int getType()/*-{ return this.type; }-*/; public final native void setType(int type)/*-{ this.type = type; }-*/; public final native Vector2 getOffset()/*-{ return this.offset; }-*/; public final native void setOffset(Vector2 offset)/*-{ this.offset = offset; }-*/; public final native Vector2 getRepeat()/*-{ return this.repeat; }-*/; public final native void setRepeat(Vector2 repeat)/*-{ this.repeat = repeat; }-*/; public final native boolean isGenerateMipmaps()/*-{ return this.generateMipmaps; }-*/; public final native void setGenerateMipmaps(boolean generateMipmaps)/*-{ this.generateMipmaps = generateMipmaps; }-*/; public final native boolean isPremultiplyAlpha()/*-{ return this.premultiplyAlpha; }-*/; public final native void setPremultiplyAlpha(boolean premultiplyAlpha)/*-{ this.premultiplyAlpha = premultiplyAlpha; }-*/; public final native boolean isFlipY()/*-{ return this.flipY; }-*/; public final native void setFlipY(boolean flipY)/*-{ this.flipY = flipY; }-*/; public final native int getUnpackAlignment()/*-{ return this.unpackAlignment; }-*/; public final native void setUnpackAlignment(int unpackAlignment)/*-{ this.unpackAlignment = unpackAlignment; }-*/; public final native boolean isNeedsUpdate()/*-{ return this.needsUpdate; }-*/; public final native void setNeedsUpdate(boolean needsUpdate)/*-{ this.needsUpdate = needsUpdate; }-*/; public final native JavaScriptObject getOnUpdate()/*-{ return this.onUpdate; }-*/; public final native void setOnUpdate(JavaScriptObject onUpdate)/*-{ this.onUpdate = onUpdate; }-*/; public final native Texture clone(Texture texture)/*-{ return this.clone(texture); }-*/; public final native void dispose()/*-{ this.dispose(); }-*/; public static final native Texture getDefaultImage()/*-{ return $wnd.THREE.Texture.DEFAULT_IMAGE; }-*/; public static final native JavaScriptObject getDefaultMapping()/*-{ return $wnd.THREE.Texture.DEFAULT_MAPPING; }-*/; public final native String getSourceFile()/*-{ return this.sourceFile; }-*/; public final native void setSourceFile(String sourceFile)/*-{ this.sourceFile = sourceFile; }-*/; }
package org.verapdf.report; import java.io.OutputStream; import java.util.Formatter; import java.util.GregorianCalendar; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.log4j.Logger; import org.verapdf.features.tools.FeaturesCollection; import org.verapdf.pdfa.MetadataFixerResult; import org.verapdf.pdfa.results.ValidationResult; import org.verapdf.pdfa.validation.Profiles; import org.verapdf.pdfa.validation.ValidationProfile; /** * @author Maksim Bezrukov */ @XmlRootElement(name = "report") public class MachineReadableReport { private static final Logger LOGGER = Logger .getLogger(MachineReadableReport.class); private static final long MS_IN_SEC = 1000L; private static final int SEC_IN_MIN = 60; private static final long MS_IN_MIN = SEC_IN_MIN * MS_IN_SEC; private static final int MIN_IN_HOUR = 60; private static final long MS_IN_HOUR = MS_IN_MIN * MIN_IN_HOUR; @XmlAttribute private final String creationDate; @XmlAttribute private final String processingTime; @XmlElement(name = "validationReport") private final ValidationReport validationReport; @XmlElement private final FeaturesReport pdfFeaturesReport; private MachineReadableReport() { this( ValidationReport.fromValues(Profiles.defaultProfile(), null, false), "", "", null); } private MachineReadableReport(ValidationReport report, String creationDate, String processingTime, FeaturesReport featuresReport) { this.validationReport = report; this.creationDate = creationDate; this.processingTime = processingTime; this.pdfFeaturesReport = featuresReport; } /** * @param profile * @param validationResult * @param reportPassedChecks * @param fixerResult * @param collection * @param processingTime * @return a MachineReadableReport instance initialised from the passed * values */ public static MachineReadableReport fromValues(ValidationProfile profile, ValidationResult validationResult, boolean reportPassedChecks, MetadataFixerResult fixerResult, FeaturesCollection collection, long processingTime) { ValidationReport validationReport = null; if (validationResult != null) { validationReport = ValidationReport.fromValues(profile, validationResult, reportPassedChecks, fixerResult); } FeaturesReport featuresReport = FeaturesReport.fromValues(collection); return new MachineReadableReport(validationReport, getNowDateString(), getProcessingTime(processingTime), featuresReport); } /** * @param toConvert * @param stream * @param prettyXml * @throws JAXBException */ public static void toXml(final MachineReadableReport toConvert, final OutputStream stream, Boolean prettyXml) throws JAXBException { Marshaller varMarshaller = getMarshaller(prettyXml); varMarshaller.marshal(toConvert, stream); } private static Marshaller getMarshaller(Boolean setPretty) throws JAXBException { JAXBContext context = JAXBContext .newInstance(MachineReadableReport.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, setPretty); return marshaller; } private static String getNowDateString() { String creationDate = ""; GregorianCalendar gregorianCalendar = new GregorianCalendar(); try { XMLGregorianCalendar now = DatatypeFactory.newInstance() .newXMLGregorianCalendar(gregorianCalendar); creationDate = now.toXMLFormat(); } catch (DatatypeConfigurationException e) { LOGGER.error(e); creationDate = e.getMessage(); } return creationDate; } private static String getProcessingTime(long processTime) { long processingTime = processTime; Long hours = Long.valueOf(processingTime / MS_IN_HOUR); processingTime %= MS_IN_HOUR; Long mins = Long.valueOf(processingTime / MS_IN_MIN); processingTime %= MS_IN_MIN; Long sec = Long.valueOf(processingTime / MS_IN_SEC); processingTime %= MS_IN_SEC; Long ms = Long.valueOf(processingTime); String res; try (Formatter formatter = new Formatter()) { formatter.format("%02d:", hours); formatter.format("%02d:", mins); formatter.format("%02d.", sec); formatter.format("%03d", ms); res = formatter.toString(); } return res; } }
package com.coolweather.app.activity; import java.util.ArrayList; import java.util.List; import com.coolweather.app.R; import com.coolweather.app.model.City; import com.coolweather.app.model.CoolWeatherDB; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; public class ChooseAreaActivity extends Activity { // clone public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private ListView listView; private ArrayAdapter<String> adapter; private CoolWeatherDB coolWeatherDB; private List<String> dataList = new ArrayList<String>(); private List<Province> provinceList; private List<City> cityList; private List<County> countyList; private Province selectedProvince; private City selectedCity; private int currentLevel; private boolean isFromWeatherActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) { Intent intent = new Intent(this, WeatherActivity.class); startActivity(intent); finish(); return; } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); listView = (ListView) findViewById(R.id.list_view); titleText = (TextView) findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,dataList); listView.setAdapter(adapter); coolWeatherDB = CoolWeatherDB.getInstance(this); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(index); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(index); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { String countyCode = countyList.get(index).getCountyCode(); Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class); intent.putExtra("county_code", countyCode); startActivity(intent); finish(); } } }); queryProvinces(); } private void queryProvinces(){ provinceList = coolWeatherDB.loadProvinces(); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText("й"); currentLevel = LEVEL_PROVINCE; } else { queryFromServer(null, "province"); } } private void queryCities(){ cityList = coolWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY; } else { queryFromServer(selectedProvince.getProvinceCode(), "city"); } } private void queryCounties(){ countyList = coolWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTY; } else { queryFromServer(selectedCity.getCityCode(), "county"); } } private void queryFromServer(final String code, final String type){ String address; if (!TextUtils.isEmpty(code)) { address = "http: } else { address = "http: } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { // TODO Auto-generated method stub boolean result = false; if ("province".equals(type)) { result = Utility.handleProvincesResponse(coolWeatherDB, response); } else if ("city".equals(type)){ result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId()); } else if ("county".equals(type)){ result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId()); } if (result) { runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)){ queryCities(); } else if ("county".equals(type)){ queryCounties(); } } }); } } @Override public void onError(Exception e) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(ChooseAreaActivity.this, "ʧ", Toast.LENGTH_SHORT).show(); } }); } }); } private void showProgressDialog(){ if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setMessage("ڼء"); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog(){ if (progressDialog != null) { progressDialog.dismiss(); } } @Override public void onBackPressed(){ if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY){ queryProvinces(); } else { if (isFromWeatherActivity) { Intent intent = new Intent(this, WeatherActivity.class); startActivity(intent); } finish(); } } }
package com.haskforce.settings; import com.haskforce.HaskellIcons; import com.haskforce.highlighting.HaskellSyntaxHighlighter; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; public class HaskellColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[] { new AttributesDescriptor("Pragma", HaskellSyntaxHighlighter.PRAGMA), new AttributesDescriptor("Reserved IDs", HaskellSyntaxHighlighter.RESERVEDID), new AttributesDescriptor("Constructor", HaskellSyntaxHighlighter.CONID), new AttributesDescriptor("Variable", HaskellSyntaxHighlighter.VARID), new AttributesDescriptor("Infix Function", HaskellSyntaxHighlighter.INFIXVARID), new AttributesDescriptor("Symbol", HaskellSyntaxHighlighter.VARSYM), new AttributesDescriptor("Cons Symbol", HaskellSyntaxHighlighter.CONSYM), new AttributesDescriptor("Reserved Symbol", HaskellSyntaxHighlighter.RESERVEDOP), new AttributesDescriptor("Special", HaskellSyntaxHighlighter.SPECIAL), new AttributesDescriptor("String", HaskellSyntaxHighlighter.STRING), new AttributesDescriptor("Integer", HaskellSyntaxHighlighter.INTEGER), new AttributesDescriptor("Float", HaskellSyntaxHighlighter.FLOAT), new AttributesDescriptor("Char", HaskellSyntaxHighlighter.CHAR), new AttributesDescriptor("Line Comment", HaskellSyntaxHighlighter.COMMENT), new AttributesDescriptor("Block Comment", HaskellSyntaxHighlighter.NCOMMENT), new AttributesDescriptor("Doc Comment", HaskellSyntaxHighlighter.HADDOCK), new AttributesDescriptor("Escape", HaskellSyntaxHighlighter.ESCAPE), new AttributesDescriptor("Quasi Quotes", HaskellSyntaxHighlighter.QQTEXT), }; @Nullable @Override public Icon getIcon() { return HaskellIcons.FILE; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new HaskellSyntaxHighlighter(); } @NotNull @Override public String getDemoText() { return "{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}\n" + "<ri>module</ri> Example <sp>(</sp><vi>foo</vi><sp>,</sp> <vi>bar</vi><sp>)</sp> <ri>where</ri>\n" + "\n" + "<ri>import</ri> Control.Monad <ri>as</ri> M\n" + "<ri>import</ri> Control.Monad <sp>(</sp><vi>liftM2</vi><sp>)</sp>\n" + "<ri>import</ri> Control.Monad.Zip <ri>as</ri> Z\n" + "\n" + "<nc>{-\n" + " - Multiline comment\n" + " - {-\n" + " - - Nested comment\n" + " - -}\n" + " -}</nc>\n" + "\n" + "<ri>class</ri> Fooable <vi>a</vi> <ri>where</ri>\n" + " <vi>foo</vi> <ro>::</ro> <vi>a</vi> --^ Haddock comment\n" + " <ro>-></ro> String\n" + "\n" + "-- Line comment.\n" + "\n" + "<ri>instance</ri> MonadZip Maybe <ri>where</ri>\n" + " <vi>mzip</vi> <ro>=</ro> <vi>liftM2</vi> <sp>(</sp><sp>,</sp><sp>)</sp>\n" + "\n" + "(<vs><~></vs>) <ro>::</ro> Maybe <vi>a</vi> <ro>-></ro> Maybe <vi>b</vi> <ro>-></ro> Maybe <sp>(</sp><vi>a</vi><sp>,</sp> <vi>b</vi><sp>)</sp>\n" + "(<vs><~></vs>) <ro>=</ro> <vi>mzip</vi>\n" + "\n" + "<vi>bar</vi> <ro>::</ro> [<vi>a</vi>] <ro>-></ro> Int <ro>-></ro> <sp>[</sp><vi>a</vi><sp>]</sp>\n" + "<vi>bar</vi> <vi>xs</vi> 0 <ro>=</ro> <sp>[</sp><sp>]</sp>\n" + "<vi>bar</vi> <vi>xs</vi> <vi>n</vi> <ro>=</ro> <vi>xs</vi> <vs>++</vs> <sp>(</sp><vi>bar</vi> <vi>xs</vi> <sp>(</sp><vi>n</vi> <vs>-</vs> 1<sp>)</sp><sp>)</sp>\n" + "\n" + "<vi>listToBool</vi> <ro>::</ro> <sp>[</sp><vi>a</vi><sp>]</sp> <ro>-></ro> Bool\n" + "<vi>listToBool</vi> <sp>[</sp><sp>]</sp> <ro>=</ro> False\n" + "<vi>listToBool</vi> <ri>_</ri> <ro>=</ro> True\n" + "\n" + "<vi>listToBool'</vi> <vi>xs</vi> <ro>=</ro> <ri>if</ri> <vi>length</vi> <vi>xs</vi> <vs>></vs> 0 <ri>then</ri> True <ri>else</ri> False\n" + "\n" + "<vi>listToBool''</vi> <ro>=</ro> <vi>not</vi> <vs>.</vs> <vi>null</vi>\n" + "\n" + "<vi>x</vi> <ro>=</ro> <sp>(</sp><vs>+</vs>1<sp>)</sp> <iv>`M.liftM`</iv> <sp>(</sp>Just 3<sp>)</sp>\n" + "\n" + "<vi>int</vi> <ro>=</ro> 1\n" + "<vi>float</vi> <ro>=</ro> 1.2\n" + "<vi>char</vi> <ro>=</ro> 'a'\n" + "<vi>list</vi> <ro>=</ro> 1<cs>:</cs><sp>[]</sp>\n" + "<vi>string</vi> <ro>=</ro> \"I'm a string.\"\n" + "<vi>multiline</vi> <ro>=</ro> \"\\\n" + " \\This string \\\n" + " \\spans \\\"multiple\\\" \\\n" + " \\lines!\\\n" + " \\\"\n" + "quasiQuoted <ro>=</ro> <sp>[</sp>myQuoter|<qq>\n" + " Here's some quasi quotes!\n" + "</qq><sp>|]</sp>"; } @Nullable @Override public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { @NonNls final Map<String, TextAttributesKey> map = new THashMap<String, TextAttributesKey>(); map.put("ri", HaskellSyntaxHighlighter.RESERVEDID); map.put("ro", HaskellSyntaxHighlighter.RESERVEDOP); map.put("vs", HaskellSyntaxHighlighter.VARSYM); map.put("cs", HaskellSyntaxHighlighter.CONSYM); map.put("vi", HaskellSyntaxHighlighter.VARID); map.put("iv", HaskellSyntaxHighlighter.INFIXVARID); map.put("nc", HaskellSyntaxHighlighter.NCOMMENT); map.put("sp", HaskellSyntaxHighlighter.SPECIAL); map.put("qq", HaskellSyntaxHighlighter.QQTEXT); return map; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "Haskell"; } }
package com.haskforce.settings; import com.haskforce.ui.JTextAccessorField; import com.haskforce.utils.ExecUtil; import com.haskforce.utils.GuiUtil; import com.haskforce.utils.NotificationUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.NotificationType; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Pair; import com.intellij.ui.JBColor; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.TextAccessor; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import scala.runtime.AbstractFunction1; import javax.swing.*; import java.awt.*; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The "Haskell Tools" option in Preferences->Project Settings. */ public class HaskellToolsConfigurable implements SearchableConfigurable { public static final String HASKELL_TOOLS_ID = "Haskell Tools"; private static final Logger LOG = Logger.getInstance(HaskellToolsConfigurable.class); private PropertiesComponent propertiesComponent; // Swing components. private JPanel mainPanel; private TextFieldWithBrowseButton stylishPath; private RawCommandLineEditor stylishFlags; private JButton stylishAutoFind; private JTextField stylishVersion; private TextFieldWithBrowseButton hlintPath; private RawCommandLineEditor hlintFlags; private JButton hlintAutoFind; private JTextField hlintVersion; private TextFieldWithBrowseButton ghcModPath; private RawCommandLineEditor ghcModFlags; private JButton ghcModAutoFind; private JTextField ghcModVersion; private TextFieldWithBrowseButton ghcModiPath; private JButton ghcModiAutoFind; private JTextField ghcModiVersion; private RawCommandLineEditor ghcModiFlags; private JTextAccessorField ghcModiTimeout; private TextFieldWithBrowseButton hindentPath; private JButton hindentAutoFind; private JTextField hindentVersion; private RawCommandLineEditor hindentFlags; private List<Property> properties; public HaskellToolsConfigurable(@NotNull Project project) { this.propertiesComponent = PropertiesComponent.getInstance(project); properties = Arrays.asList( new Tool(project, "stylish-haskell", ToolKey.STYLISH_HASKELL_KEY, stylishPath, stylishFlags, stylishAutoFind, stylishVersion, "--help"), new Tool(project, "hlint", ToolKey.HLINT_KEY, hlintPath, hlintFlags, hlintAutoFind, hlintVersion), new Tool(project, "ghc-mod", ToolKey.GHC_MOD_KEY, ghcModPath, ghcModFlags, ghcModAutoFind, ghcModVersion, "version"), new Tool(project, "ghc-modi", ToolKey.GHC_MODI_KEY, ghcModiPath, ghcModiFlags, ghcModiAutoFind, ghcModiVersion, "version", SettingsChangeNotifier.GHC_MODI_TOPIC), new PropertyField(ToolKey.GHC_MODI_TIMEOUT_KEY, ghcModiTimeout, Long.toString(ToolKey.getGhcModiTimeout(project))), new Tool(project, "hindent", ToolKey.HINDENT_KEY, hindentPath, hindentFlags, hindentAutoFind, hindentVersion) ); // Validate that we can only enter numbers in the timeout field. final Color originalBackground = ghcModiTimeout.getBackground(); ghcModiTimeout.setInputVerifier(new InputVerifier() { @Override public boolean verify(JComponent input) { JTextAccessorField field = (JTextAccessorField)input; try { //noinspection ResultOfMethodCallIgnored Long.parseLong(field.getText()); } catch (NumberFormatException e) { field.setBackground(JBColor.RED); return false; } field.setBackground(originalBackground); return true; } }); } interface Property { boolean isModified(); void saveState(); void restoreState(); } interface Versioned { void updateVersion(); } /** * Manages the state of a PropertyComponent and its respective field. */ class PropertyField implements Property { public String oldValue; public String propertyKey; public final TextAccessor field; PropertyField(@NotNull String propertyKey, @NotNull TextAccessor field) { this(propertyKey, field, ""); } PropertyField(@NotNull String propertyKey, @NotNull TextAccessor field, @NotNull String defaultValue) { this.propertyKey = propertyKey; this.field = field; this.oldValue = propertiesComponent.getValue(propertyKey, defaultValue); field.setText(oldValue); } public boolean isModified() { return !field.getText().equals(oldValue); } public void saveState() { propertiesComponent.setValue(propertyKey, oldValue = field.getText()); } public void restoreState() { field.setText(oldValue); } } /** * Manages the group of fields which reside to a particular tool. */ class Tool implements Property, Versioned { public final Project project; public final String command; public final ToolKey key; public final TextFieldWithBrowseButton pathField; public final RawCommandLineEditor flagsField; public final JTextField versionField; public final String versionParam; public final JButton autoFindButton; public final List<PropertyField> propertyFields; public final @Nullable Topic<SettingsChangeNotifier> topic; private final @Nullable SettingsChangeNotifier publisher; Tool(Project project, String command, ToolKey key, TextFieldWithBrowseButton pathField, RawCommandLineEditor flagsField, JButton autoFindButton, JTextField versionField) { this(project, command, key, pathField, flagsField, autoFindButton, versionField, "--version"); } Tool(Project project, String command, ToolKey key, TextFieldWithBrowseButton pathField, RawCommandLineEditor flagsField, JButton autoFindButton, JTextField versionField, String versionParam) { this(project, command, key, pathField, flagsField, autoFindButton, versionField, versionParam, null); } Tool(Project project, String command, ToolKey key, TextFieldWithBrowseButton pathField, RawCommandLineEditor flagsField, JButton autoFindButton, JTextField versionField, String versionParam, @Nullable Topic<SettingsChangeNotifier> topic) { this.project = project; this.command = command; this.key = key; this.pathField = pathField; this.flagsField = flagsField; this.versionField = versionField; this.versionParam = versionParam; this.autoFindButton = autoFindButton; this.topic = topic; this.publisher = topic == null ? null : project.getMessageBus().syncPublisher(topic); this.propertyFields = Arrays.asList( new PropertyField(key.pathKey, pathField), new PropertyField(key.flagsKey, flagsField)); GuiUtil.addFolderListener(pathField, command); GuiUtil.addApplyPathAction(autoFindButton, pathField, command); updateVersion(); } public void updateVersion() { String pathText = pathField.getText(); if (pathText.isEmpty()) { versionField.setText(""); } else { versionField.setText(getVersion(pathText, versionParam).split("\r\n|\r|\n")[0]); } } public boolean isModified() { for (PropertyField propertyField : propertyFields) { if (propertyField.isModified()) { return true; } } return false; } public void saveState() { if (isModified() && publisher != null) { publisher.onSettingsChanged(new ToolSettings(pathField.getText(), flagsField.getText())); } for (PropertyField propertyField : propertyFields) { propertyField.saveState(); } } public void restoreState() { for (PropertyField propertyField : propertyFields) { propertyField.restoreState(); } } } @NotNull @Override public String getId() { return HASKELL_TOOLS_ID; } @Nullable @Override public Runnable enableSearch(String s) { // TODO return null; } @Nls @Override public String getDisplayName() { return HASKELL_TOOLS_ID; } @Nullable @Override public String getHelpTopic() { return null; } @Nullable @Override public JComponent createComponent() { return mainPanel; } /** * Enables the apply button if anything changed. */ @Override public boolean isModified() { for (Property property : properties) { if (property.isModified()) { return true; } } return false; } /** * Triggered when the user pushes the apply button. */ @Override public void apply() throws ConfigurationException { validate(); updateVersionInfoFields(); saveState(); } public void validate() throws ConfigurationException { validateExecutableIfNonEmpty("stylish", stylishPath); validateExecutableIfNonEmpty("hlint", hlintPath); // Validate ghcModPath if either it or ghcModiPath have been set. if (ghcModPath.getText().isEmpty() && !ghcModiPath.getText().isEmpty()) { throw new ConfigurationException("ghc-mod must be configured if ghc-modi is configured."); } validateExecutableIfNonEmpty("ghc-mod", ghcModPath); validateExecutableIfNonEmpty("ghc-modi", ghcModiPath); validateExecutableIfNonEmpty("hindent", hindentPath); } public void validateExecutable(String name, TextAccessor field) throws ConfigurationException { if (new File(field.getText()).canExecute()) return; throw new ConfigurationException("Not a valid '" + name + "' executable: '" + field.getText() + "'"); } public void validateExecutableIfNonEmpty(String name, TextAccessor field) throws ConfigurationException { if (field.getText().isEmpty()) return; validateExecutable(name, field); } /** * Triggered when the user pushes the cancel button. */ @Override public void reset() { restoreState(); } @Override public void disposeUIResources() { } /** * Heuristically finds the version number. Current implementation is the * identity function since cabal plays nice. */ @Nullable private static String getVersion(String cmd, String versionFlag) { return ExecUtil.readCommandLine(null, cmd, versionFlag).fold( new AbstractFunction1<ExecUtil.ExecError, String>() { @Override public String apply(ExecUtil.ExecError e) { NotificationUtil.displaySimpleNotification( NotificationType.ERROR, null, "Haskell Tools", e.getMessage() ); return null; } }, new AbstractFunction1<String, String>() { @Override public String apply(String s) { return s; } } ); } /** * Updates the version info fields for all files configured. */ private void updateVersionInfoFields() { for (Property property : properties) { if (property instanceof Versioned) { ((Versioned)property).updateVersion(); } } } /** * Persistent save of the current state. */ private void saveState() { preSaveHook(); for (Property property : properties) { property.saveState(); } } /** * Updates tool settings before saving. */ private void preSaveHook() { ghcModLegacyInteractivePreSaveHook(); } private static Pattern GHC_MOD_VERSION_REGEX = Pattern.compile("(\\d+)\\.(\\d+)"); @Nullable public static Pair<Integer, Integer> parseGhcModVersion(String version) { if (version == null) return null; Matcher m = GHC_MOD_VERSION_REGEX.matcher(version); if (!m.find()) { LOG.error("Could not find ghc-mod version number from string: " + version); return null; } return Pair.create(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2))); } /** * If we're using ghc-mod >= 5.4, ghc-modi will be configured as `ghc-mod legacy-interactive` */ private void ghcModLegacyInteractivePreSaveHook() { // If ghc-mod is not configured or is not >= 5.4, we can't infer legacy-interactive. if (ghcModPath.getText().isEmpty() || !isGhcMod5_4(ghcModPath.getText())) return; // If ghc-modi is configured and it is not >= 5.4, leave it alone. if (!ghcModiPath.getText().isEmpty() && !isGhcMod5_4(ghcModiPath.getText())) return; // If all is good, configure ghc-modi as legacy-interactive. ghcModiPath.setText(ghcModPath.getText()); // If the current ghc-modi flags contains the `legacy-interactive` command, do not add it back. if (!ghcModiFlags.getText().contains("legacy-interactive")) { ghcModiFlags.setText(ghcModiFlags.getText() + " legacy-interactive"); } } private boolean isGhcMod5_4(String exePath) { String versionStr = getVersion(exePath, "version"); if (versionStr == null) { LOG.warn("Could not retrieve ghc-mod version from " + exePath); return false; } Pair<Integer, Integer> version = parseGhcModVersion(versionStr); if (version == null) { LOG.warn("Could not parse ghc-mod version from string: " + versionStr); return false; } return version.first > 5 || (version.first == 5 && version.second >= 4); } /** * Restore components to the initial state. */ private void restoreState() { for (Property property : properties) { property.restoreState(); } } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * * @author Tyler */ public class RobotShoot { //// ADDED: SWITCHED THE SIGNS ON THE WIND AND UNWIND SPEED public static final double UNWIND_SPEED = -0.3; // TODO: may change public static final double WAIT_TIME = 0.75; public static final double WIND_SPEED = 1.0; public static final double MAX_REVS = 1500; public static final double QUICK_SHOOT_REVS = .8 * MAX_REVS; public static final double BACKWARDS_REV = -(MAX_REVS + 500.0); public static final double TENSION_TOLERANCE = 15; //private static double tensionTargetTicks = 1200; // Practice robot private static double tensionTargetTicks = 1075; // WONT CHANGE AUTON VALUE, GO TO THE AUTON CLASS private static double givenTensionTargetTicks = 1075; private static int tensionTargetDirection = -1; private static Timer timer; public static Timer gameTime; private static double updatedSpeed; private static boolean inManualMode = true; private static boolean latch; private static String currentStage; private static int stage; private static int returnStage = 0; public static double voltage; public static double current; public static void setTargetTicks(double ticks) { ticks = Math.max(500, Math.min(1400, ticks)); givenTensionTargetTicks = ticks; tensionTargetTicks = ticks; tensionTargetTicks = Math.max(500, Math.min(1400, tensionTargetTicks)); SmartDashboard.putNumber("shooter TICKS", ticks); SmartDashboard.putNumber("shooter TARGET TICKS", tensionTargetTicks); SmartDashboard.putNumber("shooter GIVEN TICKS", givenTensionTargetTicks); } public static void adjustTargetUp() { setTargetTicks(givenTensionTargetTicks + 25); } public static void adjustTargetDown() { setTargetTicks(givenTensionTargetTicks - 25); } public static void initialize() { latch(); timer = new Timer(); updatedSpeed = 0.0; currentStage = ""; stage = 0; gameTime = new Timer(); RobotSensors.shooterWinchEncoder.start(); } public static void startShoot() { stage = 2; zeroedBefore = false; // CHANGED: 4/4/14 //stage = 1; } public static void useManual() { inManualMode = true; } public static void useAutomatic() { inManualMode = false; } public static boolean isManual() { return inManualMode; } public static boolean isReadyToShoot() { return stage == 6 && Math.abs(getEncoder() - tensionTargetTicks) < TENSION_TOLERANCE * 1.5; } // releases the latch public static void releaseBall() { currentStage = "1"; if (RobotPickup.isPickupInShootPosition() || RobotPickup.isPickupInTrussPosition()) { releaseLatch(); stage = 2; } else { stage = returnStage; } } // Is Shown in our diagram as the shooter head moving forward // Nothing that is controlled is happening nows public static void ballInMotion() { currentStage = "2"; timer.stop(); timer.reset(); timer.start(); releaseLatch(); stage = 3; } // waiting the 0.5 seconds before unwinding the shooter motor public static void waitToUnwind() { currentStage = "3"; double time = timer.get(); if (time >= WAIT_TIME) { timer.stop(); timer.reset(); stage = 4; } } // unwindes the shooter until it hits the back limit switch or reaches max revolutions //and returns the limit value static boolean zeroedBefore = false; public static void unwind() { currentStage = "4"; releaseLatch(); if (getAtBack() && timer.get() <= .05) { timer.start(); if (!zeroedBefore) { RobotSensors.shooterWinchEncoder.reset(); zeroedBefore = true; } System.out.println("RobotShoot.java\tHIT BACK"); } automatedUnwind(); SmartDashboard.putNumber("STAGE 4 TIMER", timer.get()); if ((zeroedBefore && (timer.get() > 0.5 || getEncoder() < -200)) || timer.get() > 3) { updatedSpeed = 0.0; System.out.println("RobotShoot.java\tSTOP:"); System.out.println("RobotShoot.java\tTimer " + timer.get()); System.out.println("RobotShoot.java\tEncoder " + getEncoder()); timer.stop(); timer.reset(); stage = 5; } } // relatches the shooter public static void latchShooter() { currentStage = "5"; if (timer.get() == 0.0) { timer.start(); } latch(); //// TODO: CHANGE THE TIME ON THIS LATER ON //// CHANGED: Latch time from 1.0 if (timer.get() >= 0.5) { timer.stop(); timer.reset(); stage = 6; } updatedSpeed = 0; } // rewinds the shooter public static void rewindShooter() { currentStage = "6"; updatedSpeed = 0; if (getEncoder() <= tensionTargetTicks - TENSION_TOLERANCE && RobotSensors.shooterLoadedLim.get()) { automatedWind(); return; } if (getEncoder() >= tensionTargetTicks + TENSION_TOLERANCE && !getAtBack()) { automatedUnwind(); if (Math.abs(getEncoder() - tensionTargetTicks) < TENSION_TOLERANCE * 3) { updatedSpeed /= 5.0; // updatedSpeed /= 4.0; // 1/4/14 } return; } updatedSpeed = 0.0; } public static void reset() { RobotSensors.shooterWinchEncoder.reset(); gameTime.stop(); gameTime.reset(); timer.stop(); timer.reset(); } // reshoot method // needs to be called before reshooting public static void shoot() { //// CHANGED: ADDED IN TO MAKE SURE WE DONT FIRE IN STAGES 2,3,4,5 if ((RobotPickup.isPickupInShootPosition() || RobotPickup.isPickupInTrussPosition()) && !(stage >= 2 && stage <= 5)) { SmartDashboard.putBoolean("Truss: ", RobotPickup.isPickupInTrussPosition()); if (stage != 1) { returnStage = stage; MainRobot.logData += getEncoder() + "\t" + RobotVision.getDistance() + "\n"; } stage = 1; timer.stop(); timer.reset(); } } // Automated shoot public static void automatedShoot() { SmartDashboard.putString("Current Shooter Stage", currentStage); SmartDashboard.putNumber("Shooter Timer", timer.get()); // shoots switch (stage) { case 1: releaseBall(); break; case 2: ballInMotion(); break; case 3: waitToUnwind(); break; case 4: unwind(); break; case 5: latchShooter(); break; case 6: rewindShooter(); break; case 99: case -99: break; default: //System.out.println("You have stage Fright"); //System.out.println("Stage Issue: " + stage); break; } SmartDashboard.putNumber("latch", latch ? 1 + MathUtils.rand(1) / 1000 : 0 + MathUtils.rand(1) / 1000); SmartDashboard.putNumber("stage SHOOTER", stage + MathUtils.rand(1) / 1000); //System.out.println("-->stage: " + stage); if (stage != 1) { returnStage = stage; } } // used for calibration public static void manualShoot() { stage = -99; updatedSpeed = Gamepad.secondary.getRightY(); //SmartDashboard.putBoolean("is the shooterLoadedLim", RobotSensors.shooterLoadedLim.get()); // TODO: TAKE OUT THE OR TRUE FOR THE REAL ROBOT WHEN THE SWITCH IS FIXED /*if ((RobotSensors.shooterLoadedLim.get() || true) && getEncoder() <= BACKWARDS_REV && Gamepad.secondary.getRightY() <= 0.0) { updatedSpeed = 0.0; System.out.println("Can't move back"); }*/ //// TODO: UNCOMMENT IT OUT WHEN IT IS DONE /*if (RobotSensors.shooterLoadedLim.get() && updatedSpeed >= 0.0) { updatedSpeed = 0.0; }*/ if (Math.abs(Gamepad.secondary.getTriggers()) > .8 && (RobotPickup.isPickupInShootPosition() || RobotPickup.isPickupInTrussPosition())) { releaseLatch(); } else { latch(); } //RobotPickup.moveToShootPosition(); } // sets speed to the unwind speed private static void automatedUnwind() { updatedSpeed = UNWIND_SPEED; /*if (!zeroedBefore) { updatedSpeed = UNWIND_SPEED * 2.0/3.0; }*/ } // sets the speed to the wind speed private static void automatedWind() { updatedSpeed = WIND_SPEED; } // sets the speed to 0.0 public static void stopMotors() { updatedSpeed = 0.0; //stage = 99; } // Releases the pnuematic public static void releaseLatch() { latch = true; //zeroEncoder(); } // latches the pnuematic public static void latch() { latch = false; } // get the limit switch public static boolean getAtBack() { return !RobotSensors.shooterAtBack.get(); } // Zeroes the encoder // check to see if the encoder is bad with this /*private static void zeroEncoder() { if (getAtBack()) { beenZeroed = false; } }*/ public static void update() { if (getEncoder() >= 100 && !getAtBack()) { //System.out.println("Bad limit switch: " + getEncoder()); } // checks to see if the encoder should be zeroed if ((getEncoder() <= BACKWARDS_REV && updatedSpeed <= 0.0) || (getEncoder() >= MAX_REVS && updatedSpeed >= 0.0)) { updatedSpeed = 0.0; } /*if ((!getAtBack() && updatedSpeed <= 0) || (RobotSensors.shooterWinchEncoder.get() >= MAX_REVS && updatedSpeed >= 0.0)) { updatedSpeed = 0.0; }*/ SmartDashboard.putBoolean("Shooter At back", getAtBack()); if (!RobotSensors.shooterLoadedLim.get() && updatedSpeed >= 0) { updatedSpeed = 0.0; } // sets pnuematics RobotActuators.latchRelease.set(latch); if (RobotActuators.latchRelease.get()) { System.out.println(gameTime.get() + " Latches"); } // sets motor RobotActuators.shooterWinch.set(updatedSpeed); SmartDashboard.putNumber("Updated Speed Value",updatedSpeed); // prints to smart dashboard if (inManualMode) { manualShoot(); } else { automatedShoot(); } } public static double getEncoder() { return RobotSensors.shooterWinchEncoder.get(); } ////CURRENT CHECK CODE (ask Debjit) public static double getCurrent() { voltage = RobotSensors.currentSensor.getVoltage(); current = (voltage - 500) * 0.05 - 100; return current; //System.out.println("Current = " + current + " Voltage = " + voltage); //Not too sure about the units, though. (most likely milli-) } }
package com.haxademic.sketch.hardware.webcam; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.util.DrawUtil; import com.haxademic.core.image.ImageUtil; import processing.core.PConstants; import processing.core.PImage; import processing.video.Capture; import toxi.geom.Vec2D; import toxi.geom.Vec3D; import toxi.geom.mesh.Face; import toxi.geom.mesh.WETriangleMesh; public class WebCamTest extends PAppletHax { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } /** * Processing web cam capture object */ protected Capture _webCam; protected int _camW = 1280; protected int _camH = 720; protected WETriangleMesh _mesh; public void setup () { initWebCam(); } void initWebCam() { String[] cameras = Capture.list(); if (cameras.length == 0) { println("There are no cameras available for capture."); exit(); } else { println("Available cameras:"); for (int i = 0; i < cameras.length; i++) println("["+i+"] "+cameras[i]); _webCam = new Capture(this, cameras[15]); _webCam.start(); } } public void draw() { // if(p.frameCount == 1) _webCam = new Capture(this, camera); p.background( 0 ); p.rectMode(PConstants.CENTER); DrawUtil.resetGlobalProps( p ); DrawUtil.setCenter( p ); DrawUtil.setBasicLights( p ); p.fill( 0, 0, 0, 255 ); p.noStroke(); p.translate( 0, 0, -1000 ); p.rotateX( 0.02f*p.mouseY ); p.rotateY( 0.02f*p.mouseX ); if (_webCam.available()) { // Reads the new frame _webCam.read(); // drawDepthImage(); // drawMesh(); drawNativeMesh(); // drawImage(); } } void drawImage(){ p.image(_webCam, 0, 0); } void drawDepthImage(){ int cellsize = 3; PImage img = _webCam.get(); p.noStroke(); int x, y, color; for ( int i = 0; i < _camW; i++) { for ( int j = 0; j < _camH; j++) { x = i; y = j; color = ImageUtil.getPixelColor( img, x, y ); float z = p.brightness( color ) / 10f; // Translate to the location, set fill and stroke, and draw the rect p.pushMatrix(); p.translate(-img.width/2 + x, -img.height/2 + y, z); p.fill( color, 255 ); p.rect( 0, 0, cellsize, cellsize ); p.popMatrix(); } } } void drawMesh() { if( _mesh == null ) createMesh(); PImage img = _webCam.get(); // set draw props to draw texture mesh properly p.fill( 0 ); p.noStroke(); // iterate over all mesh triangles // and add their vertices p.beginShape(P.TRIANGLES); p.texture(img); float brightA, brightB, brightC = 0; for( Face f : _mesh.getFaces() ) { // get z-depth brightA = getBrightnessForTextureLoc( img, f.uvA.x, f.uvA.y ); brightB = getBrightnessForTextureLoc( img, f.uvB.x, f.uvB.y ); brightC = getBrightnessForTextureLoc( img, f.uvC.x, f.uvC.y ); // draw vertices p.vertex(f.a.x,f.a.y,f.a.z+brightA,f.uvA.x,f.uvA.y); p.vertex(f.b.x,f.b.y,f.b.z+brightB,f.uvB.x,f.uvB.y); p.vertex(f.c.x,f.c.y,f.c.z+brightC,f.uvC.x,f.uvC.y); } p.endShape(); } float getBrightnessForTextureLoc( PImage img, float x, float y ) { float loc = x + y * img.width; // p.Pixel array location int c = img.pixels[(int)loc]; // Grab the color return p.brightness(c) * 0.1f; } void createMesh() { _mesh = new WETriangleMesh(); int cols = _camW; int rows = _camH; for ( int i = 0; i < cols - 1; i++) { for ( int j = 0; j < rows - 1; j++) { // position mesh out from center float x = i - _camW/2; float y = j - _camH/2; // create 2 faces and their UV texture coordinates _mesh.addFace( new Vec3D( x, y, 0 ), new Vec3D( x+1, y, 0 ), new Vec3D( x+1, y+1, 0 ), new Vec2D( i, j ), new Vec2D( i+1, j ), new Vec2D( i+1, j+1 ) ); _mesh.addFace( new Vec3D( x, y, 0 ), new Vec3D( x+1, y+1, 0 ), new Vec3D( x, y+1, 0 ), new Vec2D( i, j ), new Vec2D( i+1, j+1 ), new Vec2D( i, j+1 ) ); } } } /** * Good old-fashioned Processing mesh */ void drawNativeMesh() { PImage img = _webCam.get(); int x, y, color; p.beginShape(P.TRIANGLES); int skip = 10; for ( int i = 0; i < _camW - 1; i+=skip) { for ( int j = 0; j < _camH - 1; j+=skip) { x = i; // x position y = j; // y position color = ImageUtil.getPixelColor( img, x, y ); float z = p.brightness(color); p.fill(color); p.noStroke(); // draw grid out from center x = -img.width/2 + x; y = -img.height/2 + y; // draw trianges p.vertex( x, y, z ); p.vertex( x+skip, y, z ); p.vertex( x+skip, y+skip, z ); p.vertex( x, y, z ); p.vertex( x, y+skip, z ); p.vertex( x+skip, y+skip, z ); } } p.endShape(); } }